var Z6e=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var krt=Z6e((Md,Rd)=>{(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).observe(document,{childList:!0,subtree:!0});function t(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=t(r);fetch(r.href,s)}})();var kt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function KH(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function c0e(n){if(n.__esModule)return n;var e=n.default;if(typeof e=="function"){var t=function i(){return this instanceof i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(i){var r=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return n[i]}})}),t}var $q={exports:{}},h0e=function(e,t){return function(){for(var r=new Array(arguments.length),s=0;s"u"}function J6e(n){return n!==null&&!yz(n)&&n.constructor!==null&&!yz(n.constructor)&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}var u0e=H6("ArrayBuffer");function eCe(n){var e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(n):e=n&&n.buffer&&u0e(n.buffer),e}function tCe(n){return typeof n=="string"}function iCe(n){return typeof n=="number"}function d0e(n){return n!==null&&typeof n=="object"}function VV(n){if(qq(n)!=="object")return!1;var e=Object.getPrototypeOf(n);return e===null||e===Object.prototype}var rCe=H6("Date"),sCe=H6("File"),nCe=H6("Blob"),aCe=H6("FileList");function eJ(n){return Zq.call(n)==="[object Function]"}function oCe(n){return d0e(n)&&eJ(n.pipe)}function lCe(n){var e="[object FormData]";return n&&(typeof FormData=="function"&&n instanceof FormData||Zq.call(n)===e||eJ(n.toString)&&n.toString()===e)}var cCe=H6("URLSearchParams");function hCe(n){return n.trim?n.trim():n.replace(/^\s+|\s+$/g,"")}function uCe(){return typeof navigator<"u"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window<"u"&&typeof document<"u"}function tJ(n,e){if(!(n===null||typeof n>"u"))if(typeof n!="object"&&(n=[n]),Jq(n))for(var t=0,i=n.length;t0;)s=i[r],a[s]||(e[s]=n[s],a[s]=!0);n=Object.getPrototypeOf(n)}while(n&&(!t||t(n,e))&&n!==Object.prototype);return e}function mCe(n,e,t){n=String(n),(t===void 0||t>n.length)&&(t=n.length),t-=e.length;var i=n.indexOf(e,t);return i!==-1&&i===t}function gCe(n){if(!n)return null;var e=n.length;if(yz(e))return null;for(var t=new Array(e);e-- >0;)t[e]=n[e];return t}var vCe=function(n){return function(e){return n&&e instanceof n}}(typeof Uint8Array<"u"&&Object.getPrototypeOf(Uint8Array)),Gc={isArray:Jq,isArrayBuffer:u0e,isBuffer:J6e,isFormData:lCe,isArrayBufferView:eCe,isString:tCe,isNumber:iCe,isObject:d0e,isPlainObject:VV,isUndefined:yz,isDate:rCe,isFile:sCe,isBlob:nCe,isFunction:eJ,isStream:oCe,isURLSearchParams:cCe,isStandardBrowserEnv:uCe,forEach:tJ,merge:n$,extend:dCe,trim:hCe,stripBOM:fCe,inherits:pCe,toFlatObject:_Ce,kindOf:qq,kindOfTest:H6,endsWith:mCe,toArray:gCe,isTypedArray:vCe,isFileList:aCe},lS=Gc;function Qce(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var f0e=function(e,t,i){if(!t)return e;var r;if(i)r=i(t);else if(lS.isURLSearchParams(t))r=t.toString();else{var s=[];lS.forEach(t,function(c,l){c===null||typeof c>"u"||(lS.isArray(c)?l=l+"[]":c=[c],lS.forEach(c,function(u){lS.isDate(u)?u=u.toISOString():lS.isObject(u)&&(u=JSON.stringify(u)),s.push(Qce(l)+"="+Qce(u))}))}),r=s.join("&")}if(r){var a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+r}return e},xCe=Gc;function WH(){this.handlers=[]}WH.prototype.use=function(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1};WH.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)};WH.prototype.forEach=function(e){xCe.forEach(this.handlers,function(i){i!==null&&e(i)})};var yCe=WH,ACe=Gc,CCe=function(e,t){ACe.forEach(e,function(r,s){s!==t&&s.toUpperCase()===t.toUpperCase()&&(e[t]=r,delete e[s])})},p0e=Gc;function L8(n,e,t,i,r){Error.call(this),this.message=n,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),i&&(this.request=i),r&&(this.response=r)}p0e.inherits(L8,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var _0e=L8.prototype,m0e={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach(function(n){m0e[n]={value:n}});Object.defineProperties(L8,m0e);Object.defineProperty(_0e,"isAxiosError",{value:!0});L8.from=function(n,e,t,i,r,s){var a=Object.create(_0e);return p0e.toFlatObject(n,a,function(c){return c!==Error.prototype}),L8.call(a,n.message,e,t,i,r),a.name=n.name,s&&Object.assign(a,s),a};var S5=L8,g0e={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Mp=Gc;function bCe(n,e){e=e||new FormData;var t=[];function i(s){return s===null?"":Mp.isDate(s)?s.toISOString():Mp.isArrayBuffer(s)||Mp.isTypedArray(s)?typeof Blob=="function"?new Blob([s]):Buffer.from(s):s}function r(s,a){if(Mp.isPlainObject(s)||Mp.isArray(s)){if(t.indexOf(s)!==-1)throw Error("Circular reference detected in "+a);t.push(s),Mp.forEach(s,function(c,l){if(!Mp.isUndefined(c)){var h=a?a+"."+l:l,u;if(c&&!a&&typeof c=="object"){if(Mp.endsWith(l,"{}"))c=JSON.stringify(c);else if(Mp.endsWith(l,"[]")&&(u=Mp.toArray(c))){u.forEach(function(d){!Mp.isUndefined(d)&&e.append(h,i(d))});return}}r(c,h)}}),t.pop()}else e.append(a,i(s))}return r(n),e}var v0e=bCe,qj,$ce;function ECe(){if($ce)return qj;$ce=1;var n=S5;return qj=function(t,i,r){var s=r.config.validateStatus;!r.status||!s||s(r.status)?t(r):i(new n("Request failed with status code "+r.status,[n.ERR_BAD_REQUEST,n.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))},qj}var Jj,Zce;function TCe(){if(Zce)return Jj;Zce=1;var n=Gc;return Jj=n.isStandardBrowserEnv()?function(){return{write:function(i,r,s,a,o,c){var l=[];l.push(i+"="+encodeURIComponent(r)),n.isNumber(s)&&l.push("expires="+new Date(s).toGMTString()),n.isString(a)&&l.push("path="+a),n.isString(o)&&l.push("domain="+o),c===!0&&l.push("secure"),document.cookie=l.join("; ")},read:function(i){var r=document.cookie.match(new RegExp("(^|;\\s*)("+i+")=([^;]*)"));return r?decodeURIComponent(r[3]):null},remove:function(i){this.write(i,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),Jj}var SCe=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},MCe=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},RCe=SCe,ICe=MCe,x0e=function(e,t){return e&&!RCe(t)?ICe(e,t):t},eX,qce;function PCe(){if(qce)return eX;qce=1;var n=Gc,e=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return eX=function(i){var r={},s,a,o;return i&&n.forEach(i.split(` `),function(l){if(o=l.indexOf(":"),s=n.trim(l.substr(0,o)).toLowerCase(),a=n.trim(l.substr(o+1)),s){if(r[s]&&e.indexOf(s)>=0)return;s==="set-cookie"?r[s]=(r[s]?r[s]:[]).concat([a]):r[s]=r[s]?r[s]+", "+a:a}}),r},eX}var tX,Jce;function wCe(){if(Jce)return tX;Jce=1;var n=Gc;return tX=n.isStandardBrowserEnv()?function(){var t=/(msie|trident)/i.test(navigator.userAgent),i=document.createElement("a"),r;function s(a){var o=a;return t&&(i.setAttribute("href",o),o=i.href),i.setAttribute("href",o),{href:i.href,protocol:i.protocol?i.protocol.replace(/:$/,""):"",host:i.host,search:i.search?i.search.replace(/^\?/,""):"",hash:i.hash?i.hash.replace(/^#/,""):"",hostname:i.hostname,port:i.port,pathname:i.pathname.charAt(0)==="/"?i.pathname:"/"+i.pathname}}return r=s(window.location.href),function(o){var c=n.isString(o)?s(o):o;return c.protocol===r.protocol&&c.host===r.host}}():function(){return function(){return!0}}(),tX}var iX,ehe;function jH(){if(ehe)return iX;ehe=1;var n=S5,e=Gc;function t(i){n.call(this,i??"canceled",n.ERR_CANCELED),this.name="CanceledError"}return e.inherits(t,n,{__CANCEL__:!0}),iX=t,iX}var rX,the;function DCe(){return the||(the=1,rX=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}),rX}var sX,ihe;function rhe(){if(ihe)return sX;ihe=1;var n=Gc,e=ECe(),t=TCe(),i=f0e,r=x0e,s=PCe(),a=wCe(),o=g0e,c=S5,l=jH(),h=DCe();return sX=function(d){return new Promise(function(p,_){var m=d.data,g=d.headers,v=d.responseType,x;function y(){d.cancelToken&&d.cancelToken.unsubscribe(x),d.signal&&d.signal.removeEventListener("abort",x)}n.isFormData(m)&&n.isStandardBrowserEnv()&&delete g["Content-Type"];var C=new XMLHttpRequest;if(d.auth){var b=d.auth.username||"",T=d.auth.password?unescape(encodeURIComponent(d.auth.password)):"";g.Authorization="Basic "+btoa(b+":"+T)}var S=r(d.baseURL,d.url);C.open(d.method.toUpperCase(),i(S,d.params,d.paramsSerializer),!0),C.timeout=d.timeout;function N(){if(C){var I="getAllResponseHeaders"in C?s(C.getAllResponseHeaders()):null,R=!v||v==="text"||v==="json"?C.responseText:C.response,O={data:R,status:C.status,statusText:C.statusText,headers:I,config:d,request:C};e(function(G){p(G),y()},function(G){_(G),y()},O),C=null}}if("onloadend"in C?C.onloadend=N:C.onreadystatechange=function(){!C||C.readyState!==4||C.status===0&&!(C.responseURL&&C.responseURL.indexOf("file:")===0)||setTimeout(N)},C.onabort=function(){C&&(_(new c("Request aborted",c.ECONNABORTED,d,C)),C=null)},C.onerror=function(){_(new c("Network Error",c.ERR_NETWORK,d,C,C)),C=null},C.ontimeout=function(){var R=d.timeout?"timeout of "+d.timeout+"ms exceeded":"timeout exceeded",O=d.transitional||o;d.timeoutErrorMessage&&(R=d.timeoutErrorMessage),_(new c(R,O.clarifyTimeoutError?c.ETIMEDOUT:c.ECONNABORTED,d,C)),C=null},n.isStandardBrowserEnv()){var D=(d.withCredentials||a(S))&&d.xsrfCookieName?t.read(d.xsrfCookieName):void 0;D&&(g[d.xsrfHeaderName]=D)}"setRequestHeader"in C&&n.forEach(g,function(R,O){typeof m>"u"&&O.toLowerCase()==="content-type"?delete g[O]:C.setRequestHeader(O,R)}),n.isUndefined(d.withCredentials)||(C.withCredentials=!!d.withCredentials),v&&v!=="json"&&(C.responseType=d.responseType),typeof d.onDownloadProgress=="function"&&C.addEventListener("progress",d.onDownloadProgress),typeof d.onUploadProgress=="function"&&C.upload&&C.upload.addEventListener("progress",d.onUploadProgress),(d.cancelToken||d.signal)&&(x=function(I){C&&(_(!I||I&&I.type?new l:I),C.abort(),C=null)},d.cancelToken&&d.cancelToken.subscribe(x),d.signal&&(d.signal.aborted?x():d.signal.addEventListener("abort",x))),m||(m=null);var M=h(S);if(M&&["http","https","file"].indexOf(M)===-1){_(new c("Unsupported protocol "+M+":",c.ERR_BAD_REQUEST,d));return}C.send(m)})},sX}var nX,she;function OCe(){return she||(she=1,nX=null),nX}var nc=Gc,nhe=CCe,ahe=S5,LCe=g0e,NCe=v0e,BCe={"Content-Type":"application/x-www-form-urlencoded"};function ohe(n,e){!nc.isUndefined(n)&&nc.isUndefined(n["Content-Type"])&&(n["Content-Type"]=e)}function FCe(){var n;return(typeof XMLHttpRequest<"u"||typeof process<"u"&&Object.prototype.toString.call(process)==="[object process]")&&(n=rhe()),n}function UCe(n,e,t){if(nc.isString(n))try{return(e||JSON.parse)(n),nc.trim(n)}catch(i){if(i.name!=="SyntaxError")throw i}return(t||JSON.stringify)(n)}var XH={transitional:LCe,adapter:FCe(),transformRequest:[function(e,t){if(nhe(t,"Accept"),nhe(t,"Content-Type"),nc.isFormData(e)||nc.isArrayBuffer(e)||nc.isBuffer(e)||nc.isStream(e)||nc.isFile(e)||nc.isBlob(e))return e;if(nc.isArrayBufferView(e))return e.buffer;if(nc.isURLSearchParams(e))return ohe(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var i=nc.isObject(e),r=t&&t["Content-Type"],s;if((s=nc.isFileList(e))||i&&r==="multipart/form-data"){var a=this.env&&this.env.FormData;return NCe(s?{"files[]":e}:e,a&&new a)}else if(i||r==="application/json")return ohe(t,"application/json"),UCe(e);return e}],transformResponse:[function(e){var t=this.transitional||XH.transitional,i=t&&t.silentJSONParsing,r=t&&t.forcedJSONParsing,s=!i&&this.responseType==="json";if(s||r&&nc.isString(e)&&e.length)try{return JSON.parse(e)}catch(a){if(s)throw a.name==="SyntaxError"?ahe.from(a,ahe.ERR_BAD_RESPONSE,this,null,this.response):a}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:OCe()},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};nc.forEach(["delete","get","head"],function(e){XH.headers[e]={}});nc.forEach(["post","put","patch"],function(e){XH.headers[e]=nc.merge(BCe)});var iJ=XH,kCe=Gc,VCe=iJ,zCe=function(e,t,i){var r=this||VCe;return kCe.forEach(i,function(a){e=a.call(r,e,t)}),e},aX,lhe;function y0e(){return lhe||(lhe=1,aX=function(e){return!!(e&&e.__CANCEL__)}),aX}var che=Gc,oX=zCe,HCe=y0e(),GCe=iJ,KCe=jH();function lX(n){if(n.cancelToken&&n.cancelToken.throwIfRequested(),n.signal&&n.signal.aborted)throw new KCe}var WCe=function(e){lX(e),e.headers=e.headers||{},e.data=oX.call(e,e.data,e.headers,e.transformRequest),e.headers=che.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),che.forEach(["delete","get","head","post","put","patch","common"],function(r){delete e.headers[r]});var t=e.adapter||GCe.adapter;return t(e).then(function(r){return lX(e),r.data=oX.call(e,r.data,r.headers,e.transformResponse),r},function(r){return HCe(r)||(lX(e),r&&r.response&&(r.response.data=oX.call(e,r.response.data,r.response.headers,e.transformResponse))),Promise.reject(r)})},hd=Gc,A0e=function(e,t){t=t||{};var i={};function r(h,u){return hd.isPlainObject(h)&&hd.isPlainObject(u)?hd.merge(h,u):hd.isPlainObject(u)?hd.merge({},u):hd.isArray(u)?u.slice():u}function s(h){if(hd.isUndefined(t[h])){if(!hd.isUndefined(e[h]))return r(void 0,e[h])}else return r(e[h],t[h])}function a(h){if(!hd.isUndefined(t[h]))return r(void 0,t[h])}function o(h){if(hd.isUndefined(t[h])){if(!hd.isUndefined(e[h]))return r(void 0,e[h])}else return r(void 0,t[h])}function c(h){if(h in t)return r(e[h],t[h]);if(h in e)return r(void 0,e[h])}var l={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c};return hd.forEach(Object.keys(e).concat(Object.keys(t)),function(u){var d=l[u]||s,f=d(u);hd.isUndefined(f)&&d!==c||(i[u]=f)}),i},cX,hhe;function C0e(){return hhe||(hhe=1,cX={version:"0.27.2"}),cX}var jCe=C0e().version,p3=S5,rJ={};["object","boolean","number","function","string","symbol"].forEach(function(n,e){rJ[n]=function(i){return typeof i===n||"a"+(e<1?"n ":" ")+n}});var uhe={};rJ.transitional=function(e,t,i){function r(s,a){return"[Axios v"+jCe+"] Transitional option '"+s+"'"+a+(i?". "+i:"")}return function(s,a,o){if(e===!1)throw new p3(r(a," has been removed"+(t?" in "+t:"")),p3.ERR_DEPRECATED);return t&&!uhe[a]&&(uhe[a]=!0,console.warn(r(a," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(s,a,o):!0}};function XCe(n,e,t){if(typeof n!="object")throw new p3("options must be an object",p3.ERR_BAD_OPTION_VALUE);for(var i=Object.keys(n),r=i.length;r-- >0;){var s=i[r],a=e[s];if(a){var o=n[s],c=o===void 0||a(o,s,n);if(c!==!0)throw new p3("option "+s+" must be "+c,p3.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new p3("Unknown option "+s,p3.ERR_BAD_OPTION)}}var YCe={assertOptions:XCe,validators:rJ},b0e=Gc,QCe=f0e,dhe=yCe,fhe=WCe,YH=A0e,$Ce=x0e,E0e=YCe,cS=E0e.validators;function N8(n){this.defaults=n,this.interceptors={request:new dhe,response:new dhe}}N8.prototype.request=function(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=YH(this.defaults,t),t.method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var i=t.transitional;i!==void 0&&E0e.assertOptions(i,{silentJSONParsing:cS.transitional(cS.boolean),forcedJSONParsing:cS.transitional(cS.boolean),clarifyTimeoutError:cS.transitional(cS.boolean)},!1);var r=[],s=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(t)===!1||(s=s&&f.synchronous,r.unshift(f.fulfilled,f.rejected))});var a=[];this.interceptors.response.forEach(function(f){a.push(f.fulfilled,f.rejected)});var o;if(!s){var c=[fhe,void 0];for(Array.prototype.unshift.apply(c,r),c=c.concat(a),o=Promise.resolve(t);c.length;)o=o.then(c.shift(),c.shift());return o}for(var l=t;r.length;){var h=r.shift(),u=r.shift();try{l=h(l)}catch(d){u(d);break}}try{o=fhe(l)}catch(d){return Promise.reject(d)}for(;a.length;)o=o.then(a.shift(),a.shift());return o};N8.prototype.getUri=function(e){e=YH(this.defaults,e);var t=$Ce(e.baseURL,e.url);return QCe(t,e.params,e.paramsSerializer)};b0e.forEach(["delete","get","head","options"],function(e){N8.prototype[e]=function(t,i){return this.request(YH(i||{},{method:e,url:t,data:(i||{}).data}))}});b0e.forEach(["post","put","patch"],function(e){function t(i){return function(s,a,o){return this.request(YH(o||{},{method:e,headers:i?{"Content-Type":"multipart/form-data"}:{},url:s,data:a}))}}N8.prototype[e]=t(),N8.prototype[e+"Form"]=t(!0)});var ZCe=N8,hX,phe;function qCe(){if(phe)return hX;phe=1;var n=jH();function e(t){if(typeof t!="function")throw new TypeError("executor must be a function.");var i;this.promise=new Promise(function(a){i=a});var r=this;this.promise.then(function(s){if(r._listeners){var a,o=r._listeners.length;for(a=0;a{e.style.display="none"},5e3)}function abe(n){const e=document.getElementById("login-wrap");e.style.display="flex";const t=document.getElementById("login-btn"),i=async()=>{await n()&&(t.removeEventListener("click",i),e.style.display="none")};t.addEventListener("click",i)}function B8(n,e){var t=e||new Path2D,i=n.calculative.borderRadius||0,r=i,s=n.calculative.worldRect,a=s.x,o=s.y,c=s.width,l=s.height,h=s.ex,u=s.ey;i<1&&(i=c*i,r=l*r);var d=ie.x-t&&n.xe.y-t&&n.y0&&i>0?r=180-r:t<0&&i>0?r+=180:t<0&&i<0&&(r=360-r),r}function QH(n,e){var t=n.x-e.x,i=n.y-e.y;return Math.sqrt(t*t+i*i)}function mbe(n,e){var t=zr.None;if(!e)return t;var i=n.x-e.x,r=n.y-e.y;return Math.abs(i)>Math.abs(r)?i>0?t=zr.Right:t=zr.Left:r>0?t=zr.Bottom:t=zr.Up,t}function nD(n,e,t){n&&(n.x+=e,n.y+=t,n.next&&(n.next.x+=e,n.next.y+=t),n.prev&&(n.prev.x+=e,n.prev.y+=t))}function Ahe(n,e){return n.anchorId===e.anchorId&&n.connectTo===e.connectTo}function tV(n,e,t){var i=Math.sqrt((n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y))/t.data.scale;e.rotate===0?n.x>>0,1)},emit:function(e,t){(n.get(e)||[]).slice().map(function(i){i(t)}),(n.get("*")||[]).slice().map(function(i){i(e,t)})}}}var gy;(function(n){n[n.None=-1]="None",n[n.Document=0]="Document",n[n.Canvas=1]="Canvas"})(gy||(gy={}));var Lbe={fontFamily:'"Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial',fontSize:12,lineHeight:1.5,textAlign:"center",textBaseline:"middle",color:"#222222",activeColor:"#278df8",hoverColor:"rgba(39,141,248,0.50)",anchorColor:"#278DF8",hoverAnchorColor:"#FF4101",anchorRadius:4,anchorBackground:"#fff",dockColor:"rgba(39,141,248,0.50)",dockPenColor:"#1890FF",dragColor:"#1890ff",rotateCursor:"rotate.cur",hoverCursor:"pointer",minScale:.1,maxScale:10,keydown:gy.Document,gridSize:20,gridColor:"#e2e2e2",ruleColor:"#888888",drawingLineName:"curve",interval:30,animateInterval:30,autoPolyline:!0,autoAnchor:!0,autoAlignGrid:!1,animateColor:"#ff4d4f",ruleLineColor:"#FF4101",shadowOffsetX:0,shadowOffsetY:0,shadowBlur:64,shadowColor:"#00000014",globalAlpha:1,defaultAnchors:[{x:.5,y:0},{x:1,y:.5},{x:.5,y:1},{x:0,y:.5}],measureTextWidth:!0,moveConnectedLine:!0,mouseRightActive:!0,disableClipboard:!1,drawingLineLength:0,disableTouchPadScale:!1,cdn:"",polylineSpace:10,domShapes:[],textFlip:!0,textRotate:!0,unavailableKeys:[],diagramOptions:{}},o$=function(){return o$=Object.assign||function(n){for(var e,t=1,i=arguments.length;t=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},sr;(function(n){n[n.Add=0]="Add",n[n.Update=1]="Update",n[n.Delete=2]="Delete",n[n.Replace=3]="Replace"})(sr||(sr={}));var Bbe=function(){return{data:{x:0,y:0,scale:1,pens:[],origin:{x:0,y:0},center:{x:0,y:0},paths:{}},histories:[],pens:{},path2dMap:new WeakMap,animateMap:new WeakMap,active:[],animates:new Set,options:o$({},Lbe),emitter:Obe(),bindDatas:{},bind:{},pensNetwork:{},cacheDatas:[],messageEvents:{},templatePens:{}}},Fbe=function(n){return n===void 0&&(n="default"),mr[n]||(mr[n]=Bbe(),mr[n].id=n),mr[n]},Ube=function(n,e){var t,i,r=n.data.template===e;if(r)try{for(var s=Nbe(n.data.pens),a=s.next();!a.done;a=s.next()){var o=a.value;o.canvasLayer===Ts.CanvasTemplate&&(n.templatePens[o.id]=o)}}catch(c){t={error:c}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(t)throw t.error}}n.lastScale=n.data.scale,n.data={x:0,y:0,scale:1,pens:[],origin:{x:0,y:0},center:{x:0,y:0},paths:{},template:r?e:null},n.sameTemplate=r,n.pens={},n.histories=[],n.historyIndex=null,n.path2dMap=new WeakMap,n.animateMap=new WeakMap,n.bindDatas={},n.bind={},n.pensNetwork={},n.active=[],n.hover=void 0,n.lastHover=void 0,n.animates.clear()},Che=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},kbe=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],a;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},Vbe=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i1?l:1;switch(n.whiteSpace){case"nowrap":if(n.ellipsis!==!1){var u=bhe(e.split(""),n);u[0]&&(a.push(u[0]),u.length>1&&fX(a))}else a.push(e);break;case"pre-line":a=e.split(/[\n]/g),n.ellipsis!==!1&&a.length>h&&(a=a.slice(0,h),fX(a));break;case"break-all":default:var d=e.split(/[\n]/g),f=0;try{e:for(var p=Che(d),_=p.next();!_.done;_=p.next()){var m=_.value,g=n.whiteSpace==="break-all"?m.split(""):I0e(m),v=bhe(g,n);if(v.length===0&&(v=[""]),n.ellipsis!=!1)try{for(var x=(r=void 0,Che(v)),y=x.next();!y.done;y=x.next()){var C=y.value;if(f++,f>h){fX(a);break e}else a.push(C)}}catch(T){r={error:T}}finally{try{y&&!y.done&&(s=x.return)&&s.call(x)}finally{if(r)throw r.error}}else a.push.apply(a,Vbe([],kbe(v),!1))}}catch(T){t={error:T}}finally{try{_&&!_.done&&(i=p.return)&&i.call(p)}finally{if(t)throw t.error}}break}var b=n.calculative.keepDecimal;return b!=null&&a.forEach(function(T,S){var N=Number(T);isNaN(N)||(a[S]=N.toFixed(b))}),n.calculative.textLines=a,a}function I0e(n){n===void 0&&(n="");for(var e=[],t="",i=0;i126?(t&&(e.push(t),t=""),e.push(n[i])):t+=n[i]}return t&&e.push(t),e}function bhe(n,e){var t=e.calculative.canvas,i=t.offscreen.getContext("2d"),r=e.calculative,s=r.fontStyle,a=r.fontWeight,o=r.fontSize,c=r.fontFamily,l=r.lineHeight;i.save();for(var h=[],u=n[0]||"",d=1;dh&&(h=u)}i.restore();var v=e.length*o*l;n.textAlign==="left"||(n.textAlign==="right"?n.x=n.x-(h-n.width):n.x=n.x-(h-n.width)/2),n.textBaseline==="top"||(n.textBaseline==="bottom"?n.y=n.y-(v-n.height):n.y=n.y-(v-n.height)/2),n.height=v,n.width=h,n.calculative.canvas.updatePenRect(n),n.calculative.canvas.calcActiveRect()}function At(n,e){if(e===void 0&&(e=!1),Array.isArray(n)){var t=[];return n.forEach(function(s){t.push(At(s,e))}),t}else if(typeof n=="object"){if(n===null)return null;if(n.constructor===RegExp)return n;var i={};for(var r in n)if(!(["canvas","lastFrame"].includes(r)||n[r]instanceof HTMLImageElement||n[r]instanceof HTMLMediaElement)){{if(r==="calculative"&&!e)continue;if(r==="singleton"){e?i[r]={}:i[r]=n[r];continue}}i[r]=At(n[r],e)}return i}return n}function l$(n,e,t){if(Array.isArray(n)){var i=[];return n.forEach(function(a){i.push(l$(a,e,t))}),i}else if(typeof n=="object"){if(n===null)return null;var r=function(a){if(e.includes(a))if(Array.isArray(n[a]))n[a].forEach(function(o,c){Number.isNaN(Number(o))||(n[a][c]=Number(o*t))});else{if(Number.isNaN(Number(n[a])))return"continue";n[a]=Number(n[a])*t}else n[a]=l$(n[a],e,t)};for(var s in n)r(s);return n}return n}var Od={};function P0e(n,e,t){if(Od[e.fromArrow]){var i=xo(e),r=i.x,s=i.y,a={x:r,y:s};if(a.step=(e.fromArrowSize||10)*t.data.scale,i.next)a.rotate=Rf(i.next,i)+90;else{var o=e.calculative.worldAnchors[1];if(!o)return;o.prev?a.rotate=Rf(o.prev,i)+90:a.rotate=Rf(o,i)+90}n.save(),n.beginPath(),n.setLineDash([]);var c=e.fromArrowColor||e.calculative.color;c&&(n.strokeStyle=c),Od[e.fromArrow](n,e,t,a),n.restore()}}function w0e(n,e,t){if(!(!Od[e.toArrow]||e.calculative.worldAnchors.length<2)){n.save();var i=nn(e),r=i.x,s=i.y,a={x:r,y:s};if(a.step=(e.toArrowSize||10)*t.data.scale,i.prev)a.rotate=Rf(i.prev,i)+90;else{var o=e.calculative.worldAnchors[e.calculative.worldAnchors.length-2];o.next?a.rotate=Rf(o.next,i)+90:a.rotate=Rf(o,i)+90}n.beginPath(),n.setLineDash([]);var c=e.toArrowColor||e.calculative.color;c&&(n.strokeStyle=c),Od[e.toArrow](n,e,t,a),n.restore()}}Od.triangleSolid=function(n,e,t,i){n.save(),n.translate(i.x,i.y),n.rotate(i.rotate*Math.PI/180),n.translate(-i.x,-i.y);var r=i.x-i.step;n.moveTo(r,i.y-i.step/4),n.lineTo(i.x,i.y),n.lineTo(r,i.y+i.step/4),n.closePath(),n.stroke(),n.fillStyle=n.strokeStyle,n.fill(),n.restore()};Od.triangle=function(n,e,t,i){n.save(),n.lineWidth<2&&(n.lineWidth=2),n.translate(i.x,i.y),n.rotate(i.rotate*Math.PI/180),n.translate(-i.x,-i.y);var r=i.x-i.step;n.moveTo(r,i.y-i.step/4),n.lineTo(i.x,i.y),n.lineTo(r,i.y+i.step/4),n.closePath(),n.stroke(),n.fillStyle=t.data.background||"#ffffff",n.fill(),n.restore()};Od.circleSolid=function(n,e,t,i){n.save(),n.translate(i.x,i.y),n.rotate(i.rotate*Math.PI/180),n.translate(-i.x,-i.y);var r=i.step/2;n.arc(i.x-r,i.y,r,0,2*Math.PI),n.stroke(),n.fillStyle=n.strokeStyle,n.fill(),n.restore()};Od.circle=function(n,e,t,i){n.save(),n.translate(i.x,i.y),n.rotate(i.rotate*Math.PI/180),n.translate(-i.x,-i.y);var r=i.step/2;n.arc(i.x-r,i.y,r,0,2*Math.PI),n.stroke(),n.fillStyle=t.data.background||"#ffffff",n.fill(),n.restore()};Od.diamondSolid=function(n,e,t,i){n.save(),n.translate(i.x,i.y),n.rotate(i.rotate*Math.PI/180),n.translate(-i.x,-i.y);var r=i.x-i.step,s=i.step/2;n.moveTo(r,i.y),n.lineTo(r+s,i.y-s/2),n.lineTo(i.x,i.y),n.lineTo(r+s,i.y+s/2),n.closePath(),n.stroke(),n.fillStyle=n.strokeStyle,n.fill(),n.restore()};Od.diamond=function(n,e,t,i){n.save(),n.translate(i.x,i.y),n.rotate(i.rotate*Math.PI/180),n.translate(-i.x,-i.y);var r=i.x-i.step,s=i.step/2;n.moveTo(r,i.y),n.lineTo(r+s,i.y-s/2),n.lineTo(i.x,i.y),n.lineTo(r+s,i.y+s/2),n.closePath(),n.stroke(),n.fillStyle=t.data.background||"#ffffff",n.fill(),n.restore()};Od.line=function(n,e,t,i){n.save(),n.translate(i.x,i.y),n.rotate(i.rotate*Math.PI/180),n.translate(-i.x,-i.y);var r=i.x-i.step;n.moveTo(r,i.y-i.step/3),n.lineTo(i.x,i.y),n.lineTo(r,i.y+i.step/3),n.stroke(),n.restore()};Od.lineUp=function(n,e,t,i){n.save(),n.translate(i.x,i.y),n.rotate(i.rotate*Math.PI/180),n.translate(-i.x,-i.y);var r=i.x-i.step;n.moveTo(r,i.y-i.step/3),n.lineTo(i.x,i.y),n.stroke(),n.restore()};Od.lineDown=function(n,e,t,i){n.save(),n.translate(i.x,i.y),n.rotate(i.rotate*Math.PI/180),n.translate(-i.x,-i.y);var r=i.x-i.step;n.moveTo(r,i.y+i.step/3),n.lineTo(i.x,i.y),n.stroke(),n.restore()};var Gbe=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],a;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s};function c$(n){var e=parseInt,t=Math.round,i=n.length,r={};if(i>9){var s=Gbe(n=n.split(","),4),a=s[0],o=s[1],c=s[2],l=s[3];if(i=n.length,i<3||i>4)return null;r.r=e(a[3]=="a"?a.slice(5):a.slice(4)),r.g=e(o),r.b=e(c),r.a=l?parseFloat(l):-1}else{if(i==8||i==6||i<4)return null;i<6&&(n="#"+n[1]+n[1]+n[2]+n[2]+n[3]+n[3]+(i>4?n[4]+n[4]:"")),n=e(n.slice(1),16),i==9||i==5?(r.r=n>>24&255,r.g=n>>16&255,r.b=n>>8&255,r.a=t((n&255)/.255)/1e3):(r.r=n>>16,r.g=n>>8&255,r.b=n&255,r.a=-1)}return r}function Kbe(n,e,t,i){var r,s,a,o,c,l,h,u=Math.round,d=typeof t=="string";return typeof n!="number"||n<-1||n>1||typeof e!="string"||e[0]!="r"&&e[0]!="#"||t&&!d||(h=e.length>9,h=d?t.length>9?!0:t=="c"?!h:!1:h,c=c$(e),o=n<0,l=t&&t!="c"?c$(t):o?{r:0,g:0,b:0,a:-1}:{r:255,g:255,b:255,a:-1},n=o?n*-1:n,o=1-n,!c||!l)?null:(i?(r=u(o*c.r+n*l.r),s=u(o*c.g+n*l.g),a=u(o*c.b+n*l.b)):(r=u(Math.pow(o*Math.pow(c.r,2)+n*Math.pow(l.r,2),.5)),s=u(Math.pow(o*Math.pow(c.g,2)+n*Math.pow(l.g,2),.5)),a=u(Math.pow(o*Math.pow(c.b,2)+n*Math.pow(l.b,2),.5))),d=c.a,l=l.a,c=d>=0||l>=0,d=c?d<0?l:l<0?d:d*o+l*n:0,h?"rgb"+(c?"a(":"(")+r+","+s+","+a+(c?","+u(d*1e3)/1e3:"")+")":"#"+(4294967296+r*16777216+s*65536+a*256+(c?u(d*255):0)).toString(16).slice(1,c?void 0:-2))}globalThis.pSBC=Kbe;function Cz(n,e){var t=c$(n)||{r:0,g:0,b:0};return t.a<0?"rgba("+t.r+","+t.g+","+t.b+","+e+")":"rgba("+t.r+","+t.g+","+t.b+","+(e+t.a)+")"}var aD=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],a;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},Wbe=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function iV(n,e){if(isNaN(n)){console.warn("realValue not number");return}if(typeof e!="string"){console.warn("collection must be string");return}var t=aD([e[0],e[e.length-1]],2),i=t[0],r=t[1];if(!["[","("].includes(i)){console.warn('collection must start with "[" or "("');return}if(!["]",")"].includes(r)){console.warn('collection must end with "]" or ")"');return}var s=e.substring(1,e.length-1).split(",");if(s.length!==2){console.warn("collection must have 2 numbers");return}var a=aD([+s[0],+s[1]],2),o=a[0],c=a[1];if(o>=c){console.warn("startNum must less than endNum");return}var l=n>o||i==="["&&n===o;if(!l)return!1;var h=n=m){console.warn("startNum must less than endNum");return}if(n>=_&&n<=m)return!0}else{var g=+h;if(n===g)return!0}}}catch(v){t={error:v}}finally{try{l&&!l.done&&(i=c.return)&&i.call(c)}finally{if(t)throw t.error}}return!1}function ns(){return((1+Math.random())*4294967296|0).toString(16).substring(1)}var Em=function(n){var e=0,t=0,i=0,r=0;if(typeof n=="number")e=t=i=r=n;else if(typeof n=="string"){var s=parseInt(n,10);e=t=i=r=s}else Array.isArray(n)&&(e=n[0],i=pX(n[1])?n[0]:n[1],r=pX(n[2])?n[0]:n[2],t=pX(n[3])?i:n[3]);return[e,i,r,t]};function pX(n){return n==null}var D0e=function(n,e,t,i){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(h){try{l(i.next(h))}catch(u){a(u)}}function c(h){try{l(i.throw(h))}catch(u){a(u)}}function l(h){h.done?s(h.value):r(h.value).then(o,c)}l((i=i.apply(n,e||[])).next())})},O0e=function(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,r,s,a;return a={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(l){return function(h){return c([l,h])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,r=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},Zbe=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function qbe(n,e){if(!n||!e)return!1;for(var t=xd(n);t;){if(t.id===e.id)return!0;t=xd(t)}return!1}function xd(n,e){if(!(!n||!n.parentId||!n.calculative)){var t=n.calculative.canvas.store,i=t.pens[n.parentId];return e&&xd(i,e)||i}}function dy(n,e){if(!n||!n.children)return[];var t=[];return n.children.forEach(function(i){var r=e.pens[i];r&&(t.push(r),t.push.apply(t,Zbe([],$be(dy(r,e)),!1)))}),t}function Jbe(n,e){var t=e.calculative,i=t.worldRect,r=t.gradientFromColor,s=t.gradientToColor,a=t.gradientAngle;return L0e(n,i,r,s,a)}function eEe(n,e){var t=e.calculative,i=t.worldRect,r=t.gradientFromColor,s=t.gradientToColor,a=t.gradientRadius;if(!(!r||!s)){var o=i.width,c=i.height,l=i.center,h=l.x,u=l.y,d=o;di&&r<180-i||r>180+i&&r<360-i||r<0?(r>270?r=360-r:r>180?r=r-180:r>90&&(r=180-r),s=Math.abs(t/Math.sin(r/180*Math.PI)/2)):(r>270?r=360-r:r>180?r=r-180:r>90&&(r=180-r),s=Math.abs(e/Math.cos(r/180*Math.PI)/2)),s}function G6(n){if(typeof n=="string"&&n.startsWith("linear-gradient")){var e=n.slice(16,-2).split("deg,");if(e.length>1){var t=e[1].split("%,"),i=[];return t.forEach(function(r){if(/rgba?/.test(r)){var s=r.split(") ");i.push({color:aEe(s[0]+")"),i:parseFloat(s[1])/100})}else{var a=r.split(" ");a.length>2?i.push({color:a[1],i:parseFloat(a[2])/100}):i.push({color:a[0],i:parseFloat(a[1])/100})}}),{angle:parseFloat(e[0]),colors:i}}else return{angle:parseFloat(e[0]),colors:[]}}else return{angle:0,colors:[]}}function aEe(n){if(/rgba?/.test(n)){var e=n.split(",");if(e.length<3)return"";n="#";for(var t=0,i=void 0;i=e[t++];)if(t<4)i=parseInt(i.replace(/[^\d]/gi,""),10).toString(16),n+=i.length==1?"0"+i:i;else{i=i.replace(")","");var r=parseInt(i*255+""),s=r.toString(16);s=s.length===2?s:"0"+s,n+=s}n=n.toUpperCase()}return n}function oEe(n,e){var t=e.calculative.worldRect,i=t.x,r=t.y,s=t.ex,a=t.width,o=t.height,c=t.center,l=[{x:s,y:r+o/2},{x:i,y:r+o/2}],h=G6(e.calculative.lineGradientColors),u=h.angle,d=h.colors,f=sJ(u,a,o);return l.forEach(function(p){Yn(p,u,c)}),$H(n,l,d,f)}function $H(n,e,t,i){var r=tEe(e[0].x,e[0].y,e[1].x,e[1].y,i),s=n.createLinearGradient(r[0],r[1],r[2],r[3]);return t.forEach(function(a){s.addColorStop(a.i,a.color)}),s}function ny(n,e,t){var i=[];e.calculative.gradientColorStop?i=e.calculative.gradientColorStop:(i=G6(e.calculative.lineGradientColors).colors,e.calculative.gradientColorStop=i),n.strokeStyle=$H(n,t,i,e.calculative.lineWidth/2),n.beginPath(),n.moveTo(t[0].x,t[0].y),n.lineTo(t[1].x,t[1].y),n.stroke()}function lEe(n,e){for(var t=e.calculative.worldAnchors,i=e.calculative.lineWidth*(e.calculative.gradientSmooth||e.calculative.lineSmooth||0),r=0;r0){var s=t[r-1].curvePoints;s?sV(n,e,i,s[s.length-1],t[r],t[r].curvePoints[0]):sV(n,e,i,t[r-1],t[r],t[r].curvePoints[0]);var a=Rm(i,t[r],t[r].curvePoints[0]);ny(n,e,[a,t[r].curvePoints[1]])}else ny(n,e,[t[r],t[r].curvePoints[0]]),ny(n,e,[t[r].curvePoints[0],t[r].curvePoints[1]]);for(var o=t[r].curvePoints.length-1,c=1;c0&&r0&&r0&&r0&&r0?o=e.calculative.iconSize:i.width>i.height?o=i.height:o=i.width,n.font=Ld({fontSize:o,fontWeight:a,fontFamily:c}),n.fillStyle=e.calculative.iconColor||Qy(e,t),e.calculative.iconRotate&&(n.translate(i.center.x,i.center.y),n.rotate(e.calculative.iconRotate*Math.PI/180),n.translate(-i.center.x,-i.center.y)),n.beginPath(),n.fillText(e.calculative.icon,r,s),n.restore()}function Ld(n){var e=n===void 0?{}:n,t=e.fontStyle,i=t===void 0?"normal":t,r=e.textDecoration,s=r===void 0?"normal":r,a=e.fontWeight,o=a===void 0?"normal":a,c=e.fontSize,l=c===void 0?12:c,h=e.fontFamily,u=h===void 0?"Arial":h,d=e.lineHeight,f=d===void 0?1:d;return i+" "+s+" "+o+" "+l+"px/"+f+" "+u}function Dy(n,e){var t=e.calculative.worldRect||{},i=t.x,r=t.ex,s=t.y,a=t.ey;e.calculative.flipX&&(n.translate(i+r+.5,.5),n.scale(-1,1)),e.calculative.flipY&&(n.translate(.5,s+a+.5),n.scale(1,-1))}function Um(n,e,t){t===void 0&&(t=!1);var i=e.calculative.worldRect.center,r=i.x,s=i.y;n.translate(r,s);var a=e.calculative.rotate*Math.PI/180;t||(e.calculative.flipX&&(a*=-1),e.calculative.flipY&&(a*=-1)),n.rotate(a),n.translate(-r,-s)}function ay(n,e,t){var i,r;n.save(),n.translate(.5,.5),n.beginPath();var s=e.calculative.canvas.store,a=e.textFlip||s.options.textFlip,o=e.textRotate||s.options.textRotate;(!a||!o)&&n.save(),Dy(n,e),e.calculative.rotate&&e.name!=="line"&&Um(n,e),(e.calculative.lineWidth>1||t)&&(n.lineWidth=e.calculative.lineWidth),MEe(n,s,e);var c,l=!1,h=void 0;e.calculative.hover?(h=e.hoverColor||s.options.hoverColor,c=e.hoverBackground||s.options.hoverBackground):e.calculative.active?(h=e.activeColor||s.options.activeColor,c=e.activeBackground||s.options.activeBackground):e.calculative.isDock&&(e.type===Xn.Line?h=s.options.dockPenColor:c=Cz(s.options.dockPenColor,.2));var u=e.calculative.strokeImg;if(e.calculative.strokeImage&&u)n.strokeStyle=h||n.createPattern(u,"repeat");else{var d=void 0;e.calculative.strokeType?e.calculative.lineGradientColors?e.name==="line"?l=!0:e.calculative.lineGradient?d=e.calculative.lineGradient:(d=oEe(n,e),e.calculative.lineGradient=d):d=fEe(n,e):d=e.calculative.color||aJ(s),n.strokeStyle=h||d}var f=e.calculative.backgroundImg;if(e.calculative.backgroundImage&&f)n.fillStyle=c||n.createPattern(f,"repeat"),c=!0;else{var p=void 0;e.calculative.bkType===F8.Linear?e.calculative.gradientColors?e.type||(e.calculative.gradient?p=e.calculative.gradient:(p=rEe(n,e),e.calculative.gradient=p)):p=Jbe(n,e):e.calculative.bkType===F8.Radial?e.calculative.gradientColors?e.calculative.radialGradient?p=e.calculative.radialGradient:(p=iEe(n,e),e.calculative.radialGradient=p):p=eEe(n,e):p=e.calculative.background||s.data.penBackground,n.fillStyle=c||p,c=!!p}if(U0e(n,e),k0e(n,e),Oy(n,e),e.calculative.lineDash&&n.setLineDash(e.calculative.lineDash.map(function(v){return v*e.calculative.canvas.store.data.scale})),e.calculative.lineDashOffset&&(n.lineDashOffset=e.calculative.lineDashOffset),e.calculative.shadowColor&&(n.shadowColor=e.calculative.shadowColor,n.shadowOffsetX=e.calculative.shadowOffsetX,n.shadowOffsetY=e.calculative.shadowOffsetY,n.shadowBlur=e.calculative.shadowBlur),l?(lEe(n,e),gEe(!0,n,e,s)):(V0e(!0,n,e,s,c),W0e(n,e)),!(e.image&&e.calculative.img)&&e.calculative.icon&&F0e(n,e),(!a||!o)&&n.restore(),a&&!o&&Dy(n,e),!a&&o&&e.calculative.rotate&&e.name!=="line"&&Um(n,e,!0),N0e(n,e),e.type===Xn.Line&&e.fillTexts)try{for(var _=wD(e.fillTexts),m=_.next();!m.done;m=_.next()){var g=m.value;B0e(n,e,g)}}catch(v){i={error:v}}finally{try{m&&!m.done&&(r=_.return)&&r.call(_)}finally{if(i)throw i.error}}n.restore()}function U0e(n,e){var t=e.lineCap||(e.type?"round":"square");t?n.lineCap=t:e.type&&(n.lineCap="round")}function k0e(n,e){var t=e.lineJoin;t?n.lineJoin=t:e.type&&(n.lineJoin="round")}function bz(n,e,t,i){var r,s,a,o;n.save(),t&&n.translate(-t.x,-t.y),(o=(a=n).setAttrs)===null||o===void 0||o.call(a,e);var c=e.calculative.canvas.store,l=e.textFlip||c.options.textFlip,h=e.textRotate||c.options.textRotate;n.beginPath(),(!l||!h)&&n.save(),e.calculative.flipX&&(n.translate(e.calculative.worldRect.x+e.calculative.worldRect.ex,0),n.scale(-1,1)),e.calculative.flipY&&(n.translate(0,e.calculative.worldRect.y+e.calculative.worldRect.ey),n.scale(1,-1)),e.calculative.rotate&&e.name!=="line"&&Um(n,e),(e.calculative.lineWidth>1||i)&&(n.lineWidth=e.calculative.lineWidth);var u;if(e.calculative.hover?(n.strokeStyle=e.hoverColor||c.options.hoverColor,n.fillStyle=e.hoverBackground||c.options.hoverBackground,u=e.hoverBackground||c.options.hoverBackground):e.calculative.active?(n.strokeStyle=e.activeColor||c.options.activeColor,n.fillStyle=e.activeBackground||c.options.activeBackground,u=e.activeBackground||c.options.activeBackground):(e.strokeImage?e.calculative.strokeImg&&(n.strokeStyle=n.createPattern(e.calculative.strokeImg,"repeat"),u=!0):n.strokeStyle=e.calculative.color||aJ(c),e.backgroundImage?e.calculative.backgroundImg&&(n.fillStyle=n.createPattern(e.calculative.backgroundImg,"repeat"),u=!0):(n.fillStyle=e.background,u=!!e.background)),U0e(n,e),k0e(n,e),Oy(n,e),e.calculative.lineDash&&n.setLineDash(e.calculative.lineDash),e.calculative.lineDashOffset&&(n.lineDashOffset=e.calculative.lineDashOffset),e.calculative.shadowColor&&(n.shadowColor=e.calculative.shadowColor,n.shadowOffsetX=e.calculative.shadowOffsetX,n.shadowOffsetY=e.calculative.shadowOffsetY,n.shadowBlur=e.calculative.shadowBlur),V0e(!1,n,e,c,u),W0e(n,e),e.calculative.img?(n.save(),n.shadowColor="",n.shadowBlur=0,n.shadowOffsetX=0,n.shadowOffsetY=0,$S(n,e),n.restore()):e.calculative.icon&&F0e(n,e),(!l||!h)&&n.restore(),l&&!h&&(e.calculative.flipX&&(n.translate(e.calculative.worldRect.x+e.calculative.worldRect.ex,0),n.scale(-1,1)),e.calculative.flipY&&(n.translate(0,e.calculative.worldRect.y+e.calculative.worldRect.ey),n.scale(1,-1))),!l&&h&&e.calculative.rotate&&e.name!=="line"&&Um(n,e,!0),N0e(n,e),e.type===Xn.Line&&e.fillTexts)try{for(var d=wD(e.fillTexts),f=d.next();!f.done;f=d.next()){var p=f.value;B0e(n,e,p)}}catch(_){r={error:_}}finally{try{f&&!f.done&&(s=d.return)&&s.call(d)}finally{if(r)throw r.error}}n.restore()}function V0e(n,e,t,i,r){n===void 0&&(n=!0);var s=n?i.path2dMap.get(t):mr.path2dDraws[t.name];if(s){if(t.type===Xn.Line&&t.borderWidth){e.save(),e.beginPath();var a=t.calculative.lineWidth+t.calculative.borderWidth;e.lineWidth=a,e.strokeStyle=t.borderColor,s instanceof Path2D?(r&&e.fill(s),a&&e.stroke(s)):(s(t,e),r&&e.fill(),a&&e.stroke()),e.restore()}s instanceof Path2D?r&&e.fill(s):(e.save(),s(t,e),r&&e.fill(),e.restore());var o=t.calculative.progress;if(o!=null){e.save();var c=t.calculative.worldRect,l=c.ex,h=c.x,u=c.y,d=c.width,f=c.height,p=c.ey,_=null;if(t.verticalProgress?_=t.reverseProgress?e.createLinearGradient(h,u,h,u+f*o):e.createLinearGradient(h,p,h,u+f*(1-o)):_=t.reverseProgress?e.createLinearGradient(l,u,h+d*(1-o),u):e.createLinearGradient(h,u,h+d*o,u),t.calculative.progressGradientColors){var m=G6(t.calculative.progressGradientColors).colors;m.forEach(function(x){_.addColorStop(x.i,x.color)})}else{var g=t.calculative.progressColor||t.calculative.color||i.options.activeColor;_.addColorStop(0,g),_.addColorStop(1,g)}_.addColorStop(1,"transparent"),e.fillStyle=_,s instanceof Path2D?e.fill(s):(s(t,e),e.fill()),e.restore()}if(t.calculative.lineWidth&&(s instanceof Path2D?e.stroke(s):(s(t,e),e.stroke())),t.type){if(t.calculative.animatePos){if(e.save(),z0e(e,t,i),t.lineAnimateType===Py.Arrow){var v=J0e(t,e);v instanceof Path2D?(e.stroke(v),e.fill(v)):(e.stroke(),e.fill())}else s instanceof Path2D?e.stroke(s):(s(t,e),e.stroke());e.restore()}t.fromArrow&&P0e(e,t,i),t.toArrow&&w0e(e,t,i),t.calculative.active&&!t.calculative.pencil&&H0e(e,t)}}}function gEe(n,e,t,i){n===void 0&&(n=!0);var r=n?i.path2dMap.get(t):mr.path2dDraws[t.name];if(r&&t.type){if(t.calculative.animatePos){if(e.save(),z0e(e,t,i),e.beginPath(),r instanceof Path2D)if(t.lineName==="polyline"||t.lineName==="line")if(t.lineAnimateType===Py.Arrow){var s=J0e(t);e.stroke(s),e.fill(s)}else t.calculative.gradientSmooth||t.calculative.lineSmooth?(t.calculative.gradientAnimatePath||(t.calculative.gradientAnimatePath=nJ(t)),t.calculative.gradientAnimatePath instanceof Path2D&&e.stroke(t.calculative.gradientAnimatePath)):e.stroke(r);else e.stroke(r);else r(t,e),e.stroke();e.restore()}t.fromArrow&&P0e(e,t,i),t.toArrow&&w0e(e,t,i),t.calculative.active&&!t.calculative.pencil&&H0e(e,t)}}function z0e(n,e,t){n.strokeStyle=e.animateColor||t.options.animateColor,e.animateShadow&&(n.shadowBlur=e.animateShadowBlur||e.animateLineWidth||6,n.shadowColor=e.animateShadowColor||e.animateColor||t.options.animateColor),e.calculative.animateLineWidth&&(n.lineWidth=e.calculative.animateLineWidth*t.data.scale);var i=0;switch(e.lineAnimateType){case Py.Beads:e.animateReverse?n.lineDashOffset=e.calculative.animatePos:n.lineDashOffset=e.length-e.calculative.animatePos,i=e.calculative.lineWidth||5,i<5&&(i=5);var r=e.animateLineDash&&e.animateLineDash.map(function(s){return s*i/5});n.setLineDash(r||[i,i*2]);break;case Py.Dot:e.animateReverse?n.lineDashOffset=e.calculative.animatePos:n.lineDashOffset=e.length-e.calculative.animatePos,i=e.calculative.animateDotSize||e.calculative.lineWidth*2||6,i<6&&(i=6),i>40&&(i=40),n.lineWidth=(e.calculative.animateLineWidth||i)*t.data.scale,n.setLineDash([.1,e.length]);break;case Py.Arrow:n.fillStyle=e.animateColor||t.options.animateColor,n.lineWidth=1;break;default:e.animateReverse?(n.lineDashOffset=Number.EPSILON,n.setLineDash([0,e.length-e.calculative.animatePos+1,e.calculative.animatePos])):n.setLineDash([e.calculative.animatePos,e.length+.01-e.calculative.animatePos]);break}}function aJ(n){var e=n.data,t=n.options;return e.color||t.color}function H0e(n,e){var t=e.calculative.canvas.store;n.save(),n.lineWidth=1,n.fillStyle=e.activeColor||t.options.activeColor,e.calculative.worldAnchors.forEach(function(i){!i.hidden&&!i.isTemp&&vEe(n,i,e)}),n.restore()}function vEe(n,e,t){if(e){var i=t.calculative.canvas.store.activeAnchor===t.calculative.activeAnchor&&t.calculative.activeAnchor===e,r=3;t.calculative.lineWidth>3&&(r=t.calculative.lineWidth),t.anchorRadius&&(r=t.anchorRadius),e.radius&&(r=e.radius),i?(e.prev&&(n.save(),n.strokeStyle="#4dffff",n.beginPath(),n.moveTo(e.prev.x,e.prev.y),n.lineTo(e.x,e.y),n.stroke(),n.restore(),n.save(),n.fillStyle="#ffffff",n.beginPath(),n.arc(e.prev.x,e.prev.y,r,0,Math.PI*2),n.fill(),n.stroke(),n.restore()),e.next&&(n.save(),n.strokeStyle="#4dffff",n.beginPath(),n.moveTo(e.x,e.y),n.lineTo(e.next.x,e.next.y),n.stroke(),n.restore(),n.save(),n.fillStyle="#ffffff",n.beginPath(),n.arc(e.next.x,e.next.y,r,0,Math.PI*2),n.fill(),n.stroke(),n.restore(),n.beginPath(),n.arc(e.x,e.y,r,0,Math.PI*2),n.fill(),n.stroke()),n.beginPath(),n.arc(e.x,e.y,r,0,Math.PI*2),n.fill(),n.stroke()):(n.save(),n.fillStyle="#ffffff",n.beginPath(),n.arc(e.x,e.y,r,0,Math.PI*2),n.fill(),n.stroke(),n.restore())}}function G0e(n){var e=n.calculative.canvas.store,t={x:n.x,y:n.y};if(!n.parentId||n.parentId&&!e.pens[n.parentId])n.parentId=void 0,t.width=n.width,t.height=n.height,t.rotate=n.rotate,Mo(t),To(t);else{var i=e.pens[n.parentId],r=i.calculative.worldRect;r||(r=G0e(i)),t.x=r.x+r.width*n.x,t.y=r.y+r.height*n.y,t.width=r.width*n.width,t.height=r.height*n.height,i.flipX&&(t.x=r.width-(t.x-r.x+t.width)+r.x),i.flipY&&(t.y=r.height-(t.y-r.y+t.height)+r.y),Mo(t),t.rotate=r.rotate+n.rotate,To(t)}return n.calculative.worldRect=t,oJ(n,t),t}function oJ(n,e){!n.paddingTop&&(n.calculative.paddingTop=0),!n.paddingBottom&&(n.calculative.paddingBottom=0),!n.paddingLeft&&(n.calculative.paddingLeft=0),!n.paddingRight&&(n.calculative.paddingRight=0),Math.abs(n.calculative.paddingTop)<1&&(n.calculative.paddingTop*=e.height),Math.abs(n.calculative.paddingBottom)<1&&(n.calculative.paddingBottom*=e.height),Math.abs(n.calculative.paddingLeft)<1&&(n.calculative.paddingLeft*=e.width),Math.abs(n.calculative.paddingRight)<1&&(n.calculative.paddingRight*=e.width)}function HV(n){var e=n.calculative.worldRect;if(!n.parentId){Object.assign(n,e);return}var t=n.calculative.canvas.store,i=t.pens[n.parentId].calculative.worldRect;Object.assign(n,KV(e,i))}function oD(n){var e=n.calculative.canvas.store,t=[];if(n.anchors){var i=At(n.anchors);n.flipX&&i.forEach(function(l){l.x=.5-(l.x-.5)}),n.flipY&&i.forEach(function(l){l.y=.5-(l.y-.5)}),i.forEach(function(l){t.push(xEe(n,l))})}if(!t.length&&!n.type&&!n.calculative.canvas.parent.isCombine(n)){var r=n.calculative.worldRect,s=r.x,a=r.y,o=r.width,c=r.height;t=e.options.defaultAnchors.map(function(l,h){return{id:""+h,penId:n.id,x:s+o*l.x,y:a+c*l.y}})}n.calculative.rotate&&t.forEach(function(l){Yn(l,n.calculative.rotate,n.calculative.worldRect.center)}),(!n.type||n.anchors)&&(n.calculative.worldAnchors=t),n.calculative.activeAnchor&&t.length&&(n.calculative.activeAnchor=t.find(function(l){l.id,n.calculative.activeAnchor.id})),n.calculative.gradientAnimatePath=void 0}function xEe(n,e){var t=u$({},e),i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height;return t.x=r+a*e.x,t.y=s+o*e.y,e.prev&&(t.prev={penId:n.id,connectTo:e.prev.connectTo,x:r+a*e.prev.x,y:s+o*e.prev.y}),e.next&&(t.next={penId:n.id,connectTo:e.next.connectTo,x:r+a*e.next.x,y:s+o*e.next.y}),t}function She(n,e){var t=e.calculative,i=t.paddingTop,r=t.paddingBottom,s=t.paddingLeft,a=t.paddingRight,o=s,c=i,l=e.calculative.worldRect.width-s-a,h=e.calculative.worldRect.height-i-r,u=e.calculative.iconLeft,d=e.calculative.iconTop;u&&Math.abs(u)<1&&(u=e.calculative.worldRect.width*u),d&&Math.abs(d)<1&&(d=e.calculative.worldRect.height*d),o+=u||0,c+=d||0,l-=u||0,h-=d||0;var f=e.calculative.iconRotate||0;if(e.parentId){var p=n[e.parentId].calculative;p&&(f+=p.rotate,f%=360)}o=e.calculative.worldRect.x+o,c=e.calculative.worldRect.y+c,e.calculative.worldIconRect={x:o,y:c,width:l,height:h,rotate:f},Mo(e.calculative.worldIconRect),To(e.calculative.worldIconRect)}function hS(n,e,t){Sz(n.calculative.worldRect,e,t),n.calculative.initRect&&Sz(n.calculative.initRect,e,t),n.calculative.x&&Az(n.calculative,e,t),n.type&&oD(n)}function yEe(n,e){n.anchors||(n.anchors=[]),n.calculative.worldAnchors||(n.calculative.worldAnchors=[]);var t={id:e.id,penId:n.id,x:e.x,y:e.y};if(n.calculative.worldAnchors.push(t),n.calculative.worldRect){n.rotate%360&&Yn(e,-n.rotate,n.calculative.worldRect.center);var i={id:e.id,penId:n.id,x:(e.x-n.calculative.worldRect.x)/n.calculative.worldRect.width,y:(e.y-n.calculative.worldRect.y)/n.calculative.worldRect.height};n.anchors.push(i)}return t}function AEe(n,e,t){n.anchors||(n.anchors=[]),n.calculative.worldAnchors||(n.calculative.worldAnchors=[]);var i=yTe(n,e,t);return n.calculative.worldAnchors.splice(t+1,0,i),n.anchors.splice(t+1,0,lD(i,n.calculative.worldRect)),n.calculative.activeAnchor=i,i}function CEe(n,e){if(!(!n||!n.calculative.worldAnchors)){var t=n.calculative.worldAnchors.findIndex(function(i){return i.id===e.id});t>-1&&n.calculative.worldAnchors.splice(t,1),t=n.anchors.findIndex(function(i){return i.id===e.id}),t>-1&&n.anchors.splice(t,1)}}function U8(n,e){if(!e||!e.calculative||!e.calculative.worldRect.center)return zr.None;if(n.anchorId){var t=e.anchors.filter(function(i){return i.id===n.anchorId});if(t.length&&t[0].direction>-1)return t[0].direction}return mbe(n,e.calculative.worldRect.center)}function OS(n,e){var t=1/0,i;return n.calculative.worldAnchors.forEach(function(r){var s=QH(e,r);t>s&&(t=s,i=r)}),i}function Mhe(n,e,t){n.x+=e,n.y+=t,n.anchors&&n.anchors.forEach(function(i){nD(i,e,t)}),n.calculative.worldAnchors&&n.calculative.worldAnchors.forEach(function(i){nD(i,e,t)})}function lJ(n){if(n&&n.calculative&&n.calculative.worldAnchors.length){var e=nn(n);if(!n.anchors||!n.anchors.length)for(;n.calculative.worldAnchors.length&&e!==n.calculative.activeAnchor;)n.calculative.worldAnchors.pop(),e=nn(n);else e===n.calculative.activeAnchor?n.calculative.worldAnchors=[n.calculative.worldAnchors[0]]:n.calculative.worldAnchors[0]===n.calculative.activeAnchor&&(n.calculative.worldAnchors=[n.calculative.worldAnchors[n.calculative.worldAnchors.length-1]])}}function sc(n,e,t,i){var r,s,a,o,c,l;if(!(!n||!e||!t||!i||e.twoWay===Oc.DisableConnected||e.twoWay===Oc.Disable||i.twoWay===Oc.DisableConnectTo||i.twoWay===Oc.Disable)){if(e.twoWay===Oc.In){if(t.calculative.worldAnchors.length===1)return;var h=nn(t);if(i.id!==h.id)return}if(e.twoWay===Oc.Out){var u=xo(t);if(i.id!==u.id)return}if(!(i.connectTo===n.id&&i.anchorId===e.id)){if(i.connectTo){var d=n.calculative.canvas.store.pens[i.connectTo];LS(d,oy(d,i.anchorId),t,i)}n.connectedLines||(n.connectedLines=[]);var f=n.connectedLines.findIndex(function(m){return m.lineId===t.id&&m.lineAnchor===i.id&&m.anchor===e.id});f<0&&n.connectedLines.push({lineId:t.id,lineAnchor:i.id,anchor:e.id}),i.connectTo=n.id,i.anchorId=e.id,n.type&&sc(t,i,n,e),n.calculative.canvas.store.emitter.emit("connectLine",{line:t,lineAnchor:i,pen:n,anchor:e});var p=((r=t.calculative.worldAnchors)===null||r===void 0?void 0:r.length)>=2?(s=t.calculative.worldAnchors)===null||s===void 0?void 0:s[0].connectTo:void 0,_=((a=t.calculative.worldAnchors)===null||a===void 0?void 0:a.length)>=2?(c=t.calculative.canvas.store.pens[(o=t.calculative.worldAnchors)===null||o===void 0?void 0:o[0].connectTo])===null||c===void 0?void 0:c.anchors.find(function(m){var g;return m.id===((g=t.calculative.worldAnchors)===null||g===void 0?void 0:g[0].anchorId)}):void 0;return(l=n.onConnectLine)===null||l===void 0||l.call(n,n,{line:t,lineAnchor:i,pen:n,anchor:e,fromPen:p,fromAnchor:_}),!0}}}function LS(n,e,t,i){if(!(!n||!e||!t||!i)&&!(!n.connectedLines||!n.connectedLines.length))return t.lastConnected||(t.lastConnected={}),t.lastConnected[n.id]||(t.lastConnected[n.id]=At(n.connectedLines)),n.connectedLines.forEach(function(r,s,a){(r.lineId===t.id||r.lineId===t.id)&&r.lineAnchor===i.id&&r.anchor===e.id&&a.splice(s,1)}),i.connectTo=void 0,i.anchorId=void 0,n.type&&e.connectTo===t.id&&e.anchorId===i.id&&LS(t,i,n,e),n.calculative.canvas.store.emitter.emit("disconnectLine",{line:t,lineAnchor:i,pen:n,anchor:e}),!0}function oy(n,e){var t;if(!(!n||!e))return(t=n.calculative.worldAnchors)===null||t===void 0?void 0:t.find(function(i){return i.id===e})}function xo(n){if(!(!n||!n.calculative.worldAnchors))return n.calculative.worldAnchors[0]}function nn(n){if(!(!n||!n.calculative.worldAnchors))return n.calculative.worldAnchors[n.calculative.worldAnchors.length-1]}function bEe(n,e){var t,i,r,s,a;if(n.calculative.start===0||!n.frames||!n.frames.length)return n.calculative.start=void 0,0;if(!n.calculative.duration){n.calculative.duration=0;try{for(var o=wD(n.frames),c=o.next();!c.done;c=o.next()){var l=c.value;n.calculative.duration+=l.duration;for(var h in l)h!=="duration"&&!n[h]&&h==="scale"&&(n[h]=1)}}catch(b){t={error:b}}finally{try{c&&!c.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}}if(n.animateCycle||(n.animateCycle=1/0),!n.calculative.start)n.calculative.start=e,n.calculative.frameIndex=0,n.calculative.frameStart=n.calculative.start,n.calculative.frameDuration=n.frames[0].duration,n.calculative.frameEnd=n.calculative.frameStart+n.calculative.frameDuration,n.calculative.cycleIndex=1,n.calculative.x=n.calculative.worldRect.x,n.calculative.y=n.calculative.worldRect.y,n.calculative.initRect=At(n.calculative.worldRect),n.calculative.initRect.rotate=n.calculative.rotate||0,Rhe(n);else{var u=0,d=Math.ceil((e-n.calculative.start)/n.calculative.duration);if(d>n.animateCycle)return n.currentAnimation=void 0,n.calculative.start=void 0,Ihe(n,1),0;var f=(e-n.calculative.start)%n.calculative.duration,p=0;try{for(var _=wD(n.frames),m=_.next();!m.done;m=_.next()){var g=m.value;if(p+=g.duration,f>p)++u;else break}}catch(b){r={error:b}}finally{try{m&&!m.done&&(s=_.return)&&s.call(_)}finally{if(r)throw r.error}}if(!n.frames[u])return!0;n.calculative.frameDuration=n.frames[u].duration,n.calculative.frameStart=n.calculative.start+n.calculative.duration*(d-1),n.calculative.frameEnd=n.calculative.frameStart+n.calculative.frameDuration;var v=u!==n.calculative.frameIndex,x=d>n.calculative.cycleIndex;if(v&&(n.calculative.frameIndex=u),x&&(n.calculative.cycleIndex=d),v||x)if(n.calculative.x=n.calculative.initRect.x,n.calculative.y=n.calculative.initRect.y,!((a=n.children)===null||a===void 0)&&a.length?n.calculative.canvas.rotatePen(n,(n.calculative.initRect.rotate||0)-n.calculative.rotate,n.calculative.initRect):n.calculative.rotate=n.calculative.initRect.rotate||0,u>0){n.prevFrame={};var y=n.frames[u-1];for(var h in y)n.prevFrame[h]=y[h];Object.assign(n.prevFrame,{rotate:y.rotate||0,x:y.x||0,y:y.y||0,scale:y.scale||1})}else Rhe(n)}var C=(e-n.calculative.frameStart)/n.calculative.frameDuration%1;return Ihe(n,C),!0}function Rhe(n){n.prevFrame={};for(var e in n)(typeof n[e]!="object"||e==="lineDash")&&(n.prevFrame[e]=n[e]);n.prevFrame.rotate=0,n.prevFrame.x=0,n.prevFrame.y=0,n.prevFrame.scale=1}function Ihe(n,e){var t;if(!(e<0)){e>1&&(e=1);var i=n.frames[n.calculative.frameIndex];for(var r in i)if(r!=="duration"){if(r==="scale"){n.calculative.worldRect=At(n.calculative.initRect),Sz(n.calculative.worldRect,n.prevFrame.scale,n.calculative.worldRect.center);var s=n.prevFrame.scale+(i[r]-n.prevFrame.scale)*e;Sz(n.calculative.worldRect,s/n.prevFrame.scale,n.calculative.worldRect.center),n.calculative.patchFlags=!0}else if(r==="x"){var a=mX(n,r,n.calculative.frameIndex);n.calculative.worldRect.x=n.calculative.initRect.x+a,n.calculative.worldRect.ex=n.calculative.initRect.ex+a,vy(n.calculative.worldRect,i[r]*e*n.calculative.canvas.store.data.scale,0),n.calculative.patchFlags=!0}else if(r==="y"){var a=mX(n,r,n.calculative.frameIndex);n.calculative.worldRect.y=n.calculative.initRect.y+a,n.calculative.worldRect.ey=n.calculative.initRect.ey+a,vy(n.calculative.worldRect,0,i[r]*e*n.calculative.canvas.store.data.scale),n.calculative.patchFlags=!0}else if(r==="rotate"){n.prevFrame[r]>=360&&(n.prevFrame[r]%=360);var a=mX(n,r,n.calculative.frameIndex),o=(n.calculative.initRect.rotate+a+i[r]*e)%360-(n.calculative.rotate||0);!((t=n.children)===null||t===void 0)&&t.length?n.calculative.canvas.rotatePen(n,o,n.calculative.initRect):n.calculative.rotate=(n.calculative.initRect.rotate+a+i[r]*e)%360,n.calculative.patchFlags=!0}else if(r==="image")n.image=i.image,n.calculative.image=void 0,n.calculative.canvas.loadImage(n),n.canvasLayer===Ts.CanvasImageBottom?n.calculative.canvas.canvasImageBottom.init():n.canvasLayer===Ts.CanvasImage&&n.calculative.canvas.canvasImage.init();else if(EEe(i[r],r,n)){n.prevFrame[r]==null&&(r==="globalAlpha"?n.prevFrame[r]=1:n.prevFrame[r]=0);var c=n.prevFrame[r]+(i[r]-n.prevFrame[r])*e;n.calculative[r]=Math.round(c*100)/100}else{r==="visible"&&n.calculative.image&&(n.canvasLayer===Ts.CanvasImageBottom?n.calculative.canvas.canvasImageBottom.init():n.canvasLayer===Ts.CanvasImage&&n.calculative.canvas.canvasImage.init()),n.calculative[r]=i[r];var l={};l[r]=i[r],cJ(n,l)}r==="text"&&M5(n)}}}function EEe(n,e,t){var i=["strokeType","bkType","showChild"];return typeof n=="number"&&t.linear!==!1&&!i.includes(e)}function TEe(n,e){if(n.calculative.start===0)return n.calculative.start=void 0,0;if(n.animateCycle||(n.animateCycle=1/0),n.animateSpan||(n.animateSpan=1),n.calculative.animatePos+=n.animateSpan*(n.calculative.canvas.store.data.scale||1),!n.calculative.start)n.calculative.start=Date.now(),n.calculative.animatePos=n.animateSpan*(n.calculative.canvas.store.data.scale||1),n.calculative.cycleIndex=1;else if(n.calculative.animatePos>n.length){if(++n.calculative.cycleIndex,n.calculative.cycleIndex>n.animateCycle)return n.currentAnimation=void 0,n.calculative.start=void 0,0;n.calculative.animatePos=n.animateSpan}return!0}function RS(n,e){if(e===void 0&&(e=!0),!!n.children){var t=n.calculative.canvas.store;n.children.forEach(function(i){var r=t.pens[i];r&&(r.calculative.active=e,RS(r,e))})}}function Xw(n,e){if(e===void 0&&(e=!0),!!n){var t=n.calculative.canvas.store;n.calculative.hover=e,n.children&&n.children.forEach(function(i){var r,s;((r=t.pens[i])===null||r===void 0?void 0:r.hoverColor)==null&&((s=t.pens[i])===null||s===void 0?void 0:s.hoverBackground)==null&&Xw(t.pens[i],e)})}}function za(n,e){if(e){var t=n.calculative.canvas.store,i=n.calculative.worldRect;e.style.opacity=n.globalAlpha+"",e.style.position="absolute",e.style.outline="none",e.style.left=i.x+t.data.x+"px",e.style.top=i.y+t.data.y+"px",e.style.width=i.width+"px",e.style.height=i.height+"px",e.style.display=n.calculative.inView!=!1?n.calculative.cssDisplay||"inline":"none",!n.calculative.rotate&&(n.calculative.rotate=0),e.style.transform="rotate("+n.calculative.rotate+"deg)",n.calculative.rotate||(n.calculative.flipX&&(e.style.transform="rotateY(180deg)"),n.calculative.flipY&&(e.style.transform="rotateX(180deg)"),n.calculative.flipX&&n.calculative.flipY&&(e.style.transform="rotateZ(180deg)")),e.style.zIndex=n.calculative.zIndex!==void 0?n.calculative.zIndex+"":"5",n.calculative.zIndex>n.calculative.canvas.maxZindex&&(n.calculative.canvas.maxZindex=n.calculative.zIndex),n.locked===js.DisableEdit||n.locked===js.DisableMove||t.data.locked?(e.style.userSelect="initial",e.style.pointerEvents="initial",n.name==="gif"&&(e.style.userSelect="none",e.style.pointerEvents="none")):(e.style.userSelect="none",e.style.pointerEvents="none")}}function _X(n){return n.every(function(e){return e.locked})}function Phe(n){return n.every(function(e){return e.disableRotate})}function K0e(n,e,t){var i;n.type?(n.calculative.worldAnchors.forEach(function(r){Yn(r,e,t.center)}),SEe(n),HV(n)):(n.calculative.rotate?n.calculative.rotate+=e:n.calculative.rotate=e,Yn(n.calculative.worldRect.center,e,t.center),n.parentId&&(n.calculative.worldRect.x=n.calculative.worldRect.center.x-n.calculative.worldRect.width/2,n.calculative.worldRect.y=n.calculative.worldRect.center.y-n.calculative.worldRect.height/2,n.x=(n.calculative.worldRect.x-t.x)/t.width,n.y=(n.calculative.worldRect.y-t.y)/t.height)),(i=n.children)===null||i===void 0||i.forEach(function(r){var s=n.calculative.canvas.store.pens[r];K0e(s,e,t)})}function SEe(n){var e;if(!((e=n.calculative.worldAnchors)===null||e===void 0)&&e.length&&!(!isFinite(n.x)||!isFinite(n.x))&&!(n.x==null||n.y==null)){var t=g$(n);n.parentId||Object.assign(n,t);var i=n.calculative.canvas.store.options,r=i.fontSize,s=i.lineHeight;n.fontSize||(n.fontSize=r,n.calculative.fontSize=n.fontSize*n.calculative.canvas.store.data.scale),n.lineHeight||(n.lineHeight=s,n.calculative.lineHeight=n.lineHeight),To(t),n.calculative.worldRect=t,oJ(n,t),I0(n),n.calculative.worldAnchors&&(n.anchors=n.calculative.worldAnchors.map(function(a){return lD(a,n.calculative.worldRect)}))}}function whe(n){return n.every(function(e){return e.disableSize})}function mX(n,e,t){if(!n.frames||!e)return 0;for(var i=0,r=0;r=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},d$=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],a;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},GV=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i0&&v0&&x=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function Ohe(n){var e,t;if(n.id=ns(),Array.isArray(n.anchors))try{for(var i=PEe(n.anchors),r=i.next();!r.done;r=i.next()){var s=r.value;n.type&&(s.id=ns()),s.penId=n.id,s.prev&&(n.type&&(s.prev.id=ns()),s.prev.penId=n.id),s.next&&(n.type&&(s.next.id=ns()),s.next.penId=n.id)}}catch(a){e={error:a}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}}var Lhe=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],a;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},Nhe=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},LEe=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],a;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},NEe=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;ie.x&&n.xe.y&&n.y=i-t&&n.x<=s+t&&n.y>=r-t&&n.y<=a+t}function To(n){n.center||(n.center={}),n.center.x=n.x+n.width/2,n.center.y=n.y+n.height/2}function Mo(n){n.ex=n.x+n.width,n.ey=n.y+n.height}function BEe(n,e){var t,i;if(e.length<3)return!1;var r=!1,s=e[e.length-1];try{for(var a=Y0e(e),o=a.next();!o.done;o=a.next()){var c=o.value;s.y>n.y!=c.y>n.y&&c.x+(n.y-c.y)*(s.x-c.x)/(s.y-c.y)>n.x&&(r=!r),s=c}}catch(l){t={error:l}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(t)throw t.error}}return r}function B0(n){var e=[];n.forEach(function(i){if(!i.isRuleLine){var r=i.calculative.worldRect;if(r){var s=km(r);e.push.apply(e,NEe([],LEe(s),!1))}}});var t=OO(e);return To(t),t}function km(n){var e=[{x:n.x,y:n.y},{x:n.ex,y:n.y},{x:n.ex,y:n.ey},{x:n.x,y:n.ey}];return n.rotate&&(n.center||To(n),e.forEach(function(t){Yn(t,n.rotate,n.center)})),e}function OO(n){var e=1/0,t=1/0,i=-1/0,r=-1/0;return n==null||n.forEach(function(s){!isFinite(s.x)||!isFinite(s.y)||(e=Math.min(e,s.x),t=Math.min(t,s.y),i=Math.max(i,s.x),r=Math.max(r,s.y))}),{x:e,y:t,ex:i,ey:r,width:i-e,height:r-t}}function Tz(n,e,t){return n.rotate&&(n=OO(km(n))),t?n.x>e.x&&n.exe.y&&n.eye.ex||n.exe.ey)}function FEe(n,e){return(e.x>n.ex||e.exn.ey||e.ey0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},HEe=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},KEe=/^[\t\n\f\r ]*([MLHVZCSQTAmlhvzcsqta])[\t\n\f\r ]*/,Fhe=/^[01]/,sa=/^[+-]?(([0-9]*\.[0-9]+)|([0-9]+\.)|([0-9]+))([eE][+-]?[0-9]+)?/,WEe=/^(([\t\n\f\r ]+,?[\t\n\f\r ]*)|(,[\t\n\f\r ]*))/,jEe={M:[sa,sa],L:[sa,sa],H:[sa],V:[sa],Z:[],C:[sa,sa,sa,sa,sa,sa],S:[sa,sa,sa,sa],Q:[sa,sa,sa,sa],T:[sa,sa],A:[sa,sa,sa,Fhe,Fhe,sa,sa]};function XEe(n){for(var e=0,t=[];ei&&(i=a)):(ar&&(r=a))})}),--e,--t,{x:e,y:t,ex:i,ey:r,width:i-e+1,height:r-t+1}}function YEe(n,e,t){t==null&&(t=e),n.commands.forEach(function(i,r){if(!(i.relative&&r))switch(i.key){case"A":case"a":i.values[5]+=e,i.values[6]+=t;break;case"V":case"v":i.values[0]+=t;break;default:i.values.forEach(function(s,a){i.values[a]=s+(a%2===0?e:t)});break}})}function QEe(n,e,t){t==null&&(t=e),n.commands.forEach(function(i){switch(i.key){case"A":case"a":var r=i.values[0],s=i.values[1],a=Math.PI*i.values[2]/180,o=Math.cos(a),c=Math.sin(a),l=s*s*t*t*o*o+r*r*t*t*c*c,h=2*e*t*o*c*(s*s-r*r),u=r*r*e*e*o*o+s*s*e*e*c*c,d=-(r*r*s*s*e*e*t*t),f=h*h-4*l*u,p=Math.sqrt((l-u)*(l-u)+h*h);i.values[2]=h!==0?Math.atan((u-l-p)/h)*180/Math.PI:l=0?i.values[4]:1-i.values[4];break;case"V":case"v":i.values[0]*=t;break;default:i.values.forEach(function(_,m){i.values[m]=_*(m%2===0?e:t)});break}})}function $Ee(n){var e="";return n.commands.forEach(function(t){e+=t.key+" ",t.values.forEach(function(i){e+=i+" "})}),e}function ZEe(n,e,t){for(var i,r,s=jEe[n.toUpperCase()],a=[];t<=e.length;){var o={key:n,values:[]};try{for(var c=(i=void 0,GEe(s)),l=c.next();!l.done;l=c.next()){var h=l.value,u=e.slice(t).match(h);if(u!==null){o.values.push(+u[0]),t+=u[0].length;var d=e.slice(t).match(WEe);d!==null&&(t+=d[0].length)}else{if(o.values.length===0)return{cursor:t,commands:a};throw new Error("malformed path (first error at "+t+")")}}}catch(f){i={error:f}}finally{try{l&&!l.done&&(r=c.return)&&r.call(c)}finally{if(i)throw i.error}}if(o.relative=o.key.toUpperCase()!==o.key,a.push(o),s.length===0)return{cursor:t,commands:a};n==="m"&&(n="l"),n==="M"&&(n="L")}throw new Error("malformed path (first error at "+t+")")}function qEe(n,e){for(var t=[],i=n.relative&&e?{x:e.worldPoints[e.worldPoints.length-2],y:e.worldPoints[e.worldPoints.length-1]}:{x:0,y:0},r=0;r0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},oTe=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;is?s:r,c=a.x,l=a.y,h=l-o/2,u=l-o/4,d=-(u-l)*Math.sin(Math.PI/180*324)+c,f=(u-l)*Math.cos(Math.PI/180*324)+l;t.moveTo(d,f);for(var p=0;p<5;++p)t.lineTo(-(h-l)*Math.sin(Math.PI/180*72*p)+c,(h-l)*Math.cos(Math.PI/180*72*p)+l),t.lineTo((d-c)*Math.cos(Math.PI/180*72*(p+1))-(f-l)*Math.sin(Math.PI/180*72*(p+1))+c,(d-c)*Math.sin(Math.PI/180*72*(p+1))+(f-l)*Math.cos(Math.PI/180*72*(p+1))+l);if(t.closePath(),t instanceof Path2D)return t}function Q0e(n){for(var e=n.width,t=n.height,i=e>t?t:e,r=[],s=0;s<5;++s)r.push({flag:1,id:String(s),penId:n.id,x:.5+i/2*Math.sin(Math.PI/180*72*s)/e,y:-i/2*Math.cos(Math.PI/180*72*s)/t+.5});n.anchors=r}function cTe(n){var e,t=n.anchors.filter(function(i){return i.flag!==1});Q0e(n),n.anchors=(e=n.anchors).concat.apply(e,oTe([],aTe(t),!1))}function hTe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height;if(t.moveTo(r+a/4,s),t.lineTo(r+a*3/4,s),t.lineTo(r+a,s+o/2),t.lineTo(r+a*3/4,s+o),t.lineTo(r+a*1/4,s+o),t.lineTo(r,s+o/2),t.lineTo(r+a/4,s),t.closePath(),t instanceof Path2D)return t}function uTe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height;if(t.moveTo(r,s+o/2),t.lineTo(r+o/2,s),t.lineTo(r+o/2,s+o/3),t.lineTo(r+a,s+o/3),t.lineTo(r+a,s+o*2/3),t.lineTo(r+o/2,s+o*2/3),t.lineTo(r+o/2,s+o*2/3),t.lineTo(r+o/2,s+o),t.closePath(),t instanceof Path2D)return t}function dTe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height;if(t.moveTo(r,s+o/3),t.lineTo(r+(a-o/2),s+o/3),t.lineTo(r+(a-o/2),s),t.lineTo(r+a,s+o/2),t.lineTo(r+(a-o/2),s+o),t.lineTo(r+(a-o/2),s+o*2/3),t.lineTo(r,s+o*2/3),t.closePath(),t instanceof Path2D)return t}function fTe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height;if(t.moveTo(r,s+o/2),t.lineTo(r+o/2,s),t.lineTo(r+o/2,s+o/3),t.lineTo(r+(a-o/2),s+o/3),t.lineTo(r+(a-o/2),s),t.lineTo(r+a,s+o/2),t.lineTo(r+(a-o/2),s+o),t.lineTo(r+(a-o/2),s+o*2/3),t.lineTo(r+o/2,s+o*2/3),t.lineTo(r+o/2,s+o),t.closePath(),t instanceof Path2D)return t}function pTe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=i.ey;if(t.moveTo(r,s),t.lineTo(r+a,s),t.lineTo(r+a,s+o*3/4),t.lineTo(r+a*8/16,s+o*3/4),t.lineTo(r+a/4,c),t.lineTo(r+a*5/16,s+o*3/4),t.lineTo(r,s+o*3/4),t.closePath(),t instanceof Path2D)return t}function _Te(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height;if(t.moveTo(r+a/5,s+o*13/16),t.bezierCurveTo(r-a/15,s+o*13/16,r-a/15,s+o*7/16,r+a/5,s+o*7/16),t.bezierCurveTo(r+a/5,s,r+a*4/5,s,r+a*4/5,s+o*7/16),t.bezierCurveTo(r+a*16/15,s+o*7/16,r+a*16/15,s+o*13/16,r+a*4/5,s+o*13/16),t.closePath(),t instanceof Path2D)return t}function mTe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.ex,c=i.ey,l=a/6;if(t.moveTo(r,s),t.lineTo(o-l,s),t.lineTo(o,s+l),t.lineTo(o,c),t.lineTo(r,c),t.closePath(),t.moveTo(o-l,s),t.lineTo(o-l,s+l),t.lineTo(o,s+l),t.closePath(),t instanceof Path2D)return t}function gTe(n,e){var t=e.calculative.worldRect,i=t.x,r=t.y,s=t.width,a=t.ex,o=t.ey,c=s*.25,l=e.z;l>1?c=l:l>0&&(c=s*l);var h={x:i,y:r+c},u={x:a-c,y:r+c},d={x:a-c,y:o},f={x:i,y:o};gX(n,[h,u,d,f],e.backgroundFront||e.background,e.color),gX(n,[h,{x:i+c,y:r},{x:a,y:r},u],e.backgroundUp||e.background,e.color),gX(n,[u,{x:a,y:r},{x:a,y:o-c},d],e.backgroundRight||e.background,e.color)}function gX(n,e,t,i){t===void 0&&(t=""),i===void 0&&(i=""),n.save(),t&&(n.fillStyle=t),i&&(n.strokeStyle=i),n.beginPath();for(var r=0;ri.x?o=zr.Right:o=zr.Left),i.next={id:ns(),penId:e.id,x:i.x,y:i.y,prevNextType:2},r.prev={id:ns(),penId:e.id,x:r.x,y:r.y,prevNextType:2},o){case zr.Up:i.next.y-=s,r.prev.y=i.y;break;case zr.Bottom:i.next.y+=s,r.prev.y=i.y;break;case zr.Left:i.next.x-=s,r.prev.x=i.x;break;default:i.next.x+=s,r.prev.x=i.x;break}}}}var Vhe=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],a;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},zhe=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function CTe(n,e){var t=e||new Path2D;if((n.lineName==="line"||n.lineName==="polyline")&&n.calculative.lineSmooth){var i=nJ(n);if(t.addPath(i),t instanceof Path2D)return t}var r=n.calculative.worldAnchors;if(r.length>1){var s;r.forEach(function(a){s?Hhe(t,s,a):a.start=!0,s=a}),n.close&&Hhe(t,s,r[0])}if(t instanceof Path2D)return t}function bTe(n,e,t){var i;if(e.calculative.worldAnchors||(e.calculative.worldAnchors=[]),!(e.calculative.worldAnchors.length<2||((i=e.anchors)===null||i===void 0?void 0:i.length)>1)){var r=xo(e),s=nn(e);!r||!s||!s.id||r===s||(r.next=void 0,lJ(e),s.prev=void 0,e.calculative.worldAnchors.push(s))}}function Hhe(n,e,t){!t||t.isTemp||(e.start&&n.moveTo(e.x,e.y),e.next?t.prev?n.bezierCurveTo(e.next.x,e.next.y,t.prev.x,t.prev.y,t.x,t.y):n.quadraticCurveTo(e.next.x,e.next.y,t.x,t.y):t.prev?n.quadraticCurveTo(t.prev.x,t.prev.y,t.x,t.y):n.lineTo(t.x,t.y))}function g$(n){return v$(n),OO(ETe(n))}function ETe(n){var e=[],t;return n.calculative.worldAnchors.forEach(function(i){e.push(i),t&&e.push.apply(e,zhe([],Vhe(Ghe(t,i,n)),!1)),t=i}),n.close&&n.calculative.worldAnchors.length>1&&e.push.apply(e,zhe([],Vhe(Ghe(t,n.calculative.worldAnchors[0],n)),!1)),e}function Mz(n){return n!=null&&n.lineWidth?n.lineWidth/2+4:4}function Ghe(n,e,t){var i=[];if(!e)return i;var r=.02;if(n.lineLength){var s=Mz(t);r=s/n.lineLength}if(n.next)if(e.prev)for(var a=r;a<1;a+=r)i.push($0e(a,n,n.next,e.prev,e));else for(var a=r;a<1;a+=r)i.push(m$(a,n,n.next,e));else if(e.prev)for(var a=r;a<1;a+=r)i.push(m$(a,n,e.prev,e));else i.push({x:e.x,y:e.y});return i.length>1&&(n.curvePoints=i),i}function TTe(n,e){var t,i,r=Mz(e),s=0,a,o;try{for(var c=Z0e(e.calculative.worldAnchors),l=c.next();!l.done;l=c.next()){var h=l.value;if(a){if(o=Khe(n,a,h,r),o)return{i:s,point:o};++s}a=h}}catch(u){t={error:u}}finally{try{l&&!l.done&&(i=c.return)&&i.call(c)}finally{if(t)throw t.error}}if(e.close&&e.calculative.worldAnchors.length>1&&(o=Khe(n,a,e.calculative.worldAnchors[0],r)))return{i:s,point:o}}function Khe(n,e,t,i){var r,s;if(i===void 0&&(i=4),!e.next&&!t.prev){var a=e.x,o=e.y,c=t.x,l=t.y,h=Math.min(a,c),u=Math.max(a,c),d=Math.min(o,l),f=Math.max(o,l);return n.x>=h-i&&n.x<=u+i&&n.y>=d-i&&n.y<=f+i?STe(n,e,t,i):void 0}else if(e.curvePoints)try{for(var p=Z0e(e.curvePoints),_=p.next();!_.done;_=p.next()){var m=_.value;if(SS(n,m,i))return m}}catch(g){r={error:g}}finally{try{_&&!_.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}}function STe(n,e,t,i){if(i===void 0&&(i=4),e.x===t.x){var r=Math.abs(n.x-e.x);if(r<=i)return{x:e.x,y:n.y}}else{var s=(e.y-t.y)/(e.x-t.x),a=e.y-s*e.x,r=Math.abs((s*n.x+a-n.y)/Math.sqrt(s*s+1));if(r<=i){var o=n.x+s*n.y,c=(o-s*a)/(s*s+1);return{x:c,y:s*c+a}}}}function Whe(n,e,t,i){if(!e&&!t)return Math.sqrt(Math.pow(Math.abs(n.x-i.x),2)+Math.pow(Math.abs(n.y-i.y),2))||0;var r=document.createElementNS("http://www.w3.org/2000/svg","path");return e&&t?r.setAttribute("d","M"+n.x+" "+n.y+" C"+e.x+" "+e.y+" "+t.x+" "+t.y+" "+i.x+" "+i.y):e?r.setAttribute("d","M"+n.x+" "+n.y+" Q"+e.x+" "+e.y+" "+i.x+" "+i.y):r.setAttribute("d","M"+n.x+" "+n.y+" Q"+t.x+" "+t.y+" "+i.x+" "+i.y),r.getTotalLength()||0}function v$(n){if(n.calculative.worldAnchors.length<2)return 0;var e=0,t;if(n.calculative.worldAnchors.forEach(function(r){t&&(t.lineLength=Whe(t,t.next,r.prev,r),e+=t.lineLength),t=r}),n.close){var i=xo(n);t.lineLength=Whe(t,t.next,i.prev,i),e+=t.lineLength}return n.calculative.animatePos&&(n.calculative.animatePos=e/n.length*n.calculative.animatePos),n.length=e,e}function MTe(n,e){for(var t=n.calculative.worldAnchors,i=0;i=0&&u*l+d*h+f<=0||u*o+d*c+f<=0&&u*l+d*h+f>=0||u*o+d*h+f>=0&&u*l+d*c+f<=0||u*o+d*h+f<=0&&u*l+d*c+f>=0){if(o>l){var p=o;o=l,l=p}if(cl&&s>l||r>c&&a>c||r0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},Rw=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;ip.y&&r.yp.y))){_=f;var m=Iu;r.xn.y)r=n.x+(e.x-n.x)/2,i.push({x:r,y:n.y},{x:r,y:e.y});else{var a=(n.y+e.y)/2;i.push({x:n.x,y:a},{x:e.x,y:a})}break;case zr.Right:r=e.x,s=n.y,e.xn.x&&e.yn.y-Iu)r=n.x+(e.x-n.x)/2,i.push({x:r,y:n.y},{x:r,y:e.y});else{var a=(n.y+e.y+Iu)/2;i.push({x:n.x,y:a},{x:e.x,y:a})}break}return i}function wTe(n,e,t){if(n.x===e.x||n.y===e.y)return[];var i=[],r,s;switch(t){case zr.Up:r=n.x,s=e.y,e.x>n.x&&e.y>n.y&&(r=e.x,s=n.y),i.push({x:r,y:s});break;case zr.Bottom:r=n.x,s=e.y,e.x>n.x&&e.yn.y&&(r=n.x,s=e.y),i.push({x:r,y:s});break;case zr.Bottom:n.y>e.y?(r=e.x,s=n.y):(r=n.x,s=e.y),i.push({x:r,y:s});break;case zr.Left:r=e.x,s=n.y,e.x>n.x&&e.y>n.y&&(r=n.x,s=e.y),i.push({x:r,y:s});break;default:if(r=n.x,e.yn.y&&(r=e.x,s=n.y),i.push({x:r,y:s});break;case zr.Bottom:r=n.x,s=e.y,e.xn.x)r=e.x,s=n.y+(e.y-n.y)/2,i.push({x:n.x,y:s},{x:e.x,y:s});else{var a=(n.x+e.x)/2;i.push({x:a,y:n.y},{x:a,y:e.y})}break;case zr.Left:e.x>n.x?i.push({x:n.x,y:e.y}):i.push({x:e.x,y:n.y});break;default:if(r=n.x,s=e.y,e.xMath.abs(t.y-e.y));var r=n.calculative.worldAnchors.findIndex(function(a){return a.id==e.id});if(r>1){var s=n.calculative.worldAnchors[r-1];if(s.x===e.x&&s.y!==e.y)return i.push({x:t.x,y:e.y}),i;if(s.y===e.y&&s.x!==e.x)return i.push({x:e.x,y:t.y}),i}return n.calculative.worldAnchors.length&&(t.isTemp=void 0,n.calculative.drawlineH?(i.push({x:t.x,y:e.y}),Math.abs(t.y-e.y)-1;h--)if(a=n.anchors[h],l==null&&(l=a.y===c.y),l===!0)if(a.y===c.y)n.calculative.worldAnchors[h].y=t.y;else break;else if(a.x===c.x)n.calculative.worldAnchors[h].x=t.x;else break;l=void 0;for(var h=i+1;h-1;h--)if(a=n.anchors[h],l==null&&(l=a.x===c.x),l===!0)if(a.x===c.x)n.calculative.worldAnchors[h].x=t.x;else break;else if(a.y===c.y)n.calculative.worldAnchors[h].y=t.y;else break;l=void 0;for(var h=i+1;h0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},Yhe=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i1?(l=_.x-p.x,h=_.y-p.y):m>0?(l=_.x-(o+u*m),h=_.y-(c+d*m)):(l=_.x-o,h=_.y-c)):(l=_.x-o,h=_.y-c),g=l*l+h*h,g>s&&(a=x,s=g);return s>e&&(a-t>1&&r.push.apply(r,Yhe([],Xhe(x$(n,e,t,a)),!1)),r.push({id:n[a].id,penId:n[a].penId,x:n[a].x,y:n[a].y}),i-a>1&&r.push.apply(r,Yhe([],Xhe(x$(n,e,a,i)),!1))),r}function BTe(n,e,t){if(e===void 0&&(e=.8),t===void 0&&(t=!1),n.length<3)return n;var i,r,s,a,o,c,l,h,u,d,f,p,_,m,g,v=function(C,b,T,S){return a=Math.sqrt(C*C+b*b),a>0?(p=C/a,m=b/a):(p=1,m=0),o=Math.sqrt(T*T+S*S),o>0?(_=T/o,g=S/o):(_=1,g=0),Math.acos(p*_+m*g)};d=[],f=n.length,i=n[0],n[f-1],d.push(py({},n[0]));for(var x=0;x1)for(var h=void 0,u=0,d=0;da*2)&&m>c+a*2&&g-m>c){var v=uS({x:_.x+s,y:_.y+.57*s},{x:_.x,y:_.y},p),x=uS({x:_.x+s,y:_.y-.57*s},{x:_.x,y:_.y},p),y=uS({x:_.x+s,y:_.y+l/2},{x:_.x,y:_.y},p),C=uS({x:_.x+a,y:_.y+l/2},{x:_.x,y:_.y},p),b=uS({x:_.x+s,y:_.y-l/2},{x:_.x,y:_.y},p),T=uS({x:_.x+a,y:_.y-l/2},{x:_.x,y:_.y},p);t.moveTo(v.x,v.y),t.lineTo(_.x,_.y),t.lineTo(x.x,x.y),t.lineTo(b.x,b.y),t.lineTo(T.x,T.y),t.lineTo(C.x,C.y),t.lineTo(y.x,y.y),t.lineTo(v.x,v.y)}_.x+=o*Math.cos(p*Math.PI/180),_.y-=o*Math.sin(p*Math.PI/180),m=Math.sqrt(Math.pow(_.x-h.x,2)+Math.pow(_.y-h.y,2))}}h=f}if(t instanceof Path2D)return t}function FTe(n,e){var t=e.x-n.x,i=e.y-n.y,r=Math.atan(i/t)*180/Math.PI;return e.x>=n.x?r=-r:r=180-r,r}function uS(n,e,t){var i=(180-t)*Math.PI/180;return{x:(n.x-e.x)*Math.cos(i)-(n.y-e.y)*Math.sin(i)+e.x,y:(n.x-e.x)*Math.sin(i)+(n.y-e.y)*Math.cos(i)+e.y}}function UTe(n){var e;n.onDestroy||(n.onDestroy=kTe,n.onMove=oV,n.onResize=oV,n.onRotate=oV,n.onValue=oV,n.onMouseMove=zTe,n.onBeforeValue=VTe,n.onRenderPenRaw=GTe),n.calculative.singleton||(n.calculative.singleton={});var t=n.calculative.worldRect;if(!n.calculative.singleton.div){var i=document.createElement("div");i.style.position="absolute",i.style.outline="none",i.style.left="-9999px",i.style.top="-9999px",i.style.width=t.width+"px",i.style.height=t.height+"px",document.body.appendChild(i),(e=n.calculative.canvas.externalElements)===null||e===void 0||e.parentElement.appendChild(i),za(n,i),n.calculative.singleton.div=i;var r=document.createElement("iframe");r.style.width="100%",r.style.height="100%",r.scrolling=n.scrolling||"no",r.frameBorder="0",r.src=n.iframe,n.calculative.iframe=n.iframe,i.appendChild(r),t_e(n),r.onload=function(){r.setAttribute("document.domain","")}}return n.calculative.patchFlags&&za(n,n.calculative.singleton.div),n.onRenderPenRaw(n),new Path2D}function kTe(n){n.calculative.singleton&&n.calculative.singleton.div&&(n.calculative.singleton.div.remove(),delete n.calculative.singleton.div)}function oV(n){n.calculative.singleton.div&&za(n,n.calculative.singleton.div)}function VTe(n,e){if(e.iframe&&n.calculative.singleton.div&&(n.calculative.singleton.div.children[0].src=e.iframe,n.calculative.iframe=e.iframe),e.operationalRect||e["operationalRect.x"]!==void 0||e["operationalRect.y"]!==void 0||e["operationalRect.width"]!==void 0||e["operationalRect.height"]!==void 0){n.operationalRect||(n.operationalRect={});var t=At(e);if(t.operationalRect||(t.operationalRect={}),t["operationalRect.x"]!==void 0&&(t.operationalRect.x=t["operationalRect.x"]),t["operationalRect.y"]!==void 0&&(t.operationalRect.y=t["operationalRect.y"]),t["operationalRect.width"]!==void 0&&(t.operationalRect.width=t["operationalRect.width"]),t["operationalRect.height"]!==void 0&&(t.operationalRect.height=t["operationalRect.height"]),Object.assign(n.operationalRect,t.operationalRect),n.calculative.singleton.div){var i=n.calculative.singleton.div.children.length;i===1?t_e(n):(n.calculative.singleton.div.children[1].style.height=n.operationalRect.y*100+"%",n.calculative.singleton.div.children[1].style.left=n.operationalRect.x*100+"%",n.calculative.singleton.div.children[1].style.width=n.operationalRect.width*100+"%",n.calculative.singleton.div.children[2].style.width=(1-n.operationalRect.x-n.operationalRect.width)*100+"%",n.calculative.singleton.div.children[3].style.height=(1-n.operationalRect.y-n.operationalRect.height)*100+"%",n.calculative.singleton.div.children[3].style.left=n.operationalRect.x*100+"%",n.calculative.singleton.div.children[3].style.width=n.operationalRect.width*100+"%",n.calculative.singleton.div.children[4].style.width=n.operationalRect.x*100+"%")}}if(e.blur!==void 0)for(var r=1;r<5;r++)n.calculative.singleton.div.children[r].style["backdrop-filter"]="blur("+(e.blur||2)+"px)";if(e.blurBackground!==void 0)for(var r=1;r<5;r++)n.calculative.singleton.div.children[r].style.backgroundColor=e.blurBackground;return e}function zTe(n,e){if(!(!n.calculative.canvas.store.data.locked&&!n.locked)&&e_e(n.operationalRect)&&n.calculative.zIndex<5&&e.x>n.x+n.width*n.operationalRect.x&&e.xn.y+n.height*n.operationalRect.y&&e.y0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},eSe=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;it+r-a&&(h=cV(t+r-a,h+a,l,a,-1)),e.push({id:String(e.length),flag:1,penId:n.id,x:(l-t)/r,y:(h-i)/s})}for(var u=3,c=0;ci+s-a&&(l=lV(l-a,i+s-a,h,a)),e.push({id:String(e.length),flag:1,penId:n.id,x:(l-t)/r,y:(h-i)/s})}for(var d=5,c=0;ct+r-a&&(h=cV(t+r-a,h-a,l,a)),e.push({id:String(e.length),flag:1,penId:n.id,x:(l-t)/r,y:(h-i)/s})}for(var f=3,c=0;ci+s-a&&(l=lV(l+a,i+s-a,h,a,-1)),e.push({id:String(e.length),flag:1,penId:n.id,x:(l-t)/r,y:(h-i)/s})}n.anchors=e}function rSe(n){var e=n.calculative.borderRadius||0,t=n.calculative.borderRadius||0,i=n.width,r=n.height;n.calculative.borderRadius<1&&(e=i*n.calculative.borderRadius,t=r*n.calculative.borderRadius);var s=e0?(this.arrowUp.style.borderBottomColor="transparent",this.arrowDown.style.borderTopColor="#777777"):(o+=r.height+s.height+5,this.arrowUp.style.borderBottomColor="#777777",this.arrowDown.style.borderTopColor="transparent"),this.x=a,this.y=o,this.box.style.left=this.x+"px",this.box.style.top=this.y+"px"},n.prototype.hide=function(){this.currentPen=null,this.x=-9999,this.box.style.left="-9999px"},n.prototype.translate=function(e,t){this.x<-1e3||(this.x+=e,this.y+=t,this.box.style.left=this.x+"px",this.box.style.top=this.y+"px")},n.prototype.destroy=function(){this.box.onmouseleave=null},n}(),n_e=function(){function n(e){var t=this;this.parent=e,this.onMouseDownH=function(a){a.preventDefault(),a.stopPropagation(),t.isDownH=a.x,t.x=t.parent.store.data.x||0,t.lastScrollX=t.scrollX},this.onMouseDownV=function(a){a.preventDefault(),a.stopPropagation(),t.isDownV=a.y,t.y=t.parent.store.data.y||0,t.lastScrollY=t.scrollY},this.onMouseMove=function(a){if(t.isDownH){var o=a.x-t.isDownH;t.scrollX=t.lastScrollX+o,t.h.style.left=t.scrollX+"px",t.parent.store.data.x=t.x-o*t.rect.width/t.parent.parentElement.clientWidth}if(t.isDownV){var c=a.y-t.isDownV;if(t.pageMode&&t.canMouseMove(c))return;t.scrollY=t.lastScrollY+c,t.v.style.top=t.scrollY+"px",t.parent.store.data.y=t.y-c*t.rect.height/t.parent.parentElement.clientHeight}(t.isDownH||t.isDownV)&&(t.parent.onMovePens(),t.parent.canvasTemplate.init(),t.parent.canvasImage.init(),t.parent.canvasImageBottom.init(),t.parent.render())},this.onMouseUp=function(a){!t.isDownH&&!t.isDownV||(t.isDownH=void 0,t.isDownV=void 0,t.scrollX<20?(t.scrollX=20,t.h.style.left=t.scrollX+"px"):t.scrollX>t.parent.parentElement.clientWidth-t.hSize-20&&(t.scrollX=t.parent.parentElement.clientWidth-t.hSize-20,t.h.style.left=t.scrollX+"px"),t.scrollY<20?(t.scrollY=20,t.v.style.top=t.scrollY+"px"):t.scrollY>t.parent.parentElement.clientHeight-t.vSize-20&&(t.scrollY=t.parent.parentElement.clientHeight-t.vSize-20,t.v.style.top=t.scrollY+"px"),t.resize())},this.h=document.createElement("div"),this.v=document.createElement("div"),this.parent.externalElements.appendChild(this.h),this.parent.externalElements.appendChild(this.v),this.h.className="meta2d-scroll h",this.h.onmousedown=this.onMouseDownH,this.v.className="meta2d-scroll v",this.v.onmousedown=this.onMouseDownV,document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp);for(var i,r=0;r=0||e>0&&t.ey-this.parent.height+this.parent.store.data.y<=0},n.prototype.changeMode=function(){this.pageMode=!0,this.h.style.display="none";var e=this.parent.parent.getRect();e.height0?this.rect.width+=this.parent.store.data.x+(this.rect.x>0?0:this.rect.x):this.rect.width-=this.parent.store.data.x+(this.rect.x>0?0:this.rect.x),this.parent.store.data.y>0?this.rect.height+=this.parent.store.data.y+(this.rect.y>0?0:this.rect.y):this.rect.height-=this.parent.store.data.y+(this.rect.y>0?0:this.rect.y),this.rect.width<1400&&(this.rect.width=1400),this.rect.height<900&&(this.rect.height=900),this.hSize=1e3*this.parent.parentElement.clientWidth/this.rect.width/3,this.vSize=1e3*this.parent.parentElement.clientHeight/this.rect.height/3,this.h.style.width=this.hSize+"px",this.v.style.height=this.vSize+"px"},n.prototype.show=function(){this.isShow=!0,this.h.style.display="block",this.v.style.display="block",document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp)},n.prototype.hide=function(){this.isShow=!1,this.h.style.display="none",this.v.style.display="none",this.destroy()},n.prototype.translate=function(e,t){e&&(this.scrollX-=e*this.parent.parentElement.clientWidth/this.rect.width,this.h.style.left=this.scrollX+"px"),t&&(this.scrollY-=t*this.parent.parentElement.clientHeight/this.rect.height,this.v.style.top=this.scrollY+"px")},n.prototype.wheel=function(e){var t=10;e&&(t=-10),!(this.pageMode&&this.canMouseMove(t))&&(this.scrollY+=t,this.v.style.top=this.scrollY+"px",this.parent.store.data.y-=t*this.rect.height/this.parent.parentElement.clientHeight,this.parent.onMovePens(),this.parent.canvasTemplate.init(),this.parent.canvasImage.init(),this.parent.canvasImageBottom.init(),this.parent.render())},n.prototype.destroy=function(){document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mouseup",this.onMouseUp)},n}(),Iw=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Zhe=function(){function n(e,t,i){this.parentElement=e,this.store=t,this.isBottom=i,this.canvas=document.createElement("canvas"),this.otherOffsreen=k3(),this.offscreen=k3(),this.animateOffsScreen=k3(),e.appendChild(this.canvas),this.canvas.style.backgroundRepeat="no-repeat",this.canvas.style.backgroundSize="100% 100%",this.canvas.style.position="absolute",this.canvas.style.top="0",this.canvas.style.left="0"}return n.prototype.resize=function(e,t){this.canvas.style.width=e+"px",this.canvas.style.height=t+"px",e=e*this.store.dpiRatio|0,t=t*this.store.dpiRatio|0,this.canvas.width=e,this.canvas.height=t,this.otherOffsreen.width=e,this.otherOffsreen.height=t,this.offscreen.width=e,this.offscreen.height=t,this.animateOffsScreen.width=e,this.animateOffsScreen.height=t,this.otherOffsreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.otherOffsreen.getContext("2d").textBaseline="middle",this.offscreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.offscreen.getContext("2d").textBaseline="middle",this.animateOffsScreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.animateOffsScreen.getContext("2d").textBaseline="middle",this.init()},n.prototype.init=function(){var e,t;this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.animateOffsScreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height);try{for(var i=Iw(this.store.data.pens),r=i.next();!r.done;r=i.next()){var s=r.value;this.hasImage(s)&&(s.calculative.imageDrawed=!1)}}catch(a){e={error:a}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}this.store.patchFlagsTop=!0},n.prototype.clear=function(){this.otherOffsreen.getContext("2d").clearRect(0,0,this.otherOffsreen.width,this.otherOffsreen.height),this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.animateOffsScreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)},n.prototype.hasImage=function(e){return e.calculative.hasImage=e.calculative&&e.calculative.inView&&(this.isBottom&&e.canvasLayer===Ts.CanvasImageBottom||!this.isBottom&&e.canvasLayer===Ts.CanvasImage)&&e.image&&e.calculative.img&&e.name!=="gif",e.calculative.hasImage},n.prototype.render=function(){var e,t,i,r,s,a,o,c,l=!1,h=!1;try{for(var u=Iw(this.store.data.pens),d=u.next();!d.done;d=u.next()){var f=d.value;this.hasImage(f)&&(this.store.animates.has(f)?h=!0:f.calculative.imageDrawed||(l=!0),f.parentId&&this.store.animates.has(xd(f,!0))&&(h=!0))}}catch(S){e={error:S}}finally{try{d&&!d.done&&(t=u.return)&&t.call(u)}finally{if(e)throw e.error}}var p=this.store.patchFlagsTop;if(p&&!this.isBottom){var _=this.otherOffsreen.getContext("2d");_.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderRule(_)}var m=this.store.patchFlagsLast;if(m){var _=this.offscreen.getContext("2d");_.clearRect(0,0,this.canvas.width,this.canvas.height)}if(l){var _=this.offscreen.getContext("2d");_.save(),_.clearRect(0,0,this.canvas.width,this.canvas.height),_.translate(this.store.data.x,this.store.data.y);try{for(var g=Iw(this.store.data.pens),v=g.next();!v.done;v=g.next()){var f=v.value;!f.calculative.hasImage||this.store.animates.has(f)||this.store.animates.has(xd(f,!0))||f.canvasLayer!==Ts.CanvasTemplate&&(f.calculative.imageDrawed=!0,_.save(),Dy(_,f),f.calculative.rotate&&Um(_,f),Oy(_,f),$S(_,f),_.restore())}}catch(N){i={error:N}}finally{try{v&&!v.done&&(r=g.return)&&r.call(g)}finally{if(i)throw i.error}}_.restore()}if(h){var _=this.animateOffsScreen.getContext("2d");_.save(),_.clearRect(0,0,this.canvas.width,this.canvas.height),_.translate(this.store.data.x,this.store.data.y);try{for(var x=Iw(this.store.animates),y=x.next();!y.done;y=x.next()){var f=y.value;f.calculative.hasImage&&f.canvasLayer!==Ts.CanvasTemplate&&(f.calculative.imageDrawed=!0,_.save(),Dy(_,f),f.calculative.rotate&&Um(_,f),Oy(_,f),$S(_,f),_.restore())}}catch(N){s={error:N}}finally{try{y&&!y.done&&(a=x.return)&&a.call(x)}finally{if(s)throw s.error}}try{for(var C=Iw(this.store.data.pens),b=C.next();!b.done;b=C.next()){var f=b.value;!f.calculative.hasImage||!f.parentId||f.canvasLayer!==Ts.CanvasTemplate&&this.store.animates.has(xd(f,!0))&&(f.calculative.imageDrawed=!0,_.save(),Dy(_,f),f.calculative.rotate&&Um(_,f),Oy(_,f),$S(_,f),_.restore())}}catch(N){o={error:N}}finally{try{b&&!b.done&&(c=C.return)&&c.call(C)}finally{if(o)throw o.error}}_.restore()}if(l||h||this.isBottom||p&&!this.isBottom){var T=this.canvas.getContext("2d");T.clearRect(0,0,this.canvas.width,this.canvas.height),T.drawImage(this.offscreen,0,0,this.canvas.width,this.canvas.height),T.drawImage(this.animateOffsScreen,0,0,this.canvas.width,this.canvas.height),this.isBottom||(T.drawImage(this.otherOffsreen,0,0,this.canvas.width,this.canvas.height),this.store.patchFlagsTop=!1)}},n.prototype.renderRule=function(e){var t,i,r,s,a,o,c,l,h=this.store,u=h.data,d=h.options,f=u.rule,p=u.ruleColor,_=u.scale,m=u.origin;if(f??d.rule){var g=_*10;e.save();var v=p||d.ruleColor;e.strokeStyle=Cz(v,.7);var x=m.x+u.x,y=m.y+u.y,C=this.canvas,b=C.width,T=C.height,S=((t=d.ruleOptions)===null||t===void 0?void 0:t.height)||20;!((i=d.ruleOptions)===null||i===void 0)&&i.background&&(e.beginPath(),e.fillStyle=(r=d.ruleOptions)===null||r===void 0?void 0:r.background,e.rect(0,0,b,S),e.fill(),e.rect(0,0,S,T),e.fill()),!((s=d.ruleOptions)===null||s===void 0)&&s.underline&&(e.beginPath(),e.fillStyle=Cz(v,.7),e.moveTo(0,S),e.lineTo(b,S),e.stroke(),e.moveTo(S,0),e.lineTo(S,T),e.stroke());var N=S/4;((a=d.ruleOptions)===null||a===void 0?void 0:a.baseline)==="bottom"&&(N=S*3/4),e.beginPath(),e.lineWidth=S/2,e.lineDashOffset=-x%g,e.setLineDash([1,g-1]),e.moveTo(0,N),e.lineTo(b,N),e.stroke(),e.beginPath(),e.lineDashOffset=-y%g,e.moveTo(N,0),e.lineTo(N,T),e.stroke(),e.strokeStyle=v,e.beginPath(),e.lineWidth=S,e.lineDashOffset=-x%(g*10),e.setLineDash([1,g*10-1]),e.moveTo(0,S/2),e.lineTo(b,S/2),e.stroke(),e.beginPath(),e.lineDashOffset=-y%(g*10),e.moveTo(S/2,0),e.lineTo(S/2,T),e.stroke(),e.beginPath(),e.fillStyle=((o=d.ruleOptions)===null||o===void 0?void 0:o.textColor)||e.strokeStyle;var D=0-Math.floor(x/g/10)*100,M=((c=d.ruleOptions)===null||c===void 0?void 0:c.textTop)||16,I=((l=d.ruleOptions)===null||l===void 0?void 0:l.textLeft)||4;x<0&&(D-=100);for(var R=x%(g*10);R `;var r=document.createElement("div");this.iframe=document.createElement("iframe"),this.iframe.setAttribute("frameborder","0"),this.box.className="meta2d-dialog_mask",this.dialog.className="meta2d-dialog",r.className="meta2d-dialog_body",i.className="meta2d-dialog_header",this.title.className="meta2d-dialog-content",this.close.className="meta2d-dialog-close",i.appendChild(this.title),i.appendChild(this.close),r.appendChild(this.iframe),this.dialog.appendChild(i),this.dialog.appendChild(r),this.box.appendChild(this.dialog),e.appendChild(this.box),this.dialog.onclick=function(c){c.stopPropagation()},this.box.onclick=function(){t.hide()},this.close.onclick=function(){t.hide()};for(var s,a=0;a=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},fSe=function(){function n(e,t){this.parentElement=e,this.store=t,this.canvas=document.createElement("canvas"),this.offscreen=k3(),this.bgOffscreen=k3(),e.appendChild(this.canvas),this.canvas.style.backgroundRepeat="no-repeat",this.canvas.style.backgroundSize="100% 100%",this.canvas.style.position="absolute",this.canvas.style.top="0",this.canvas.style.left="0"}return n.prototype.resize=function(e,t){this.canvas.style.width=e+"px",this.canvas.style.height=t+"px",e=e*this.store.dpiRatio|0,t=t*this.store.dpiRatio|0,this.canvas.width=e,this.canvas.height=t,this.bgOffscreen.width=e,this.bgOffscreen.height=t,this.offscreen.width=e,this.offscreen.height=t,this.bgOffscreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.bgOffscreen.getContext("2d").textBaseline="middle",this.offscreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.offscreen.getContext("2d").textBaseline="middle",this.init()},n.prototype.init=function(){this.bgOffscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.patchFlags=!0,this.bgPatchFlags=!0},n.prototype.hidden=function(){this.canvas.style.display="none"},n.prototype.show=function(){this.canvas.style.display="block"},n.prototype.clear=function(){this.bgOffscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.bgPatchFlags=!0,this.patchFlags=!0},n.prototype.render=function(){var e,t,i;if(this.bgPatchFlags){var r=this.bgOffscreen.getContext("2d");r.clearRect(0,0,this.canvas.width,this.canvas.height);var s=this.store.data.width||this.store.options.width,a=this.store.data.height||this.store.options.height,o=this.store.data.x||this.store.options.x||0,c=this.store.data.y||this.store.options.y||0,l=this.store.data.background||this.store.options.background;l&&(r.save(),r.fillStyle=l,s&&a?(r.globalAlpha=(i=this.store.data.globalAlpha)!==null&&i!==void 0?i:this.store.options.globalAlpha,r.shadowOffsetX=this.store.options.shadowOffsetX,r.shadowOffsetY=this.store.options.shadowOffsetY,r.shadowBlur=this.store.options.shadowBlur,r.shadowColor=this.store.options.shadowColor,r.fillRect(this.store.data.origin.x+o,this.store.data.origin.y+c,s*this.store.data.scale,a*this.store.data.scale)):r.fillRect(0,0,this.canvas.width,this.canvas.height),r.restore()),s&&a&&this.store.bkImg&&(r.save(),r.drawImage(this.store.bkImg,this.store.data.origin.x+o,this.store.data.origin.y+c,s*this.store.data.scale,a*this.store.data.scale),r.restore()),this.renderGrid(r)}if(this.patchFlags){var r=this.offscreen.getContext("2d");r.save(),r.clearRect(0,0,this.canvas.width,this.canvas.height),r.translate(this.store.data.x,this.store.data.y);try{for(var h=dSe(this.store.data.pens),u=h.next();!u.done;u=h.next()){var d=u.value;isFinite(d.x)&&d.canvasLayer===Ts.CanvasTemplate&&d.calculative.inView&&(ay(r,d),d.image&&d.name!=="gif"&&d.calculative.img&&(r.save(),Dy(r,d),d.calculative.rotate&&Um(r,d),Oy(r,d),$S(r,d),r.restore()))}}catch(_){e={error:_}}finally{try{u&&!u.done&&(t=h.return)&&t.call(h)}finally{if(e)throw e.error}}r.restore()}if(this.patchFlags||this.bgPatchFlags){var f=this.canvas.getContext("2d");f.clearRect(0,0,this.canvas.width,this.canvas.height),f.drawImage(this.bgOffscreen,0,0,this.canvas.width,this.canvas.height),f.drawImage(this.offscreen,0,0,this.canvas.width,this.canvas.height),this.patchFlags=!1,this.bgPatchFlags=!1}},n.prototype.renderGrid=function(e){var t=this.store,i=t.data,r=t.options,s=i.grid,a=i.gridRotate,o=i.gridColor,c=i.gridSize,l=i.scale,h=i.origin;if(s??r.grid){e.save();var u=(i.width||r.width)*l,d=(i.height||r.height)*l,f=(i.x||r.x||0)+h.x,p=(i.y||r.y||0)+h.y;a&&(e.translate(u/2,d/2),e.rotate(a*Math.PI/180),e.translate(-u/2,-d/2)),e.lineWidth=1,e.strokeStyle=o||r.gridColor,e.beginPath();var _=(c||r.gridSize)*l;if(!u||!d){for(var m=this.store.dpiRatio,g=this.canvas.width/m,v=this.canvas.height/m,x=f/_,y=p/_,C=_*10,b=f-Math.ceil(x)*_,T=p-Math.ceil(y)*_,S=g+b+C,N=v+T+C,D=b;D<=S;D+=_)e.moveTo(D,T),e.lineTo(D,v+T+C);for(var D=T;D<=N;D+=_)e.moveTo(b,D),e.lineTo(g+b+C,D)}else{for(var S=u+f,N=d+p,D=f;D<=S;D+=_)e.moveTo(D,p),e.lineTo(D,d+p);for(var D=p;D<=N;D+=_)e.moveTo(f,D),e.lineTo(u+f,D)}e.stroke(),e.restore()}},n}(),ch=function(){return ch=Object.assign||function(n){for(var e,t=1,i=arguments.length;t0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},f0=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},p0="-moving",qhe=function(){function n(e,t,i){var r=this;this.parent=e,this.parentElement=t,this.store=i,this.canvas=document.createElement("canvas"),this.offscreen=k3(),this.externalElements=document.createElement("div"),this.lastRotate=0,this.hoverType=Qi.None,this.resizeIndex=0,this.lastOffsetX=0,this.lastOffsetY=0,this.drawLineFns=f0([],d0(_be),!1),this.patchFlagsLines=new Set,this.lastMouseTime=0,this.hoverTimer=0,this.patchFlags=!1,this.lastRender=0,this.touchStart=0,this.lastAnimateRender=0,this.animateRendering=!1,this.pointSize=8,this.pasteOffset=!0,this.opening=!1,this.maxZindex=5,this.canMoveLine=!1,this.inputParent=document.createElement("div"),this.inputDiv=document.createElement("div"),this.inputRight=document.createElement("div"),this.dropdown=document.createElement("ul"),this.mousePos={x:0,y:0},this.autoPolylineFlag=!1,this.stopPropagation=function(s){s.stopPropagation()},this.curve=xTe,this.polyline=ITe,this.mind=ATe,this.line=bTe,this.onCopy=function(s){r.store.options.disableClipboard||s.target!==r.externalElements&&s.target!==document.body&&s.target.offsetParent!==r.externalElements||r.copy()},this.onCut=function(s){r.store.options.disableClipboard||s.target!==r.externalElements&&s.target!==document.body&&s.target.offsetParent!==r.externalElements||r.cut()},this.onPaste=function(s){if(!r.store.options.disableClipboard&&!(s.target!==r.externalElements&&s.target!==document.body&&s.target.offsetParent!==r.externalElements)){var a;if(navigator.clipboard&&s.clipboardData){var o=s.clipboardData.items;if(o){for(var c=0;c100&&r.store.options.scroll&&r.scroll){r.scroll.wheel(s.deltaY<0);return}if(!r.store.options.disableTouchPadScale){var o=.015,c=/mac os /i.test(navigator.userAgent);if(c)s.ctrlKey?s.deltaY>0&&(o*=-1):o*=s.wheelDeltaY/240;else{var l=.2;s.deltaY.toString().indexOf(".")!==-1&&(l=.01),s.deltaY>0?o=-l:o=l}var h=s.offsetX,u=s.offsetY;r.scale(r.store.data.scale+o,{x:h,y:u}),r.externalElements.focus()}}}},this.onkeydown=function(s){var a,o,c;if(r.store.data.locked>=js.DisableEdit&&s.target.tagName!=="INPUT"&&s.target.tagName!=="TEXTAREA"&&!s.target.dataset.meta2dIgnore&&r.store.active.forEach(function(m){var g;(g=m.onKeyDown)===null||g===void 0||g.call(m,m,s.key)}),!(r.store.data.locked>=js.DisableEdit||s.target.tagName==="INPUT"||s.target.tagName==="TEXTAREA"||s.target.dataset.meta2dIgnore)&&!r.store.options.unavailableKeys.includes(s.key)){r.keyOptions||(r.keyOptions={}),r.keyOptions.altKey=s.altKey,r.keyOptions.shiftKey=s.shiftKey,r.keyOptions.ctrlKey=s.ctrlKey,r.keyOptions.metaKey=s.metaKey;var l=10,h=10,u=null;if(r.store.options.strictScope){var d=r.store.data.width||r.store.options.width,f=r.store.data.height||r.store.options.height;d&&f&&(u={x:r.store.data.origin.x,y:r.store.data.origin.y,width:d*r.store.data.scale,height:f*r.store.data.scale})}switch(s.key){case" ":r.hotkeyType=un.Translate;break;case"Control":r.drawingLine?r.drawingLine.calculative.drawlineH=!r.drawingLine.calculative.drawlineH:r.hotkeyType||(r.patchFlags=!0,r.hotkeyType=un.Select);break;case"Meta":break;case"Shift":r.store.active.length===1&&r.store.active[0].type&&r.store.activeAnchor?r.toggleAnchorHand():r.hotkeyType||(r.patchFlags=!0,r.store.options.resizeMode||(r.hotkeyType=un.Resize));break;case"Alt":if(!s.ctrlKey&&!s.shiftKey&&r.drawingLine){var p=nn(r.drawingLine);p!==r.drawingLine.calculative.activeAnchor?(lJ(r.drawingLine),r.drawingLine.calculative.worldAnchors.push(p)):r.drawingLine.calculative.worldAnchors.push({x:p.x,y:p.y});var _=r.drawLineFns.indexOf(r.drawingLineName);r.drawingLineName=r.drawLineFns[(_+1)%r.drawLineFns.length],r.drawingLine.lineName=r.drawingLineName,r.drawline(),r.patchFlags=!0}s.preventDefault();break;case"a":case"A":s.ctrlKey||s.metaKey?(r.active(r.store.data.pens.filter(function(m){return!m.parentId&&m.locked!==js.Disable})),s.preventDefault()):r.toggleAnchorMode();break;case"Delete":case"Backspace":!r.store.data.locked&&r.delete();break;case"ArrowLeft":if(r.movingAnchor){r.translateAnchor(-1,0);break}if(l=-1,s.shiftKey&&(l=-5),(s.ctrlKey||s.metaKey)&&(l=-10),l=l*r.store.data.scale,r.store.activeAnchor&&r.store.active&&r.store.active.length===1&&r.store.active[0].type){r.moveLineAnchor({x:r.store.activeAnchor.x+l,y:r.store.activeAnchor.y},{});break}u&&r.activeRect.x+lu.x+u.width&&(l=u.x+u.width-(r.activeRect.x+r.activeRect.width)),r.translatePens(r.store.active,l,0);break;case"ArrowDown":if(r.movingAnchor){r.translateAnchor(0,1);break}if(h=1,s.shiftKey&&(h=5),(s.ctrlKey||s.metaKey)&&(h=10),h=h*r.store.data.scale,u&&r.activeRect.y+r.activeRect.height+h>u.y+u.height&&(h=u.y+u.height-(r.activeRect.y+r.activeRect.height)),r.store.activeAnchor&&r.store.active&&r.store.active.length===1&&r.store.active[0].type){r.moveLineAnchor({x:r.store.activeAnchor.x,y:r.store.activeAnchor.y+h},{});break}r.translatePens(r.store.active,0,h);break;case"d":case"D":!((a=r.store.active[0])===null||a===void 0)&&a.locked||r.removeAnchorHand();break;case"h":case"H":!((o=r.store.active[0])===null||o===void 0)&&o.locked||r.addAnchorHand();break;case"m":case"M":r.toggleMagnifier();break;case"g":case"G":r.hoverType===Qi.NodeAnchor&&(r.movingAnchor=r.store.hoverAnchor,r.externalElements.style.cursor="move");break;case"s":case"S":!r.store.data.locked&&r.hoverType===Qi.LineAnchor&&r.store.hover===r.store.active[0]&&r.splitLine(r.store.active[0],r.store.hoverAnchor),(s.ctrlKey||s.metaKey)&&r.store.emitter.emit("save",{event:s});break;case"c":case"C":(s.ctrlKey||s.metaKey)&&r.store.options.disableClipboard&&r.copy();break;case"x":case"X":(s.ctrlKey||s.metaKey)&&r.store.options.disableClipboard&&r.cut();break;case"√":case"v":case"V":!s.ctrlKey&&!s.metaKey&&(r.pencil&&r.stopPencil(),r.drawingLineName?(r.finishDrawline(),r.drawingLineName=""):r.drawingLineName=r.store.options.drawingLineName),(s.ctrlKey||s.metaKey)&&(r.store.options.disableClipboard||!r.store.options.disableClipboard&&s.altKey)&&r.paste();break;case"b":case"B":r.drawingLineName&&(r.finishDrawline(),r.drawingLineName=""),r.pencil?r.stopPencil():r.drawingPencil();break;case"y":case"Y":(s.ctrlKey||s.metaKey)&&r.redo();break;case"z":case"Z":s.ctrlKey||s.metaKey?r.undo():s.shiftKey&&r.redo();break;case"Enter":r.drawingLineName&&(r.finishDrawline(!0),r.store.active[0].anchors[0].connectTo?r.drawingLineName="":r.drawingLineName=r.store.options.drawingLineName),r.store.active&&(r.store.active.forEach(function(m){m.type&&(m.close=!m.close,r.store.path2dMap.set(m,mr.path2dDraws.line(m)),v$(m))}),r.render());break;case"Escape":r.drawingLineName&&r.finishDrawline(),r.drawingLineName=void 0,r.stopPencil(),r.movingPens&&(r.getAllByPens(r.movingPens).forEach(function(m){r.store.pens[m.id]=void 0}),r.movingPens=void 0,r.mouseDown=void 0,r.clearDock(),(c=r.store.active)===null||c===void 0||c.forEach(function(m){r.updateLines(m)}),r.calcActiveRect(),r.patchFlags=!0),r.hotkeyType=un.None,r.movingAnchor=void 0,r.magnifierCanvas.magnifier&&(r.magnifierCanvas.magnifier=!1,r.patchFlags=!0);break;case"E":case"e":r.store.options.disableAnchor=!r.store.options.disableAnchor,r.store.emitter.emit("disableAnchor",r.store.options.disableAnchor);break;case"=":(s.ctrlKey||s.metaKey)&&(r.scale(r.store.data.scale+.1),s.preventDefault(),s.stopPropagation());break;case"-":(s.ctrlKey||s.metaKey)&&(r.scale(r.store.data.scale-.1),s.preventDefault(),s.stopPropagation());break;case"l":case"L":r.canMoveLine=!0;break;case"[":r.parent.down();break;case"]":r.parent.up();break;case"{":r.parent.bottom();break;case"}":r.parent.top();break}r.render(!1)}},this.onkeyup=function(s){switch(s.key){case"l":case"L":r.canMoveLine=!1;break}r.hotkeyType&&r.render(),r.hotkeyType=0&&f<0||d<=0&&f>0)&&(p>=0&&_<0||p<=0&&_>0)?r.touchScaling=!0:r.touchMoving=!0}if(r.touchScaling){if(r.store.options.disableScale)return;var m=Math.hypot(c[0].pageX-c[1].pageX,c[0].pageY-c[1].pageY)/r.initTouchDis;r.scale(r.initScale*m,At(r.touchCenter))}if(r.touchMoving){if(r.store.data.locked>=js.DisableMove&&r.store.data.locked!==js.DisableScale||r.store.options.disableScale)return;if(r.lastOffsetX){var m=r.store.data.scale;r.translate((h-r.lastOffsetX)/m,(u-r.lastOffsetY)/m)}r.lastOffsetX=h,r.lastOffsetY=u}}}}},this.ontouchend=function(s){if(r.store.data.locked!==js.Disable){r.touchCenter=void 0,r.touchScaling=void 0,r.touchMoving=void 0,r.startTouches=void 0,r.lastOffsetX=0,r.lastOffsetY=0;var a=s.changedTouches[0].pageX-r.clientRect.x,o=s.changedTouches[0].pageY-r.clientRect.y;r.onMouseUp({x:a,y:o,clientX:s.changedTouches[0].clientX,clientY:s.changedTouches[0].clientY,pageX:s.changedTouches[0].pageX,pageY:s.changedTouches[0].pageY,ctrlKey:s.ctrlKey||s.metaKey,shiftKey:s.shiftKey,altKey:s.altKey,buttons:1}),setTimeout(function(){r.render()},20)}},this.onGesturestart=function(s){s.preventDefault()},this.onMouseDown=function(s){var a,o,c;if(s.buttons===2&&!r.drawingLine&&(r.mouseRight=hm.Down),r.hideInput(),r.store.data.locked===js.Disable||s.buttons!==1&&s.buttons!==2){r.hoverType=Qi.None;return}if(!r.magnifierCanvas.magnifier){if(r.calibrateMouse(s),r.mousePos.x=s.x,r.mousePos.y=s.y,r.mouseDown=s,r.lastMouseTime=performance.now(),r.hotkeyType===un.AddAnchor){r.setAnchor(r.store.pointAt);return}if(!r.store.options.autoAnchor&&!r.drawingLine&&s.shiftKey&&s.ctrlKey&&s.altKey){r.setAnchor(r.store.pointAt),r.drawingLineName=r.store.options.drawingLineName;var l=r.store.activeAnchor;if(!l)return;var h={id:ns(),x:l.x,y:l.y};r.drawingLine=r.createDrawingLine(h);var u=xo(r.drawingLine);r.drawingLine.calculative.activeAnchor=u,sc(r.store.hover,l,r.drawingLine,h),r.drawline();return}if(!(r.hotkeyType===un.Translate||r.mouseRight===hm.Down&&!r.store.options.mouseRightActive)){if(r.drawingLine){if(r.store.hoverAnchor){var d=nn(r.drawingLine);r.store.hoverAnchor.type===fm.Line?tV(d,r.store.hoverAnchor,r.store):(d.x=r.store.hoverAnchor.x,d.y=r.store.hoverAnchor.y),sc(r.store.hover,r.store.hoverAnchor,r.drawingLine,d),r.drawline(),r.finishDrawline(!0);return}if(!r.store.options.autoAnchor&&s.shiftKey&&s.altKey&&s.ctrlKey){r.setAnchor(r.store.pointAt);var f=nn(r.drawingLine),l=r.store.activeAnchor;if(!l)return;f.x=l.x,f.y=l.y,sc(r.store.hover,l,r.drawingLine,f),r.drawline(),r.finishDrawline(!0);return}if(s.buttons===2||r.drawingLineName==="mind"&&((a=r.drawingLine)===null||a===void 0?void 0:a.calculative.worldAnchors.length)>1||r.store.options.drawingLineLength&&((o=r.drawingLine)===null||o===void 0?void 0:o.calculative.worldAnchors.length)>r.store.options.drawingLineLength){r.finishDrawline(!0),!((c=r.store.active[0])===null||c===void 0)&&c.anchors[0].connectTo||r.store.active.length==0?r.drawingLineName="":r.drawingLineName=r.store.options.drawingLineName;return}if(r.store.options.autoAnchor&&r.hoverType===Qi.Node){var p=nn(r.drawingLine),l=OS(r.store.hover,s);p.x=l.x,p.y=l.y,r.drawingLine.autoTo=!0,sc(r.store.hover,l,r.drawingLine,p),r.drawline(),r.finishDrawline(!0);return}var _=nn(r.drawingLine);_.isTemp?(r.drawingLine.calculative.activeAnchor=r.drawingLine.calculative.worldAnchors[r.drawingLine.calculative.worldAnchors.length-2],_.isTemp=void 0):(r.drawingLine.calculative.activeAnchor=_,r.drawingLine.calculative.worldAnchors.push({x:_.x,y:_.y,penId:_.penId})),r.drawingLine.calculative.drawlineH=void 0,r.drawingLineName!=="polyline"&&r.drawline()}if(r.drawingLineName){if(r.hoverType===Qi.Node)if(r.store.options.autoAnchor){r.inactive(!0);var l=OS(r.store.hover,s);r.store.hoverAnchor=l;var h={id:ns(),x:l.x,y:l.y};r.drawingLine=r.createDrawingLine(h),r.drawingLine.autoFrom=!0,sc(r.store.hover,l,r.drawingLine,h)}else r.inactive(),r.hoverType=Qi.None;else if(r.hoverType===Qi.NodeAnchor){r.drawingLineName=r.store.options.drawingLineName;var h={id:ns(),x:r.store.hoverAnchor.x,y:r.store.hoverAnchor.y};r.drawingLine=r.createDrawingLine(h),r.drawingLine.calculative.activeAnchor=h,sc(r.store.hover,r.store.hoverAnchor,r.drawingLine,h)}else if(!r.drawingLine&&r.drawingLineName!=="curve"){r.inactive(!0);var h={id:ns(),x:s.x,y:s.y};r.drawingLine=r.createDrawingLine(h),r.drawingLine.calculative.activeAnchor=h}}else if(r.pencil){r.inactive(!0);var m=ns(),h={x:s.x,y:s.y,id:ns(),penId:m};r.pencilLine=r.getInitPencilLine(h)}else{switch(r.hoverType){case Qi.None:(r.store.data.rule||r.store.options.rule)&&!r.store.options.disableRuleLine&&r.addRuleLine(s),r.store.options.resizeMode&&(r.hotkeyType=un.None),r.inactive();break;case Qi.Node:case Qi.Line:if(r.store.hover){var g=xd(r.store.hover,!0)||r.store.hover;s.ctrlKey&&!s.shiftKey?(g.calculative.active?r.willInactivePen=g:(g.calculative.active=!0,RS(g),r.store.active.push(g),r.store.emitter.emit("active",r.store.active)),r.patchFlags=!0):s.ctrlKey&&s.shiftKey&&r.store.hover.parentId?r.active([r.store.hover]):g.calculative.active||(r.active([g]),r.store.options.resizeMode&&(r.hotkeyType=un.Resize)),r.calcActiveRect()}break;case Qi.LineAnchor:r.store.activeAnchor=r.store.hoverAnchor,r.store.hover.calculative.activeAnchor=r.store.hoverAnchor,r.active([r.store.hover]);break;case Qi.LineAnchorPrev:case Qi.LineAnchorNext:r.store.activeAnchor&&(r.prevAnchor=ch({},r.store.activeAnchor.prev),r.nextAnchor=ch({},r.store.activeAnchor.next));break;case Qi.Resize:r.activeInitPos=[],r.store.active.forEach(function(v){r.activeInitPos.push({x:(v.calculative.worldRect.x-r.activeRect.x)/r.activeRect.width,y:(v.calculative.worldRect.y-r.activeRect.y)/r.activeRect.height})});break}r.store.emitter.emit("mousedown",{x:s.x,y:s.y,pen:r.store.hover})}r.render()}}},this.onMouseMove=function(s){var a,o,c,l,h,u;if(r.store.data.locked===js.Disable){r.hoverType=Qi.None;return}if(r.mouseDown&&!r.mouseDown.restore&&s.buttons!==1&&s.buttons!==2){r.onMouseUp(s);return}if(r.lastMouseTime){var d=performance.now();if(d-r.lastMouseTime<50){r.lastMouseTime=0;return}r.lastMouseTime=0}if(r.calibrateMouse(s),r.mousePos.x=s.x,r.mousePos.y=s.y,r.magnifierCanvas.magnifier){r.render();return}if(r.mouseDown&&!r.store.options.disableTranslate){if(r.mouseRight===hm.Down&&(r.mouseRight=hm.Translate),r.store.data.locked===js.DisableEdit||r.store.data.locked===js.DisableScale||r.hotkeyType===un.Translate||r.mouseRight===hm.Translate){var f=r.store.data.scale,p=(s.x-r.mouseDown.x)/f,_=(s.y-r.mouseDown.y)/f;s.shiftKey&&!s.ctrlKey&&(_=0),s.ctrlKey&&(p=0),r.translate(p,_);return}if(r.store.data.locked)return;if(!r.drawingLine&&!r.pencil){if(!r.drawingLineName&&!r.movingAnchor){if(r.hoverType===Qi.NodeAnchor){r.drawingLineName=r.store.options.drawingLineName;var m={id:ns(),x:r.store.hoverAnchor.x,y:r.store.hoverAnchor.y};r.drawingLine=r.createDrawingLine(m),r.drawingLine.calculative.activeAnchor=m,sc(r.store.hover,r.store.hoverAnchor,r.drawingLine,m),r.drawline();return}}else if(r.drawingLineName&&r.hoverType===Qi.None){var m={id:ns(),x:s.x,y:s.y};r.drawingLine=r.createDrawingLine(m),r.drawingLine.calculative.activeAnchor=m,r.drawline();return}if(s.buttons===1&&!r.hoverType&&!r.hotkeyType){r.dragRect={x:Math.min(r.mouseDown.x,s.x),y:Math.min(r.mouseDown.y,s.y),ex:Math.max(r.mouseDown.x,s.x),ey:Math.max(r.mouseDown.y,s.y),width:Math.abs(s.x-r.mouseDown.x),height:Math.abs(s.y-r.mouseDown.y)},r.render();return}if(r.movingAnchor){var p=s.x-r.movingAnchor.x,_=s.y-r.movingAnchor.y;r.translateAnchor(p,_),r.render();return}else if(!(!((a=r.store.active[0])===null||a===void 0)&&a.locked)){var m={x:s.x,y:s.y};if(r.hoverType===Qi.LineAnchor){(r.dockInAnchor(s)||r.store.active[0].lineName==="line")&&!r.store.options.disableDock&&!r.store.options.disableLineDock&&(r.clearDock(),r.dock=Dhe(r.store,m,r.store.activeAnchor),!((o=r.dock)===null||o===void 0)&&o.xDock&&(m.x+=r.dock.xDock.step),!((c=r.dock)===null||c===void 0)&&c.yDock&&(m.y+=r.dock.yDock.step)),r.moveLineAnchor(m,s);return}if(r.hoverType===Qi.LineAnchorPrev){r.moveLineAnchorPrev(s);return}if(r.hoverType===Qi.LineAnchorNext){r.moveLineAnchorNext(s);return}}if(r.hoverType===Qi.Rotate){r.rotatePens({x:s.x,y:s.y});return}if(r.hoverType===Qi.Resize){r.resizePens(s);return}if(r.hoverType===Qi.Node||r.hoverType===Qi.Line){var p=s.x-r.mouseDown.x,_=s.y-r.mouseDown.y,g=20;if(s.ctrlKey&&!s.shiftKey&&(Math.abs(p)>=g||Math.abs(_)>=g)&&(r.willInactivePen=void 0),r.store.active.length===1){var v=r.store.active[0];v.locked1&&(x=nn(r.drawingLine)),x?(x.prev=void 0,x.next=void 0,x.id||(x.id=ns()),x.x=m.x,x.y=m.y,x.connectTo=void 0):(x=ch({},m),r.drawingLine.calculative.worldAnchors.push(x)),(r.hoverType===Qi.NodeAnchor||r.hoverType===Qi.LineAnchor)&&(r.store.hoverAnchor.type!==fm.Line&&(x.x=r.store.hoverAnchor.x,x.y=r.store.hoverAnchor.y),x.connectTo=r.store.hoverAnchor.penId,r.drawingLineName==="polyline"&&(x.isTemp=!1)),r.drawingLineName==="line"){if(s.ctrlKey&&!s.shiftKey)x.x=r.drawingLine.calculative.worldAnchors[r.drawingLine.calculative.worldAnchors.length-2].x;else if(s.shiftKey&&!s.ctrlKey)x.y=r.drawingLine.calculative.worldAnchors[r.drawingLine.calculative.worldAnchors.length-2].y;else if(s.shiftKey&&s.ctrlKey){var y=r.drawingLine.calculative.worldAnchors[r.drawingLine.calculative.worldAnchors.length-2];r.getSpecialAngle(x,y)}}r.drawline()}}globalThis.debug&&console.time("hover");var C=performance.now();C-r.hoverTimer>50&&(r.hoverTimer=C,r.getHover(s)),globalThis.debug&&console.timeEnd("hover"),r.hotkeyType===un.AddAnchor&&(r.patchFlags=!0),r.render(!1)},this.onMouseUp=function(s){var a,o;if(r.store.data.locked===js.Disable){r.hoverType=Qi.None;return}if(r.mouseDown){if(r.mouseRight===hm.Down&&r.store.emitter.emit("contextmenu",{e:s,clientRect:r.clientRect,pen:r.store.hover}),r.mouseRight=hm.None,r.calibrateMouse(s),r.mousePos.x=s.x,r.mousePos.y=s.y,r.pencil&&r.finishPencil(),r.drawingLine){if(r.store.hoverAnchor){var c=nn(r.drawingLine);r.store.hoverAnchor.type===fm.Line?tV(c,r.store.hoverAnchor,r.store):(c.x=r.store.hoverAnchor.x,c.y=r.store.hoverAnchor.y),sc(r.store.hover,r.store.hoverAnchor,r.drawingLine,c),r.drawline(),r.finishDrawline(!0);return}if(r.store.options.autoAnchor&&r.hoverType===Qi.Node){var c=nn(r.drawingLine),l=OS(r.store.hover,s);c.x=l.x,c.y=l.y,r.drawingLine.autoTo=!0,sc(r.store.hover,l,r.drawingLine,c),r.drawline(),r.finishDrawline(!0);return}}if(r.hoverType===Qi.LineAnchor&&r.store.hover&&r.store.active[0]&&r.store.active[0].name==="line"&&r.store.active[0]!==r.store.hover){var h=r.store.active[0],u=xo(h),c=nn(h);if(r.store.hoverAnchor){var d=r.store.hover,f=xo(d)===r.store.hoverAnchor,p=nn(d)===r.store.hoverAnchor,_=u===r.store.activeAnchor,m=c===r.store.activeAnchor;if((s.ctrlKey||s.altKey)&&d.type===Xn.Line&&(f||p)&&(_||m)){var g=d.calculative.worldAnchors.map(function(C){return ch(ch({},C),{penId:h.id})});f?g.shift():p&&g.pop(),(f&&_||p&&m)&&g.reverse(),_?(h.calculative.worldAnchors[0].connectTo=void 0,(a=h.calculative.worldAnchors).unshift.apply(a,f0([],d0(g),!1))):m&&(h.calculative.worldAnchors[h.calculative.worldAnchors.length-1].connectTo=void 0,(o=h.calculative.worldAnchors).push.apply(o,f0([],d0(g),!1))),r.delete([d]),r.render()}else r.store.activeAnchor&&(r.store.hoverAnchor.type===fm.Line?tV(r.store.activeAnchor,r.store.hoverAnchor,r.store):(r.store.activeAnchor.x=r.store.hoverAnchor.x,r.store.activeAnchor.y=r.store.hoverAnchor.y),sc(r.store.hover,r.store.hoverAnchor,h,r.store.activeAnchor));r[h.lineName]&&h.lineName!=="polyline"&&r[h.lineName](r.store,h),r.store.path2dMap.set(h,mr.path2dDraws.line(h)),r.initLineRect(h)}else u===r.store.activeAnchor&&h.autoFrom?r.calcAutoAnchor(h,u,r.store.hover):c===r.store.activeAnchor&&h.autoTo&&r.calcAutoAnchor(h,c,r.store.hover)}if(r.addCaches&&r.addCaches.length){if(!r.store.data.locked){if(r.dragRect&&r.addCaches.length===1){var v=r.addCaches[0];v.width=r.dragRect.width/r.store.data.scale,v.height=r.dragRect.height/r.store.data.scale,s.x=(r.dragRect.x+r.dragRect.ex)/2,s.y=(r.dragRect.y+r.dragRect.ey)/2}r.dropPens(r.addCaches,s)}r.addCaches=void 0}if(r.hoverType===Qi.Rotate&&(r.getSizeCPs(),r.store.active.forEach(function(y){y.rotate=y.calculative.rotate})),r.patchFlagsLines.forEach(function(y){y.type&&r.initLineRect(y)}),r.patchFlagsLines.clear(),r.dragRect){var x=r.store.data.pens.filter(function(y){if(y.visible===!1||y.locked>=js.DisableMove||y.parentId)return!1;if(Tz(y.calculative.worldRect,r.dragRect,r.store.options.dragAllIn))return y.type===Xn.Line&&!r.store.options.dragAllIn?MTe(y,r.dragRect):!0});r.active(x)}s.button!==2&&(QH(r.mouseDown,s)<2&&(r.store.hover&&r.store.hover.input&&r.showInput(r.store.hover),r.store.emitter.emit("click",{x:s.x,y:s.y,pen:r.store.hover})),r.store.emitter.emit("mouseup",{x:s.x,y:s.y,pen:r.store.hover})),r.willInactivePen&&(r.willInactivePen.calculative.active=void 0,RS(r.willInactivePen,!1),r.store.active.splice(r.store.active.findIndex(function(y){return y===r.willInactivePen}),1),r.calcActiveRect(),r.willInactivePen=void 0,r.store.emitter.emit("inactive",[r.willInactivePen]),r.render()),r.movingPens&&(s.altKey&&!s.shiftKey?r.copyMovedPens():r.movedActivePens(s.ctrlKey&&s.shiftKey),r.getAllByPens(r.movingPens).forEach(function(y){r.store.pens[y.id]=void 0}),r.movingPens=void 0),r.store.active&&r.store.active[0]&&(r.store.active[0].calculative.h=void 0),r.mouseDown=void 0,r.lastOffsetX=0,r.lastOffsetY=0,r.clearDock(),r.dragRect=void 0,r.initActiveRect=void 0,r.render()}},this.clearDock=function(){var s,a,o,c,l=(a=(s=r.dock)===null||s===void 0?void 0:s.xDock)===null||a===void 0?void 0:a.penId,h=(c=(o=r.dock)===null||o===void 0?void 0:o.yDock)===null||c===void 0?void 0:c.penId,u=r.store.pens[l];u&&(u.calculative.isDock=!1);var d=r.store.pens[h];d&&(d.calculative.isDock=!1),r.dock=void 0},this.onResize=function(){r.timer&&clearTimeout(r.timer),r.timer=setTimeout(function(){r.resize(),r.timer=void 0},100)},this.onScroll=function(){r.timer&&clearTimeout(r.timer),r.timer=setTimeout(function(){r.clientRect=r.canvas.getBoundingClientRect(),r.timer=void 0},100)},this.calibrateMouse=function(s){return s.x-=r.store.data.x,s.y-=r.store.data.y,s},this.getHover=function(s){var a,o;if(!r.dragRect){var c=Qi.None;r.store.hover=void 0,r.store.hoverAnchor=void 0,r.title.hide(),r.store.pointAt=void 0,r.store.pointAtIndex=void 0;var l=r.store.active.length===1&&r.store.active[0].type;if(!r.drawingLineName&&r.hotkeyType!==un.AddAnchor&&r.activeRect&&!l&&!r.store.data.locked){var h=_X(r.store.active),u=Phe(r.store.active)||r.store.options.disableRotate,d=whe(r.store.active)||r.store.options.disableSize;if(!h&&!u){var f={x:r.activeRect.center.x,y:r.activeRect.y-30};r.activeRect.rotate&&Yn(f,r.activeRect.rotate,r.activeRect.center),!r.hotkeyType&&SS(s,f,r.pointSize)&&(c=Qi.Rotate,r.externalElements.style.cursor='url("'+r.store.options.rotateCursor+'"), auto')}if(!h&&!d)for(var p=0;p<8;p++){var _=p<4,m=r.hotkeyType===un.Resize||_&&!r.hotkeyType;if(m&&SS(s,r.sizeCPs[p],r.pointSize)){var g=_?xhe:yhe,v=0;Math.abs(r.activeRect.rotate%90-45)<25?(g=_?yhe:xhe,v=Math.round((r.activeRect.rotate-45)/90)+(_?0:1)):v=Math.round(r.activeRect.rotate/90),c=Qi.Resize,r.resizeIndex=p,r.externalElements.style.cursor=g[(p+v)%4];break}}}c===Qi.None&&(c=r.inPens(s,r.store.data.pens)),!c&&!l&&Yw(s,r.activeRect)&&(c=Qi.Node,r.externalElements.style.cursor="move"),r.hoverType=c,c===Qi.None&&(r.drawingLineName||r.pencil?r.externalElements.style.cursor="crosshair":r.mouseDown||(r.externalElements.style.cursor="default"),r.store.hover=void 0),r.store.lastHover!==r.store.hover&&(r.patchFlags=!0,r.store.lastHover&&(r.store.lastHover.calculative.hover=!1,Xw(xd(r.store.lastHover,!0)||r.store.lastHover,!1),r.store.emitter.emit("leave",r.store.lastHover),r.tooltip.hide()),r.store.hover&&(r.store.hover.calculative.hover=!0,Xw(xd(r.store.hover,!0)||r.store.hover),r.store.emitter.emit("enter",r.store.hover),r.tooltip.show(r.store.hover,s)),r.store.lastHover=r.store.hover),(o=(a=r.store.hover)===null||a===void 0?void 0:a.onMouseMove)===null||o===void 0||o.call(a,r.store.hover,r.mousePos)}},this.inPens=function(s,a){var o=Qi.None,c=function(u){var d,f,p,_,m=a[u];if(m.visible==!1||m.calculative.inView==!1||m.locked===js.Disable)return"continue";var g=Mz(m);if(!m.calculative.active&&!Ly(s,m.calculative.worldRect,g)&&!Yw(s,m.calculative.worldRect))return"continue";if(!r.store.data.locked&&r.hotkeyType!==un.Resize&&m.calculative.worldAnchors)try{for(var v=(d=void 0,Za(m.calculative.worldAnchors)),x=v.next();!x.done;x=v.next()){var y=x.value;if(o=r.inAnchor(s,m,y),o){var C=At(y);return Object.assign(C,s),r.title.show(C,m),"break-outer"}}}catch(z){d={error:z}}finally{try{x&&!x.done&&(f=v.return)&&f.call(v)}finally{if(d)throw d.error}}if(m.type){var b=TTe(s,m);if(b)return!r.store.data.locked&&!m.locked?r.hotkeyType===un.AddAnchor?r.externalElements.style.cursor="pointer":r.externalElements.style.cursor="move":r.externalElements.style.cursor=r.store.options.hoverCursor,r.store.hover=m,r.store.pointAt=b.point,r.store.pointAtIndex=b.i,r.initTemplateCanvas([r.store.hover]),o=Qi.Line,"break"}else{if(m.children){var T=[];if(m.children.forEach(function(z){r.store.pens[z]&&T.push(r.store.pens[z])}),o=r.inPens(s,T),o)return"break"}var S=!1;if(m.name==="line"?S=Ly(s,m.calculative.worldRect,m.lineWidth):S=Yw(s,m.calculative.worldRect),S){if(!r.store.data.locked&&!m.locked?r.hotkeyType===un.AddAnchor?r.externalElements.style.cursor="pointer":r.externalElements.style.cursor="move":r.externalElements.style.cursor=r.store.options.hoverCursor,r.store.hover=m,r.initTemplateCanvas([r.store.hover]),o=Qi.Node,r.store.pointAt=s,!s.ctrlKey){var N=r.store.hover.calculative.worldRect,D=N.x,M=N.y,I=N.ex,R=N.ey,O=N.rotate,H=N.center;if(O){var G=[{x:D,y:M},{x:I,y:M},{x:I,y:R},{x:D,y:R}];G.forEach(function(z){Yn(z,O,H)});var Q=G[G.length-1];try{for(var $=(p=void 0,Za(G)),V=$.next();!V.done;V=$.next()){var j=V.value;if(Q.y>s.y!=j.y>s.y){var k=j.x+(s.y-j.y)*(Q.x-j.x)/(Q.y-j.y);Math.abs(k-r.store.pointAt.x)<10&&(r.store.pointAt.x=k)}Q=j}}catch(z){p={error:z}}finally{try{V&&!V.done&&(_=$.return)&&_.call($)}finally{if(p)throw p.error}}}else r.store.pointAt.x-10I&&(r.store.pointAt.x=I),r.store.pointAt.y-10R&&(r.store.pointAt.y=R)}return"break"}}};e:for(var l=a.length-1;l>=0;--l){var h=c(l);if(h==="break")break;switch(h){case"break-outer":break e}}return o},this.dockInAnchor=function(s){var a,o,c,l;r.store.hover=void 0;for(var h=r.store.data.pens.length-1;h>=0;--h){var u=r.store.data.pens[h];if(!(u.visible==!1||u.locked===js.Disable||u===r.store.active[0])){var d=Mz(u);if(d+=2*r.store.options.anchorRadius,!!Ly(s,u.calculative.worldRect,d)&&(r.store.hover=u,r.hotkeyType!==un.Resize&&u.calculative.worldAnchors))try{for(var f=(a=void 0,Za(u.calculative.worldAnchors)),p=f.next();!p.done;p=f.next()){var _=p.value;if(_.twoWay===Oc.In){var m=nn(r.store.active[0]);if(r.store.activeAnchor.id!==m.id)continue}if(_.twoWay===Oc.Out){var g=xo(r.store.active[0]);if(r.store.activeAnchor.id!==g.id)continue}if(!(_.twoWay===Oc.DisableConnected||_.twoWay===Oc.Disable||((c=r.store.activeAnchor)===null||c===void 0?void 0:c.twoWay)===Oc.DisableConnectTo||((l=r.store.activeAnchor)===null||l===void 0?void 0:l.twoWay)===Oc.Disable)&&(r.title.hide(),r.inAnchor(s,u,_))){var v=At(_);return Object.assign(v,s),r.title.show(v,u),!0}}}catch(x){a={error:x}}finally{try{p&&!p.done&&(o=f.return)&&o.call(f)}finally{if(a)throw a.error}}}}},this.render=function(s){if(s&&(r.opening=!1),!r.opening){var a;if(s==null||s===!0||s===1/0?(a=performance.now(),r.patchFlags=!0):s>1?a=s:a=performance.now(),!!r.patchFlags){if(a-r.lastRenderjs.DisableEdit)){if(o===r.store.hoverAnchor){s.save();var c=r.store.hover.hoverAnchorColor||r.store.options.hoverAnchorColor;s.strokeStyle=c,s.fillStyle=c}s.beginPath();var l=o.radius||r.store.hover.anchorRadius||r.store.options.anchorRadius;if(r.store.hover.type&&!o.radius&&!r.store.hover.anchorRadius&&(l=3,r.store.hover.calculative.lineWidth>3&&(l=r.store.hover.calculative.lineWidth)),o.type===fm.Line){var h=r.store.pens[o.penId].rotate||0;r.store.pens[o.penId].calculative.flipX&&(h*=-1),r.store.pens[o.penId].calculative.flipY&&(h*=-1);var u=o.rotate+h;r.store.pens[o.penId].calculative.flipX&&(u*=-1),r.store.pens[o.penId].calculative.flipY&&(u*=-1),s.save(),s.translate(o.x,o.y),s.rotate(u*Math.PI/180),s.translate(-o.x,-o.y),s.rect(o.x-o.length*r.store.data.scale/2,o.y-l,o.length*r.store.data.scale,l*2),s.restore()}else s.arc(o.x,o.y,l,0,Math.PI*2);if(r.store.hover.type&&r.store.hoverAnchor===o?(s.save(),s.strokeStyle=r.store.hover.activeColor||r.store.options.activeColor,s.fillStyle=s.strokeStyle):(o.color||o.background)&&(s.save(),s.strokeStyle=o.color,s.fillStyle=o.background),s.fill(),s.stroke(),o===r.store.hoverAnchor&&s.restore(),(r.store.hover.type&&r.store.hoverAnchor===o||o.color||o.background)&&s.restore(),!r.store.hover.parentId&&r.store.hover.children&&r.store.hover.children.length>0&&o===r.store.hoverAnchor){s.save(),s.beginPath(),s.lineWidth=3;var c=r.store.hover.hoverAnchorColor||r.store.options.hoverAnchorColor;globalThis.pSBC&&(s.strokeStyle=globalThis.pSBC(.5,c)),s.arc(o.x,o.y,l+1.5,0,Math.PI*2),s.stroke(),s.restore()}}}))}r.hotkeyType!==un.AddAnchor&&!r.movingPens&&r.activeRect&&!(r.store.active.length===1&&r.store.active[0].type)&&!_X(r.store.active)&&!whe(r.store.active)&&!r.store.options.disableSize&&(s.strokeStyle=r.store.options.activeColor,s.fillStyle="#ffffff",r.sizeCPs.forEach(function(o,c){r.activeRect.rotate&&(s.save(),s.translate(o.x,o.y),s.rotate(r.activeRect.rotate*Math.PI/180),s.translate(-o.x,-o.y)),(c<4||r.hotkeyType===un.Resize)&&(s.beginPath(),s.fillRect(o.x-4.5,o.y-4.5,8,8),s.strokeRect(o.x-5.5,o.y-5.5,10,10)),r.activeRect.rotate&&s.restore()})),!r.store.data.locked&&r.dragRect&&(s.save(),s.fillStyle=Cz(r.store.options.dragColor,.2),s.strokeStyle=r.store.options.dragColor,s.beginPath(),s.strokeRect(r.dragRect.x,r.dragRect.y,r.dragRect.width,r.dragRect.height),s.fillRect(r.dragRect.x,r.dragRect.y,r.dragRect.width,r.dragRect.height),s.restore()),r.dock&&(s.strokeStyle=r.store.options.dockColor,r.dock.xDock&&(s.beginPath(),s.moveTo(r.dock.xDock.x,r.dock.xDock.y),s.lineTo(r.dock.xDock.x,r.dock.xDock.prev.y),s.stroke()),r.dock.yDock&&(s.beginPath(),s.moveTo(r.dock.yDock.x,r.dock.yDock.y),s.lineTo(r.dock.yDock.prev.x,r.dock.yDock.y),s.stroke())),s.restore()}},this.pastePen=function(s,a){var o,c,l=s.id;if(Ohe(s),s.parentId=a,s.type===Xn.Line?r.changeNodeConnectedLine(l,s,r.store.clipboard.pens):r.changeLineAnchors(l,s,r.store.clipboard.pens),!s.parentId){var h=r.getPenRect(s,r.store.clipboard.origin,r.store.clipboard.scale),u=r.getPenRect(r.store.clipboard.initRect,r.store.clipboard.origin,r.store.clipboard.scale),d=r.store.data,f=d.origin,p=d.scale;s.x=f.x+h.x*p,s.y=f.y+h.y*p,s.width=h.width*p,s.height=h.height*p,u.x=f.x+u.x*p,u.y=f.y+u.y*p,To(u),r.store.clipboard.pos&&(s.x-=u.center.x-r.store.clipboard.pos.x,s.y-=u.center.y-r.store.clipboard.pos.y),r.keyOptions&&r.keyOptions.altKey&&(r.keyOptions.ctrlKey||r.keyOptions.metaKey)?(s.x=-r.store.data.x+r.width/2-s.width/2,s.y=-r.store.data.y+r.height/2-s.height/2):r.keyOptions&&r.keyOptions.shiftKey&&(r.keyOptions.ctrlKey||r.keyOptions.metaKey)||(s.x+=r.store.clipboard.offset*r.store.data.scale,s.y+=r.store.clipboard.offset*r.store.data.scale)}r.makePen(s);var _=[];if(Array.isArray(s.children)){var m=function(y){var C=r.store.clipboard.pens.find(function(b){return b.id===y});C&&_.push(r.pastePen(C,s.id).id)};try{for(var g=Za(s.children),v=g.next();!v.done;v=g.next()){var x=v.value;m(x)}}catch(y){o={error:y}}finally{try{v&&!v.done&&(c=g.return)&&c.call(g)}finally{if(o)throw o.error}}}return s.children=_,fy(s,!0),s},this.ondblclick=function(s){r.store.hover&&(!r.store.data.locked||r.store.hover.dbInput)&&!r.store.options.disableInput&&(r.store.hover.onShowInput?r.store.hover.onShowInput(r.store.hover,s):r.showInput(r.store.hover)),r.store.emitter.emit("dblclick",{x:s.x,y:s.y,pen:r.store.hover})},this.showInput=function(s,a,o){if(o===void 0&&(o="transparent"),!(!window||!r.store.hover||r.store.hover.locked||r.store.hover.externElement||r.store.hover.disableInput)){if(r.inputDiv.dataset.penId===s.id){r.inputDiv.dataset.isInput="true",r.inputDiv.contentEditable="true",r.inputDiv.focus();var c=window.getSelection();c.selectAllChildren(r.inputDiv),c.collapseToEnd(),r.inputDiv.scrollTop=r.inputDiv.scrollHeight,r.inputDiv.scrollLeft=r.inputDiv.scrollWidth;return}!a&&!s.dbInput?r.setInputStyle(s):(r.inputDiv.style.width="100%",r.inputDiv.style.height="100%");var l=a||s.calculative.worldTextRect,h=s.calculative.tempText||s.text+""||"",u=h.replace(/\x20/g," ").split(/[\s\n]/),d=(u.join("
")+"
").replace("","").replace(/\\<\/div\>/g,"

");r.inputDiv.innerHTML=d,r.inputParent.style.left=l.x+r.store.data.x-(s.textLeft||0)+"px",r.inputParent.style.top=l.y+r.store.data.y-(s.textTop||0)+"px";var f=l.width+(s.textLeft||0);r.inputParent.style.width=(f<0?12:f)+"px",r.inputParent.style.height=l.height+(s.textTop||0)+"px",r.inputParent.style.zIndex="9999",r.inputParent.style.background=o,s.rotate%360?r.inputParent.style.transform="rotate("+s.rotate+"deg)":r.inputParent.style.transform=null,r.inputParent.style.display="flex",r.inputDiv.dataset.penId=s.id,r.inputDiv.contentEditable=s.disableInput==null?"true":s.disableInput.toString(),s.dropdownList&&r.dropdown.style.display!=="block"?(r.store.data.locked||(r.inputRight.style.display="none"),r.setDropdownList()):r.inputRight.style.display="none",r.inputDiv.contentEditable="true",r.inputDiv.focus();var p=window.getSelection();p.selectAllChildren(r.inputDiv),p.collapseToEnd(),r.inputDiv.scrollTop=r.inputDiv.scrollHeight,r.inputDiv.scrollLeft=r.inputDiv.scrollWidth,s.calculative.text=void 0,r.initTemplateCanvas([s]),r.render()}},this.setInputStyle=function(s){s.text||(s.text="");for(var a,o=0;o1?s.textLeft*h:s.textLeft*h/u)+"px;"),s.textTop&&(c+="margin-top:"+(u>1?s.textTop*h:s.textTop*h/u)+"px;"),s.lineHeight&&(c+="line-height:"+(u>1?s.fontSize*s.lineHeight*u:s.fontSize*s.lineHeight*h)+"px;"),s.textHeight)c+="height:"+(u>1?s.textHeight*h*u:s.textHeight*h)+"px;";else{var p=s.calculative.worldRect.height/u-(s.textTop||0);p<0&&(p=0);var _=s.fontSize*u<12?p*h:p*u*h;_-1?s.textWidth*s.calculative.worldRect.width:s.textWidth,s.whiteSpace!=="pre-line"&&(m1?m*h*u:m*h)+"px;");else if(s.whiteSpace===void 0||s.whiteSpace==="break-all"){var p=(s.calculative.worldTextRect.width||12)/u;p<0&&(p=0),c+="width:"+(s.fontSize*u<12?p*h:p*u)+"px;"}if(s.whiteSpace&&(s.whiteSpace==="pre-line"?c+="white-space:pre;":(c+="white-space:"+s.whiteSpace+";",s.whiteSpace==="nowrap"&&(l+="display:contents;"))),s.whiteSpace!=="nowrap"){var g=s.fontSize*1.2*s.text.length,v=(m||s.calculative.worldRect.width/u)*Math.floor(s.calculative.worldRect.height/u/(s.lineHeight*s.fontSize));g>v&&(c+="justify-content: start;")}a.deleteRule(0),a.deleteRule(0),a.insertRule(`.meta2d-input .input-div{ resize:none;border:none;outline:none;background:transparent;position:absolute;flex-grow:1;height:100%;width: 100%;position:absolute;left:0;top:0;display:flex;flex-direction: column;cursor: text;`+c+"}"),a.insertRule(".input-div div{"+l+"}")},this.hideInput=function(){if(r.inputParent.style.display==="flex"){r.inputParent.style.display="none";var s=r.store.pens[r.inputDiv.dataset.penId];if(!s)return;if(s.calculative.text=s.text,r.inputDiv.dataset.value=r.inputDiv.innerHTML.replace(/\/g,` `).replace(/\<\/div\>/g,"").replace(/\/g,"").replace(/ /g," ").replace(/(<([^>]+)>)/gi,""),r.inputDiv.dataset.value=r.convertSpecialCharacter(r.inputDiv.dataset.value),s.onInput)s.onInput(s,r.inputDiv.dataset.value);else if(s.text!==r.inputDiv.dataset.value){var a=[At(s,!0)];s.text=r.inputDiv.dataset.value,s.calculative.text=s.text,r.inputDiv.dataset.penId=void 0,s.name==="text"&&s.textAutoAdjust&&Hbe(s),I0(s),r.patchFlags=!0,r.pushHistory({type:sr.Update,pens:[At(s,!0)],initPens:a}),r.store.emitter.emit("valueUpdate",s)}else s.text===r.inputDiv.dataset.value&&s.calculative.textLines.length==0&&I0(s);r.initTemplateCanvas([s])}r.inputDiv.dataset.penId=void 0,r.dropdown.style.display="none",r.inputDiv.dataset.isInput="false",r.inputDiv.contentEditable="false",r.render()},this.setDropdownList=function(s){var a,o;if(r.clearDropdownList(),!!r.store.data.locked){r.dropdown.style.display="block",r.inputRight.style.display="block",setTimeout(function(){r.inputRight.style.transform="rotate(315deg)",r.inputRight.style.zoom=r.store.data.scale});var c=r.store.pens[r.inputDiv.dataset.penId];if(!c||!c.dropdownList){r.dropdown.style.display="none",r.inputRight.style.display="none",r.inputRight.style.transform="rotate(135deg)";return}if(!c.dropdownList.length){var l=document.createElement("div");l.innerText="None",l.style.padding="5px 12px",l.style.color="#ddd",r.dropdown.appendChild(l);return}var h=r.inputDiv.innerHTML.replace(/\/g,` `).replace(/\<\/div\>/g,"").replace(/\/g,""),u=0;try{for(var d=Za(c.dropdownList),f=d.next();!f.done;f=d.next()){var p=f.value,_=typeof p=="string"?p:p.text;s&&h?_.includes(h)&&r.dropdownAppendOption(_,u):r.dropdownAppendOption(_,u),++u}}catch(m){a={error:m}}finally{try{f&&!f.done&&(o=d.return)&&o.call(d)}finally{if(a)throw a.error}}if(!r.dropdown.hasChildNodes()){var l=document.createElement("div");l.innerText="None",l.style.padding="5px 12px",l.style.color="#ddd",r.dropdown.appendChild(l)}}},this.selectDropdown=function(s){var a=s.target,o=r.store.pens[r.inputDiv.dataset.penId];if(!(!a||!o||!o.dropdownList)){var c=+a.dataset.i,l=o.dropdownList[c];if(l){var h=[At(o,!0)];typeof l=="object"?(r.updateValue(o,ch({},l)),o.calculative.text=void 0,r.calcActiveRect()):o.text=l+"",r.inputDiv.innerText=o.text,r.hideInput(),r.pushHistory({type:sr.Update,pens:[At(o,!0)],initPens:h}),r.render(),r.store.emitter.emit("valueUpdate",o)}}},this.canvasTemplate=new fSe(t,i),this.canvasTemplate.canvas.style.zIndex="1",this.canvasImageBottom=new Zhe(t,i,!0),this.canvasImageBottom.canvas.style.zIndex="2",t.appendChild(this.canvas),this.canvas.style.position="absolute",this.canvas.style.backgroundRepeat="no-repeat",this.canvas.style.backgroundSize="100% 100%",this.canvas.style.zIndex="3",this.canvasImage=new Zhe(t,i),this.canvasImage.canvas.style.zIndex="4",this.magnifierCanvas=new cSe(this,t,i),this.magnifierCanvas.canvas.style.zIndex="5",this.externalElements.style.position="absolute",this.externalElements.style.left="0",this.externalElements.style.top="0",this.externalElements.style.outline="none",this.externalElements.style.background="transparent",this.externalElements.style.zIndex="5",t.style.position="relative",t.appendChild(this.externalElements),this.createInput(),this.tooltip=new lSe(t,i),this.tooltip.box.onmouseleave=function(s){r.patchFlags=!0,r.store.lastHover&&(r.store.lastHover.calculative.hover=!1);var a=r.store.data.pens.find(function(o){return o.calculative.hover===!0});Xw(a,!1)},this.dialog=new hSe(t),this.title=new uSe(t),this.store.options.scroll&&(this.scroll=new n_e(this)),this.store.dpiRatio=globalThis.devicePixelRatio||1,this.store.dpiRatio<1?this.store.dpiRatio=1:this.store.dpiRatio>1&&this.store.dpiRatio<1.5&&(this.store.dpiRatio=1.5),this.clientRect=this.externalElements.getBoundingClientRect(),this.listen(),window==null||window.addEventListener("resize",this.onResize),window==null||window.addEventListener("scroll",this.onScroll)}return n.prototype.listen=function(){var e=this;switch(this.externalElements.addEventListener("gesturestart",this.onGesturestart),this.externalElements.ondragover=function(t){return t.preventDefault()},this.externalElements.ondrop=this.ondrop,this.externalElements.oncontextmenu=function(t){return t.preventDefault()},this.store.options.interval=50,this.externalElements.ontouchstart=this.ontouchstart,this.externalElements.ontouchmove=this.ontouchmove,this.externalElements.ontouchend=this.ontouchend,this.externalElements.onmousedown=function(t){e.onMouseDown({x:t.offsetX,y:t.offsetY,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey,buttons:t.buttons})},this.externalElements.onmousemove=function(t){t.target===e.externalElements&&e.onMouseMove({x:t.offsetX,y:t.offsetY,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey,buttons:t.buttons})},this.externalElements.onmouseup=function(t){e.onMouseUp({x:t.offsetX,y:t.offsetY,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey,buttons:t.buttons,button:t.button})},this.externalElements.onmouseleave=function(t){e.store.data.pens.forEach(function(i){i.calculative.hover&&(i.calculative.hover=!1)}),e.store.hover&&(e.store.hover.calculative.hover=!1,e.store.hover=void 0),e.render(),t.toElement!==e.tooltip.box&&t.toElement!==e.tooltip.arrowUp&&t.toElement!==e.tooltip.arrowDown&&(e.tooltip.hide(),e.store.lastHover=void 0)},this.externalElements.ondblclick=this.ondblclick,this.externalElements.tabIndex=0,this.externalElements.onblur=function(){e.mouseDown=void 0},this.externalElements.onwheel=this.onwheel,document.addEventListener("copy",this.onCopy),document.addEventListener("cut",this.onCut),document.addEventListener("paste",this.onPaste),this.store.options.keydown){case gy.Document:document.addEventListener("keydown",this.onkeydown),document.addEventListener("keyup",this.onkeyup);break;case gy.Canvas:this.externalElements.addEventListener("keydown",this.onkeydown),this.externalElements.addEventListener("keyup",this.onkeyup);break}},n.prototype.splitLine=function(e,t){var i=e.calculative.worldAnchors,r=i.findIndex(function(h){return h===t});if(![-1,0,i.length-1].includes(r)){var s=At(e,!0),a=At(e,!0),o=ns();a.id=o,a.calculative.canvas=this,a.calculative.active=!1,a.calculative.hover=!1;var c=At(i.slice(0,r+1)),l=At(i.slice(r)).map(function(h){return h.penId=o,h});e.calculative.worldAnchors=c,a.calculative.worldAnchors=l,this.initLineRect(e),this.initLineRect(a),this.store.data.pens.push(a),this.store.pens[o]=a,this.pushHistory({type:sr.Add,pens:[At(a,!0)],step:2}),this.pushHistory({type:sr.Update,initPens:[s],pens:[At(e,!0)],step:2})}},n.prototype.translateAnchor=function(e,t){var i=this;this.movingAnchor.x+=e,this.movingAnchor.y+=t;var r=this.movingAnchor.penId;if(r){var s=this.store.pens[r],a=s.calculative.worldRect;this.movingAnchor.xa.ex&&(this.movingAnchor.x=a.ex),this.movingAnchor.ya.ey&&(this.movingAnchor.y=a.ey);var o=lD(this.movingAnchor,a),c=s.anchors.findIndex(function(l){return l.id===i.movingAnchor.id});s.anchors[c]=o,this.patchFlags=!0}},n.prototype.fileToPen=function(e,t){return Rp(this,void 0,void 0,function(){var i;return Ip(this,function(r){switch(r.label){case 0:return i="",this.store.options.uploadFn?[4,this.store.options.uploadFn(e)]:[3,2];case 1:return i=r.sent(),[3,6];case 2:return this.store.options.uploadUrl?[4,Xbe(e,this.store.options.uploadUrl,this.store.options.uploadParams,this.store.options.uploadHeaders)]:[3,4];case 3:return i=r.sent(),[3,6];case 4:return[4,jbe(e)];case 5:i=r.sent(),r.label=6;case 6:return[2,new Promise(function(s,a){var o=new Image;o.onload=function(){mr.htmlElements[i]=o,s({width:o.width,height:o.height,name:t?"gif":"image",image:i})},o.onerror=function(c){a(c)},o.crossOrigin="anonymous",o.src=i})]}})})},n.prototype.dropPens=function(e,t){var i;return Rp(this,void 0,void 0,function(){var r,s,v,a,o,v,c,l,v,h,u,v,d,f,p,_,m,g,v,x,y,C,b,T,S,N,D,M,I,R,O=this;return Ip(this,function(H){switch(H.label){case 0:this.randomIdObj={};try{for(r=Za(e),s=r.next();!s.done;s=r.next())v=s.value,!v.parentId&&this.randomCombineId(v,e)}catch(G){y={error:G}}finally{try{s&&!s.done&&(C=r.return)&&C.call(r)}finally{if(y)throw y.error}}if(Object.keys(this.randomIdObj).length!==0)try{for(a=Za(e),o=a.next();!o.done;o=a.next())v=o.value,v.type?(v.anchors[0].connectTo=this.randomIdObj[v.anchors[0].connectTo],v.anchors[v.anchors.length-1].connectTo=this.randomIdObj[v.anchors[v.anchors.length-1].connectTo]):(i=v.connectedLines)===null||i===void 0||i.forEach(function(G){G.lineAnchor=O.randomIdObj[G.lineAnchor],G.lineId=O.randomIdObj[G.lineId]})}catch(G){b={error:G}}finally{try{o&&!o.done&&(T=a.return)&&T.call(a)}finally{if(b)throw b.error}}try{for(c=Za(e),l=c.next();!l.done;l=c.next())v=l.value,v.id||(v.id=ns()),!v.calculative&&(v.calculative={canvas:this}),this.store.pens[v.id]=v}catch(G){S={error:G}}finally{try{l&&!l.done&&(N=c.return)&&N.call(c)}finally{if(S)throw S.error}}try{for(h=Za(e),u=h.next();!u.done;u=h.next())v=u.value,v.parentId||(v.width*=this.store.data.scale,v.height*=this.store.data.scale,v.x=t.x-v.width/2,v.y=t.y-v.height/2,v.tags&&v.tags.includes("meta3d")&&(v.x=this.store.data.origin.x,v.y=this.store.data.origin.y))}catch(G){D={error:G}}finally{try{u&&!u.done&&(M=h.return)&&M.call(h)}finally{if(D)throw D.error}}if(d=this.store.data.width||this.store.options.width,f=this.store.data.height||this.store.options.height,d&&f){p={x:this.store.data.origin.x,y:this.store.data.origin.y,width:d*this.store.data.scale,height:f*this.store.data.scale},_=!0;try{for(m=Za(e),g=m.next();!g.done;g=m.next())if(v=g.value,!v.parentId&&(x=[{x:v.x,y:v.y},{x:v.x+v.width,y:v.y},{x:v.x,y:v.y+v.height},{x:v.x+v.width,y:v.y+v.height},{x:v.x+v.width/2,y:v.y+v.height/2}],v.x===p.x&&v.y===p.y&&v.width===p.width&&v.height===p.height||x.some(function(G){return Yw(G,p)}))){_=!1,this.store.options.strictScope&&(v.xp.x+p.width&&(v.x=p.x+p.width-v.width),v.y+v.height>p.y+p.height&&(v.y=p.y+p.height-v.height));break}}catch(G){I={error:G}}finally{try{g&&!g.done&&(R=m.return)&&R.call(m)}finally{if(I)throw I.error}}if(_)return console.info("画笔在大屏范围外"),[2]}return[4,this.addPens(e,!0)];case 1:return H.sent(),this.active(e.filter(function(G){return!G.parentId})),this.render(),this.externalElements.focus(),[2]}})})},n.prototype.randomCombineId=function(e,t,i){var r,s,a=null;e.type?(e.anchors[0].connectTo||e.anchors[e.anchors.length-1].connectTo)&&(a=[e.id,e.anchors[0].id,e.anchors[e.anchors.length-1].id]):e.connectedLines&&e.connectedLines.length&&(a=[e.id]),Ohe(e),a&&(a.length===1?this.randomIdObj[a[0]]=e.id:(this.randomIdObj[a[0]]=e.id,this.randomIdObj[a[1]]=e.anchors[0].id,this.randomIdObj[a[2]]=e.anchors[e.anchors.length-1].id)),e.parentId=i;var o=[];if(Array.isArray(e.children)){var c=function(f){var p=t.find(function(_){return _.id===f});p&&o.push(l.randomCombineId(p,t,e.id).id)},l=this;try{for(var h=Za(e.children),u=h.next();!u.done;u=h.next()){var d=u.value;c(d)}}catch(f){r={error:f}}finally{try{u&&!u.done&&(s=h.return)&&s.call(h)}finally{if(r)throw r.error}}}return e.children=o,e},n.prototype.addPens=function(e,t){return Rp(this,void 0,void 0,function(){var i,r,s,a,o,c,l;return Ip(this,function(h){switch(h.label){case 0:return i=this.beforeAddPens,i?[4,this.beforeAddPens(e)]:[3,2];case 1:i=h.sent()!=!0,h.label=2;case 2:if(i)return[2,[]];r=[];try{for(s=Za(e),a=s.next();!a.done;a=s.next())o=a.value,!(this.beforeAddPen&&this.beforeAddPen(o)!=!0)&&(this.makePen(o),r.push(o))}catch(u){c={error:u}}finally{try{a&&!a.done&&(l=s.return)&&l.call(s)}finally{if(c)throw c.error}}return this.render(),this.store.emitter.emit("add",r),t&&this.pushHistory({type:sr.Add,pens:At(r,!0)}),[2,r]}})})},n.prototype.getInitPencilLine=function(e){var t=this.store,i=t.data,r=t.options,s=i.scale,a=i.lineWidth||1;return{id:e.penId,name:"line",x:e.x,y:e.y,type:Xn.Line,calculative:{canvas:this,pencil:!0,active:!0,worldAnchors:[e],lineWidth:a*s},fromArrow:i.fromArrow||r.fromArrow,toArrow:i.toArrow||r.toArrow,lineWidth:a}},n.prototype.createDrawingLine=function(e){this.inactive();var t=this.store,i=t.data,r=t.options,s=i.scale,a=i.lineWidth||1;return e.penId=ns(),{id:e.penId,name:"line",lineName:this.drawingLineName,x:e.x,y:e.y,type:Xn.Line,calculative:{canvas:this,active:!0,worldAnchors:[e],lineWidth:a*s},fromArrow:i.fromArrow||r.fromArrow,toArrow:i.toArrow||r.toArrow,lineWidth:a}},n.prototype.addRuleLine=function(e){var t=this.store.data,i=t.x,r=t.y,s=t.scale,a=t.origin,o=e.x+i,c=e.y+r,l=e.x,h=e.y,u=0,d=0,f=0,p=0;if(o<=c&&o<20)l=-i,u=this.width,f=1,e.ctrlKey||(h=Math.round((h-a.y)/(s*10))*(s*10)+a.y);else if(c0?i-=180:i+=180)):t.y>e.y?i=90:t.yjs.DisableEdit||!(t.type&&t.calculative.active)&&this.store.options.disableAnchor||t.disableAnchor)return Qi.None;if((this.mouseDown||this.drawingLine)&&t.name==="line"&&i.connectTo){var s=this.findOne(i.connectTo);if(s!=null&&s.calculative&&!(s!=null&&s.calculative.active)){t=s;var a=s.calculative.worldAnchors.find(function(c){return c.id===i.anchorId});a&&(i=a)}}if(i.twoWay===Oc.Disable&&t.name!=="line")return Qi.None;if(t.name==="line"&&i.connectTo){var o=(r=this.findOne(i.connectTo))===null||r===void 0?void 0:r.anchors.find(function(c){return c.id===i.anchorId});if(o&&o.twoWay)return Qi.None}if(this.drawingLine){if(i.twoWay===Oc.Out)return Qi.None}else if(!(this.mouseDown&&this.hoverType===Qi.LineAnchor)){if(i.twoWay===Oc.In)return Qi.None}if(SS(e,i,this.pointSize,i.penId?this.store.pens[i.penId]:void 0))return i!==this.store.hoverAnchor&&(this.patchFlags=!0),this.store.hoverAnchor=i,this.store.hover=t,t.type?i.connectTo&&!t.calculative.active&&(this.store.hover=this.store.pens[i.connectTo],this.store.hover)?(this.store.hoverAnchor=this.store.hover.calculative.worldAnchors.find(function(c){return c.id===i.anchorId}),this.externalElements.style.cursor="crosshair",Qi.NodeAnchor):(this.hotkeyType===un.AddAnchor?this.externalElements.style.cursor="vertical-text":this.externalElements.style.cursor="pointer",Qi.LineAnchor):(this.hotkeyType===un.AddAnchor?this.externalElements.style.cursor="vertical-text":this.externalElements.style.cursor="crosshair",Qi.NodeAnchor);if(!this.mouseDown&&t.type){if(t.calculative.active&&i.prev&&SS(e,i.prev,this.pointSize))return this.store.hoverAnchor=i,this.store.hover=t,this.externalElements.style.cursor="pointer",Qi.LineAnchorPrev;if(t.calculative.active&&i.next&&SS(e,i.next,this.pointSize))return this.store.hoverAnchor=i,this.store.hover=t,this.externalElements.style.cursor="pointer",Qi.LineAnchorNext}return Qi.None},n.prototype.resize=function(e,t){var i,r;e=e||this.parentElement.clientWidth,t=t||this.parentElement.clientHeight,this.width=e,this.height=t,this.canvasRect={x:0,y:0,width:e,height:t},Mo(this.canvasRect),this.canvas.style.width=e+"px",this.canvas.style.height=t+"px",this.externalElements.style.width=e+"px",this.externalElements.style.height=t+"px",this.canvasTemplate.resize(e,t),this.canvasImage.resize(e,t),this.canvasImageBottom.resize(e,t),this.magnifierCanvas.resize(e,t),e=e*this.store.dpiRatio|0,t=t*this.store.dpiRatio|0,this.canvas.width=e,this.canvas.height=t,this.offscreen.width=e,this.offscreen.height=t,this.clientRect=this.externalElements.getBoundingClientRect(),this.canvas.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.offscreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.offscreen.getContext("2d").textBaseline="middle";try{for(var s=Za(this.store.data.pens),a=s.next();!a.done;a=s.next()){var o=a.value;o.isRuleLine&&(o.width?o.height||(o.width=this.width):o.height=this.height),fy(o)}}catch(c){i={error:c}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(i)throw i.error}}this.render()},n.prototype.clearCanvas=function(){this.activeRect=void 0,this.sizeCPs=void 0,this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.offscreen.getContext("2d").clearRect(0,0,this.offscreen.width,this.offscreen.height),this.store.data.template||this.canvasTemplate.clear(),this.canvasImage.clear(),this.canvasImageBottom.clear()},n.prototype.addPen=function(e,t,i){return Rp(this,void 0,void 0,function(){var r;return Ip(this,function(s){switch(s.label){case 0:return r=this.beforeAddPens,r?[4,this.beforeAddPens([e])]:[3,2];case 1:r=s.sent()!=!0,s.label=2;case 2:return r?[2]:this.beforeAddPen&&this.beforeAddPen(e)!=!0?[2]:(this.makePen(e),this.active([e]),this.render(),i&&this.store.emitter.emit("add",[e]),t&&this.pushHistory({type:sr.Add,pens:[e]}),[2,e])}})})},n.prototype.pushHistory=function(e){var t=this,i;if(!this.store.data.locked){var r=this.store.data,s=r.origin,a=r.scale;e.origin=At(s),e.scale=a,e.type!==sr.Update&&e.pens&&e.pens.forEach(function(o){o.calculative&&(o.calculative.layer=t.store.data.pens.findIndex(function(c){return c.id===o.id}))}),this.store.historyIndex1;){var i=this.store.histories[this.store.historyIndex--];this.doEditAction(i,!0),t--}(e.type==sr.Add||e.type==sr.Delete)&&this.activeHistory()}},n.prototype.redo=function(){if(!(this.store.data.locked||this.store.historyIndex==null||this.store.historyIndex>this.store.histories.length-2)){var e=this.store.histories[++this.store.historyIndex];this.doEditAction(e,!1);for(var t=e.step;t>1;){var i=this.store.histories[++this.store.historyIndex];this.doEditAction(i,!1),t--}(e.type==sr.Add||e.type==sr.Delete)&&this.activeHistory()}},n.prototype.activeHistory=function(){var e=this,t=this.store.histories[this.store.historyIndex];if(t&&t.type===sr.Add){var i=[];t.pens.forEach(function(r){i.push(e.store.pens[r.id])}),this.active(i)}},n.prototype.doEditAction=function(e,t){var i=this;switch(this.inactive(),this.store.hoverAnchor=void 0,this.store.hover=void 0,e.type){case sr.Add:e.pens.forEach(function(c){var l,h=At(c,!0),u=i.store.data.pens.findIndex(function(d){return d.id===h.id});u>-1&&((l=h.onDestroy)===null||l===void 0||l.call(h,i.store.pens[h.id]),i.store.data.pens.splice(u,1),i.store.pens[h.id]=void 0,h.calculative||(h.calculative={}),h.calculative.canvas=i,i.store.animates.delete(h),i.store.animateMap.delete(h))}),e.type=sr.Delete;break;case sr.Update:var r=t?e.initPens:e.pens,s=t?e.pens:e.initPens;r.forEach(function(c){var l=At(c,!0),h=i.store.data.pens.findIndex(function(_){return _.id===l.id});if(h>-1){if(l.calculative=i.store.data.pens[h].calculative,i.store.data.pens[h].type&&i.store.data.pens[h].lastConnected)for(var u in i.store.data.pens[h].lastConnected)i.store.pens[u].connectedLines=i.store.data.pens[h].lastConnected[u];i.store.data.pens[h]=l,i.store.pens[l.id]=l;for(var d in l)(typeof l[d]!="object"||d==="lineDash")&&(l.calculative[d]=l[d]);l.calculative.image=void 0;var f=i.getPenRect(l,e.origin,e.scale);if(i.setPenRect(l,f,!1),i.updateLines(l,!0),l.calculative.canvas.parent.isCombine(l)){var p=s.find(function(_){return _.id===l.id});S0e.forEach(function(_){var m;l[_]!==p[_]&&i.parent.setValue((m={id:l.id},m[_]=l[_],m),{render:!0,doEvent:!1})})}}});break;case sr.Delete:e.pens.reverse().forEach(function(c){var l,h,u=At(c,!0);if(u.calculative||(u.calculative={}),i.store.data.pens.splice(((l=u.calculative)===null||l===void 0?void 0:l.layer)!==-1?(h=u.calculative)===null||h===void 0?void 0:h.layer:i.store.data.pens.length,0,u),i.store.pens[u.id]=u,u.type&&u.lastConnected)for(var d in u.lastConnected)i.store.pens[d].connectedLines=u.lastConnected[d];u.calculative.canvas=i}),e.pens.reverse().forEach(function(c){var l=i.store.pens[c.id],h=i.getPenRect(l,e.origin,e.scale);i.setPenRect(l,h,!1),l.calculative.image=void 0,l.calculative.backgroundImage=void 0,l.calculative.strokeImage=void 0,i.loadImage(l)}),e.type=sr.Add;break;case sr.Replace:{var a=t?e.initPens:e.pens,o=t?e.pens:e.initPens;o.forEach(function(c){var l,h=At(c,!0),u=i.store.data.pens.findIndex(function(f){return f.id===h.id});if(u>-1){(l=h.onDestroy)===null||l===void 0||l.call(h,i.store.data.pens.find(function(f){return f.id===h.id}));var d=i.store.data.pens.findIndex(function(f){return f.id===h.id});i.store.data.pens.splice(d,1),i.store.pens[h.id]=void 0,h.calculative||(h.calculative={}),h.calculative.canvas=i,i.store.animates.delete(h),i.store.animateMap.delete(h)}}),a.reverse().forEach(function(c){var l,h,u=At(c,!0);if(u.calculative||(u.calculative={}),i.store.data.pens.splice(((l=u.calculative)===null||l===void 0?void 0:l.layer)!==-1?(h=u.calculative)===null||h===void 0?void 0:h.layer:i.store.data.pens.length,0,u),i.store.pens[u.id]=u,u.type&&u.lastConnected)for(var d in u.lastConnected)i.store.pens[d].connectedLines=u.lastConnected[d];u.calculative.canvas=i}),a.reverse().forEach(function(c){var l=i.store.data.pens.find(function(u){return u.id===c.id}),h=i.getPenRect(l,e.origin,e.scale);i.setPenRect(l,h,!1),l.calculative.image=void 0,l.calculative.backgroundImage=void 0,l.calculative.strokeImage=void 0,i.loadImage(l)}),e.type=sr.Replace;break}}if(e.type===sr.Update){var r=f0(f0([],d0(e.pens),!1),d0(e.initPens),!1);this.initImageCanvas(r),this.initTemplateCanvas(r)}else this.initImageCanvas(e.pens),this.initTemplateCanvas(e.pens);this.parent.onSizeUpdate(),this.render(),this.store.emitter.emit(t?"undo":"redo",e)},n.prototype.makePen=function(e){var t=this,i;if(e.id||(e.id=ns()),Math.abs(this.store.lastScale-this.store.data.scale)<1e-4&&this.store.sameTemplate&&this.store.templatePens[e.id]&&e.canvasLayer===Ts.CanvasTemplate){e=this.store.templatePens[e.id],this.store.data.pens.push(e),this.updatePenRect(e);return}if(this.store.data.pens.push(e),this.store.pens[e.id]=e,e.path){!e.pathId&&(e.pathId=ns());var r=this.store.data.paths;!r[e.pathId]&&(r[e.pathId]=e.path),e.path=void 0}e.lineWidth==null&&(e.lineWidth=1);var s=this.store.options,a=s.fontSize,o=s.lineHeight;e.fontSize||(e.fontSize=a),e.lineHeight||(e.lineHeight=o),e.image&&e.name!=="gif"&&e.canvasLayer===void 0&&(e.isBottom?e.canvasLayer=Ts.CanvasImageBottom:e.canvasLayer=Ts.CanvasImage,delete e.isBottom),e.template&&(e.canvasLayer=Ts.CanvasTemplate),e.calculative={canvas:this,singleton:(i=e.calculative)===null||i===void 0?void 0:i.singleton},(e.video||e.audio)&&(e.calculative.onended=function(l){t.nextAnimate(l)});for(var c in e)(typeof e[c]!="object"||c==="lineDash")&&(e.calculative[c]=e[c]);e.calculative.image=void 0,e.calculative.backgroundImage=void 0,e.calculative.strokeImage=void 0,!e.anchors&&mr.anchors[e.name]&&(e.anchors||(e.anchors=[]),mr.anchors[e.name](e)),this.updatePenRect(e),!e.anchors&&e.calculative.worldAnchors&&(e.anchors=e.calculative.worldAnchors.map(function(l){return lD(l,e.calculative.worldRect)})),!e.rotate&&(e.rotate=0),this.loadImage(e),this.parent.penNetwork(e)},n.prototype.drawline=function(e){var t;this.drawingLine&&((t=this[this.drawingLineName])===null||t===void 0||t.call(this,this.store,this.drawingLine,e),this.store.path2dMap.set(this.drawingLine,mr.path2dDraws.line(this.drawingLine)),this.patchFlags=!0)},n.prototype.initLineRect=function(e){var t;if(e){if(!(!((t=e.calculative.worldAnchors)===null||t===void 0)&&t.length)){this._del([e]);return}if(!(!isFinite(e.x)||!isFinite(e.x))&&!(e.x==null||e.y==null)){var i=g$(e);e.parentId||Object.assign(e,i);var r=this.store.options,s=r.fontSize,a=r.lineHeight;e.fontSize||(e.fontSize=s,e.calculative.fontSize=e.fontSize*this.store.data.scale),e.lineHeight||(e.lineHeight=a,e.calculative.lineHeight=e.lineHeight),To(i),e.calculative.worldRect=i,oJ(e,i),I0(e),fy(e),e.calculative&&(e.calculative.gradientAnimatePath=void 0),this.store.path2dMap.set(e,mr.path2dDraws[e.name](e)),e.calculative.worldAnchors&&(e.anchors=e.calculative.worldAnchors.map(function(o){return lD(o,e.calculative.worldRect)}))}}},n.prototype.drawingPencil=function(){a_e(this.store),this.pencil=!0,this.externalElements.style.cursor="crosshair"},n.prototype.stopPencil=function(){this.pencil=!1,this.pencilLine=void 0,this.externalElements.style.cursor="default"},n.prototype.finishDrawline=function(e){return Rp(this,void 0,void 0,function(){var t,i,r,s,a,o,c=this;return Ip(this,function(l){switch(l.label){case 0:if(!this.drawingLine)return[2];if(t=xo(this.drawingLine),i=nn(this.drawingLine),i.isTemp&&(this.drawingLine.calculative.worldAnchors.pop(),i=nn(this.drawingLine)),!e&&(!i.connectTo&&this.drawingLine.calculative.worldAnchors.pop(),xo(this.drawingLine)===this.drawingLine.calculative.activeAnchor))return this.drawingLine=void 0,this.render(),[2];if(!t.connectTo||!i.connectTo){if(this.store.options.disableEmptyLine)return t.connectTo&&(this.store.pens[t.connectTo].connectedLines=this.store.pens[t.connectTo].connectedLines.filter(function(h){return h.lineId!==c.drawingLine.id})),this.drawingLine=void 0,this.render(),[2]}else if(this.store.options.disableRepeatLine&&(r=this.store.data.pens.find(function(h){if(h.type){var u=xo(h),d=nn(h);return Ahe(u,t)&&Ahe(d,i)}}),r))return this.drawingLine=void 0,this.render(),[2];return s=g$(this.drawingLine),Object.assign(this.drawingLine,s),this.drawingLine.calculative.worldRect=s,this.drawingLine.calculative.activeAnchor=nn(this.drawingLine),this.store.activeAnchor=this.drawingLine.calculative.activeAnchor,o=!this.beforeAddPens,o?[3,2]:[4,this.beforeAddPens([this.drawingLine])];case 1:o=l.sent(),l.label=2;case 2:return a=o&&(!this.beforeAddPen||this.beforeAddPen(this.drawingLine)),a&&(this.initLineRect(this.drawingLine),this.store.data.pens.push(this.drawingLine),this.store.pens[this.drawingLine.id]=this.drawingLine,this.store.emitter.emit("add",[this.drawingLine]),this.active([this.drawingLine]),this.pushHistory({type:sr.Add,pens:At([this.drawingLine],!0)})),this.store.path2dMap.set(this.drawingLine,mr.path2dDraws[this.drawingLine.name](this.drawingLine)),this.drawingLine=void 0,this.drawingLineName=void 0,this.render(),[2]}})})},n.prototype.finishPencil=function(){return Rp(this,void 0,void 0,function(){var e,t,i,r;return Ip(this,function(s){switch(s.label){case 0:return this.pencilLine?(e=x$(this.pencilLine.calculative.worldAnchors,10,0,this.pencilLine.calculative.worldAnchors.length-1),t=xo(this.pencilLine),e.unshift({id:t.id,penId:t.penId,x:t.x,y:t.y}),t=nn(this.pencilLine),e.push({id:t.id,penId:t.penId,x:t.x,y:t.y}),this.pencilLine.calculative.worldAnchors=BTe(e),this.pencilLine.calculative.worldAnchors.length>1?(this.pencilLine.calculative.pencil=!1,this.store.path2dMap.set(this.pencilLine,mr.path2dDraws[this.pencilLine.name](this.pencilLine)),r=!this.beforeAddPens,r?[3,2]:[4,this.beforeAddPens([this.pencilLine])]):[3,3]):[3,4];case 1:r=s.sent(),s.label=2;case 2:i=r&&(!this.beforeAddPen||this.beforeAddPen(this.pencilLine)),i&&(this.initLineRect(this.pencilLine),this.store.data.pens.push(this.pencilLine),this.store.pens[this.pencilLine.id]=this.pencilLine,this.store.emitter.emit("add",[this.pencilLine]),this.active([this.pencilLine]),this.pushHistory({type:sr.Add,pens:At([this.pencilLine],!0)})),s.label=3;case 3:this.pencilLine=void 0,this.render(),s.label=4;case 4:return[2]}})})},n.prototype.firefoxLoadSvg=function(e){var t=this,i=new Image,r=new XMLHttpRequest;r.open("GET",e.image,!0),r.onload=function(){var s=new DOMParser,a=s.parseFromString(r.responseText,"text/xml"),o=a.getElementsByTagName("svg")[0],c=e.calculative.worldRect,l=c.width,h=c.height;o.setAttribute("width",l+"px"),o.setAttribute("height",h+"px");var u=btoa(unescape(encodeURIComponent(new XMLSerializer().serializeToString(o)))),d="data:image/svg+xml;base64,"+u;i.src=d,i.onload=function(){e.calculative.img=i,e.calculative.imgNaturalWidth=i.naturalWidth||e.iconWidth,e.calculative.imgNaturalHeight=i.naturalHeight||e.iconHeight,mr.htmlElements[e.image]=i,t.imageLoaded(),e.canvasLayer===Ts.CanvasTemplate&&t.templateImageLoaded()}},r.send()},n.prototype.loadImage=function(e){var t=this;if(e.image!==e.calculative.image||!e.calculative.img){if(e.calculative.img=void 0,e.image)if(mr.htmlElements[e.image]){var i=mr.htmlElements[e.image];e.calculative.img=i,e.calculative.imgNaturalWidth=i.naturalWidth||e.iconWidth,e.calculative.imgNaturalHeight=i.naturalHeight||e.iconHeight,this.imageLoaded(),e.canvasLayer===Ts.CanvasTemplate&&this.templateImageLoaded()}else if(navigator.userAgent.includes("Firefox")&&e.image.endsWith(".svg"))this.firefoxLoadSvg(e);else{var r=new Image;r.crossOrigin=e.crossOrigin==="undefined"?void 0:e.crossOrigin||"anonymous",r.src=e.image,this.store.options.cdn&&!(e.image.startsWith("http")||e.image.startsWith("//")||e.image.startsWith("data:image"))&&(r.src=this.store.options.cdn+e.image),r.onload=function(){e.calculative.img=r,e.calculative.imgNaturalWidth=r.naturalWidth||e.iconWidth,e.calculative.imgNaturalHeight=r.naturalHeight||e.iconHeight,mr.htmlElements[e.image]=r,t.imageLoaded(),e.canvasLayer===Ts.CanvasTemplate&&t.templateImageLoaded()}}e.calculative.image=e.image}if(e.backgroundImage!==e.calculative.backgroundImage){if(e.calculative.backgroundImg=void 0,e.backgroundImage)if(mr.htmlElements[e.backgroundImage]){var i=mr.htmlElements[e.backgroundImage];e.calculative.backgroundImg=i}else{var s=new Image;s.crossOrigin="anonymous",s.src=e.backgroundImage,this.store.options.cdn&&!(e.backgroundImage.startsWith("http")||e.backgroundImage.startsWith("//")||e.backgroundImage.startsWith("data:image"))&&(s.src=this.store.options.cdn+e.backgroundImage),s.onload=function(){e.calculative.backgroundImg=s,mr.htmlElements[e.backgroundImage]=s,t.imageLoaded(),e.canvasLayer===Ts.CanvasTemplate&&t.templateImageLoaded()}}e.calculative.backgroundImage=e.backgroundImage}if(e.strokeImage!==e.calculative.strokeImage){if(e.calculative.strokeImg=void 0,e.strokeImage)if(mr.htmlElements[e.strokeImage]){var i=mr.htmlElements[e.strokeImage];e.calculative.strokeImg=i}else{var a=new Image;a.crossOrigin="anonymous",a.src=e.strokeImage,this.store.options.cdn&&!(e.strokeImage.startsWith("http")||e.strokeImage.startsWith("//")||e.strokeImage.startsWith("data:image"))&&(a.src=this.store.options.cdn+e.strokeImage),a.onload=function(){e.calculative.strokeImg=a,mr.htmlElements[e.strokeImage]=a,t.imageLoaded(),e.canvasLayer===Ts.CanvasTemplate&&e.name!=="gif"&&t.templateImageLoaded()}}e.calculative.strokeImage=e.strokeImage}},n.prototype.imageLoaded=function(){var e=this;this.imageTimer&&clearTimeout(this.imageTimer),this.imageTimer=setTimeout(function(){e.canvasImage.init(),e.canvasImageBottom.init(),e.render()},100)},n.prototype.templateImageLoaded=function(){var e=this;this.templateImageTimer&&clearTimeout(this.templateImageTimer),this.templateImageTimer=setTimeout(function(){e.canvasTemplate.init(),e.render()},100)},n.prototype.setCalculativeByScale=function(e){var t=this.store.data.scale;e.calculative.lineWidth=e.lineWidth*t,e.calculative.fontSize=e.fontSize*t,e.fontSize<1&&(e.calculative.fontSize=e.fontSize*e.calculative.worldRect.height),e.calculative.iconSize=e.iconSize*t,e.calculative.iconWidth=e.iconWidth*t,e.calculative.iconHeight=e.iconHeight*t,e.calculative.iconLeft=e.iconLeft<1&&e.iconLeft>-1?e.iconLeft:e.iconLeft*t,e.calculative.iconTop=e.iconTop<1&&e.iconTop>-1?e.iconTop:e.iconTop*t,e.calculative.textWidth=e.textWidth<1&&e.textWidth>-1?e.textWidth:e.textWidth*t,e.calculative.textHeight=e.textHeight<1&&e.textHeight>-1?e.textHeight:e.textHeight*t,e.calculative.textLeft=e.textLeft<1&&e.textLeft>-1?e.textLeft:e.textLeft*t,e.calculative.textTop=e.textTop<1&&e.textTop>-1?e.textTop:e.textTop*t,e.type===Xn.Line&&e.borderWidth&&(e.calculative.borderWidth=e.borderWidth*t)},n.prototype.updatePenRect=function(e,t){var i=this,r=t===void 0?{}:t,s=r.worldRectIsReady,a=r.playingAnimate;s?HV(e):G0e(e),a||this.setCalculativeByScale(e),oD(e),She(this.store.pens,e),I0(e),fy(e),mr.path2dDraws[e.name]&&this.store.path2dMap.set(e,mr.path2dDraws[e.name](e)),e.calculative.patchFlags=!0,this.patchFlags=!0,e.children&&e.children.forEach(function(o){var c=i.store.pens[o];c&&i.updatePenRect(c,{worldRectIsReady:!1})}),e.type&&this.initLineRect(e),e.calculative.gradientTimer&&clearTimeout(e.calculative.gradientTimer),e.calculative.gradientTimer=setTimeout(function(){e.calculative.lineGradient&&(e.calculative.lineGradient=null),e.calculative.gradient&&(e.calculative.gradient=null),e.calculative.radialGradient&&(e.calculative.radialGradient=null),i.patchFlags=!0,e.calculative.gradientTimer=void 0},50)},n.prototype.translate=function(e,t){if(e===void 0&&(e=0),t===void 0&&(t=0),this.store.data.x+=e*this.store.data.scale,this.store.data.y+=t*this.store.data.scale,this.store.data.x=Math.round(this.store.data.x),this.store.data.y=Math.round(this.store.data.y),this.store.options.padding){var i=Em(this.store.options.padding),r=this.store.data.width||this.store.options.width,s=this.store.data.height||this.store.options.height;this.width<(r+i[1]+i[3])*this.store.data.scale&&(this.store.data.x+this.store.data.origin.x>i[3]*this.store.data.scale&&(this.store.data.x=i[3]*this.store.data.scale-this.store.data.origin.x),this.store.data.x+this.store.data.origin.x+r*this.store.data.scalei[0]*this.store.data.scale&&(this.store.data.y=i[0]*this.store.data.scale-this.store.data.origin.y),this.store.data.y+this.store.data.origin.y+s*this.store.data.scale=s&&e<=a){this.calibrateMouse(t);var o=e/this.store.data.scale;this.store.data.scale=e,this.store.data.center=t,!((r=this.store.clipboard)===null||r===void 0)&&r.pos&&Az(this.store.clipboard.pos,o,t),Az(this.store.data.origin,o,t),this.store.data.pens.forEach(function(l){if(!l.parentId){if(hS(l,o,t),l.onScale&&l.onScale(l),l.isRuleLine){var h=1/o,u=l.calculative.worldRect.center;l.width&&l.height||hS(l,h,u)}i.updatePenRect(l,{worldRectIsReady:!0}),i.execPenResize(l)}}),this.onMovePens(),this.calcActiveRect(),this.canvasTemplate.init(),this.canvasImage.init(),this.canvasImageBottom.init();var c=this.parent.map;c&&c.isShow&&c.setView(),this.render(),this.store.emitter.emit("scale",this.store.data.scale)}},n.prototype.templateScale=function(e,t){var i=this;t===void 0&&(t={x:0,y:0});var r=this.store.options,s=r.minScale,a=r.maxScale;if(e>=s&&e<=a){var o=e/this.store.data.scale;this.store.data.scale=e,this.store.data.center={x:0,y:0},this.store.data.origin={x:0,y:0},this.store.data.pens.forEach(function(c){if(!c.parentId){if(hS(c,o,t),c.onScale&&c.onScale(c),c.isRuleLine){var l=o>1?1:1/o/o,h=c.calculative.worldRect.center;c.width&&c.height||hS(c,l,h)}i.execPenResize(c)}}),this.calcActiveRect()}},n.prototype.rotatePens=function(e){var t,i,r=this;this.initPens||(this.initPens=At(this.getAllByPens(this.store.active))),this.activeRect.rotate=Rf(e,this.activeRect.center),this.activeRect.rotate%90<10&&(this.activeRect.rotate-=this.activeRect.rotate%90),this.activeRect.rotate%90>80&&(this.activeRect.rotate+=90-this.activeRect.rotate%90),this.store.active.length===1&&(this.lastRotate=this.store.active[0].rotate||0);var s=this.activeRect.rotate-this.lastRotate;try{for(var a=Za(this.store.active),o=a.next();!o.done;o=a.next()){var c=o.value;if(c.parentId)return;this.rotatePen(c,s,this.activeRect),c.onRotate&&c.onRotate(c),this.updateLines(c)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(t)throw t.error}}this.lastRotate=this.activeRect.rotate,this.getSizeCPs(),this.initImageCanvas(this.store.active),this.initTemplateCanvas(this.store.active),this.render(),this.store.emitter.emit("rotatePens",this.store.active),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(function(){r.timer=void 0,r.pushHistory({type:sr.Update,pens:At(r.getAllByPens(r.store.active)),initPens:r.initPens}),r.initPens=void 0},200)},n.prototype.resizePens=function(e){var t=this;if(this.initPens||(this.initPens=At(this.store.active,!0)),!this.initActiveRect){this.initActiveRect=At(this.activeRect);return}var i={x:this.mouseDown.x,y:this.mouseDown.y},r={x:e.x,y:e.y},s=r.x-i.x,a=r.y-i.y,o=At(this.initActiveRect);if(Bhe(o,s,a,this.resizeIndex),To(o),!this.store.options.disableDock){this.clearDock();var c=this.customResizeDock||IEe;this.dock=c(this.store,o,this.store.active,this.resizeIndex);var l=this.dock,h=l.xDock,u=l.yDock;if(h){s+=h.step;var d=this.store.pens[h.penId];d.calculative.isDock=!0}if(u){a+=u.step;var d=this.store.pens[u.penId];d.calculative.isDock=!0}}var f=this.activeRect.width,p=this.activeRect.height,_=s-this.lastOffsetX,m=a-this.lastOffsetY;if(this.lastOffsetX=s,this.lastOffsetY=a,e.ctrlKey||this.initPens.length===1&&this.initPens[0].ratio){var g=[1,3].includes(this.resizeIndex)?-1:1;m=g*(_*p)/f}if(this.activeRect.ratio=this.initPens[0].ratio,Bhe(this.activeRect,_,m,this.resizeIndex),this.store.options.strictScope){var v=this.store.data.width||this.store.options.width,x=this.store.data.height||this.store.options.height;if(v&&x){var y={x:this.store.data.origin.x,y:this.store.data.origin.y,width:v*this.store.data.scale,height:x*this.store.data.scale};this.activeRect.xy.x+y.width&&(this.activeRect.width=this.activeRect.width-(this.activeRect.x+this.activeRect.width-(y.x+y.width)),this.activeRect.x=y.x+y.width-this.activeRect.width,this.activeRect.ex=this.activeRect.x+this.activeRect.width),this.activeRect.y+this.activeRect.height>y.y+y.height&&(this.activeRect.height=this.activeRect.height-(this.activeRect.y+this.activeRect.height-(y.y+y.height)),this.activeRect.y=y.y+y.height-this.activeRect.height,this.activeRect.ey=this.activeRect.y+this.activeRect.height)}}To(this.activeRect);var C=this.activeRect.width/f,b=this.activeRect.height/p;this.store.active.forEach(function(T,S){T.calculative.worldRect.x=t.activeInitPos[S].x*t.activeRect.width+t.activeRect.x,T.calculative.worldRect.y=t.activeInitPos[S].y*t.activeRect.height+t.activeRect.y,T.calculative.worldRect.width*=C,T.calculative.iconWidth&&(T.calculative.iconWidth*=C),T.calculative.worldRect.height*=b,T.calculative.iconHeight&&(T.calculative.iconHeight*=b),Mo(T.calculative.worldRect),To(T.calculative.worldRect),t.updatePenRect(T,{worldRectIsReady:!0}),t.execPenResize(T),t.updateLines(T)}),this.getSizeCPs(),this.initImageCanvas(this.store.active),this.initTemplateCanvas(this.store.active),this.render(),this.store.emitter.emit("resizePens",this.store.active),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(function(){t.timer=void 0,t.pushHistory({type:sr.Update,pens:At(t.store.active,!0),initPens:t.initPens}),t.initPens=void 0},200)},n.prototype.movePens=function(e){var t,i;if(!(!this.activeRect||this.store.data.locked)){if(!this.initActiveRect){this.initActiveRect=At(this.activeRect);return}if(!(!this.store.options.moveConnectedLine&&!this.canMoveLine&&this.store.active.length===1&&(!((t=this.store.active[0].anchors[0])===null||t===void 0)&&t.connectTo||!((i=this.store.active[0].anchors[this.store.active[0].anchors.length-1])===null||i===void 0)&&i.connectTo))&&(this.movingPens||(this.initMovingPens(),this.store.active.forEach(function(g){Xw(g,!1)}),this.store.hover=void 0),!!this.mouseDown)){var r=e.x-this.mouseDown.x,s=e.y-this.mouseDown.y;e.shiftKey&&!e.ctrlKey&&(s=0),e.ctrlKey&&(r=0);var a=At(this.initActiveRect);vy(a,r,s);var o=!1;if(this.store.options.strictScope){var c=this.store.data.width||this.store.options.width,l=this.store.data.height||this.store.options.height;if(c&&l){var h={x:this.store.data.origin.x,y:this.store.data.origin.y,width:c*this.store.data.scale,height:l*this.store.data.scale};a.xh.x+h.width&&(a.x=h.x+h.width-a.width,o=!0),a.y+a.height>h.y+h.height&&(a.y=h.y+h.height-a.height,o=!0)}}var u={x:a.x-this.activeRect.x,y:a.y-this.activeRect.y};if(!this.store.options.disableDock&&!o){this.clearDock();var d=this.customMoveDock||REe;this.dock=d(this.store,a,this.movingPens,u);var f=this.dock,p=f.xDock,_=f.yDock,m=void 0;p&&(u.x+=p.step,m=this.store.pens[p.penId],m.calculative.isDock=!0),_&&(u.y+=_.step,m=this.store.pens[_.penId],m.calculative.isDock=!0)}this.translatePens(this.movingPens,u.x,u.y,!0)}}},n.prototype.changeIdsByMoving=function(e,t){e.id+=p0,e.parentId&&t.find(function(i){return i.id===e.parentId})&&(e.parentId+=p0),e.children&&(e.children=e.children.map(function(i){return i+p0})),e.connectedLines&&(e.connectedLines=e.connectedLines.map(function(i){return t.find(function(r){return r.id===i.lineId})&&(i.lineId+=p0),i})),e.type&&e.calculative.worldAnchors&&(e.calculative.worldAnchors=e.calculative.worldAnchors.map(function(i){return i.connectTo&&t.find(function(r){return r.id===i.connectTo})&&(i.connectTo+=p0),i}))},n.prototype.initMovingPens=function(){var e=this,t,i;if(!this.store.options.moveConnectedLine&&!this.canMoveLine)for(var r=0;r0&&h.forEach(function(v){var x=i.store.pens[v.lineId];LS(i.store.pens[i.store.activeAnchor.penId],i.store.activeAnchor,x,oy(x,v.lineAnchor))});var u=this.store.active[0];xo(u);var d=nn(u);if(u.lineName==="polyline"&&!t.shiftKey)NTe(u,this.store.activeAnchor,e);else{var f=0,p=0;if(u.lineName==="line"){var _=u.calculative.worldAnchors.findIndex(function(v){return v.id===i.store.activeAnchor.id});_===0&&(_=2);var m=u.calculative.worldAnchors[_-1];if(t.ctrlKey&&t.shiftKey){var g=At(e);this.getSpecialAngle(g,m),f=g.x-this.store.activeAnchor.x,p=g.y-this.store.activeAnchor.y}else if(!t.ctrlKey&&t.shiftKey){var g={x:e.x,y:m.y};f=g.x-this.store.activeAnchor.x,p=g.y-this.store.activeAnchor.y}else if(t.ctrlKey&&!t.shiftKey){var g={x:m.x,y:e.y};f=g.x-this.store.activeAnchor.x,p=g.y-this.store.activeAnchor.y}else f=e.x-this.store.activeAnchor.x,p=e.y-this.store.activeAnchor.y}else f=e.x-this.store.activeAnchor.x,p=e.y-this.store.activeAnchor.y;nD(this.store.activeAnchor,f,p),this.store.hover&&this.store.hoverAnchor&&this.store.hoverAnchor.penId!==this.store.activeAnchor.penId&&(this.store.hoverAnchor.type===fm.Line?(f=e.x-this.store.activeAnchor.x,p=e.y-this.store.activeAnchor.y,tV(this.store.activeAnchor,this.store.hoverAnchor,this.store)):(f=this.store.hoverAnchor.x-this.store.activeAnchor.x,p=this.store.hoverAnchor.y-this.store.activeAnchor.y),nD(this.store.activeAnchor,f,p),d.prev=void 0,u.lineName!=="polyline"&&((o=this[u.lineName])===null||o===void 0||o.call(this,this.store,u)))}this.patchFlagsLines.add(u),this.store.path2dMap.set(u,mr.path2dDraws[u.name](u)),this.render(),this.store.active[0].calculative&&(this.store.active[0].calculative.gradientAnimatePath=void 0),this.store.emitter.emit("moveLineAnchor",{pen:this.store.active[0],anchor:this.store.activeAnchor}),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(function(){i.timer=void 0,i.pushHistory({type:sr.Update,pens:At(i.store.active,!0),initPens:i.initPens}),i.initPens=void 0},500)}},n.prototype.moveLineAnchorPrev=function(e){var t=this;if(!(!this.activeRect||this.store.data.locked||!this.store.activeAnchor)){if(this.initPens||(this.initPens=At(this.store.active,!0)),this.store.activeAnchor.prev.x=e.x,this.store.activeAnchor.prev.y=e.y,this.store.activeAnchor.next){if(!this.store.activeAnchor.prevNextType)this.store.activeAnchor.next.x=e.x,this.store.activeAnchor.next.y=e.y,Yn(this.store.activeAnchor.next,180,this.store.activeAnchor);else if(this.store.activeAnchor.prevNextType===wy.Bilateral&&this.prevAnchor){var i=Rf(e,this.store.activeAnchor),r=Rf(this.prevAnchor,this.store.activeAnchor);this.store.activeAnchor.next.x=this.nextAnchor.x,this.store.activeAnchor.next.y=this.nextAnchor.y,Yn(this.store.activeAnchor.next,i-r,this.store.activeAnchor)}}var s=this.store.active[0];this.patchFlagsLines.add(s),this.store.path2dMap.set(s,mr.path2dDraws[s.name](s)),this.render(),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(function(){t.timer=void 0,t.pushHistory({type:sr.Update,pens:At(t.store.active,!0),initPens:t.initPens}),t.initPens=void 0},200)}},n.prototype.moveLineAnchorNext=function(e){var t=this;if(!(!this.activeRect||this.store.data.locked||!this.store.activeAnchor)){if(this.initPens||(this.initPens=At(this.store.active,!0)),this.store.activeAnchor.next.x=e.x,this.store.activeAnchor.next.y=e.y,this.store.activeAnchor.prev){if(!this.store.activeAnchor.prevNextType)this.store.activeAnchor.prev.x=e.x,this.store.activeAnchor.prev.y=e.y,Yn(this.store.activeAnchor.prev,180,this.store.activeAnchor);else if(this.store.activeAnchor.prevNextType===wy.Bilateral&&this.nextAnchor){var i=Rf(e,this.store.activeAnchor),r=Rf(this.nextAnchor,this.store.activeAnchor);this.store.activeAnchor.prev.x=this.prevAnchor.x,this.store.activeAnchor.prev.y=this.prevAnchor.y,Yn(this.store.activeAnchor.prev,i-r,this.store.activeAnchor)}}var s=this.store.active[0];this.patchFlagsLines.add(s),this.store.path2dMap.set(s,mr.path2dDraws[s.name](s)),this.render(),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(function(){t.timer=void 0,t.pushHistory({type:sr.Update,pens:At(t.store.active,!0),initPens:t.initPens}),t.initPens=void 0},200)}},n.prototype.setAnchor=function(e){var t;return Rp(this,void 0,void 0,function(){var i,r,s,a,o,o;return Ip(this,function(c){switch(c.label){case 0:return i=[At(this.store.hover,!0)],r=this.store.hover,this.store.hoverAnchor?(s=this.beforeRemoveAnchor,s?[4,this.beforeRemoveAnchor(r,this.store.hoverAnchor)]:[3,2]):[3,3];case 1:s=!c.sent(),c.label=2;case 2:return s?[2]:(r.type===Xn.Line&&((t=r.calculative.worldAnchors)===null||t===void 0?void 0:t.length)<=2?this.delete([r]):(CEe(r,this.store.hoverAnchor),r.type===Xn.Line&&this.initLineRect(r)),this.store.hoverAnchor=void 0,this.store.activeAnchor=void 0,this.externalElements.style.cursor="default",[3,6]);case 3:return r?(a=this.beforeAddAnchor,a?[4,this.beforeAddAnchor(r,this.store.pointAt)]:[3,5]):[3,6];case 4:a=!c.sent(),c.label=5;case 5:if(a)return[2];r.type===Xn.Line?(this.store.activeAnchor=AEe(r,this.store.pointAt,this.store.pointAtIndex),this.initLineRect(r),o={x:e.x,y:e.y},this.getHover(o)):(o={id:ns(),x:e.x,y:e.y},this.store.activeAnchor=yEe(r,o)),c.label=6;case 6:return this.hotkeyType=un.None,this.render(),r&&this.pushHistory({type:sr.Update,pens:[At(r,!0)],initPens:i}),[2]}})})},n.prototype.checkDisconnect=function(e,t){var i=this;if(e.id.indexOf(p0)>0){var r=e.id;e=this.store.pens[r.replace(p0,"")]}e.anchors.forEach(function(s){if(s.connectTo&&!t.find(function(o){return o.id===s.connectTo||o.id===s.connectTo+p0})){var a=i.store.pens[s.connectTo];if(!a||a.type)return;LS(a,oy(a,s.anchorId),e,s)}})},n.prototype.translatePens=function(e,t,i,r){var s=this;if(e===void 0&&(e=this.store.active),!(!e||!e.length)){var a=e.some(function(l){if(l.locked>=js.DisableMove)return!0});if(!a){var o=!r&&At(e,!0);this.activeRect&&vy(this.activeRect,t,i);var c=this.getAllByPens(e);e.forEach(function(l){var h,u;if(!(l.locked>=js.DisableMove)){if(l.type===Xn.Line){if(!s.store.options.moveConnectedLine&&!s.canMoveLine)return;Mhe(l,t,i),s.checkDisconnect(l,c),s.store.path2dMap.set(l,mr.path2dDraws[l.name](l)),r||(s.initLineRect(l),(h=l.connectedLines)===null||h===void 0||h.forEach(function(d){var f=s.store.pens[d.lineId];s.initLineRect(f)}))}else vy(l.calculative.worldRect,t,i),s.updatePenRect(l,{worldRectIsReady:!0}),l.calculative.x=l.x,l.calculative.y=l.y,l.calculative.initRect&&(l.calculative.initRect.x=l.calculative.x,l.calculative.initRect.y=l.calculative.y,l.calculative.initRect.ex=l.calculative.x+l.calculative.width,l.calculative.initRect.ey=l.calculative.y+l.calculative.height);s.updateLines(l),(u=l.onMove)===null||u===void 0||u.call(l,l)}}),this.activeRect&&this.getSizeCPs(),this.render(),this.tooltip.translate(t,i),r||(this.pushHistory({type:sr.Update,pens:At(e,!0),initPens:o}),this.initImageCanvas(e),this.initTemplateCanvas(e),this.store.emitter.emit("translatePens",e)),this.store.emitter.emit("translatingPens",e)}}},n.prototype.templateTranslatePens=function(e,t,i){var r=this;if(e===void 0&&(e=this.store.active),!(!e||!e.length)){var s=this.getAllByPens(e);e.forEach(function(a){var o;if(a.type===Xn.Line){if(!r.store.options.moveConnectedLine&&!r.canMoveLine)return;Mhe(a,t,i),r.checkDisconnect(a,s),r.store.path2dMap.set(a,mr.path2dDraws[a.name](a))}else vy(a.calculative.worldRect,t,i),r.updatePenRect(a,{worldRectIsReady:!0}),a.calculative.x=a.x,a.calculative.y=a.y,a.calculative.initRect&&(a.calculative.initRect.x=a.calculative.x,a.calculative.initRect.y=a.calculative.y,a.calculative.initRect.ex=a.calculative.x+a.calculative.width,a.calculative.initRect.ey=a.calculative.y+a.calculative.height);(o=a.onMove)===null||o===void 0||o.call(a,a)})}},n.prototype.calcAutoAnchor=function(e,t,i,r){var s=xo(e),a=nn(e),o=OS(i,t===s?a:s);o&&(t.x=o.x,t.y=o.y,t.prev=void 0,t.next=void 0,r?r.anchor=o.id:sc(i,o,e,t),this[e.lineName]&&this[e.lineName](this.store,e),this.store.path2dMap.set(e,mr.path2dDraws.line(e)),this.initLineRect(e))},n.prototype.restoreNodeAnimate=function(e){var t,i;if(e.calculative.initRect){if(e.keepAnimateState)for(var r in e)e.calculative[r]!==void 0&&r!=="x"&&r!=="y"&&r!=="width"&&r!=="height"&&r!=="initRect"&&(typeof e[r]!="object"||r==="lineDash")&&(r==="fontSize"||r==="lineWidth"?e[r]=e.calculative[r]/e.calculative.canvas.store.data.scale:e[r]=e.calculative[r]);else{var s=e.calculative.initRect.rotate-e.calculative.rotate;for(var r in e)r!=="x"&&r!=="y"&&r!=="width"&&r!=="height"&&r!=="initRect"&&r!=="rotate"&&(typeof e[r]!="object"||r==="lineDash")&&(e.calculative[r]=e[r]);!((t=e.children)===null||t===void 0)&&t.length?s&&K0e(e,s,e.calculative.worldRect):e.calculative.rotate=e.rotate;var a=At(this.store.animateMap.get(e));a&&(a.id=e.id,this.parent.setValue(a,{doEvent:!1,render:!0,history:!1})),e.calculative.worldRect=e.calculative.initRect}this.updatePenRect(e,{worldRectIsReady:!0}),this.updateLines(e),e.calculative.text!==e.text&&(e.calculative.text=e.text,M5(e)),!((i=this.store.active)===null||i===void 0)&&i.length&&this.calcActiveRect(),e.calculative.initRect=void 0}},n.prototype.updateLines=function(e,t){var i=this,r;(r=e.children)===null||r===void 0||r.forEach(function(s){var a=i.store.pens[s];a&&i.updateLines(a,t)}),e.connectedLines&&e.connectedLines.forEach(function(s){var a=i.store.pens[s.lineId];if(!(!a||a.calculative.active)){var o=oy(a,s.lineAnchor);if(o){if(a.autoFrom){var c=xo(a);c.id===o.id&&i.calcAutoAnchor(a,c,e,s)}if(a.autoTo){var l=nn(a);l.id===o.id&&i.calcAutoAnchor(a,l,e,s)}var h=oy(e,s.anchor);if(h){var u=e.rotate;e.flipX&&(u*=-1),e.flipY&&(u*=-1);var d=o.distance*i.store.data.scale*Math.cos((u+h.rotate)/180*Math.PI)||0,f=o.distance*i.store.data.scale*Math.sin((u+h.rotate)/180*Math.PI)||0;if(e.flipX&&(d=-d),e.flipY&&(f=-f),nD(o,h.x-o.x+d,h.y-o.y+f),i.store.options.autoPolyline&&!i.autoPolylineFlag&&a.autoPolyline!==!1&&a.lineName==="polyline"){var c=xo(a),l=nn(a),p=!1;c.id===o.id?(c=o,p=!0):l.id===o.id&&(l=o,p=!0),p&&(a.calculative.worldAnchors=[c,l],a.calculative.activeAnchor=c,i.polyline(i.store,a,l),i.initLineRect(a))}i.store.path2dMap.set(a,mr.path2dDraws[a.name](a)),i.patchFlagsLines.add(a),a.calculative.gradientSmooth&&(a.calculative.gradientAnimatePath=nJ(a)),t&&v$(a)}}}})},n.prototype.calcActiveRect=function(){var e=this.store.active.filter(function(t){return(!t.locked||t.locked-1})),i&&(i.forEach(function(r){var s,a,o,c,l;if(r.calculative.pause){var h=Date.now()-r.calculative.pause;r.calculative.pause=void 0,r.calculative.frameStart+=h,r.calculative.frameEnd+=h}else if(r.name==="video")r.calculative.media.currentTime=0,(s=r.calculative.media)===null||s===void 0||s.play(),(a=r.onStartVideo)===null||a===void 0||a.call(r,r);else if(r.type||!((o=r.frames)===null||o===void 0)&&o.length||r.animations&&r.animations.length){if(r.type){if(!((l=r.animations)===null||l===void 0)&&l.length){var f=At(r.animations[0]);delete f.name,f.currentAnimation=0,t.parent.setValue(ch({id:r.id},f),{doEvent:!1,history:!1})}}else{if(!r.frames&&r.animations&&r.animations.length){var u=(c=r.animations)===null||c===void 0?void 0:c.findIndex(function(p){return p.autoPlay}),d=u===-1?0:u,f=At(r.animations[d]);delete f.name,f.currentAnimation=d,!r.type&&f.frames&&(f.showDuration=t.parent.calcAnimateDuration(f)),t.parent.setValue(ch({id:r.id},f),{doEvent:!1,history:!1})}t.store.animateMap.set(r,t.getFrameProps(r))}t.store.animates.add(r)}}),this.animate())}},n.prototype.getFrameProps=function(e){var t={};return e.frames&&e.frames.forEach(function(i){for(var r in i)!["duration","x","y","width","height","rotate"].includes(r)&&!t[r]&&(t[r]=e[r])}),t},n.prototype.animate=function(){var e=this;this.animateRendering||requestAnimationFrame(function(){var t,i,r=Date.now();if(r-e.lastAnimateRender0&&e.animate();return}e.lastAnimateRender=r,e.animateRendering=!0;var s=[],a=!1,o=function(u){if(u.calculative.pause)return"continue";if(u.calculative.active&&!u.type&&!e.movingPens&&(a=!0),!u.type)bEe(u,r)?u.calculative.patchFlags&&(To(u.calculative.worldRect),e.updatePenRect(u,{worldRectIsReady:!0,playingAnimate:!0})):(requestAnimationFrame(function(){e.restoreNodeAnimate(u)}),s.push(u),e.nextAnimate(u)),e.updateLines(u,!0);else if(!TEe(u)){if(u.keepAnimateState){for(var d in u)u.calculative[d]!==void 0&&d!=="length"&&(typeof u[d]!="object"||d==="lineDash")&&(d==="lineWidth"?u[d]=u.calculative[d]/u.calculative.canvas.store.data.scale:u[d]=u.calculative[d]);HV(u)}else for(var d in u)(typeof u[d]!="object"||d==="lineDash")&&(d==="lineWidth"?u.calculative[d]=u[d]*u.calculative.canvas.store.data.scale:u.calculative[d]=u[d]);s.push(u),e.nextAnimate(u)}e.patchFlags=!0};try{for(var c=Za(e.store.animates),l=c.next();!l.done;l=c.next()){var h=l.value;o(h)}}catch(u){t={error:u}}finally{try{l&&!l.done&&(i=c.return)&&i.call(c)}finally{if(t)throw t.error}}a&&e.calcActiveRect(),s.forEach(function(u){e.store.animates.delete(u)}),e.render(!1),e.animateRendering=!1,e.animate()})},Object.defineProperty(n.prototype,"clipboardName",{get:function(){return"meta2d-clipboard"},enumerable:!1,configurable:!0}),n.prototype.copy=function(e,t){return t===void 0&&(t=!0),Rp(this,void 0,void 0,function(){var i,r,s,a,o,c,l=this;return Ip(this,function(h){switch(h.label){case 0:if(i=ns(),r=this.store.data,s=r.origin,a=r.scale,this.store.clipboard=void 0,localStorage.removeItem(this.clipboardName),sessionStorage.setItem("page",i),o=this.getAllByPens(At(e||this.store.active,!0)),o.forEach(function(u){u.copyIndex=l.store.data.pens.findIndex(function(d){return d.id===u.id})}),o.sort(function(u,d){return u.copyIndex-d.copyIndex}),o.forEach(function(u){delete u.copyIndex}),c={meta2d:!0,pens:o,origin:At(s),scale:a,page:i,initRect:At(this.activeRect),offset:10},!(navigator.clipboard&&!this.store.options.disableClipboard&&!navigator.userAgent.includes("Firefox")))return[3,5];h.label=1;case 1:return h.trys.push([1,3,,4]),[4,navigator.clipboard.writeText(JSON.stringify(c))];case 2:return h.sent(),[3,4];case 3:return h.sent(),localStorage.setItem(this.clipboardName,JSON.stringify(c)),[3,4];case 4:return[3,6];case 5:localStorage.setItem(this.clipboardName,JSON.stringify(c)),h.label=6;case 6:return t&&this.store.emitter.emit("copy",c.pens),[2]}})})},n.prototype.cut=function(e){this.copy(e,!1),this.delete(e),this.store.emitter.emit("cut",e)},n.prototype.paste=function(){var e;return Rp(this,void 0,void 0,function(){var t,i,r,s,a,o,c,l,h,u,d,f;return Ip(this,function(p){switch(p.label){case 0:if(!(navigator.clipboard&&!this.store.options.disableClipboard&&!navigator.userAgent.includes("Firefox")))return[3,5];p.label=1;case 1:return p.trys.push([1,3,,4]),[4,(e=navigator.clipboard)===null||e===void 0?void 0:e.readText()];case 2:return t=p.sent(),[3,4];case 3:return p.sent(),t=localStorage.getItem(this.clipboardName),[3,4];case 4:return[3,6];case 5:t=localStorage.getItem(this.clipboardName),p.label=6;case 6:if(t){try{i=JSON.parse(t)}catch(_){return console.warn("剪切板数据不是json",_.message),[2]}if(!i||!i.meta2d)return[2]}else return[2];return r=this.beforeAddPens,r?[4,this.beforeAddPens(i.pens)]:[3,8];case 7:r=p.sent()!=!0,p.label=8;case 8:if(r)return[2];this.store.clipboard&&(s=this.store.clipboard.offset+10,a=this.store.clipboard.pos),this.store.clipboard=At(i),o=sessionStorage.getItem("page"),o!==i.page?(this.store.clipboard.pos={x:this.mousePos.x,y:this.mousePos.y},this.store.clipboard.offset=0):this.pasteOffset?(s&&(this.store.clipboard.offset=s),a&&(this.store.clipboard.pos=a)):(this.store.clipboard.offset=0,this.pasteOffset=!0),c=this.store.clipboard.pens.filter(function(_){return!_.parentId});try{for(l=Za(c),h=l.next();!h.done;h=l.next())u=h.value,this.pastePen(u,void 0)}catch(_){d={error:_}}finally{try{h&&!h.done&&(f=l.return)&&f.call(l)}finally{if(d)throw d.error}}return sessionStorage.setItem("page",i.page),this.active(c),this.pushHistory({type:sr.Add,pens:this.store.clipboard.pens}),this.render(),this.store.emitter.emit("add",this.store.clipboard.pens),this.store.emitter.emit("paste",this.store.clipboard.pens),[2]}})})},n.prototype.getAllByPens=function(e){var t,i,r=[];try{for(var s=Za(e),a=s.next();!a.done;a=s.next()){var o=a.value;r.push.apply(r,f0([],d0(At(dy(o,this.store),!0)),!1))}}catch(c){t={error:c}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(t)throw t.error}}return r.concat(e)},n.prototype.changeLineAnchors=function(e,t,i){if(Array.isArray(t.connectedLines))for(var r=function(o){var c=t.connectedLines[o].lineId,l=i.find(function(d){return d.id===c});if(l){var h=l.anchors[0],u=l.anchors[l.anchors.length-1];h.connectTo===e&&(h.connectTo=t.id),u.connectTo===e&&(u.connectTo=t.id)}else t.connectedLines.splice(o,1),o--;s=o},s,a=0;a-1){var s=this.store.pens[e.id];s.calculative.active=void 0,t.push(s)}e.children&&e.children.forEach(function(a){i.getDelPens(i.store.pens[a],t)})}},n.prototype.getLockedParent=function(e){if(!e.parentId)return!1;var t=xd(e);if(t.locked)return t;this.getLockedParent(t)},n.prototype.delForce=function(e){var t=this,i;if(e){var r=this.store.data.pens.findIndex(function(s){return s.id===e.id});r>-1&&(this.delConnectedLines(this.store.data.pens[r]),this.store.data.pens.splice(r,1),this.store.pens[e.id]=void 0,delete this.store.pens[e.id]),this.store.animates.delete(e),this.store.animateMap.delete(e),e.children&&e.children.forEach(function(s){t.delForce(t.store.pens[s])}),(i=e.onDestroy)===null||i===void 0||i.call(e,e)}},n.prototype.delConnectedLines=function(e){var t=this,i;if(e.connectedLines)for(var r=function(o){var c=e.connectedLines[o],l=c.lineId,h=c.lineAnchor,u=s.store.pens[l];if(u){var d=u.anchors.find(function(f){return f.id===h});(d==null?void 0:d.connectTo)===e.id&&(d.connectTo=void 0,d.anchorId=void 0,d.prev&&(d.prev.connectTo=void 0),d.next&&(d.next.connectTo=void 0)),d=oy(u,h),d&&(d.connectTo=void 0,d.anchorId=void 0,d.prev&&(d.prev.connectTo=void 0),d.next&&(d.next.connectTo=void 0))}},s=this,a=0;a",nbsp:" ",amp:"&",quot:'"'};return e.replace(/&(lt|gt|nbsp|amp|quot);/gi,function(i,r){return t[r]})},n.prototype.createInput=function(){var e=this;this.inputParent.classList.add("meta2d-input"),this.inputRight.classList.add("right"),this.inputDiv.classList.add("input-div"),this.inputParent.appendChild(this.inputDiv),this.inputParent.appendChild(this.inputRight),this.dropdown.onmouseleave=function(){e.store.hover=null},this.inputParent.appendChild(this.dropdown),this.externalElements.appendChild(this.inputParent),this.inputParent.onmousedown=this.stopPropagation,this.inputDiv.onmousedown=this.stopPropagation,this.inputDiv.contentEditable="false",this.inputRight.onmousedown=this.stopPropagation,this.dropdown.onmousedown=this.stopPropagation,this.inputRight.style.transform="rotate(135deg)";for(var t,i=0;i'}}else if(s.target.innerText)e.inputDiv.style.paddingTop="";else{var o=window.getComputedStyle(e.inputDiv,null);o.justifyContent==="center"&&(e.inputDiv.style.paddingTop=" "+(e.inputDiv.offsetHeight/2-parseFloat(o.lineHeight)/2)+"px")}},this.inputDiv.oninput=function(s){if(navigator.userAgent.includes("Firefox")){if(!s.target.innerText.trim()){var a=e.inputDiv.offsetWidth/2,o=window.getComputedStyle(e.inputDiv,null);o.textAlign!=="center"&&(a=0),e.inputDiv.innerHTML='
'}}else if(s.target.innerText)e.inputDiv.style.paddingTop="";else{var o=window.getComputedStyle(e.inputDiv,null);o.justifyContent==="center"&&(e.inputDiv.style.paddingTop=" "+(e.inputDiv.offsetHeight/2-parseFloat(o.lineHeight)/2)+"px")}},this.inputDiv.onclick=function(s){s.stopPropagation();var a=e.store.pens[e.inputDiv.dataset.penId];e.dropdown.style.display==="block"?(e.dropdown.style.display="none",e.inputRight.style.transform="rotate(135deg)"):a!=null&&a.dropdownList&&e.store.data.locked&&(e.dropdown.style.display="block",e.inputRight.style.transform="rotate(315deg)"),e.store.emitter.emit("clickInput",a)},this.inputDiv.onkeyup=function(s){e.setDropdownList(!0);var a=e.store.pens[e.inputDiv.dataset.penId];e.store.emitter.emit("input",{pen:a,text:s.key}),s.stopPropagation()},this.inputDiv.onkeydown=function(s){s.stopPropagation()},this.inputDiv.onmousedown=this.stopPropagation,this.inputDiv.onwheel=function(s){s.stopPropagation()},this.inputDiv.onpaste=function(s){s.preventDefault();var a="";s.clipboardData&&s.clipboardData.getData&&(a=s.clipboardData.getData("text/plain")),document.execCommand("insertHTML",!1,a)}},n.prototype.clearDropdownList=function(){if(this.dropdown.hasChildNodes())for(var e=0;e-1})},n.prototype.findOne=function(e){return this.store.data.pens.find(function(t){return t.id==e||t.tags&&t.tags.indexOf(e)>-1})},n.prototype.changePenId=function(e,t){var i=this,r,s,a,o,c;if(e!==t){var l=this.store.pens[e];if(l&&!this.store.pens[t]){if(l.id=t,this.store.pens[t]=this.store.pens[e],(r=l.onChangeId)===null||r===void 0||r.call(l,l,e,t),delete this.store.pens[e],l.parentId){var h=this.store.pens[l.parentId],u=(s=h.children)===null||s===void 0?void 0:s.findIndex(function(d){return d===e});u!==-1&&((a=h.children)===null||a===void 0||a.splice(u,1,t))}(o=l.children)===null||o===void 0||o.forEach(function(d){var f=i.store.pens[d];f.parentId=t}),l.type===Xn.Line?this.changeNodeConnectedLine(e,l,this.store.data.pens):(this.changeLineAnchors(e,l,this.store.data.pens),(c=l.connectedLines)===null||c===void 0||c.forEach(function(d){var f=d.lineId,p=i.store.pens[f];oD(p)}))}}},n.prototype.updateValue=function(e,t){var i,r,s,a,o,c=this.getPenRect(e),l=e.name;Object.assign(e,t);var h=l!==e.name;t.newId&&this.changePenId(e.id,t.newId);var u=!1,d=!1,f=!1,p=!1,_=!1,m=!1,g=void 0,v=!1;for(var x in t)x.indexOf(".")===-1?(x==="rotate"?g=e.calculative.rotate||0:x==="canvasLayer"||x==="isBottom"?m=!0:x==="image"&&(v=!0),(typeof e[x]!="object"||x==="lineDash")&&(e.calculative[x]=t[x]),cbe.includes(x)&&(d=!0),["name","borderRadius","lineSmooth"].includes(x)&&(u=!0),hbe.includes(x)&&(_=!0),ube.includes(x)&&(f=!0),dbe.includes(x)&&(p=!0)):(delete e[x],Qbe(e,x,t[x])),x.split(".")[0]==="anchors"&&oD(e);if(this.setCalculativeByScale(e),h&&((i=e.onDestroy)===null||i===void 0||i.call(e,e),pbe(e)),_){var y={x:(r=t.x)!==null&&r!==void 0?r:c.x,y:(s=t.y)!==null&&s!==void 0?s:c.y,width:(a=t.width)!==null&&a!==void 0?a:c.width,height:(o=t.height)!==null&&o!==void 0?o:c.height};this.setPenRect(e,y,!1),this.updateLines(e,!0),this.store.active&&this.store.active.length&&e.id===this.store.active[0].id&&this.calcActiveRect()}else f?this.updatePenRect(e):(d&&I0(e),p&&She(this.store.pens,e),u&&mr.path2dDraws[e.name]&&this.store.path2dMap.set(e,mr.path2dDraws[e.name](e)));if(g!==void 0){var C=e.calculative.rotate;e.calculative.rotate=g,this.rotatePen(e,C-g,e.calculative.worldRect)}(t.image||t.backgroundImage||t.strokeImage)&&(e.calculative.image=void 0,e.calculative.backgroundImage=void 0,e.calculative.strokeImage=void 0,this.loadImage(e)),t.lineGradientColors&&(e.calculative.lineGradient=void 0,e.calculative.gradientColorStop=void 0),t.gradientColors&&(e.calculative.gradient=void 0,e.calculative.radialGradient=void 0),t.gradientRadius&&(e.calculative.gradient=void 0,e.calculative.radialGradient=void 0),t.animateLineWidth&&(e.calculative.gradientAnimatePath=void 0),t.gradientSmooth&&(e.calculative.gradientAnimatePath=void 0),m?(this.canvasImage.init(),this.canvasImageBottom.init()):v?(e.canvasLayer===void 0&&(e.canvasLayer=Ts.CanvasImageBottom,e.calculative.canvasLayer=Ts.CanvasImageBottom),e.canvasLayer===Ts.CanvasImageBottom?this.canvasImageBottom.init():e.canvasLayer===Ts.CanvasImage&&this.canvasImage.init()):this.initImageCanvas([e]),(t.canvasLayer!==void 0||e.canvasLayer===Ts.CanvasTemplate)&&this.initTemplateCanvas([e]),t.zIndex!==void 0&&e.calculative.singleton.div&&za(e,e.calculative.singleton.div)},n.prototype.execPenResize=function(e){var t=this,i,r;(i=e.onResize)===null||i===void 0||i.call(e,e),(r=e.children)===null||r===void 0||r.forEach(function(s){var a=t.store.pens[s];a&&t.execPenResize(a)})},n.prototype.setPenRect=function(e,t,i){if(i===void 0&&(i=!0),e.parentId)Object.assign(e,t);else{var r=this.store.data,s=r.origin,a=r.scale;e.x=s.x+t.x*a,e.y=s.y+t.y*a,e.width=t.width*a,e.height=t.height*a}this.updatePenRect(e),this.execPenResize(e),i&&this.render()},n.prototype.getPenRect=function(e,t,i){if(t===void 0&&(t=this.store.data.origin),i===void 0&&(i=this.store.data.scale),!!e)return e.parentId?{x:e.x,y:e.y,width:e.width,height:e.height}:{x:(e.x-t.x)/i,y:(e.y-t.y)/i,width:e.width/i,height:e.height/i}},n.prototype.toPng=function(e,t,i,r){var s,a;e===void 0&&(e=2),i===void 0&&(i=!1);var o=B0(this.store.data.pens),c=this.store.data.scale;if(!isFinite(o.width))throw new Error("can not to png, because width is not finite");var l=At(o),h=this.store.data,u=i&&!h.background&&this.store.bkImg,d=!1,f=!1;if(u){if(o.x+=h.x,o.y+=h.y,Mo(o),Tz(o,this.canvasRect,!0))Object.assign(o,this.canvasRect);else{var p=OO(f0(f0([],d0(km(o)),!1),d0(km(this.canvasRect)),!1));Object.assign(o,p)}d=o.x===0,f=o.y===0}var _=this.store.data.width||this.store.options.width,m=this.store.data.height||this.store.options.height,g=!1;_&&m&&!this.store.data.component&&(g=!0),g&&(o.x=this.store.data.origin.x,o.y=this.store.data.origin.y,o.width=_*this.store.data.scale,o.height=m*this.store.data.scale);var v=At(o),x=Em(e);o.x-=x[3]*c,o.y-=x[0]*c,o.width+=(x[3]+x[1])*c,o.height+=(x[0]+x[2])*c;var y=(r||1920)/o.width;o.width*=y,o.height*=y,Mo(o);var C=document.createElement("canvas");if(C.width=o.width,C.height=o.height,C.width>32767||C.height>32767||!navigator.userAgent.includes("Firefox")&&C.height*C.width>268435456||navigator.userAgent.includes("Firefox")&&C.height*C.width>472907776)throw new Error("can not to png, because the size exceeds the browser limit");var b=C.getContext("2d");b.textBaseline="middle",b.scale(y,y);var T=this.store.data.background||this.store.options.background;if(T&&(b.save(),b.fillStyle=T,g?b.fillRect(0,0,v.width+(x[1]+x[3])*c,v.height+(x[0]+x[2])*c):b.fillRect(0,0,l.width+(x[3]+x[1])*c,l.height+(x[0]+x[2])*c),b.restore()),u)if(g)b.drawImage(this.store.bkImg,x[3]*c||0,x[0]*c||0,v.width,v.height);else{var S=o.x<0?-o.x:0,N=o.y<0?-o.y:0;b.drawImage(this.store.bkImg,S,N,this.canvasRect.width,this.canvasRect.height)}u?g?b.translate(-l.x+x[3]*c||0,-l.y+x[0]*c||0):b.translate((d?h.x:-l.x)+x[3]*c||0,(f?h.y:-l.y)+x[0]*c||0):b.translate(-o.x,-o.y);try{for(var D=Za(this.store.data.pens),M=D.next();!M.done;M=D.next()){var I=M.value;if(!(!Ez(I,this.store)||I.visible==!1)){var R=I.calculative.active;I.calculative.active=!1,I.calculative.img?bz(b,I):ay(b,I,!0),I.calculative.active=R}}}catch(O){s={error:O}}finally{try{M&&!M.done&&(a=D.return)&&a.call(D)}finally{if(s)throw s.error}}if(t){C.toBlob(t);return}return C.toDataURL()},n.prototype.activeToPng=function(e){var t,i;e===void 0&&(e=2);var r=this.getAllByPens(this.store.active),s=r.map(function(_){return _.id}),a=B0(r);if(!isFinite(a.width))throw new Error("can not to png, because width is not finite");var o=At(a),c=Em(e);a.x-=c[3],a.y-=c[0],a.width+=c[3]+c[1],a.height+=c[0]+c[2],Mo(a);var l=document.createElement("canvas");if(l.width=a.width,l.height=a.height,l.width>32767||l.height>32767||!navigator.userAgent.includes("Firefox")&&l.height*l.width>268435456||navigator.userAgent.includes("Firefox")&&l.height*l.width>472907776)throw new Error("can not to png, because the size exceeds the browser limit");var h=l.getContext("2d");h.textBaseline="middle",h.translate(-o.x,-o.y);try{for(var u=Za(this.store.data.pens),d=u.next();!d.done;d=u.next()){var f=d.value;if(s.includes(f.id)){if(!Ez(f,this.store)||f.visible==!1)continue;var p=f.calculative.active;f.calculative.active=!1,f.calculative.img?bz(h,f):ay(h,f),f.calculative.active=p}}}catch(_){t={error:_}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(t)throw t.error}}return l.toDataURL()},n.prototype.toggleAnchorMode=function(){var e;if(this.hotkeyType)this.hotkeyType===un.AddAnchor&&(this.hotkeyType=un.None,this.store.hoverAnchor?this.externalElements.style.cursor="vertical-text":this.store.hover&&(this.externalElements.style.cursor="move"));else{if(this.store.options.disableAnchor||!((e=this.store.hover)===null||e===void 0)&&e.disableAnchor)return;this.hotkeyType=un.AddAnchor,this.store.hover&&(this.externalElements.style.cursor="pointer")}this.patchFlags=!0},n.prototype.addAnchorHand=function(){if(this.store.activeAnchor&&this.store.active&&this.store.active.length===1&&this.store.active[0].type){var e=[At(this.store.active[0],!0)];this.store.activeAnchor.prev?this.store.activeAnchor.next||(this.store.activeAnchor.next=ch({},this.store.activeAnchor.prev),Yn(this.store.activeAnchor.next,180,this.store.activeAnchor),this.initLineRect(this.store.active[0]),this.patchFlags=!0):(this.store.activeAnchor.next||(this.store.activeAnchor.next={penId:this.store.activeAnchor.penId,x:this.store.activeAnchor.x+50,y:this.store.activeAnchor.y}),this.store.activeAnchor.prev=ch({},this.store.activeAnchor.next),Yn(this.store.activeAnchor.prev,180,this.store.activeAnchor),this.initLineRect(this.store.active[0]),this.patchFlags=!0),this.pushHistory({type:sr.Update,pens:[At(this.store.active[0],!0)],initPens:e})}},n.prototype.removeAnchorHand=function(){if(this.store.activeAnchor&&this.store.active&&this.store.active.length===1&&this.store.active[0].type){var e=[At(this.store.active[0],!0)];this.hoverType===Qi.LineAnchorPrev?(this.store.activeAnchor.prev=void 0,this.initLineRect(this.store.active[0]),this.patchFlags=!0):this.hoverType===Qi.LineAnchorNext?(this.store.activeAnchor.next=void 0,this.initLineRect(this.store.active[0]),this.patchFlags=!0):(this.store.activeAnchor.prev=void 0,this.store.activeAnchor.next=void 0,this.initLineRect(this.store.active[0]),this.patchFlags=!0),this.pushHistory({type:sr.Update,pens:[At(this.store.active[0])],initPens:e})}},n.prototype.toggleAnchorHand=function(){this.store.active.length===1&&this.store.active[0].type&&this.store.activeAnchor&&(this.store.activeAnchor.prevNextType||(this.store.activeAnchor.prevNextType=wy.Mirror),this.store.activeAnchor.prevNextType=(this.store.activeAnchor.prevNextType+1)%3)},n.prototype.gotoView=function(e,t){var i=B0(this.store.data.pens);if(!isFinite(i.width))throw new Error("can not move view, because width is not finite");this.store.data.x=this.canvas.clientWidth/2-e*i.width-i.x,this.store.data.y=this.canvas.clientHeight/2-t*i.height-i.y,this.onMovePens(),this.canvasTemplate.init(),this.canvasImage.init(),this.canvasImageBottom.init(),this.render()},n.prototype.showMagnifier=function(){this.magnifierCanvas.magnifier=!0,this.externalElements.style.cursor="default",this.render()},n.prototype.hideMagnifier=function(){this.magnifierCanvas.magnifier=!1,this.externalElements.style.cursor="default",this.render()},n.prototype.toggleMagnifier=function(){this.magnifierCanvas.magnifier=!this.magnifierCanvas.magnifier,this.magnifierCanvas.magnifier&&(this.externalElements.style.cursor="default"),this.render()},n.prototype.destroy=function(){var e,t,i;switch(this.scroll&&this.scroll.destroy(),(e=this.tooltip)===null||e===void 0||e.destroy(),(t=this.dialog)===null||t===void 0||t.destroy(),(i=this.title)===null||i===void 0||i.destroy(),this.externalElements.removeEventListener("gesturestart",this.onGesturestart),this.externalElements.ondragover=function(r){return r.preventDefault()},this.externalElements.ondrop=void 0,this.externalElements.ontouchstart=void 0,this.externalElements.ontouchmove=void 0,this.externalElements.ontouchend=void 0,this.externalElements.onmousedown=void 0,this.externalElements.onmousemove=void 0,this.externalElements.onmouseup=void 0,this.externalElements.onmouseleave=void 0,this.externalElements.ondblclick=void 0,this.store.options.keydown){case gy.Document:document.removeEventListener("keydown",this.onkeydown),document.removeEventListener("keyup",this.onkeyup);break;case gy.Canvas:this.externalElements.removeEventListener("keydown",this.onkeydown),this.externalElements.removeEventListener("keyup",this.onkeyup);break}document.removeEventListener("copy",this.onCopy),document.removeEventListener("cut",this.onCut),document.removeEventListener("paste",this.onPaste),window&&window.removeEventListener("resize",this.onResize),window&&window.removeEventListener("scroll",this.onScroll)},n}(),_l;(function(n){n[n.Link=0]="Link",n[n.SetProps=1]="SetProps",n[n.StartAnimate=2]="StartAnimate",n[n.PauseAnimate=3]="PauseAnimate",n[n.StopAnimate=4]="StopAnimate",n[n.JS=5]="JS",n[n.GlobalFn=6]="GlobalFn",n[n.Emit=7]="Emit",n[n.StartVideo=8]="StartVideo",n[n.PauseVideo=9]="PauseVideo",n[n.StopVideo=10]="StopVideo",n[n.SendPropData=11]="SendPropData",n[n.SendVarData=12]="SendVarData",n[n.Navigator=13]="Navigator",n[n.Dialog=14]="Dialog",n[n.SendData=15]="SendData",n[n.PostMessage=16]="PostMessage",n[n.PostMessageToParent=17]="PostMessageToParent"})(_l||(_l={}));var pSe=function(){function n(e){var t=this;this.parent=e,this.boxWidth=320,this.boxHeight=180,this.ratio=this.boxWidth/this.boxHeight,this.padding=5,this.onMouseDown=function(a){a.preventDefault(),a.stopPropagation(),t.isDown=!0},this.onMouseMove=function(a){if(a.preventDefault(),a.stopPropagation(),t.isDown)try{t.parent.gotoView(a.offsetX/t.box.clientWidth,a.offsetY/t.box.clientHeight)}catch(o){console.warn(o.message),t.isDown=!1}},this.onMouseUp=function(a){a.preventDefault(),a.stopPropagation();try{t.parent.gotoView(a.offsetX/t.box.clientWidth,a.offsetY/t.box.clientHeight)}catch(o){console.warn(o.message)}finally{t.isDown=!1}},this.box=document.createElement("div"),this.img=new Image,this.view=document.createElement("div"),this.box.appendChild(this.img),this.box.appendChild(this.view),this.parent.externalElements.appendChild(this.box),this.box.className="meta2d-map",this.box.onmousedown=this.onMouseDown,this.box.onmousemove=this.onMouseMove,this.box.onmouseup=this.onMouseUp;for(var i,r=0;rthis.ratio){var r=t.width/this.ratio;t.y-=(r-t.height)/2,t.height=r,Mo(t)}else{var s=t.height*this.ratio;t.x-=(s-t.width)/2,t.width=s,Mo(t)}var a=this.parent.canvasRect,o=0,c=0;if(t.x<0)o=-t.x/t.width;else if(t.x+t.width>a.width){var l=0;a.width>t.width&&(l=a.width-t.width),o=(-t.x+l)/t.width}if(t.y<0)c=-t.y/t.height;else if(t.y+t.height>a.height){var l=0;a.height>t.height&&(l=a.height-t.height),c=(-t.y+l)/t.height}var h=a.width>t.width?1:a.width/t.width,u=a.height>t.height?1:a.height/t.height;this.view.style.left=this.padding+o*this.boxWidth+"px",this.view.style.width=h*this.boxWidth+"px",this.view.style.top=this.padding+c*this.boxHeight+"px",this.view.style.height=u*this.boxHeight+"px"}},n}();function F0(n){throw new Error('Could not dynamically require "'+n+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var o_e={exports:{}};(function(n,e){(function(t){n.exports=t()})(function(){return function(){return function t(i,r,s){function a(l,h){if(!r[l]){if(!i[l]){var u=typeof F0=="function"&&F0;if(!h&&u)return u(l,!0);if(o)return o(l,!0);var d=new Error("Cannot find module '"+l+"'");throw d.code="MODULE_NOT_FOUND",d}var f=r[l]={exports:{}};i[l][0].call(f.exports,function(p){return a(i[l][1][p]||p)},f,f.exports,t,i,r,s)}return r[l].exports}for(var o=typeof F0=="function"&&F0,c=0;c0&&(O.topicAliasMaximum>65535?x("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new l(O.topicAliasMaximum)),this.on("connect",function(){const Q=this.queue;x("connect :: sending queued packets"),function $(){const V=Q.shift();x("deliver :: entry %o",V);let j=null;if(!V)return void G._resubscribe();j=V.packet,x("deliver :: call _sendPacket for %o",j);let k=!0;j.messageId&&j.messageId!==0&&(G.messageIdProvider.register(j.messageId)||(k=!1)),k?G._sendPacket(j,function(z){V.cb&&V.cb(z),$()}):(x("messageId: %d has already used. The message is skipped and removed.",j.messageId),$())}()}),this.on("close",function(){x("close :: connected set to `false`"),this.connected=!1,x("close :: clearing connackTimer"),clearTimeout(this.connackTimer),x("close :: clearing ping timer"),G.pingTimer!==null&&(G.pingTimer.clear(),G.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),x("close :: calling _setupReconnect"),this._setupReconnect()}),o.call(this),x("MqttClient :: setting up stream"),this._setupStream()}p(I,o),I.prototype._setupStream=function(){const R=this,O=new f,H=u.parser(this.options);let G=null;const Q=[];function $(){if(Q.length)y(V);else{const k=G;G=null,k()}}function V(){x("work :: getting next packet in queue");const k=Q.shift();if(k)x("work :: packet pulled from queue"),R._handlePacket(k,$);else{x("work :: no packets in queue");const z=G;G=null,x("work :: done flag is %s",!!z),z&&z()}}x("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),x("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),H.on("packet",function(k){x("parser :: on packet push to packets array."),Q.push(k)}),O._write=function(k,z,Y){G=Y,x("writable stream :: parsing buffer"),H.parse(k),V()},x("_setupStream :: pipe stream to writable stream"),this.stream.pipe(O),this.stream.on("error",function(k){x("streamErrorHandler :: error",k.message),k.code?(x("streamErrorHandler :: emitting error"),R.emit("error",k)):M(k)}),this.stream.on("close",function(){var k;x("(%s)stream :: on close",R.options.clientId),(k=R.outgoing)&&(x("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(k).forEach(function(z){k[z].volatile&&typeof k[z].cb=="function"&&(k[z].cb(new Error("Connection closed")),delete k[z])})),x("stream: emit close to MqttClient"),R.emit("close")}),x("_setupStream: sending packet `connect`");const j=Object.create(this.options);if(j.cmd="connect",this.topicAliasRecv&&(j.properties||(j.properties={}),this.topicAliasRecv&&(j.properties.topicAliasMaximum=this.topicAliasRecv.max)),N(this,j),H.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return R.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"&&N(this,v({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(function(){x("!!connectTimeout hit!! Calling _cleanUp with force `true`"),R._cleanUp(!0)},this.options.connectTimeout)},I.prototype._handlePacket=function(R,O){const H=this.options;if(H.protocolVersion===5&&H.properties&&H.properties.maximumPacketSize&&H.properties.maximumPacketSize0||!V())&&this._storeProcessingQueue.push({invoke:V,cbStorePut:H.cbStorePut,callback:G}),this},I.prototype.subscribe=function(){const R=this,O=new Array(arguments.length);for(let J=0;J0){const ue={qos:le.qos};j===5&&(ue.nl=le.nl||!1,ue.rap=le.rap||!1,ue.rh=le.rh||0,ue.properties=le.properties),R._resubscribeTopics[le.topic]=ue,he.push(le.topic)}}),R.messageIdToTopic[re.messageId]=he}return R.outgoing[re.messageId]={volatile:!0,cb:function(he,le){if(!he){const ue=le.granted;for(let L=0;L0||!Y())&&this._storeProcessingQueue.push({invoke:Y,callback:$}),this},I.prototype.unsubscribe=function(){const R=this,O=new Array(arguments.length);for(let j=0;j0||!V())&&this._storeProcessingQueue.push({invoke:V,callback:G}),this},I.prototype.end=function(R,O,H){const G=this;function Q(){x("end :: (%s) :: finish :: calling _cleanUp with force %s",G.options.clientId,R),G._cleanUp(R,()=>{x("end :: finish :: calling process.nextTick on closeStores"),y((function(){x("end :: closeStores: closing incoming and outgoing stores"),G.disconnected=!0,G.incomingStore.close(function($){G.outgoingStore.close(function(V){if(x("end :: closeStores: emitting end"),G.emit("end"),H){const j=$||V;x("end :: closeStores: invoking callback with args"),H(j)}})}),G._deferredReconnect&&G._deferredReconnect()}).bind(G))},O)}return x("end :: (%s)",this.options.clientId),R!=null&&typeof R=="boolean"||(H=O||M,O=R,R=!1,typeof O!="object"&&(H=O,O=null,typeof H!="function"&&(H=M))),typeof O!="object"&&(H=O,O=null),x("end :: cb? %s",!!H),H=H||M,this.disconnecting?(H(),this):(this._clearReconnect(),this.disconnecting=!0,!R&&Object.keys(this.outgoing).length>0?(x("end :: (%s) :: calling finish in 10ms once outgoing is empty",G.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,Q,10))):(x("end :: (%s) :: immediately calling finish",G.options.clientId),Q()),this)},I.prototype.removeOutgoingMessage=function(R){const O=this.outgoing[R]?this.outgoing[R].cb:null;return delete this.outgoing[R],this.outgoingStore.del({messageId:R},function(){O(new Error("Message removed"))}),this},I.prototype.reconnect=function(R){x("client reconnect");const O=this,H=function(){R?(O.options.incomingStore=R.incomingStore,O.options.outgoingStore=R.outgoingStore):(O.options.incomingStore=null,O.options.outgoingStore=null),O.incomingStore=O.options.incomingStore||new c,O.outgoingStore=O.options.outgoingStore||new c,O.disconnecting=!1,O.disconnected=!1,O._deferredReconnect=null,O._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=H:H(),this},I.prototype._reconnect=function(){x("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this._setupStream()}),x("client already connected. disconnecting first.")):(x("_reconnect: calling _setupStream"),this._setupStream())},I.prototype._setupReconnect=function(){const R=this;!R.disconnecting&&!R.reconnectTimer&&R.options.reconnectPeriod>0?(this.reconnecting||(x("_setupReconnect :: emit `offline` state"),this.emit("offline"),x("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),x("_setupReconnect :: setting reconnectTimer for %d ms",R.options.reconnectPeriod),R.reconnectTimer=setInterval(function(){x("reconnectTimer :: reconnect triggered!"),R._reconnect()},R.options.reconnectPeriod)):x("_setupReconnect :: doing nothing...")},I.prototype._clearReconnect=function(){x("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},I.prototype._cleanUp=function(R,O){const H=arguments[2];if(O&&(x("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",O)),x("_cleanUp :: forced? %s",R),R)this.options.reconnectPeriod===0&&this.options.clean&&(G=this.outgoing)&&(x("flush: queue exists? %b",!!G),Object.keys(G).forEach(function(Q){typeof G[Q].cb=="function"&&(G[Q].cb(new Error("Connection closed")),delete G[Q])})),x("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const Q=v({cmd:"disconnect"},H);x("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(Q,C.bind(null,this.stream.end.bind(this.stream)))}var G;this.disconnecting||(x("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this.pingTimer!==null&&(x("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),O&&!this.connected&&(x("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",O),O())},I.prototype._sendPacket=function(R,O,H){x("_sendPacket :: (%s) :: start",this.options.clientId),H=H||M,O=O||M;const G=function(Q,$){if(Q.options.protocolVersion===5&&$.cmd==="publish"){let V;$.properties&&(V=$.properties.topicAlias);const j=$.topic.toString();if(Q.topicAliasSend)if(V){if(j.length!==0&&(x("applyTopicAlias :: register topic: %s - alias: %d",j,V),!Q.topicAliasSend.put(j,V)))return x("applyTopicAlias :: error out of range. topic: %s - alias: %d",j,V),new Error("Sending Topic Alias out of range")}else j.length!==0&&(Q.options.autoAssignTopicAlias?(V=Q.topicAliasSend.getAliasByTopic(j))?($.topic="",$.properties={...$.properties,topicAlias:V},x("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",j,V)):(V=Q.topicAliasSend.getLruAlias(),Q.topicAliasSend.put(j,V),$.properties={...$.properties,topicAlias:V},x("applyTopicAlias :: auto assign topic: %s - alias: %d",j,V)):Q.options.autoUseTopicAlias&&(V=Q.topicAliasSend.getAliasByTopic(j))&&($.topic="",$.properties={...$.properties,topicAlias:V},x("applyTopicAlias :: auto use topic: %s - alias: %d",j,V)));else if(V)return x("applyTopicAlias :: error out of range. topic: %s - alias: %d",j,V),new Error("Sending Topic Alias out of range")}}(this,R);if(G)O(G);else{if(!this.connected)return R.cmd==="auth"?(this._shiftPingInterval(),void N(this,R,O)):(x("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(R,O,H));switch(this._shiftPingInterval(),R.cmd){case"publish":break;case"pubrel":return void D(this,R,O,H);default:return void N(this,R,O)}switch(R.qos){case 2:case 1:D(this,R,O,H);break;case 0:default:N(this,R,O)}x("_sendPacket :: (%s) :: end",this.options.clientId)}},I.prototype._storePacket=function(R,O,H){x("_storePacket :: packet: %o",R),x("_storePacket :: cb? %s",!!O),H=H||M;let G=R;if(G.cmd==="publish"){const Q=S(this,G=m(R));if(Q)return O&&O(Q)}(G.qos||0)===0&&this.queueQoSZero||G.cmd!=="publish"?this.queue.push({packet:G,cb:O}):G.qos>0?(O=this.outgoing[G.messageId]?this.outgoing[G.messageId].cb:null,this.outgoingStore.put(G,function(Q){if(Q)return O&&O(Q);H()})):O&&O(new Error("No connection to broker"))},I.prototype._setupPingTimer=function(){x("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const R=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=_(function(){R._checkPing()},1e3*this.options.keepalive))},I.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},I.prototype._checkPing=function(){x("_checkPing :: checking ping..."),this.pingResp?(x("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(x("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},I.prototype._handlePingresp=function(){this.pingResp=!0},I.prototype._handleConnack=function(R){x("_handleConnack");const O=this.options,H=O.protocolVersion===5?R.reasonCode:R.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,R.properties){if(R.properties.topicAliasMaximum){if(R.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));R.properties.topicAliasMaximum>0&&(this.topicAliasSend=new h(R.properties.topicAliasMaximum))}R.properties.serverKeepAlive&&O.keepalive&&(O.keepalive=R.properties.serverKeepAlive,this._shiftPingInterval()),R.properties.maximumPacketSize&&(O.properties||(O.properties={}),O.properties.maximumPacketSize=R.properties.maximumPacketSize)}if(H===0)this.reconnecting=!1,this._onConnect(R);else if(H>0){const G=new Error("Connection refused: "+T[H]);G.code=H,this.emit("error",G)}},I.prototype._handleAuth=function(R){const O=this.options.protocolVersion,H=O===5?R.reasonCode:R.returnCode;if(O!==5){const Q=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+O);return Q.code=H,void this.emit("error",Q)}const G=this;this.handleAuth(R,function(Q,$){if(Q)G.emit("error",Q);else if(H===24)G.reconnecting=!1,G._sendPacket($);else{const V=new Error("Connection refused: "+T[H]);Q.code=H,G.emit("error",V)}})},I.prototype.handleAuth=function(R,O){O()},I.prototype._handlePublish=function(R,O){x("_handlePublish: packet %o",R),O=O!==void 0?O:M;let H=R.topic.toString();const G=R.payload,Q=R.qos,$=R.messageId,V=this,j=this.options,k=[0,16,128,131,135,144,145,151,153];if(this.options.protocolVersion===5){let z;if(R.properties&&(z=R.properties.topicAlias),z!==void 0)if(H.length===0){if(!(z>0&&z<=65535))return x("_handlePublish :: topic alias out of range. alias: %d",z),void this.emit("error",new Error("Received Topic Alias is out of range"));{const Y=this.topicAliasRecv.getTopicByAlias(z);if(!Y)return x("_handlePublish :: unregistered topic alias. alias: %d",z),void this.emit("error",new Error("Received unregistered Topic Alias"));x("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",H=Y,z)}}else{if(!this.topicAliasRecv.put(H,z))return x("_handlePublish :: topic alias out of range. alias: %d",z),void this.emit("error",new Error("Received Topic Alias is out of range"));x("_handlePublish :: registered topic: %s - alias: %d",H,z)}}switch(x("_handlePublish: qos %d",Q),Q){case 2:j.customHandleAcks(H,G,R,function(z,Y){return z instanceof Error||(Y=z,z=null),z?V.emit("error",z):k.indexOf(Y)===-1?V.emit("error",new Error("Wrong reason code for pubrec")):void(Y?V._sendPacket({cmd:"pubrec",messageId:$,reasonCode:Y},O):V.incomingStore.put(R,function(){V._sendPacket({cmd:"pubrec",messageId:$},O)}))});break;case 1:j.customHandleAcks(H,G,R,function(z,Y){return z instanceof Error||(Y=z,z=null),z?V.emit("error",z):k.indexOf(Y)===-1?V.emit("error",new Error("Wrong reason code for puback")):(Y||V.emit("message",H,G,R),void V.handleMessage(R,function(J){if(J)return O&&O(J);V._sendPacket({cmd:"puback",messageId:$,reasonCode:Y},O)}))});break;case 0:this.emit("message",H,G,R),this.handleMessage(R,O);break;default:x("_handlePublish: unknown QoS. Doing nothing.")}},I.prototype.handleMessage=function(R,O){O()},I.prototype._handleAck=function(R){const O=R.messageId,H=R.cmd;let G=null;const Q=this.outgoing[O]?this.outgoing[O].cb:null,$=this;let V;if(Q){switch(x("_handleAck :: packet type",H),H){case"pubcomp":case"puback":{const j=R.reasonCode;j&&j>0&&j!==16&&((V=new Error("Publish error: "+T[j])).code=j,Q(V,R)),delete this.outgoing[O],this.outgoingStore.del(R,Q),this.messageIdProvider.deallocate(O),this._invokeStoreProcessingQueue();break}case"pubrec":{G={cmd:"pubrel",qos:2,messageId:O};const j=R.reasonCode;j&&j>0&&j!==16?((V=new Error("Publish error: "+T[j])).code=j,Q(V,R)):this._sendPacket(G);break}case"suback":delete this.outgoing[O],this.messageIdProvider.deallocate(O);for(let j=0;j0)if(this.options.resubscribe)if(this.options.protocolVersion===5){x("_resubscribe: protocolVersion 5");for(let O=0;O0){const R=this._storeProcessingQueue[0];if(R&&R.invoke())return this._storeProcessingQueue.shift(),!0}return!1},I.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},I.prototype._flushStoreProcessingQueue=function(){for(const R of this._storeProcessingQueue)R.cbStorePut&&R.cbStorePut(new Error("Connection closed")),R.callback&&R.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},i.exports=I}).call(this)}).call(this,t("_process"),typeof kt<"u"?kt:typeof self<"u"?self:typeof window<"u"?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(t,i,r){const{Buffer:s}=t("buffer"),a=t("readable-stream").Transform,o=t("duplexify");let c,l,h,u=!1;i.exports=function(d,f){if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");const p=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";(function(m){m.hostname||(m.hostname="localhost"),m.path||(m.path="/"),m.wsOptions||(m.wsOptions={})})(f);const _=function(m,g){const v=m.protocol==="alis"?"wss":"ws";let x=v+"://"+m.hostname+m.path;return m.port&&m.port!==80&&m.port!==443&&(x=v+"://"+m.hostname+":"+m.port+m.path),typeof m.transformWsUrl=="function"&&(x=m.transformWsUrl(x,m,g)),x}(f,d);return(c=f.my).connectSocket({url:_,protocols:p}),l=function(){const m=new a;return m._write=function(g,v,x){c.sendSocketMessage({data:g.buffer,success:function(){x()},fail:function(){x(new Error)}})},m._flush=function(g){c.closeSocket({success:function(){g()}})},m}(),h=o.obj(),u||(u=!0,c.onSocketOpen(function(){h.setReadable(l),h.setWritable(l),h.emit("connect")}),c.onSocketMessage(function(m){if(typeof m.data=="string"){const g=s.from(m.data,"base64");l.push(g)}else{const g=new FileReader;g.addEventListener("load",function(){let v=g.result;v=v instanceof ArrayBuffer?s.from(v):s.from(v,"utf8"),l.push(v)}),g.readAsArrayBuffer(m.data)}}),c.onSocketClose(function(){h.end(),h.destroy()}),c.onSocketError(function(m){h.destroy(m)})),h}},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(t,i,r){const s=t("net"),a=t("debug")("mqttjs:tcp");i.exports=function(o,c){c.port=c.port||1883,c.hostname=c.hostname||c.host||"localhost";const l=c.port,h=c.hostname;return a("port %d and host %s",l,h),s.createConnection(l,h)}},{debug:18,net:16}],4:[function(t,i,r){const s=t("tls"),a=t("net"),o=t("debug")("mqttjs:tls");i.exports=function(c,l){l.port=l.port||8883,l.host=l.hostname||l.host||"localhost",a.isIP(l.host)===0&&(l.servername=l.host),l.rejectUnauthorized=l.rejectUnauthorized!==!1,delete l.path,o("port %d host %s rejectUnauthorized %b",l.port,l.host,l.rejectUnauthorized);const h=s.connect(l);function u(d){l.rejectUnauthorized&&c.emit("error",d),h.end()}return h.on("secureConnect",function(){l.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",u)}),h.on("error",u),h}},{debug:18,net:16,tls:16}],5:[function(t,i,r){(function(s){(function(){const{Buffer:a}=t("buffer"),o=t("ws"),c=t("debug")("mqttjs:ws"),l=t("duplexify"),h=t("readable-stream").Transform,u=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],d=s!==void 0&&s.title==="browser"||typeof __webpack_require__=="function";function f(_,m){let g=_.protocol+"://"+_.hostname+":"+_.port+_.path;return typeof _.transformWsUrl=="function"&&(g=_.transformWsUrl(g,_,m)),g}function p(_){const m=_;return _.hostname||(m.hostname="localhost"),_.port||(_.protocol==="wss"?m.port=443:m.port=80),_.path||(m.path="/"),_.wsOptions||(m.wsOptions={}),d||_.protocol!=="wss"||u.forEach(function(g){Object.prototype.hasOwnProperty.call(_,g)&&!Object.prototype.hasOwnProperty.call(_.wsOptions,g)&&(m.wsOptions[g]=_[g])}),m}i.exports=d?function(_,m){let g;c("browserStreamBuilder");const v=function(R){const O=p(R);if(O.hostname||(O.hostname=O.host),!O.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");const H=new URL(document.URL);O.hostname=H.hostname,O.port||(O.port=H.port)}return O.objectMode===void 0&&(O.objectMode=!(O.binary===!0||O.binary===void 0)),O}(m).browserBufferSize||524288,x=m.browserBufferTimeout||1e3,y=!m.objectMode,C=function(R,O){const H=O.protocolId==="MQIsdp"&&O.protocolVersion===3?"mqttv3.1":"mqtt",G=f(O,R),Q=new WebSocket(G,[H]);return Q.binaryType="arraybuffer",Q}(_,m),b=function(R,O,H){const G=new h({objectModeMode:R.objectMode});return G._write=O,G._flush=H,G}(m,function R(O,H,G){C.bufferedAmount>v&&setTimeout(R,x,O,H,G),y&&typeof O=="string"&&(O=a.from(O,"utf8"));try{C.send(O)}catch(Q){return G(Q)}G()},function(R){C.close(),R()});m.objectMode||(b._writev=I),b.on("close",()=>{C.close()});const T=C.addEventListener!==void 0;function S(){g.setReadable(b),g.setWritable(b),g.emit("connect")}function N(){g.end(),g.destroy()}function D(R){g.destroy(R)}function M(R){let O=R.data;O=O instanceof ArrayBuffer?a.from(O):a.from(O,"utf8"),b.push(O)}function I(R,O){const H=new Array(R.length);for(let G=0;G{y.destroy()}),y}}).call(this)}).call(this,t("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(t,i,r){const{Buffer:s}=t("buffer"),a=t("readable-stream").Transform,o=t("duplexify");let c,l,h;i.exports=function(u,d){if(d.hostname=d.hostname||d.host,!d.hostname)throw new Error("Could not determine host. Specify host manually.");const f=d.protocolId==="MQIsdp"&&d.protocolVersion===3?"mqttv3.1":"mqtt";(function(m){m.hostname||(m.hostname="localhost"),m.path||(m.path="/"),m.wsOptions||(m.wsOptions={})})(d);const p=function(m,g){const v=m.protocol==="wxs"?"wss":"ws";let x=v+"://"+m.hostname+m.path;return m.port&&m.port!==80&&m.port!==443&&(x=v+"://"+m.hostname+":"+m.port+m.path),typeof m.transformWsUrl=="function"&&(x=m.transformWsUrl(x,m,g)),x}(d,u);c=wx.connectSocket({url:p,protocols:[f]}),l=function(){const m=new a;return m._write=function(g,v,x){c.send({data:g.buffer,success:function(){x()},fail:function(y){x(new Error(y))}})},m._flush=function(g){c.close({success:function(){g()}})},m}(),(h=o.obj())._destroy=function(m,g){c.close({success:function(){g&&g(m)}})};const _=h.destroy;return h.destroy=(function(){h.destroy=_;const m=this;setTimeout(function(){c.close({fail:function(){m._destroy(new Error)}})},0)}).bind(h),c.onOpen(function(){h.setReadable(l),h.setWritable(l),h.emit("connect")}),c.onMessage(function(m){let g=m.data;g=g instanceof ArrayBuffer?s.from(g):s.from(g,"utf8"),l.push(g)}),c.onClose(function(){h.end(),h.destroy()}),c.onError(function(m){h.destroy(new Error(m.errMsg))}),h}},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(t,i,r){function s(){if(!(this instanceof s))return new s;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}s.prototype.allocate=function(){const a=this.nextId++;return this.nextId===65536&&(this.nextId=1),a},s.prototype.getLastAllocated=function(){return this.nextId===1?65535:this.nextId-1},s.prototype.register=function(a){return!0},s.prototype.deallocate=function(a){},s.prototype.clear=function(){},i.exports=s},{}],8:[function(t,i,r){const s=t("xtend"),a=t("readable-stream").Readable,o={objectMode:!0},c={clean:!0};function l(h){if(!(this instanceof l))return new l(h);this.options=h||{},this.options=s(c,h),this._inflights=new Map}l.prototype.put=function(h,u){return this._inflights.set(h.messageId,h),u&&u(),this},l.prototype.createStream=function(){const h=new a(o),u=[];let d=!1,f=0;return this._inflights.forEach(function(p,_){u.push(p)}),h._read=function(){!d&&fthis.max)&&(this.aliasToTopic[o]=a,this.length=Object.keys(this.aliasToTopic).length,!0)},s.prototype.getTopicByAlias=function(a){return this.aliasToTopic[a]},s.prototype.clear=function(){this.aliasToTopic={}},i.exports=s},{}],10:[function(t,i,r){const s=t("lru-cache"),a=t("number-allocator").NumberAllocator;function o(c){if(!(this instanceof o))return new o(c);c>0&&(this.aliasToTopic=new s({max:c}),this.topicToAlias={},this.numberAllocator=new a(1,c),this.max=c,this.length=0)}o.prototype.put=function(c,l){if(l===0||l>this.max)return!1;const h=this.aliasToTopic.get(l);return h&&delete this.topicToAlias[h],this.aliasToTopic.set(l,c),this.topicToAlias[c]=l,this.numberAllocator.use(l),this.length=this.aliasToTopic.length,!0},o.prototype.getTopicByAlias=function(c){return this.aliasToTopic.get(c)},o.prototype.getAliasByTopic=function(c){const l=this.topicToAlias[c];return l!==void 0&&this.aliasToTopic.get(l),l},o.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},o.prototype.getLruAlias=function(){return this.numberAllocator.firstVacant()||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},i.exports=o},{"lru-cache":37,"number-allocator":46}],11:[function(t,i,r){function s(a){const o=a.split("/");for(let c=0;c0?g-4:g;for(_=0;_>16&255,x[y++]=p>>8&255,x[y++]=255&p;return v===2&&(p=a[f.charCodeAt(_)]<<2|a[f.charCodeAt(_+1)]>>4,x[y++]=255&p),v===1&&(p=a[f.charCodeAt(_)]<<10|a[f.charCodeAt(_+1)]<<4|a[f.charCodeAt(_+2)]>>2,x[y++]=p>>8&255,x[y++]=255&p),x},r.fromByteArray=function(f){for(var p,_=f.length,m=_%3,g=[],v=0,x=_-m;vx?x:v+16383));return m===1?(p=f[_-1],g.push(s[p>>2]+s[p<<4&63]+"==")):m===2&&(p=(f[_-2]<<8)+f[_-1],g.push(s[p>>10]+s[p>>4&63]+s[p<<2&63]+"=")),g.join("")};for(var s=[],a=[],o=typeof Uint8Array<"u"?Uint8Array:Array,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=0,h=c.length;l0)throw new Error("Invalid string. Length must be a multiple of 4");var _=f.indexOf("=");return _===-1&&(_=p),[_,_===p?0:4-_%4]}function d(f,p,_){for(var m,g,v=[],x=p;x<_;x+=3)m=(f[x]<<16&16711680)+(f[x+1]<<8&65280)+(255&f[x+2]),v.push(s[(g=m)>>18&63]+s[g>>12&63]+s[g>>6&63]+s[63&g]);return v.join("")}a[45]=62,a[95]=63},{}],14:[function(t,i,r){const{Buffer:s}=t("buffer"),a=Symbol.for("BufferList");function o(c){if(!(this instanceof o))return new o(c);o._init.call(this,c)}o._init=function(c){Object.defineProperty(this,a,{value:!0}),this._bufs=[],this.length=0,c&&this.append(c)},o.prototype._new=function(c){return new o(c)},o.prototype._offset=function(c){if(c===0)return[0,0];let l=0;for(let h=0;hthis.length||c<0)return;const l=this._offset(c);return this._bufs[l[0]][l[1]]},o.prototype.slice=function(c,l){return typeof c=="number"&&c<0&&(c+=this.length),typeof l=="number"&&l<0&&(l+=this.length),this.copy(null,0,c,l)},o.prototype.copy=function(c,l,h,u){if((typeof h!="number"||h<0)&&(h=0),(typeof u!="number"||u>this.length)&&(u=this.length),h>=this.length||u<=0)return c||s.alloc(0);const d=!!c,f=this._offset(h),p=u-h;let _=p,m=d&&l||0,g=f[1];if(h===0&&u===this.length){if(!d)return this._bufs.length===1?this._bufs[0]:s.concat(this._bufs,this.length);for(let v=0;vx)){this._bufs[v].copy(c,m,g,g+_),m+=x;break}this._bufs[v].copy(c,m,g),m+=x,_-=x,g&&(g=0)}return c.length>m?c.slice(0,m):c},o.prototype.shallowSlice=function(c,l){if(c=c||0,l=typeof l!="number"?this.length:l,c<0&&(c+=this.length),l<0&&(l+=this.length),c===l)return this._new();const h=this._offset(c),u=this._offset(l),d=this._bufs.slice(h[0],u[0]+1);return u[1]===0?d.pop():d[d.length-1]=d[d.length-1].slice(0,u[1]),h[1]!==0&&(d[0]=d[0].slice(h[1])),this._new(d)},o.prototype.toString=function(c,l,h){return this.slice(l,h).toString(c)},o.prototype.consume=function(c){if(c=Math.trunc(c),Number.isNaN(c)||c<=0)return this;for(;this._bufs.length;){if(!(c>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(c),this.length-=c;break}c-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},o.prototype.duplicate=function(){const c=this._new();for(let l=0;lthis.length?this.length:l;const u=this._offset(l);let d=u[0],f=u[1];for(;d=c.length){const _=p.indexOf(c,f);if(_!==-1)return this._reverseOffset([d,_]);f=p.length-c.length+1}else{const _=this._reverseOffset([d,f]);if(this._match(_,c))return _;f++}f=0}return-1},o.prototype._match=function(c,l){if(this.length-cc)throw new RangeError('The value "'+L+'" is invalid for option "size"');var F=new Uint8Array(L);return F.__proto__=h.prototype,F}function h(L,F,W){if(typeof L=="number"){if(typeof F=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return f(L)}return u(L,F,W)}function u(L,F,W){if(typeof L=="string")return function(ne,pe){if(typeof pe=="string"&&pe!==""||(pe="utf8"),!h.isEncoding(pe))throw new TypeError("Unknown encoding: "+pe);var ye=0|m(ne,pe),Pe=l(ye),Fe=Pe.write(ne,pe);return Fe!==ye&&(Pe=Pe.slice(0,Fe)),Pe}(L,F);if(ArrayBuffer.isView(L))return p(L);if(L==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof L);if(le(L,ArrayBuffer)||L&&le(L.buffer,ArrayBuffer))return function(ne,pe,ye){if(pe<0||ne.byteLength=c)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+c.toString(16)+" bytes");return 0|L}function m(L,F){if(h.isBuffer(L))return L.length;if(ArrayBuffer.isView(L)||le(L,ArrayBuffer))return L.byteLength;if(typeof L!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof L);var W=L.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&W===0)return 0;for(var oe=!1;;)switch(F){case"ascii":case"latin1":case"binary":return W;case"utf8":case"utf-8":return J(L).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*W;case"hex":return W>>>1;case"base64":return re(L).length;default:if(oe)return te?-1:J(L).length;F=(""+F).toLowerCase(),oe=!0}}function g(L,F,W){var te=L[F];L[F]=L[W],L[W]=te}function v(L,F,W,te,oe){if(L.length===0)return-1;if(typeof W=="string"?(te=W,W=0):W>2147483647?W=2147483647:W<-2147483648&&(W=-2147483648),ue(W=+W)&&(W=oe?0:L.length-1),W<0&&(W=L.length+W),W>=L.length){if(oe)return-1;W=L.length-1}else if(W<0){if(!oe)return-1;W=0}if(typeof F=="string"&&(F=h.from(F,te)),h.isBuffer(F))return F.length===0?-1:x(L,F,W,te,oe);if(typeof F=="number")return F&=255,typeof Uint8Array.prototype.indexOf=="function"?oe?Uint8Array.prototype.indexOf.call(L,F,W):Uint8Array.prototype.lastIndexOf.call(L,F,W):x(L,[F],W,te,oe);throw new TypeError("val must be string, number or Buffer")}function x(L,F,W,te,oe){var ne,pe=1,ye=L.length,Pe=F.length;if(te!==void 0&&((te=String(te).toLowerCase())==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(L.length<2||F.length<2)return-1;pe=2,ye/=2,Pe/=2,W/=2}function Fe(gt,rt){return pe===1?gt[rt]:gt.readUInt16BE(rt*pe)}if(oe){var He=-1;for(ne=W;neye&&(W=ye-Pe),ne=W;ne>=0;ne--){for(var ot=!0,Xe=0;Xeoe&&(te=oe):te=oe;var ne=F.length;te>ne/2&&(te=ne/2);for(var pe=0;pe>8,Pe=pe%256,Fe.push(Pe),Fe.push(ye);return Fe}(F,L.length-W),L,W,te)}function D(L,F,W){return F===0&&W===L.length?a.fromByteArray(L):a.fromByteArray(L.slice(F,W))}function M(L,F,W){W=Math.min(L.length,W);for(var te=[],oe=F;oe239?4:Fe>223?3:Fe>191?2:1;if(oe+ot<=W)switch(ot){case 1:Fe<128&&(He=Fe);break;case 2:(192&(ne=L[oe+1]))==128&&(Pe=(31&Fe)<<6|63&ne)>127&&(He=Pe);break;case 3:ne=L[oe+1],pe=L[oe+2],(192&ne)==128&&(192&pe)==128&&(Pe=(15&Fe)<<12|(63&ne)<<6|63&pe)>2047&&(Pe<55296||Pe>57343)&&(He=Pe);break;case 4:ne=L[oe+1],pe=L[oe+2],ye=L[oe+3],(192&ne)==128&&(192&pe)==128&&(192&ye)==128&&(Pe=(15&Fe)<<18|(63&ne)<<12|(63&pe)<<6|63&ye)>65535&&Pe<1114112&&(He=Pe)}He===null?(He=65533,ot=1):He>65535&&(He-=65536,te.push(He>>>10&1023|55296),He=56320|1023&He),te.push(He),oe+=ot}return function(Xe){var gt=Xe.length;if(gt<=I)return String.fromCharCode.apply(String,Xe);for(var rt="",ut=0;ut"u"||typeof console.error!="function"||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.buffer}}),Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.byteOffset}}),typeof Symbol<"u"&&Symbol.species!=null&&h[Symbol.species]===h&&Object.defineProperty(h,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),h.poolSize=8192,h.from=function(L,F,W){return u(L,F,W)},h.prototype.__proto__=Uint8Array.prototype,h.__proto__=Uint8Array,h.alloc=function(L,F,W){return function(te,oe,ne){return d(te),te<=0?l(te):oe!==void 0?typeof ne=="string"?l(te).fill(oe,ne):l(te).fill(oe):l(te)}(L,F,W)},h.allocUnsafe=function(L){return f(L)},h.allocUnsafeSlow=function(L){return f(L)},h.isBuffer=function(L){return L!=null&&L._isBuffer===!0&&L!==h.prototype},h.compare=function(L,F){if(le(L,Uint8Array)&&(L=h.from(L,L.offset,L.byteLength)),le(F,Uint8Array)&&(F=h.from(F,F.offset,F.byteLength)),!h.isBuffer(L)||!h.isBuffer(F))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(L===F)return 0;for(var W=L.length,te=F.length,oe=0,ne=Math.min(W,te);oethis.length||((te===void 0||te>this.length)&&(te=this.length),te<=0)||(te>>>=0)<=(W>>>=0))return"";for(F||(F="utf8");;)switch(F){case"hex":return H(this,W,te);case"utf8":case"utf-8":return M(this,W,te);case"ascii":return R(this,W,te);case"latin1":case"binary":return O(this,W,te);case"base64":return D(this,W,te);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G(this,W,te);default:if(oe)throw new TypeError("Unknown encoding: "+F);F=(F+"").toLowerCase(),oe=!0}}).apply(this,arguments)},h.prototype.toLocaleString=h.prototype.toString,h.prototype.equals=function(L){if(!h.isBuffer(L))throw new TypeError("Argument must be a Buffer");return this===L||h.compare(this,L)===0},h.prototype.inspect=function(){var L="",F=r.INSPECT_MAX_BYTES;return L=this.toString("hex",0,F).replace(/(.{2})/g,"$1 ").trim(),this.length>F&&(L+=" ... "),""},h.prototype.compare=function(L,F,W,te,oe){if(le(L,Uint8Array)&&(L=h.from(L,L.offset,L.byteLength)),!h.isBuffer(L))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof L);if(F===void 0&&(F=0),W===void 0&&(W=L?L.length:0),te===void 0&&(te=0),oe===void 0&&(oe=this.length),F<0||W>L.length||te<0||oe>this.length)throw new RangeError("out of range index");if(te>=oe&&F>=W)return 0;if(te>=oe)return-1;if(F>=W)return 1;if(F>>>=0,W>>>=0,te>>>=0,oe>>>=0,this===L)return 0;for(var ne=oe-te,pe=W-F,ye=Math.min(ne,pe),Pe=this.slice(te,oe),Fe=L.slice(F,W),He=0;He>>=0,isFinite(W)?(W>>>=0,te===void 0&&(te="utf8")):(te=W,W=void 0)}var oe=this.length-F;if((W===void 0||W>oe)&&(W=oe),L.length>0&&(W<0||F<0)||F>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");for(var ne=!1;;)switch(te){case"hex":return y(this,L,F,W);case"utf8":case"utf-8":return C(this,L,F,W);case"ascii":return b(this,L,F,W);case"latin1":case"binary":return T(this,L,F,W);case"base64":return S(this,L,F,W);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,L,F,W);default:if(ne)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),ne=!0}},h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var I=4096;function R(L,F,W){var te="";W=Math.min(L.length,W);for(var oe=F;oete)&&(W=te);for(var oe="",ne=F;neW)throw new RangeError("Trying to access beyond buffer length")}function $(L,F,W,te,oe,ne){if(!h.isBuffer(L))throw new TypeError('"buffer" argument must be a Buffer instance');if(F>oe||FL.length)throw new RangeError("Index out of range")}function V(L,F,W,te,oe,ne){if(W+te>L.length)throw new RangeError("Index out of range");if(W<0)throw new RangeError("Index out of range")}function j(L,F,W,te,oe){return F=+F,W>>>=0,oe||V(L,0,W,4),o.write(L,F,W,te,23,4),W+4}function k(L,F,W,te,oe){return F=+F,W>>>=0,oe||V(L,0,W,8),o.write(L,F,W,te,52,8),W+8}h.prototype.slice=function(L,F){var W=this.length;L=~~L,F=F===void 0?W:~~F,L<0?(L+=W)<0&&(L=0):L>W&&(L=W),F<0?(F+=W)<0&&(F=0):F>W&&(F=W),F>>=0,F>>>=0,W||Q(L,F,this.length);for(var te=this[L],oe=1,ne=0;++ne>>=0,F>>>=0,W||Q(L,F,this.length);for(var te=this[L+--F],oe=1;F>0&&(oe*=256);)te+=this[L+--F]*oe;return te},h.prototype.readUInt8=function(L,F){return L>>>=0,F||Q(L,1,this.length),this[L]},h.prototype.readUInt16LE=function(L,F){return L>>>=0,F||Q(L,2,this.length),this[L]|this[L+1]<<8},h.prototype.readUInt16BE=function(L,F){return L>>>=0,F||Q(L,2,this.length),this[L]<<8|this[L+1]},h.prototype.readUInt32LE=function(L,F){return L>>>=0,F||Q(L,4,this.length),(this[L]|this[L+1]<<8|this[L+2]<<16)+16777216*this[L+3]},h.prototype.readUInt32BE=function(L,F){return L>>>=0,F||Q(L,4,this.length),16777216*this[L]+(this[L+1]<<16|this[L+2]<<8|this[L+3])},h.prototype.readIntLE=function(L,F,W){L>>>=0,F>>>=0,W||Q(L,F,this.length);for(var te=this[L],oe=1,ne=0;++ne=(oe*=128)&&(te-=Math.pow(2,8*F)),te},h.prototype.readIntBE=function(L,F,W){L>>>=0,F>>>=0,W||Q(L,F,this.length);for(var te=F,oe=1,ne=this[L+--te];te>0&&(oe*=256);)ne+=this[L+--te]*oe;return ne>=(oe*=128)&&(ne-=Math.pow(2,8*F)),ne},h.prototype.readInt8=function(L,F){return L>>>=0,F||Q(L,1,this.length),128&this[L]?-1*(255-this[L]+1):this[L]},h.prototype.readInt16LE=function(L,F){L>>>=0,F||Q(L,2,this.length);var W=this[L]|this[L+1]<<8;return 32768&W?4294901760|W:W},h.prototype.readInt16BE=function(L,F){L>>>=0,F||Q(L,2,this.length);var W=this[L+1]|this[L]<<8;return 32768&W?4294901760|W:W},h.prototype.readInt32LE=function(L,F){return L>>>=0,F||Q(L,4,this.length),this[L]|this[L+1]<<8|this[L+2]<<16|this[L+3]<<24},h.prototype.readInt32BE=function(L,F){return L>>>=0,F||Q(L,4,this.length),this[L]<<24|this[L+1]<<16|this[L+2]<<8|this[L+3]},h.prototype.readFloatLE=function(L,F){return L>>>=0,F||Q(L,4,this.length),o.read(this,L,!0,23,4)},h.prototype.readFloatBE=function(L,F){return L>>>=0,F||Q(L,4,this.length),o.read(this,L,!1,23,4)},h.prototype.readDoubleLE=function(L,F){return L>>>=0,F||Q(L,8,this.length),o.read(this,L,!0,52,8)},h.prototype.readDoubleBE=function(L,F){return L>>>=0,F||Q(L,8,this.length),o.read(this,L,!1,52,8)},h.prototype.writeUIntLE=function(L,F,W,te){L=+L,F>>>=0,W>>>=0,te||$(this,L,F,W,Math.pow(2,8*W)-1,0);var oe=1,ne=0;for(this[F]=255&L;++ne>>=0,W>>>=0,te||$(this,L,F,W,Math.pow(2,8*W)-1,0);var oe=W-1,ne=1;for(this[F+oe]=255&L;--oe>=0&&(ne*=256);)this[F+oe]=L/ne&255;return F+W},h.prototype.writeUInt8=function(L,F,W){return L=+L,F>>>=0,W||$(this,L,F,1,255,0),this[F]=255&L,F+1},h.prototype.writeUInt16LE=function(L,F,W){return L=+L,F>>>=0,W||$(this,L,F,2,65535,0),this[F]=255&L,this[F+1]=L>>>8,F+2},h.prototype.writeUInt16BE=function(L,F,W){return L=+L,F>>>=0,W||$(this,L,F,2,65535,0),this[F]=L>>>8,this[F+1]=255&L,F+2},h.prototype.writeUInt32LE=function(L,F,W){return L=+L,F>>>=0,W||$(this,L,F,4,4294967295,0),this[F+3]=L>>>24,this[F+2]=L>>>16,this[F+1]=L>>>8,this[F]=255&L,F+4},h.prototype.writeUInt32BE=function(L,F,W){return L=+L,F>>>=0,W||$(this,L,F,4,4294967295,0),this[F]=L>>>24,this[F+1]=L>>>16,this[F+2]=L>>>8,this[F+3]=255&L,F+4},h.prototype.writeIntLE=function(L,F,W,te){if(L=+L,F>>>=0,!te){var oe=Math.pow(2,8*W-1);$(this,L,F,W,oe-1,-oe)}var ne=0,pe=1,ye=0;for(this[F]=255&L;++ne>0)-ye&255;return F+W},h.prototype.writeIntBE=function(L,F,W,te){if(L=+L,F>>>=0,!te){var oe=Math.pow(2,8*W-1);$(this,L,F,W,oe-1,-oe)}var ne=W-1,pe=1,ye=0;for(this[F+ne]=255&L;--ne>=0&&(pe*=256);)L<0&&ye===0&&this[F+ne+1]!==0&&(ye=1),this[F+ne]=(L/pe>>0)-ye&255;return F+W},h.prototype.writeInt8=function(L,F,W){return L=+L,F>>>=0,W||$(this,L,F,1,127,-128),L<0&&(L=255+L+1),this[F]=255&L,F+1},h.prototype.writeInt16LE=function(L,F,W){return L=+L,F>>>=0,W||$(this,L,F,2,32767,-32768),this[F]=255&L,this[F+1]=L>>>8,F+2},h.prototype.writeInt16BE=function(L,F,W){return L=+L,F>>>=0,W||$(this,L,F,2,32767,-32768),this[F]=L>>>8,this[F+1]=255&L,F+2},h.prototype.writeInt32LE=function(L,F,W){return L=+L,F>>>=0,W||$(this,L,F,4,2147483647,-2147483648),this[F]=255&L,this[F+1]=L>>>8,this[F+2]=L>>>16,this[F+3]=L>>>24,F+4},h.prototype.writeInt32BE=function(L,F,W){return L=+L,F>>>=0,W||$(this,L,F,4,2147483647,-2147483648),L<0&&(L=4294967295+L+1),this[F]=L>>>24,this[F+1]=L>>>16,this[F+2]=L>>>8,this[F+3]=255&L,F+4},h.prototype.writeFloatLE=function(L,F,W){return j(this,L,F,!0,W)},h.prototype.writeFloatBE=function(L,F,W){return j(this,L,F,!1,W)},h.prototype.writeDoubleLE=function(L,F,W){return k(this,L,F,!0,W)},h.prototype.writeDoubleBE=function(L,F,W){return k(this,L,F,!1,W)},h.prototype.copy=function(L,F,W,te){if(!h.isBuffer(L))throw new TypeError("argument should be a Buffer");if(W||(W=0),te||te===0||(te=this.length),F>=L.length&&(F=L.length),F||(F=0),te>0&&te=this.length)throw new RangeError("Index out of range");if(te<0)throw new RangeError("sourceEnd out of bounds");te>this.length&&(te=this.length),L.length-F=0;--ne)L[ne+F]=this[ne+W];else Uint8Array.prototype.set.call(L,this.subarray(W,te),F);return oe},h.prototype.fill=function(L,F,W,te){if(typeof L=="string"){if(typeof F=="string"?(te=F,F=0,W=this.length):typeof W=="string"&&(te=W,W=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!h.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(L.length===1){var oe=L.charCodeAt(0);(te==="utf8"&&oe<128||te==="latin1")&&(L=oe)}}else typeof L=="number"&&(L&=255);if(F<0||this.length>>=0,W=W===void 0?this.length:W>>>0,L||(L=0),typeof L=="number")for(ne=F;ne55295&&W<57344){if(!oe){if(W>56319){(F-=3)>-1&&ne.push(239,191,189);continue}if(pe+1===te){(F-=3)>-1&&ne.push(239,191,189);continue}oe=W;continue}if(W<56320){(F-=3)>-1&&ne.push(239,191,189),oe=W;continue}W=65536+(oe-55296<<10|W-56320)}else oe&&(F-=3)>-1&&ne.push(239,191,189);if(oe=null,W<128){if((F-=1)<0)break;ne.push(W)}else if(W<2048){if((F-=2)<0)break;ne.push(W>>6|192,63&W|128)}else if(W<65536){if((F-=3)<0)break;ne.push(W>>12|224,W>>6&63|128,63&W|128)}else{if(!(W<1114112))throw new Error("Invalid code point");if((F-=4)<0)break;ne.push(W>>18|240,W>>12&63|128,W>>6&63|128,63&W|128)}}return ne}function re(L){return a.toByteArray(function(F){if((F=(F=F.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;F.length%4!=0;)F+="=";return F}(L))}function he(L,F,W,te){for(var oe=0;oe=F.length||oe>=L.length);++oe)F[oe+W]=L[oe];return oe}function le(L,F){return L instanceof F||L!=null&&L.constructor!=null&&L.constructor.name!=null&&L.constructor.name===F.name}function ue(L){return L!=L}}).call(this)}).call(this,t("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(t,i,r){(function(s){(function(){r.formatArgs=function(o){if(o[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+o[0]+(this.useColors?"%c ":" ")+"+"+i.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;o.splice(1,0,c,"color: inherit");let l=0,h=0;o[0].replace(/%[a-zA-Z%]/g,u=>{u!=="%%"&&u==="%c"&&(h=++l)}),o.splice(h,0,c)},r.save=function(o){try{o?r.storage.setItem("debug",o):r.storage.removeItem("debug")}catch{}},r.load=function(){let o;try{o=r.storage.getItem("debug")}catch{}return!o&&s!==void 0&&"env"in s&&(o=s.env.DEBUG),o},r.useColors=function(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},r.storage=function(){try{return localStorage}catch{}}(),r.destroy=(()=>{let o=!1;return()=>{o||(o=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),r.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],r.log=console.debug||console.log||(()=>{}),i.exports=t("./common")(r);const{formatters:a}=i.exports;a.j=function(o){try{return JSON.stringify(o)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}).call(this)}).call(this,t("_process"))},{"./common":19,_process:50}],19:[function(t,i,r){i.exports=function(s){function a(l){let h,u,d,f=null;function p(..._){if(!p.enabled)return;const m=p,g=Number(new Date),v=g-(h||g);m.diff=v,m.prev=h,m.curr=g,h=g,_[0]=a.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let x=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(y,C)=>{if(y==="%%")return"%";x++;const b=a.formatters[C];if(typeof b=="function"){const T=_[x];y=b.call(m,T),_.splice(x,1),x--}return y}),a.formatArgs.call(m,_),(m.log||a.log).apply(m,_)}return p.namespace=l,p.useColors=a.useColors(),p.color=a.selectColor(l),p.extend=o,p.destroy=a.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(u!==a.namespaces&&(u=a.namespaces,d=a.enabled(l)),d),set:_=>{f=_}}),typeof a.init=="function"&&a.init(p),p}function o(l,h){const u=a(this.namespace+(h===void 0?":":h)+l);return u.log=this.log,u}function c(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}return a.debug=a,a.default=a,a.coerce=function(l){return l instanceof Error?l.stack||l.message:l},a.disable=function(){const l=[...a.names.map(c),...a.skips.map(c).map(h=>"-"+h)].join(",");return a.enable(""),l},a.enable=function(l){let h;a.save(l),a.namespaces=l,a.names=[],a.skips=[];const u=(typeof l=="string"?l:"").split(/[\s,]+/),d=u.length;for(h=0;h{a[l]=s[l]}),a.names=[],a.skips=[],a.formatters={},a.selectColor=function(l){let h=0;for(let u=0;u0&&N.length>T){N.warned=!0;var D=new Error("Possible EventEmitter memory leak detected. "+N.length+' "'+String(y)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');D.name="MaxListenersExceededWarning",D.emitter=x,D.type=y,D.count=N.length,typeof console=="object"&&console.warn&&console.warn("%s: %s",D.name,D.message)}}else N=S[y]=C,++x._eventsCount;return x}function p(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var x=new Array(arguments.length),y=0;y1&&(y=arguments[1]),y instanceof Error)throw y;var M=new Error('Unhandled "error" event. ('+y+")");throw M.context=y,M}if(!(C=N[x]))return!1;var I=typeof C=="function";switch(b=arguments.length){case 1:(function(R,O,H){if(O)R.call(H);else for(var G=R.length,Q=v(R,G),$=0;$=0;S--)if(C[S]===y||C[S].listener===y){N=C[S].listener,T=S;break}if(T<0)return this;T===0?C.shift():function(D,M){for(var I=M,R=I+1,O=D.length;R=0;b--)this.removeListener(x,y[b]);return this},c.prototype.listeners=function(x){return m(this,x,!0)},c.prototype.rawListeners=function(x){return m(this,x,!1)},c.listenerCount=function(x,y){return typeof x.listenerCount=="function"?x.listenerCount(y):g.call(x,y)},c.prototype.listenerCount=g,c.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(t,i,r){r.read=function(s,a,o,c,l){var h,u,d=8*l-c-1,f=(1<>1,_=-7,m=o?l-1:0,g=o?-1:1,v=s[a+m];for(m+=g,h=v&(1<<-_)-1,v>>=-_,_+=d;_>0;h=256*h+s[a+m],m+=g,_-=8);for(u=h&(1<<-_)-1,h>>=-_,_+=c;_>0;u=256*u+s[a+m],m+=g,_-=8);if(h===0)h=1-p;else{if(h===f)return u?NaN:1/0*(v?-1:1);u+=Math.pow(2,c),h-=p}return(v?-1:1)*u*Math.pow(2,h-c)},r.write=function(s,a,o,c,l,h){var u,d,f,p=8*h-l-1,_=(1<>1,g=l===23?Math.pow(2,-24)-Math.pow(2,-77):0,v=c?0:h-1,x=c?1:-1,y=a<0||a===0&&1/a<0?1:0;for(a=Math.abs(a),isNaN(a)||a===1/0?(d=isNaN(a)?1:0,u=_):(u=Math.floor(Math.log(a)/Math.LN2),a*(f=Math.pow(2,-u))<1&&(u--,f*=2),(a+=u+m>=1?g/f:g*Math.pow(2,1-m))*f>=2&&(u++,f/=2),u+m>=_?(d=0,u=_):u+m>=1?(d=(a*f-1)*Math.pow(2,l),u+=m):(d=a*Math.pow(2,m-1)*Math.pow(2,l),u=0));l>=8;s[o+v]=255&d,v+=x,d/=256,l-=8);for(u=u<0;s[o+v]=255&u,v+=x,u/=256,p-=8);s[o+v-x]|=128*y}},{}],24:[function(t,i,r){typeof Object.create=="function"?i.exports=function(s,a){a&&(s.super_=a,s.prototype=Object.create(a.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}))}:i.exports=function(s,a){if(a){s.super_=a;var o=function(){};o.prototype=a.prototype,s.prototype=new o,s.prototype.constructor=s}}},{}],25:[function(t,i,r){Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function a(o,c){this.color=!0,this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0,this.leftChild=void 0,this.rightChild=void 0,this.key=o,this.value=c}return a.prototype.rotateLeft=function(){var o=this.parent,c=this.brother,l=this.leftChild,h=this.rightChild;if(!h)throw new Error("unknown error");var u=h.leftChild,d=h.rightChild;return o&&(o.leftChild===this?o.leftChild=h:o.rightChild===this&&(o.rightChild=h)),h.parent=o,h.brother=c,h.leftChild=this,h.rightChild=d,c&&(c.brother=h),this.parent=h,this.brother=d,this.leftChild=l,this.rightChild=u,d&&(d.parent=h,d.brother=this),l&&(l.parent=this,l.brother=u),u&&(u.parent=this,u.brother=l),h},a.prototype.rotateRight=function(){var o=this.parent,c=this.brother,l=this.leftChild;if(!l)throw new Error("unknown error");var h=this.rightChild,u=l.leftChild,d=l.rightChild;return o&&(o.leftChild===this?o.leftChild=l:o.rightChild===this&&(o.rightChild=l)),l.parent=o,l.brother=c,l.leftChild=u,l.rightChild=this,c&&(c.brother=l),u&&(u.parent=l,u.brother=this),this.parent=l,this.brother=u,this.leftChild=d,this.rightChild=h,d&&(d.parent=this,d.brother=h),h&&(h.parent=this,h.brother=d),l},a.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},a.TreeNodeColorType={red:!0,black:!1},a}();Object.freeze(s),r.default=s},{}],26:[function(t,i,r){var s=this&&this.__generator||function(o,c){var l,h,u,d,f={label:0,sent:function(){if(1&u[0])throw u[1];return u[1]},trys:[],ops:[]};return d={next:p(0),throw:p(1),return:p(2)},typeof Symbol=="function"&&(d[Symbol.iterator]=function(){return this}),d;function p(_){return function(m){return function(g){if(l)throw new TypeError("Generator is already executing.");for(;f;)try{if(l=1,h&&(u=2&g[0]?h.return:g[0]?h.throw||((u=h.return)&&u.call(h),0):h.next)&&!(u=u.call(h,g[1])).done)return u;switch(h=0,u&&(g=[2&g[0],u.value]),g[0]){case 0:case 1:u=g;break;case 4:return f.label++,{value:g[1],done:!1};case 5:f.label++,h=g[1],g=[0];continue;case 7:g=f.ops.pop(),f.trys.pop();continue;default:if(!(u=(u=f.trys).length>0&&u[u.length-1])&&(g[0]===6||g[0]===2)){f=0;continue}if(g[0]===3&&(!u||g[1]>u[0]&&g[1]C)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(y/a.bucketSize),curNodePointerIndex:y%a.bucketSize}};this.getElementByPos=function(v){var x=m(v),y=x.curNodeBucketIndex,C=x.curNodePointerIndex;return l[y][C]},this.eraseElementByPos=function(v){var x=this;if(v<0||v>_)throw new Error("pos should more than 0 and less than queue's size");if(v===0)this.popFront();else if(v===this.size())this.popBack();else{for(var y=[],C=v+1;C<_;++C)y.push(this.getElementByPos(C));this.cut(v),this.popBack(),y.forEach(function(b){return x.pushBack(b)})}},this.eraseElementByValue=function(v){if(!this.empty()){var x=[];this.forEach(function(b){b!==v&&x.push(b)});for(var y=x.length,C=0;C0?--f:h0&&--_)},this.setElementByPos=function(v,x){var y=m(v),C=y.curNodeBucketIndex,b=y.curNodePointerIndex;l[C][b]=x},this.insert=function(v,x,y){var C=this;if(y===void 0&&(y=1),v===0)for(;y--;)this.pushFront(x);else if(v===this.size())for(;y--;)this.pushBack(x);else{for(var b=[],T=v;T<_;++T)b.push(this.getElementByPos(T));for(this.cut(v-1),T=0;T0?--u:h>0&&(--h,u=a.bucketSize-1)),++_,l[h][u]=v},this.popFront=function(){this.empty()||(this.size()!==1&&(u0&&--_)},this.shrinkToFit=function(){var v=this,x=[];this.forEach(function(T){x.push(T)});var y=x.length;l=[];for(var C=Math.ceil(y/a.bucketSize),b=0;b0&&p[p.length-1])&&(y[0]===6||y[0]===2)){m=0;continue}if(y[0]===3&&(!p||y[1]>p[0]&&y[1]=h.length&&(h=void 0),{value:h&&h[f++],done:!h}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var o=t("../LinkList/LinkList"),c=t("../Map/Map");function l(h,u,d){var f=this;if(h===void 0&&(h=[]),u===void 0&&(u=l.initSize),d=d||function(g){var v,x,y=0,C="";if(typeof g=="number")y=((y=Math.floor(g))<<5)-y,y&=y;else{C=typeof g!="string"?JSON.stringify(g):g;try{for(var b=a(C),T=b.next();!T.done;T=b.next())y=(y<<5)-y+T.value.charCodeAt(0),y&=y}catch(S){v={error:S}}finally{try{T&&!T.done&&(x=b.return)&&x.call(b)}finally{if(v)throw v.error}}}return y^=y>>>16},(u&u-1)!=0)throw new Error("initBucketNum must be 2 to the power of n");var p=0,_=[],m=Math.max(l.initSize,Math.min(l.maxSize,u));this.size=function(){return p},this.empty=function(){return p===0},this.clear=function(){p=0,m=u,_=[]},this.forEach=function(g){var v=0;_.forEach(function(x){x.forEach(function(y){g(y,v++)})})},this.setElement=function(g,v){var x,y;if(g==null)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(v!=null){var C=d(g)&m-1;if(_[C]){var b=_[C].size();if(_[C]instanceof o.default){try{for(var T=a(_[C]),S=T.next();!S.done;S=T.next()){var N=S.value;if(N.key===g)return void(N.value=v)}}catch(M){x={error:M}}finally{try{S&&!S.done&&(y=T.return)&&y.call(T)}finally{if(x)throw x.error}}_[C].pushBack({key:g,value:v}),_[C].size()>=l.treeifyThreshold&&(_[C]=new c.default(_[C]))}else _[C].setElement(g,v);var D=_[C].size();p+=D-b}else++p,_[C]=new o.default([{key:g,value:v}]);p>m*l.sigma&&(function(M){if(!(M>=l.maxSize)){m=2*M;var I=[];_.forEach(function(R,O){if(!R.empty()){if(R instanceof o.default&&R.size()===1){var H=R.front(),G=H.key,Q=H.value;I[d(G)&m-1]=new o.default([{key:G,value:Q}])}else if(R instanceof c.default){var $=new o.default,V=new o.default;R.forEach(function(z){d(z.key)&M?V.pushBack(z):$.pushBack(z)}),$.size()>l.untreeifyThreshold?I[O]=new c.default($):$.size()&&(I[O]=$),V.size()>l.untreeifyThreshold?I[O+M]=new c.default(V):V.size()&&(I[O+M]=V)}else{var j=new o.default,k=new o.default;R.forEach(function(z){d(z.key)&M?k.pushBack(z):j.pushBack(z)}),j.size()&&(I[O]=j),k.size()&&(I[O+M]=k)}_[O].clear()}}),_=I}}).call(this,m)}else this.eraseElementByKey(g)},this.getElementByKey=function(g){var v,x,y=d(g)&m-1;if(_[y]){if(_[y]instanceof c.default)return _[y].getElementByKey(g);try{for(var C=a(_[y]),b=C.next();!b.done;b=C.next()){var T=b.value;if(T.key===g)return T.value}}catch(S){v={error:S}}finally{try{b&&!b.done&&(x=C.return)&&x.call(C)}finally{if(v)throw v.error}}}},this.eraseElementByKey=function(g){var v,x,y=d(g)&m-1;if(_[y]){var C=_[y].size();if(_[y]instanceof c.default)_[y].eraseElementByKey(g),_[y].size()<=l.untreeifyThreshold&&(_[y]=new o.default(_[y]));else{var b=-1;try{for(var T=a(_[y]),S=T.next();!S.done;S=T.next())if(++b,S.value.key===g){_[y].eraseElementByPos(b);break}}catch(D){v={error:D}}finally{try{S&&!S.done&&(x=T.return)&&x.call(T)}finally{if(v)throw v.error}}}var N=_[y].size();p+=N-C}},this.find=function(g){var v,x,y=d(g)&m-1;if(!_[y])return!1;if(_[y]instanceof c.default)return _[y].find(g);try{for(var C=a(_[y]),b=C.next();!b.done;b=C.next())if(b.value.key===g)return!0}catch(T){v={error:T}}finally{try{b&&!b.done&&(x=C.return)&&x.call(C)}finally{if(v)throw v.error}}return!1},this[Symbol.iterator]=function(){return function(){var g,v,x,y,C,b;return s(this,function(T){switch(T.label){case 0:g=0,T.label=1;case 1:if(!(g=m)return[3,10];T.label=2;case 2:T.trys.push([2,7,8,9]),C=void 0,v=a(_[g]),x=v.next(),T.label=3;case 3:return x.done?[3,6]:[4,x.value];case 4:T.sent(),T.label=5;case 5:return x=v.next(),[3,3];case 6:return[3,9];case 7:return y=T.sent(),C={error:y},[3,9];case 8:try{x&&!x.done&&(b=v.return)&&b.call(v)}finally{if(C)throw C.error}return[7];case 9:return++g,[3,1];case 10:return[2]}})}()},h.forEach(function(g){var v=g.key,x=g.value;return f.setElement(v,x)}),Object.freeze(this)}l.initSize=16,l.maxSize=1<<30,l.sigma=.75,l.treeifyThreshold=8,l.untreeifyThreshold=6,l.minTreeifySize=64,Object.freeze(l),r.default=l},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(t,i,r){var s=this&&this.__generator||function(h,u){var d,f,p,_,m={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return _={next:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(_[Symbol.iterator]=function(){return this}),_;function g(v){return function(x){return function(y){if(d)throw new TypeError("Generator is already executing.");for(;m;)try{if(d=1,f&&(p=2&y[0]?f.return:y[0]?f.throw||((p=f.return)&&p.call(f),0):f.next)&&!(p=p.call(f,y[1])).done)return p;switch(f=0,p&&(y=[2&y[0],p.value]),y[0]){case 0:case 1:p=y;break;case 4:return m.label++,{value:y[1],done:!1};case 5:m.label++,f=y[1],y=[0];continue;case 7:y=m.ops.pop(),m.trys.pop();continue;default:if(!(p=(p=m.trys).length>0&&p[p.length-1])&&(y[0]===6||y[0]===2)){m=0;continue}if(y[0]===3&&(!p||y[1]>p[0]&&y[1]=h.length&&(h=void 0),{value:h&&h[f++],done:!h}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var o=t("../Set/Set"),c=t("../LinkList/LinkList");function l(h,u,d){var f=this;if(h===void 0&&(h=[]),u===void 0&&(u=l.initSize),d=d||function(g){var v=0,x="";if(typeof g=="number")v=((v=Math.floor(g))<<5)-v,v&=v;else{x=typeof g!="string"?JSON.stringify(g):g;for(var y=0;y>>16},(u&u-1)!=0)throw new Error("initBucketNum must be 2 to the power of n");var p=0,_=[],m=Math.max(l.initSize,Math.min(l.maxSize,u));this.size=function(){return p},this.empty=function(){return p===0},this.clear=function(){p=0,m=u,_=[]},this.forEach=function(g){var v=0;_.forEach(function(x){x.forEach(function(y){g(y,v++)})})},this.insert=function(g){if(g==null)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var v=d(g)&m-1;if(_[v]){var x=_[v].size();if(_[v]instanceof c.default){if(_[v].find(g))return;_[v].pushBack(g),_[v].size()>=l.treeifyThreshold&&(_[v]=new o.default(_[v]))}else _[v].insert(g);var y=_[v].size();p+=y-x}else _[v]=new c.default([g]),++p;p>m*l.sigma&&(function(C){if(!(C>=l.maxSize)){m=2*C;var b=[];_.forEach(function(T,S){if(!T.empty()){if(T instanceof c.default&&T.size()===1){var N=T.front();if(N===void 0)throw new Error("unknown error");b[d(N)&m-1]=new c.default([N])}else if(T instanceof o.default){var D=new c.default,M=new c.default;T.forEach(function(O){d(O)&C?M.pushBack(O):D.pushBack(O)}),D.size()>l.untreeifyThreshold?b[S]=new o.default(D):D.size()&&(b[S]=D),M.size()>l.untreeifyThreshold?b[S+C]=new o.default(M):M.size()&&(b[S+C]=M)}else{var I=new c.default,R=new c.default;T.forEach(function(O){d(O)&C?R.pushBack(O):I.pushBack(O)}),I.size()&&(b[S]=I),R.size()&&(b[S+C]=R)}_[S].clear()}}),_=b}}).call(this,m)},this.eraseElementByValue=function(g){var v=d(g)&m-1;if(_[v]){var x=_[v].size();_[v].eraseElementByValue(g),_[v]instanceof o.default&&_[v].size()<=l.untreeifyThreshold&&(_[v]=new c.default(_[v]));var y=_[v].size();p+=y-x}},this.find=function(g){var v=d(g)&m-1;return!!_[v]&&_[v].find(g)},this[Symbol.iterator]=function(){return function(){var g,v,x,y,C,b;return s(this,function(T){switch(T.label){case 0:g=0,T.label=1;case 1:if(!(g=m)return[3,10];T.label=2;case 2:T.trys.push([2,7,8,9]),C=void 0,v=a(_[g]),x=v.next(),T.label=3;case 3:return x.done?[3,6]:[4,x.value];case 4:T.sent(),T.label=5;case 5:return x=v.next(),[3,3];case 6:return[3,9];case 7:return y=T.sent(),C={error:y},[3,9];case 8:try{x&&!x.done&&(b=v.return)&&b.call(v)}finally{if(C)throw C.error}return[7];case 9:return++g,[3,1];case 10:return[2]}})}()},h.forEach(function(g){return f.insert(g)}),Object.freeze(this)}l.initSize=16,l.maxSize=1<<30,l.sigma=.75,l.treeifyThreshold=8,l.untreeifyThreshold=6,l.minTreeifySize=64,Object.freeze(l),r.default=l},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(t,i,r){var s=this&&this.__generator||function(c,l){var h,u,d,f,p={label:0,sent:function(){if(1&d[0])throw d[1];return d[1]},trys:[],ops:[]};return f={next:_(0),throw:_(1),return:_(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function _(m){return function(g){return function(v){if(h)throw new TypeError("Generator is already executing.");for(;p;)try{if(h=1,u&&(d=2&v[0]?u.return:v[0]?u.throw||((d=u.return)&&d.call(u),0):u.next)&&!(d=d.call(u,v[1])).done)return d;switch(u=0,d&&(v=[2&v[0],d.value]),v[0]){case 0:case 1:d=v;break;case 4:return p.label++,{value:v[1],done:!1};case 5:p.label++,u=v[1],v=[0];continue;case 7:v=p.ops.pop(),p.trys.pop();continue;default:if(!(d=(d=p.trys).length>0&&d[d.length-1])&&(v[0]===6||v[0]===2)){p=0;continue}if(v[0]===3&&(!d||v[1]>d[0]&&v[1]=h)throw new Error("pos must more then 0 and less then the list length");for(var p=u;f--&&p;)p=p.next;if(!p||p.value===void 0)throw new Error("unknown error");return p.value},this.eraseElementByPos=function(f){if(f<0||f>=h)throw new Error("erase pos must more then 0 and less then the list length");if(f===0)this.popFront();else if(f===h-1)this.popBack();else{for(var p=u;f--;){if(!(p!=null&&p.next))throw new Error("unknown error");p=p.next}if(!p||!p.pre||!p.next)throw new Error("unknown error");var _=p.pre,m=p.next;m.pre=_,_.next=m,h>0&&--h}},this.eraseElementByValue=function(f){for(;u&&u.value===f;)this.popFront();for(;d&&d.value===f;)this.popBack();if(u)for(var p=u;p;){if(p.value===f){var _=p.pre,m=p.next;m&&(m.pre=_),_&&(_.next=m),h>0&&--h}p=p.next}},this.pushBack=function(f){if(f==null)throw new Error("you can't push null or undefined here");++h;var p=new a(f);d?(d.next=p,p.pre=d,d=p):u=d=p},this.popBack=function(){d&&(h>0&&--h,d&&(u===d?u=d=void 0:(d=d.pre)&&(d.next=void 0)))},this.setElementByPos=function(f,p){if(p==null)throw new Error("you can't set null or undefined here");if(f<0||f>=h)throw new Error("pos must more then 0 and less then the list length");for(var _=u;f--;){if(!_)throw new Error("unknown error");_=_.next}_&&(_.value=p)},this.insert=function(f,p,_){if(_===void 0&&(_=1),p==null)throw new Error("you can't insert null or undefined here");if(f<0||f>h)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(_<0)throw new Error("insert size must more than 0");if(f===0)for(;_--;)this.pushFront(p);else if(f===h)for(;_--;)this.pushBack(p);else{for(var m=u,g=1;g0&&--h;f.next=p.next,f.next&&(f.next.pre=f),f=f.next}},this.sort=function(f){var p=[];this.forEach(function(m){p.push(m)}),p.sort(f);var _=u;p.forEach(function(m){_&&(_.value=m,_=_.next)})},this.pushFront=function(f){if(f==null)throw new Error("you can't push null or undefined here");++h;var p=new a(f);u?(p.next=u,u.pre=p,u=p):u=d=p},this.popFront=function(){u&&(h>0&&--h,u&&(u===d?u=d=void 0:(u=u.next)&&(u.pre=void 0)))},this.merge=function(f){var p=this,_=u;f.forEach(function(m){for(;_&&_.value!==void 0&&_.value<=m;)_=_.next;if(_===void 0)p.pushBack(m),_=d;else if(_===u)p.pushFront(m),_=u;else{++h;var g=_.pre;g&&(g.next=new a(m),g.next.pre=g,g.next.next=_,_&&(_.pre=g.next))}})},this[Symbol.iterator]=function(){return function(){var f;return s(this,function(p){switch(p.label){case 0:f=u,p.label=1;case 1:if(f===void 0)return[3,3];if(!f.value)throw new Error("unknown error");return[4,f.value];case 2:return p.sent(),f=f.next,[3,1];case 3:return[2]}})}()},c.forEach(function(f){return l.pushBack(f)}),Object.freeze(this)}Object.freeze(o),r.default=o},{}],30:[function(t,i,r){var s=this&&this.__generator||function(l,h){var u,d,f,p,_={label:0,sent:function(){if(1&f[0])throw f[1];return f[1]},trys:[],ops:[]};return p={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function m(g){return function(v){return function(x){if(u)throw new TypeError("Generator is already executing.");for(;_;)try{if(u=1,d&&(f=2&x[0]?d.return:x[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,x[1])).done)return f;switch(d=0,f&&(x=[2&x[0],f.value]),x[0]){case 0:case 1:f=x;break;case 4:return _.label++,{value:x[1],done:!1};case 5:_.label++,d=x[1],x=[0];continue;case 7:x=_.ops.pop(),_.trys.pop();continue;default:if(!(f=(f=_.trys).length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){_=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]=l.length&&(l=void 0),{value:l&&l[d++],done:!l}}};throw new TypeError(h?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var o=t("../Base/TreeNode");function c(l,h){var u=this;l===void 0&&(l=[]),h=h||function(M,I){return MI?1:0};var d=0,f=new o.default;f.color=o.default.TreeNodeColorType.black,this.size=function(){return d},this.empty=function(){return d===0},this.clear=function(){d=0,f.key=f.value=void 0,f.leftChild=f.rightChild=f.brother=void 0};var p=function(M){if(!M||M.key===void 0)throw new Error("unknown error");return M.leftChild?p(M.leftChild):M},_=function(M){if(!M||M.key===void 0)throw new Error("unknown error");return M.rightChild?_(M.rightChild):M};this.front=function(){if(!this.empty()){var M=p(f);if(M.key===void 0||M.value===void 0)throw new Error("unknown error");return{key:M.key,value:M.value}}},this.back=function(){if(!this.empty()){var M=_(f);if(M.key===void 0||M.value===void 0)throw new Error("unknown error");return{key:M.key,value:M.value}}},this.forEach=function(M){var I,R,O=0;try{for(var H=a(this),G=H.next();!G.done;G=H.next())M(G.value,O++)}catch(Q){I={error:Q}}finally{try{G&&!G.done&&(R=H.return)&&R.call(H)}finally{if(I)throw I.error}}},this.getElementByPos=function(M){var I,R;if(M<0||M>=this.size())throw new Error("pos must more than 0 and less than set's size");var O=0;try{for(var H=a(this),G=H.next();!G.done;G=H.next()){var Q=G.value;if(O===M)return Q;++O}}catch($){I={error:$}}finally{try{G&&!G.done&&(R=H.return)&&R.call(H)}finally{if(I)throw I.error}}throw new Error("unknown Error")};var m=function(M,I){if(M&&M.key!==void 0&&M.value!==void 0){var R=h(M.key,I);return R===0?{key:M.key,value:M.value}:R<0?m(M.rightChild,I):m(M.leftChild,I)||{key:M.key,value:M.value}}};this.lowerBound=function(M){return m(f,M)};var g=function(M,I){if(M&&M.key!==void 0&&M.value!==void 0)return h(M.key,I)<=0?g(M.rightChild,I):g(M.leftChild,I)||{key:M.key,value:M.value}};this.upperBound=function(M){return g(f,M)};var v=function(M,I){if(M&&M.key!==void 0&&M.value!==void 0){var R=h(M.key,I);return R===0?{key:M.key,value:M.value}:R>0?v(M.leftChild,I):v(M.rightChild,I)||{key:M.key,value:M.value}}};this.reverseLowerBound=function(M){return v(f,M)};var x=function(M,I){if(M&&M.key!==void 0&&M.value!==void 0)return h(M.key,I)>=0?x(M.leftChild,I):x(M.rightChild,I)||{key:M.key,value:M.value}};this.reverseUpperBound=function(M){return x(f,M)};var y=function(M){var I=M.parent;if(!I){if(M===f)return;throw new Error("unknown error")}if(M.color!==o.default.TreeNodeColorType.red){var R=M.brother;if(!R)throw new Error("unknown error");if(M===I.leftChild)if(R.color===o.default.TreeNodeColorType.red){R.color=o.default.TreeNodeColorType.black,I.color=o.default.TreeNodeColorType.red;var O=I.rotateLeft();f===I&&(f=O),y(M)}else R.color===o.default.TreeNodeColorType.black&&(R.rightChild&&R.rightChild.color===o.default.TreeNodeColorType.red?(R.color=I.color,I.color=o.default.TreeNodeColorType.black,R.rightChild&&(R.rightChild.color=o.default.TreeNodeColorType.black),O=I.rotateLeft(),f===I&&(f=O),M.color=o.default.TreeNodeColorType.black):R.rightChild&&R.rightChild.color!==o.default.TreeNodeColorType.black||!R.leftChild||R.leftChild.color!==o.default.TreeNodeColorType.red?R.leftChild&&R.leftChild.color!==o.default.TreeNodeColorType.black||R.rightChild&&R.rightChild.color!==o.default.TreeNodeColorType.black||(R.color=o.default.TreeNodeColorType.red,y(I)):(R.color=o.default.TreeNodeColorType.red,R.leftChild&&(R.leftChild.color=o.default.TreeNodeColorType.black),O=R.rotateRight(),f===R&&(f=O),y(M)));else M===I.rightChild&&(R.color===o.default.TreeNodeColorType.red?(R.color=o.default.TreeNodeColorType.black,I.color=o.default.TreeNodeColorType.red,O=I.rotateRight(),f===I&&(f=O),y(M)):R.color===o.default.TreeNodeColorType.black&&(R.leftChild&&R.leftChild.color===o.default.TreeNodeColorType.red?(R.color=I.color,I.color=o.default.TreeNodeColorType.black,R.leftChild&&(R.leftChild.color=o.default.TreeNodeColorType.black),O=I.rotateRight(),f===I&&(f=O),M.color=o.default.TreeNodeColorType.black):R.leftChild&&R.leftChild.color!==o.default.TreeNodeColorType.black||!R.rightChild||R.rightChild.color!==o.default.TreeNodeColorType.red?R.leftChild&&R.leftChild.color!==o.default.TreeNodeColorType.black||R.rightChild&&R.rightChild.color!==o.default.TreeNodeColorType.black||(R.color=o.default.TreeNodeColorType.red,y(I)):(R.color=o.default.TreeNodeColorType.red,R.rightChild&&(R.rightChild.color=o.default.TreeNodeColorType.black),O=R.rotateLeft(),f===R&&(f=O),y(M))))}else M.color=o.default.TreeNodeColorType.black},C=function(M){for(var I=M;I.leftChild||I.rightChild;){if(I.rightChild){I=p(I.rightChild);var R=M.key;M.key=I.key,I.key=R;var O=M.value;M.value=I.value,I.value=O,M=I}I.leftChild&&(I=_(I.leftChild),R=M.key,M.key=I.key,I.key=R,O=M.value,M.value=I.value,I.value=O,M=I)}y(I),I&&I.remove(),--d,f.color=o.default.TreeNodeColorType.black},b=function(M,I){return!(!M||M.key===void 0)&&(!!b(M.leftChild,I)||!!I(M)||b(M.rightChild,I))};this.eraseElementByPos=function(M){if(M<0||M>=d)throw new Error("pos must more than 0 and less than set's size");var I=0;b(f,function(R){return M===I?(C(R),!0):(++I,!1)})},this.eraseElementByKey=function(M){if(!this.empty()){var I=N(f,M);I!==void 0&&I.key!==void 0&&h(I.key,M)===0&&C(I)}};var T=function(M,I){if(!M||M.key===void 0)throw new Error("unknown error");var R=h(I,M.key);return R<0?M.leftChild?T(M.leftChild,I):(M.leftChild=new o.default,M.leftChild.parent=M,M.leftChild.brother=M.rightChild,M.rightChild&&(M.rightChild.brother=M.leftChild),M.leftChild):R>0?M.rightChild?T(M.rightChild,I):(M.rightChild=new o.default,M.rightChild.parent=M,M.rightChild.brother=M.leftChild,M.leftChild&&(M.leftChild.brother=M.rightChild),M.rightChild):M},S=function(M){var I=M.parent;if(!I){if(M===f)return;throw new Error("unknown error")}if(I.color!==o.default.TreeNodeColorType.black&&I.color===o.default.TreeNodeColorType.red){var R=I.brother,O=I.parent;if(!O)throw new Error("unknown error");if(R&&R.color===o.default.TreeNodeColorType.red)R.color=I.color=o.default.TreeNodeColorType.black,O.color=o.default.TreeNodeColorType.red,S(O);else if(!R||R.color===o.default.TreeNodeColorType.black)if(I===O.leftChild)if(M===I.leftChild){I.color=o.default.TreeNodeColorType.black,O.color=o.default.TreeNodeColorType.red;var H=O.rotateRight();O===f&&(f=H)}else M===I.rightChild&&(H=I.rotateLeft(),O===f&&(f=H),S(I));else I===O.rightChild&&(M===I.leftChild?(H=I.rotateRight(),O===f&&(f=H),S(I)):M===I.rightChild&&(I.color=o.default.TreeNodeColorType.black,O.color=o.default.TreeNodeColorType.red,H=O.rotateLeft(),O===f&&(f=H)))}};this.setElement=function(M,I){if(M==null)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(I!=null){if(this.empty())return++d,f.key=M,f.value=I,void(f.color=o.default.TreeNodeColorType.black);var R=T(f,M);R.key===void 0||h(R.key,M)!==0?(++d,R.key=M,R.value=I,S(R),f.color=o.default.TreeNodeColorType.black):R.value=I}else this.eraseElementByKey(M)};var N=function(M,I){if(M&&M.key!==void 0){var R=h(I,M.key);return R<0?N(M.leftChild,I):R>0?N(M.rightChild,I):M}};this.find=function(M){return!!N(f,M)},this.getElementByKey=function(M){var I=N(f,M);if((I==null?void 0:I.key)===void 0||(I==null?void 0:I.value)===void 0)throw new Error("unknown error");return I.value},this.union=function(M){var I=this;M.forEach(function(R){var O=R.key,H=R.value;return I.setElement(O,H)})},this.getHeight=function(){if(this.empty())return 0;var M=function(I){return I?Math.max(M(I.leftChild),M(I.rightChild))+1:1};return M(f)};var D=function(M){return s(this,function(I){switch(I.label){case 0:return M&&M.key!==void 0&&M.value!==void 0?[5,a(D(M.leftChild))]:[2];case 1:return I.sent(),[4,{key:M.key,value:M.value}];case 2:return I.sent(),[5,a(D(M.rightChild))];case 3:return I.sent(),[2]}})};this[Symbol.iterator]=function(){return D(f)},l.forEach(function(M){var I=M.key,R=M.value;return u.setElement(I,R)}),Object.freeze(this)}Object.freeze(c),r.default=c},{"../Base/TreeNode":25}],31:[function(t,i,r){function s(a,o){a===void 0&&(a=[]),o=o||function(d,f){return d>f?-1:d=l)throw new Error("unknown error");if(f<0||f>=l)throw new Error("unknown error");var p=c[d];c[d]=c[f],c[f]=p},u=function(d){if(d<0||d>=l)throw new Error("unknown error");var f=2*d+1,p=2*d+2;f0&&h(d,f),p0&&h(d,p)};(function(){for(var d=Math.floor((l-1)/2);d>=0;--d)for(var f=d,p=2*f+1;p0&&(m=_),o(c[f],c[m])<=0)break;h(f,m),p=2*(f=m)+1}})(),this.size=function(){return l},this.empty=function(){return l===0},this.clear=function(){l=0,c.length=0},this.push=function(d){if(c.push(d),++l!==1)for(var f=l-1;f>0;){var p=Math.floor((f-1)/2);if(o(c[p],d)<=0)break;u(p),f=p}},this.pop=function(){if(!this.empty())if(this.size()!==1){var d=c[l-1];--l;for(var f=0;f=this.size())break;var m=p;if(_0&&(m=_),o(c[m],d)>=0)break;c[f]=c[m],f=m}c[f]=d}else--l},this.top=function(){return c[0]},Object.freeze(this)}Object.defineProperty(r,"__esModule",{value:!0}),Object.freeze(s),r.default=s},{}],32:[function(t,i,r){Object.defineProperty(r,"__esModule",{value:!0});var s=t("../LinkList/LinkList");function a(o){o===void 0&&(o=[]);var c=new s.default(o);this.size=function(){return c.size()},this.empty=function(){return c.empty()},this.clear=function(){c.clear()},this.push=function(l){c.pushBack(l)},this.pop=function(){c.popFront()},this.front=function(){return c.front()},Object.freeze(this)}Object.freeze(a),r.default=a},{"../LinkList/LinkList":29}],33:[function(t,i,r){var s=this&&this.__generator||function(l,h){var u,d,f,p,_={label:0,sent:function(){if(1&f[0])throw f[1];return f[1]},trys:[],ops:[]};return p={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function m(g){return function(v){return function(x){if(u)throw new TypeError("Generator is already executing.");for(;_;)try{if(u=1,d&&(f=2&x[0]?d.return:x[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,x[1])).done)return f;switch(d=0,f&&(x=[2&x[0],f.value]),x[0]){case 0:case 1:f=x;break;case 4:return _.label++,{value:x[1],done:!1};case 5:_.label++,d=x[1],x=[0];continue;case 7:x=_.ops.pop(),_.trys.pop();continue;default:if(!(f=(f=_.trys).length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){_=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]=l.length&&(l=void 0),{value:l&&l[d++],done:!l}}};throw new TypeError(h?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var o=t("../Base/TreeNode");function c(l,h){var u=this;l===void 0&&(l=[]),h=h||function(M,I){return MI?1:0};var d=0,f=new o.default;f.color=o.default.TreeNodeColorType.black,this.size=function(){return d},this.empty=function(){return d===0},this.clear=function(){d=0,f.key=void 0,f.leftChild=f.rightChild=f.brother=f.parent=void 0,f.color=o.default.TreeNodeColorType.black};var p=function(M){if(!M||M.key===void 0)throw new Error("unknown error");return M.leftChild?p(M.leftChild):M},_=function(M){if(!M||M.key===void 0)throw new Error("unknown error");return M.rightChild?_(M.rightChild):M};this.front=function(){if(!this.empty())return p(f).key},this.back=function(){if(!this.empty())return _(f).key},this.forEach=function(M){var I,R,O=0;try{for(var H=a(this),G=H.next();!G.done;G=H.next())M(G.value,O++)}catch(Q){I={error:Q}}finally{try{G&&!G.done&&(R=H.return)&&R.call(H)}finally{if(I)throw I.error}}},this.getElementByPos=function(M){var I,R;if(M<0||M>=this.size())throw new Error("pos must more than 0 and less than set's size");var O=0;try{for(var H=a(this),G=H.next();!G.done;G=H.next()){var Q=G.value;if(O===M)return Q;++O}}catch($){I={error:$}}finally{try{G&&!G.done&&(R=H.return)&&R.call(H)}finally{if(I)throw I.error}}throw new Error("unknown error")};var m=function(M){var I=M.parent;if(!I){if(M===f)return;throw new Error("unknown error")}if(M.color!==o.default.TreeNodeColorType.red){var R=M.brother;if(!R)throw new Error("unknown error");if(M===I.leftChild)if(R.color===o.default.TreeNodeColorType.red){R.color=o.default.TreeNodeColorType.black,I.color=o.default.TreeNodeColorType.red;var O=I.rotateLeft();f===I&&(f=O),m(M)}else R.color===o.default.TreeNodeColorType.black&&(R.rightChild&&R.rightChild.color===o.default.TreeNodeColorType.red?(R.color=I.color,I.color=o.default.TreeNodeColorType.black,R.rightChild&&(R.rightChild.color=o.default.TreeNodeColorType.black),O=I.rotateLeft(),f===I&&(f=O),M.color=o.default.TreeNodeColorType.black):R.rightChild&&R.rightChild.color!==o.default.TreeNodeColorType.black||!R.leftChild||R.leftChild.color!==o.default.TreeNodeColorType.red?R.leftChild&&R.leftChild.color!==o.default.TreeNodeColorType.black||R.rightChild&&R.rightChild.color!==o.default.TreeNodeColorType.black||(R.color=o.default.TreeNodeColorType.red,m(I)):(R.color=o.default.TreeNodeColorType.red,R.leftChild&&(R.leftChild.color=o.default.TreeNodeColorType.black),O=R.rotateRight(),f===R&&(f=O),m(M)));else M===I.rightChild&&(R.color===o.default.TreeNodeColorType.red?(R.color=o.default.TreeNodeColorType.black,I.color=o.default.TreeNodeColorType.red,O=I.rotateRight(),f===I&&(f=O),m(M)):R.color===o.default.TreeNodeColorType.black&&(R.leftChild&&R.leftChild.color===o.default.TreeNodeColorType.red?(R.color=I.color,I.color=o.default.TreeNodeColorType.black,R.leftChild&&(R.leftChild.color=o.default.TreeNodeColorType.black),O=I.rotateRight(),f===I&&(f=O),M.color=o.default.TreeNodeColorType.black):R.leftChild&&R.leftChild.color!==o.default.TreeNodeColorType.black||!R.rightChild||R.rightChild.color!==o.default.TreeNodeColorType.red?R.leftChild&&R.leftChild.color!==o.default.TreeNodeColorType.black||R.rightChild&&R.rightChild.color!==o.default.TreeNodeColorType.black||(R.color=o.default.TreeNodeColorType.red,m(I)):(R.color=o.default.TreeNodeColorType.red,R.rightChild&&(R.rightChild.color=o.default.TreeNodeColorType.black),O=R.rotateLeft(),f===R&&(f=O),m(M))))}else M.color=o.default.TreeNodeColorType.black},g=function(M){for(var I=M;I.leftChild||I.rightChild;){if(I.rightChild){I=p(I.rightChild);var R=M.key;M.key=I.key,I.key=R,M=I}I.leftChild&&(I=_(I.leftChild),R=M.key,M.key=I.key,I.key=R,M=I)}m(I),I&&I.remove(),--d,f.color=o.default.TreeNodeColorType.black},v=function(M,I){return!(!M||M.key===void 0)&&(!!v(M.leftChild,I)||!!I(M)||v(M.rightChild,I))};this.eraseElementByPos=function(M){if(M<0||M>=d)throw new Error("pos must more than 0 and less than set's size");var I=0;v(f,function(R){return M===I?(g(R),!0):(++I,!1)})},this.eraseElementByValue=function(M){if(!this.empty()){var I=C(f,M);I!==void 0&&I.key!==void 0&&h(I.key,M)===0&&g(I)}};var x=function(M,I){if(!M||M.key===void 0)throw new Error("unknown error");var R=h(I,M.key);return R<0?M.leftChild?x(M.leftChild,I):(M.leftChild=new o.default,M.leftChild.parent=M,M.leftChild.brother=M.rightChild,M.rightChild&&(M.rightChild.brother=M.leftChild),M.leftChild):R>0?M.rightChild?x(M.rightChild,I):(M.rightChild=new o.default,M.rightChild.parent=M,M.rightChild.brother=M.leftChild,M.leftChild&&(M.leftChild.brother=M.rightChild),M.rightChild):M},y=function(M){var I=M.parent;if(!I){if(M===f)return;throw new Error("unknown error")}if(I.color!==o.default.TreeNodeColorType.black&&I.color===o.default.TreeNodeColorType.red){var R=I.brother,O=I.parent;if(!O)throw new Error("unknown error");if(R&&R.color===o.default.TreeNodeColorType.red)R.color=I.color=o.default.TreeNodeColorType.black,O.color=o.default.TreeNodeColorType.red,y(O);else if(!R||R.color===o.default.TreeNodeColorType.black)if(I===O.leftChild)if(M===I.leftChild){I.color=o.default.TreeNodeColorType.black,O.color=o.default.TreeNodeColorType.red;var H=O.rotateRight();O===f&&(f=H)}else M===I.rightChild&&(H=I.rotateLeft(),O===f&&(f=H),y(I));else I===O.rightChild&&(M===I.leftChild?(H=I.rotateRight(),O===f&&(f=H),y(I)):M===I.rightChild&&(I.color=o.default.TreeNodeColorType.black,O.color=o.default.TreeNodeColorType.red,H=O.rotateLeft(),O===f&&(f=H)))}};this.insert=function(M){if(M==null)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++d,f.key=M,void(f.color=o.default.TreeNodeColorType.black);var I=x(f,M);I.key!==void 0&&h(I.key,M)===0||(++d,I.key=M,y(I),f.color=o.default.TreeNodeColorType.black)};var C=function(M,I){if(M&&M.key!==void 0){var R=h(I,M.key);return R<0?C(M.leftChild,I):R>0?C(M.rightChild,I):M}};this.find=function(M){var I=C(f,M);return I!==void 0&&I.key!==void 0&&h(I.key,M)===0};var b=function(M,I){if(M&&M.key!==void 0){var R=h(M.key,I);if(R===0)return M.key;if(R<0)return b(M.rightChild,I);var O=b(M.leftChild,I);return O!==void 0?O:M.key}};this.lowerBound=function(M){return b(f,M)};var T=function(M,I){if(M&&M.key!==void 0){if(h(M.key,I)<=0)return T(M.rightChild,I);var R=T(M.leftChild,I);return R!==void 0?R:M.key}};this.upperBound=function(M){return T(f,M)};var S=function(M,I){if(M&&M.key!==void 0){var R=h(M.key,I);if(R===0)return M.key;if(R>0)return S(M.leftChild,I);var O=S(M.rightChild,I);return O!==void 0?O:M.key}};this.reverseLowerBound=function(M){return S(f,M)};var N=function(M,I){if(M&&M.key!==void 0){if(h(M.key,I)>=0)return N(M.leftChild,I);var R=N(M.rightChild,I);return R!==void 0?R:M.key}};this.reverseUpperBound=function(M){return N(f,M)},this.union=function(M){var I=this;M.forEach(function(R){return I.insert(R)})},this.getHeight=function(){if(this.empty())return 0;var M=function(I){return I?Math.max(M(I.leftChild),M(I.rightChild))+1:1};return M(f)};var D=function(M){return s(this,function(I){switch(I.label){case 0:return M&&M.key!==void 0?[5,a(D(M.leftChild))]:[2];case 1:return I.sent(),[4,M.key];case 2:return I.sent(),[5,a(D(M.rightChild))];case 3:return I.sent(),[2]}})};this[Symbol.iterator]=function(){return D(f)},l.forEach(function(M){return u.insert(M)}),Object.freeze(this)}Object.freeze(c),r.default=c},{"../Base/TreeNode":25}],34:[function(t,i,r){function s(a){var o=this;a===void 0&&(a=[]);var c=0,l=[];this.size=function(){return c},this.empty=function(){return c===0},this.clear=function(){c=0,l.length=0},this.push=function(h){l.push(h),++c},this.pop=function(){l.pop(),c>0&&--c},this.top=function(){return l[c-1]},a.forEach(function(h){return o.push(h)}),Object.freeze(this)}Object.defineProperty(r,"__esModule",{value:!0}),Object.freeze(s),r.default=s},{}],35:[function(t,i,r){var s=this&&this.__generator||function(h,u){var d,f,p,_,m={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return _={next:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(_[Symbol.iterator]=function(){return this}),_;function g(v){return function(x){return function(y){if(d)throw new TypeError("Generator is already executing.");for(;m;)try{if(d=1,f&&(p=2&y[0]?f.return:y[0]?f.throw||((p=f.return)&&p.call(f),0):f.next)&&!(p=p.call(f,y[1])).done)return p;switch(f=0,p&&(y=[2&y[0],p.value]),y[0]){case 0:case 1:p=y;break;case 4:return m.label++,{value:y[1],done:!1};case 5:m.label++,f=y[1],y=[0];continue;case 7:y=m.ops.pop(),m.trys.pop();continue;default:if(!(p=(p=m.trys).length>0&&p[p.length-1])&&(y[0]===6||y[0]===2)){m=0;continue}if(y[0]===3&&(!p||y[1]>p[0]&&y[1]0)&&!(f=_.next()).done;)m.push(f.value)}catch(g){p={error:g}}finally{try{f&&!f.done&&(d=_.return)&&d.call(_)}finally{if(p)throw p.error}}return m},o=this&&this.__spreadArray||function(h,u,d){if(d||arguments.length===2)for(var f,p=0,_=u.length;p<_;p++)!f&&p in u||(f||(f=Array.prototype.slice.call(u,0,p)),f[p]=u[p]);return h.concat(f||Array.prototype.slice.call(u))},c=this&&this.__values||function(h){var u=typeof Symbol=="function"&&Symbol.iterator,d=u&&h[u],f=0;if(d)return d.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&f>=h.length&&(h=void 0),{value:h&&h[f++],done:!h}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")};function l(h){var u=this;h===void 0&&(h=[]);var d=0,f=[];this.size=function(){return d},this.empty=function(){return d===0},this.clear=function(){d=0,f.length=0},this.front=function(){if(!this.empty())return f[0]},this.back=function(){if(!this.empty())return f[d-1]},this.forEach=function(p){f.forEach(p)},this.getElementByPos=function(p){if(p<0||p>=d)throw new Error("pos must more than 0 and less than vector's size");return f[p]},this.eraseElementByPos=function(p){if(p<0||p>=d)throw new Error("pos must more than 0 and less than vector's size");for(var _=p;_m;)this.popBack()},this.pushBack=function(p){f.push(p),++d},this.popBack=function(){f.pop(),d>0&&--d},this.setElementByPos=function(p,_){if(p<0||p>=d)throw new Error("pos must more than 0 and less than vector's size");f[p]=_},this.insert=function(p,_,m){if(m===void 0&&(m=1),p<0||p>d)throw new Error("pos must more than 0 and less than or equal to vector's size");f.splice.apply(f,o([p,0],a(new Array(m).fill(_)),!1)),d+=m},this.find=function(p){return f.includes(p)},this.reverse=function(){f.reverse()},this.unique=function(){var p,_=[];this.forEach(function(g,v){v!==0&&g===p||(_.push(g),p=g)}),_.forEach(function(g,v){f[v]=g});for(var m=_.length;d>m;)this.popBack()},this.sort=function(p){f.sort(p)},this[Symbol.iterator]=function(){return function(){return s(this,function(p){switch(p.label){case 0:return[5,c(f)];case 1:return[2,p.sent()]}})}()},h.forEach(function(p){return u.pushBack(p)}),Object.freeze(this)}Object.defineProperty(r,"__esModule",{value:!0}),Object.freeze(l),r.default=l},{}],36:[function(t,i,r){Object.defineProperty(r,"__esModule",{value:!0}),r.HashMap=r.HashSet=r.Map=r.Set=r.PriorityQueue=r.Deque=r.LinkList=r.Queue=r.Stack=r.Vector=void 0;var s=t("./Vector/Vector");r.Vector=s.default;var a=t("./Stack/Stack");r.Stack=a.default;var o=t("./Queue/Queue");r.Queue=o.default;var c=t("./LinkList/LinkList");r.LinkList=c.default;var l=t("./Deque/Deque");r.Deque=l.default;var h=t("./PriorityQueue/PriorityQueue");r.PriorityQueue=h.default;var u=t("./Set/Set");r.Set=u.default;var d=t("./Map/Map");r.Map=d.default;var f=t("./HashSet/HashSet");r.HashSet=f.default;var p=t("./HashMap/HashMap");r.HashMap=p.default},{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(t,i,r){const s=t("yallist"),a=Symbol("max"),o=Symbol("length"),c=Symbol("lengthCalculator"),l=Symbol("allowStale"),h=Symbol("maxAge"),u=Symbol("dispose"),d=Symbol("noDisposeOnSet"),f=Symbol("lruList"),p=Symbol("cache"),_=Symbol("updateAgeOnGet"),m=()=>1,g=(T,S,N)=>{const D=T[p].get(S);if(D){const M=D.value;if(v(T,M)){if(y(T,D),!T[l])return}else N&&(T[_]&&(D.value.now=Date.now()),T[f].unshiftNode(D));return M.value}},v=(T,S)=>{if(!S||!S.maxAge&&!T[h])return!1;const N=Date.now()-S.now;return S.maxAge?N>S.maxAge:T[h]&&N>T[h]},x=T=>{if(T[o]>T[a])for(let S=T[f].tail;T[o]>T[a]&&S!==null;){const N=S.prev;y(T,S),S=N}},y=(T,S)=>{if(S){const N=S.value;T[u]&&T[u](N.key,N.value),T[o]-=N.length,T[p].delete(N.key),T[f].removeNode(S)}};class C{constructor(S,N,D,M,I){this.key=S,this.value=N,this.length=D,this.now=M,this.maxAge=I||0}}const b=(T,S,N,D)=>{let M=N.value;v(T,M)&&(y(T,N),T[l]||(M=void 0)),M&&S.call(D,M.value,M.key,T)};i.exports=class{constructor(T){if(typeof T=="number"&&(T={max:T}),T||(T={}),T.max&&(typeof T.max!="number"||T.max<0))throw new TypeError("max must be a non-negative number");this[a]=T.max||1/0;const S=T.length||m;if(this[c]=typeof S!="function"?m:S,this[l]=T.stale||!1,T.maxAge&&typeof T.maxAge!="number")throw new TypeError("maxAge must be a number");this[h]=T.maxAge||0,this[u]=T.dispose,this[d]=T.noDisposeOnSet||!1,this[_]=T.updateAgeOnGet||!1,this.reset()}set max(T){if(typeof T!="number"||T<0)throw new TypeError("max must be a non-negative number");this[a]=T||1/0,x(this)}get max(){return this[a]}set allowStale(T){this[l]=!!T}get allowStale(){return this[l]}set maxAge(T){if(typeof T!="number")throw new TypeError("maxAge must be a non-negative number");this[h]=T,x(this)}get maxAge(){return this[h]}set lengthCalculator(T){typeof T!="function"&&(T=m),T!==this[c]&&(this[c]=T,this[o]=0,this[f].forEach(S=>{S.length=this[c](S.value,S.key),this[o]+=S.length})),x(this)}get lengthCalculator(){return this[c]}get length(){return this[o]}get itemCount(){return this[f].length}rforEach(T,S){S=S||this;for(let N=this[f].tail;N!==null;){const D=N.prev;b(this,T,N,S),N=D}}forEach(T,S){S=S||this;for(let N=this[f].head;N!==null;){const D=N.next;b(this,T,N,S),N=D}}keys(){return this[f].toArray().map(T=>T.key)}values(){return this[f].toArray().map(T=>T.value)}reset(){this[u]&&this[f]&&this[f].length&&this[f].forEach(T=>this[u](T.key,T.value)),this[p]=new Map,this[f]=new s,this[o]=0}dump(){return this[f].map(T=>!v(this,T)&&{k:T.key,v:T.value,e:T.now+(T.maxAge||0)}).toArray().filter(T=>T)}dumpLru(){return this[f]}set(T,S,N){if((N=N||this[h])&&typeof N!="number")throw new TypeError("maxAge must be a number");const D=N?Date.now():0,M=this[c](S,T);if(this[p].has(T)){if(M>this[a])return y(this,this[p].get(T)),!1;const R=this[p].get(T).value;return this[u]&&(this[d]||this[u](T,R.value)),R.now=D,R.maxAge=N,R.value=S,this[o]+=M-R.length,R.length=M,this.get(T),x(this),!0}const I=new C(T,S,M,D,N);return I.length>this[a]?(this[u]&&this[u](T,S),!1):(this[o]+=I.length,this[f].unshift(I),this[p].set(T,this[f].head),x(this),!0)}has(T){if(!this[p].has(T))return!1;const S=this[p].get(T).value;return!v(this,S)}get(T){return g(this,T,!0)}peek(T){return g(this,T,!1)}pop(){const T=this[f].tail;return T?(y(this,T),T.value):null}del(T){y(this,this[p].get(T))}load(T){this.reset();const S=Date.now();for(let N=T.length-1;N>=0;N--){const D=T[N],M=D.e||0;if(M===0)this.set(D.k,D.v);else{const I=M-S;I>0&&this.set(D.k,D.v,I)}}}prune(){this[p].forEach((T,S)=>g(this,S,!1))}}},{yallist:83}],38:[function(t,i,r){(function(s){(function(){const a=i.exports;a.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},a.codes={};for(const c in a.types){const l=a.types[c];a.codes[l]=c}a.CMD_SHIFT=4,a.CMD_MASK=240,a.DUP_MASK=8,a.QOS_MASK=3,a.QOS_SHIFT=1,a.RETAIN_MASK=1,a.VARBYTEINT_MASK=127,a.VARBYTEINT_FIN_MASK=128,a.VARBYTEINT_MAX=268435455,a.SESSIONPRESENT_MASK=1,a.SESSIONPRESENT_HEADER=s.from([a.SESSIONPRESENT_MASK]),a.CONNACK_HEADER=s.from([a.codes.connack<[0,1].map(h=>[0,1].map(u=>{const d=s.alloc(1);return d.writeUInt8(a.codes[c]<s.from([c])),a.EMPTY={pingreq:s.from([a.codes.pingreq<<4,0]),pingresp:s.from([a.codes.pingresp<<4,0]),disconnect:s.from([a.codes.disconnect<<4,0])}}).call(this)}).call(this,t("buffer").Buffer)},{buffer:17}],39:[function(t,i,r){(function(s){(function(){const a=t("./writeToStream"),o=t("events");class c extends o{constructor(){super(),this._array=new Array(20),this._i=0}write(h){return this._array[this._i++]=h,!0}concat(){let h=0;const u=new Array(this._array.length),d=this._array;let f,p=0;for(f=0;f>8,0),u.writeUInt8(255&h,1),u}i.exports={cache:o,generateCache:function(){for(let h=0;h<65536;h++)o[h]=l(h)},generateNumber:l,genBufVariableByteInt:function(h){let u=0,d=0;const f=s.allocUnsafe(4);do u=h%128|0,(h=h/128|0)>0&&(u|=128),f.writeUInt8(u,d++);while(h>0&&d<4);return h>0&&(d=0),c?f.subarray(0,d):f.slice(0,d)},generate4ByteBuffer:function(h){const u=s.allocUnsafe(4);return u.writeUInt32BE(h,0),u}}}).call(this)}).call(this,t("buffer").Buffer)},{buffer:17}],42:[function(t,i,r){i.exports=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}},{}],43:[function(t,i,r){const s=t("bl"),a=t("events"),o=t("./packet"),c=t("./constants"),l=t("debug")("mqtt-packet:parser");class h extends a{constructor(){super(),this.parser=this.constructor.parser}static parser(d){return this instanceof h?(this.settings=d||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new h().parser(d)}_resetState(){l("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new o,this.error=null,this._list=s(),this._stateCounter=0}parse(d){for(this.error&&this._resetState(),this._list.append(d),l("parse: current state: %s",this._states[this._stateCounter]);(this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,l("parse: state complete. _stateCounter is now: %d",this._stateCounter),l("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return l("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const d=this._list.readUInt8(0);return this.packet.cmd=c.types[d>>c.CMD_SHIFT],this.packet.retain=(d&c.RETAIN_MASK)!=0,this.packet.qos=d>>c.QOS_SHIFT&c.QOS_MASK,this.packet.dup=(d&c.DUP_MASK)!=0,l("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){const d=this._parseVarByteNum(!0);return d&&(this.packet.length=d.value,this._list.consume(d.bytes)),l("_parseLength %d",d.value),!!d}_parsePayload(){l("_parsePayload: payload %O",this._list);let d=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}d=!0}return l("_parsePayload complete result: %s",d),d}_parseConnect(){let d,f,p,_;l("_parseConnect");const m={},g=this.packet,v=this._parseString();if(v===null)return this._emitError(new Error("Cannot parse protocolId"));if(v!=="MQTT"&&v!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(g.protocolId=v,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(g.protocolVersion=this._list.readUInt8(this._pos),g.protocolVersion>=128&&(g.bridgeMode=!0,g.protocolVersion=g.protocolVersion-128),g.protocolVersion!==3&&g.protocolVersion!==4&&g.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(m.username=this._list.readUInt8(this._pos)&c.USERNAME_MASK,m.password=this._list.readUInt8(this._pos)&c.PASSWORD_MASK,m.will=this._list.readUInt8(this._pos)&c.WILL_FLAG_MASK,m.will&&(g.will={},g.will.retain=(this._list.readUInt8(this._pos)&c.WILL_RETAIN_MASK)!=0,g.will.qos=(this._list.readUInt8(this._pos)&c.WILL_QOS_MASK)>>c.WILL_QOS_SHIFT),g.clean=(this._list.readUInt8(this._pos)&c.CLEAN_SESSION_MASK)!=0,this._pos++,g.keepalive=this._parseNum(),g.keepalive===-1)return this._emitError(new Error("Packet too short"));if(g.protocolVersion===5){const y=this._parseProperties();Object.getOwnPropertyNames(y).length&&(g.properties=y)}const x=this._parseString();if(x===null)return this._emitError(new Error("Packet too short"));if(g.clientId=x,l("_parseConnect: packet.clientId: %s",g.clientId),m.will){if(g.protocolVersion===5){const y=this._parseProperties();Object.getOwnPropertyNames(y).length&&(g.will.properties=y)}if((d=this._parseString())===null)return this._emitError(new Error("Cannot parse will topic"));if(g.will.topic=d,l("_parseConnect: packet.will.topic: %s",g.will.topic),(f=this._parseBuffer())===null)return this._emitError(new Error("Cannot parse will payload"));g.will.payload=f,l("_parseConnect: packet.will.paylaod: %s",g.will.payload)}if(m.username){if((_=this._parseString())===null)return this._emitError(new Error("Cannot parse username"));g.username=_,l("_parseConnect: packet.username: %s",g.username)}if(m.password){if((p=this._parseBuffer())===null)return this._emitError(new Error("Cannot parse password"));g.password=p}return this.settings=g,l("_parseConnect: complete"),g}_parseConnack(){l("_parseConnack");const d=this.packet;if(this._list.length<1)return null;if(d.sessionPresent=!!(this._list.readUInt8(this._pos++)&c.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?d.reasonCode=this._list.readUInt8(this._pos++):d.reasonCode=0;else{if(this._list.length<2)return null;d.returnCode=this._list.readUInt8(this._pos++)}if(d.returnCode===-1||d.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){const f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(d.properties=f)}l("_parseConnack: complete")}_parsePublish(){l("_parsePublish");const d=this.packet;if(d.topic=this._parseString(),d.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(d.qos>0)||this._parseMessageId()){if(this.settings.protocolVersion===5){const f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(d.properties=f)}d.payload=this._list.slice(this._pos,d.length),l("_parsePublish: payload from buffer list: %o",d.payload)}}_parseSubscribe(){l("_parseSubscribe");const d=this.packet;let f,p,_,m,g,v,x;if(d.qos!==1)return this._emitError(new Error("Wrong subscribe header"));if(d.subscriptions=[],this._parseMessageId()){if(this.settings.protocolVersion===5){const y=this._parseProperties();Object.getOwnPropertyNames(y).length&&(d.properties=y)}for(;this._pos=d.length)return this._emitError(new Error("Malformed Subscribe Payload"));_=(p=this._parseByte())&c.SUBSCRIBE_OPTIONS_QOS_MASK,v=(p>>c.SUBSCRIBE_OPTIONS_NL_SHIFT&c.SUBSCRIBE_OPTIONS_NL_MASK)!=0,g=(p>>c.SUBSCRIBE_OPTIONS_RAP_SHIFT&c.SUBSCRIBE_OPTIONS_RAP_MASK)!=0,m=p>>c.SUBSCRIBE_OPTIONS_RH_SHIFT&c.SUBSCRIBE_OPTIONS_RH_MASK,x={topic:f,qos:_},this.settings.protocolVersion===5?(x.nl=v,x.rap=g,x.rh=m):this.settings.bridgeMode&&(x.rh=0,x.rap=!0,x.nl=!0),l("_parseSubscribe: push subscription `%s` to subscription",x),d.subscriptions.push(x)}}}_parseSuback(){l("_parseSuback");const d=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(this.settings.protocolVersion===5){const f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(d.properties=f)}for(;this._pos2?(d.reasonCode=this._parseByte(),l("_parseConfirmation: packet.reasonCode `%d`",d.reasonCode)):d.reasonCode=0,d.length>3)){const f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(d.properties=f)}return!0}_parseDisconnect(){const d=this.packet;if(l("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?d.reasonCode=this._parseByte():d.reasonCode=0;const f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(d.properties=f)}return l("_parseDisconnect result: true"),!0}_parseAuth(){l("_parseAuth");const d=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));d.reasonCode=this._parseByte();const f=this._parseProperties();return Object.getOwnPropertyNames(f).length&&(d.properties=f),l("_parseAuth: result: true"),!0}_parseMessageId(){const d=this.packet;return d.messageId=this._parseNum(),d.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(l("_parseMessageId: packet.messageId %d",d.messageId),!0)}_parseString(d){const f=this._parseNum(),p=f+this._pos;if(f===-1||p>this._list.length||p>this.packet.length)return null;const _=this._list.toString("utf8",this._pos,p);return this._pos+=f,l("_parseString: result: %s",_),_}_parseStringPair(){return l("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const d=this._parseNum(),f=d+this._pos;if(d===-1||f>this._list.length||f>this.packet.length)return null;const p=this._list.slice(this._pos,f);return this._pos+=d,l("_parseBuffer: result: %o",p),p}_parseNum(){if(this._list.length-this._pos<2)return-1;const d=this._list.readUInt16BE(this._pos);return this._pos+=2,l("_parseNum: result: %s",d),d}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const d=this._list.readUInt32BE(this._pos);return this._pos+=4,l("_parse4ByteNum: result: %s",d),d}_parseVarByteNum(d){l("_parseVarByteNum");let f,p=0,_=1,m=0,g=!1;const v=this._pos?this._pos:0;for(;p<4&&v+p=p&&this._emitError(new Error("Invalid variable byte integer")),v&&(this._pos+=p),l("_parseVarByteNum: result: %o",g=!!g&&(d?{bytes:p,value:m}:m)),g}_parseByte(){let d;return this._pos=4)&&(F||ue))ne+=s.byteLength(F)+2;else{if(he<4)return z.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*ue==0)return z.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof L!="number"||L<0||L>65535||L%1!=0)return z.emit("error",new Error("Invalid keepalive")),!1;if(ne+=2,ne+=1,he===5){var pe=I(z,oe);if(!pe)return!1;ne+=pe.length}if(le){if(typeof le!="object")return z.emit("error",new Error("Invalid will")),!1;if(!le.topic||typeof le.topic!="string")return z.emit("error",new Error("Invalid will topic")),!1;if(ne+=s.byteLength(le.topic)+2,ne+=2,le.payload){if(!(le.payload.length>=0))return z.emit("error",new Error("Invalid will payload")),!1;typeof le.payload=="string"?ne+=s.byteLength(le.payload):ne+=le.payload.length}var ye={};if(he===5){if(!(ye=I(z,le.properties)))return!1;ne+=ye.length}}let Pe=!1;if(W!=null){if(!Q(W))return z.emit("error",new Error("Invalid username")),!1;Pe=!0,ne+=s.byteLength(W)+2}if(te!=null){if(!Pe)return z.emit("error",new Error("Username is required to use password")),!1;if(!Q(te))return z.emit("error",new Error("Invalid password")),!1;ne+=G(te)+2}z.write(a.CONNECT_HEADER),b(z,ne),M(z,re),J.bridgeMode&&(he+=128),z.write(he===131?a.VERSION131:he===132?a.VERSION132:he===4?a.VERSION4:he===5?a.VERSION5:a.VERSION3);let Fe=0;return Fe|=W!=null?a.USERNAME_MASK:0,Fe|=te!=null?a.PASSWORD_MASK:0,Fe|=le&&le.retain?a.WILL_RETAIN_MASK:0,Fe|=le&&le.qos?le.qos<0&&g(z,F),oe!=null&&oe.write(),u("publish: payload: %o",L),z.write(L)}($,V,j);case"puback":case"pubrec":case"pubrel":case"pubcomp":return function(k,z,Y){const J=Y?Y.protocolVersion:4,re=k||{},he=re.cmd||"puback",le=re.messageId,ue=re.dup&&he==="pubrel"?a.DUP_MASK:0;let L=0;const F=re.reasonCode,W=re.properties;let te=J===5?3:2;if(he==="pubrel"&&(L=1),typeof le!="number")return z.emit("error",new Error("Invalid messageId")),!1;let oe=null;if(J===5&&typeof W=="object"){if(!(oe=R(z,W,Y,te)))return!1;te+=oe.length}return z.write(a.ACKS[he][L][ue][0]),b(z,te),g(z,le),J===5&&z.write(s.from([F])),oe!==null&&oe.write(),!0}($,V,j);case"subscribe":return function(k,z,Y){u("subscribe: packet: ");const J=Y?Y.protocolVersion:4,re=k||{},he=re.dup?a.DUP_MASK:0,le=re.messageId,ue=re.subscriptions,L=re.properties;let F=0;if(typeof le!="number")return z.emit("error",new Error("Invalid messageId")),!1;F+=2;let W=null;if(J===5){if(!(W=I(z,L)))return!1;F+=W.length}if(typeof ue!="object"||!ue.length)return z.emit("error",new Error("Invalid subscriptions")),!1;for(let oe=0;oe2)return z.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}F+=s.byteLength(ne)+2+1}u("subscribe: writing to stream: %o",a.SUBSCRIBE_HEADER),z.write(a.SUBSCRIBE_HEADER[1][he?1:0][0]),b(z,F),g(z,le),W!==null&&W.write();let te=!0;for(const oe of ue){const ne=oe.topic,pe=oe.qos,ye=+oe.nl,Pe=+oe.rap,Fe=oe.rh;let He;T(z,ne),He=a.SUBSCRIBE_OPTIONS_QOS[pe],J===5&&(He|=ye?a.SUBSCRIBE_OPTIONS_NL:0,He|=Pe?a.SUBSCRIBE_OPTIONS_RAP:0,He|=Fe?a.SUBSCRIBE_OPTIONS_RH[Fe]:0),te=z.write(s.from([He]))}return te}($,V,j);case"suback":return function(k,z,Y){const J=Y?Y.protocolVersion:4,re=k||{},he=re.messageId,le=re.granted,ue=re.properties;let L=0;if(typeof he!="number")return z.emit("error",new Error("Invalid messageId")),!1;if(L+=2,typeof le!="object"||!le.length)return z.emit("error",new Error("Invalid qos vector")),!1;for(let W=0;Wg===N,set($){$?(d&&Object.keys(d).length!==0||(v=!0),g=N):(v=!1,g=D)}});const C={};function b($,V){if(V>a.VARBYTEINT_MAX)return $.emit("error",new Error(`Invalid variable byte integer: ${V}`)),!1;let j=C[V];return j||(j=_(V),V<16384&&(C[V]=j)),u("writeVarByteInt: writing to stream: %o",j),$.write(j)}function T($,V){const j=s.byteLength(V);return g($,j),u("writeString: %s",V),$.write(V,"utf8")}function S($,V,j){T($,V),T($,j)}function N($,V){return u("writeNumberCached: number: %d",V),u("writeNumberCached: %o",d[V]),$.write(d[V])}function D($,V){const j=f(V);return u("writeNumberGenerated: %o",j),$.write(j)}function M($,V){typeof V=="string"?T($,V):V?(g($,V.length),$.write(V)):g($,0)}function I($,V){if(typeof V!="object"||V.length!=null)return{length:1,write(){H($,{},0)}};let j=0;function k(z,Y){let J=0;switch(a.propertiesTypes[z]){case"byte":if(typeof Y!="boolean")return $.emit("error",new Error(`Invalid ${z}: ${Y}`)),!1;J+=2;break;case"int8":if(typeof Y!="number"||Y<0||Y>255)return $.emit("error",new Error(`Invalid ${z}: ${Y}`)),!1;J+=2;break;case"binary":if(Y&&Y===null)return $.emit("error",new Error(`Invalid ${z}: ${Y}`)),!1;J+=1+s.byteLength(Y)+2;break;case"int16":if(typeof Y!="number"||Y<0||Y>65535)return $.emit("error",new Error(`Invalid ${z}: ${Y}`)),!1;J+=3;break;case"int32":if(typeof Y!="number"||Y<0||Y>4294967295)return $.emit("error",new Error(`Invalid ${z}: ${Y}`)),!1;J+=5;break;case"var":if(typeof Y!="number"||Y<0||Y>268435455)return $.emit("error",new Error(`Invalid ${z}: ${Y}`)),!1;J+=1+s.byteLength(_(Y));break;case"string":if(typeof Y!="string")return $.emit("error",new Error(`Invalid ${z}: ${Y}`)),!1;J+=3+s.byteLength(Y.toString());break;case"pair":if(typeof Y!="object")return $.emit("error",new Error(`Invalid ${z}: ${Y}`)),!1;J+=Object.getOwnPropertyNames(Y).reduce((re,he)=>{const le=Y[he];return Array.isArray(le)?re+=le.reduce((ue,L)=>ue+=3+s.byteLength(he.toString())+2+s.byteLength(L.toString()),0):re+=3+s.byteLength(he.toString())+2+s.byteLength(Y[he].toString()),re},0);break;default:return $.emit("error",new Error(`Invalid property ${z}: ${Y}`)),!1}return J}if(V)for(const z in V){let Y=0,J=0;const re=V[z];if(Array.isArray(re))for(let he=0;heY;){const re=z.shift();if(!re||!V[re])return!1;delete V[re],J=I($,V)}return J}function O($,V,j){switch(a.propertiesTypes[V]){case"byte":$.write(s.from([a.properties[V]])),$.write(s.from([+j]));break;case"int8":$.write(s.from([a.properties[V]])),$.write(s.from([j]));break;case"binary":$.write(s.from([a.properties[V]])),M($,j);break;case"int16":$.write(s.from([a.properties[V]])),g($,j);break;case"int32":$.write(s.from([a.properties[V]])),function(k,z){const Y=m(z);u("write4ByteNumber: %o",Y),k.write(Y)}($,j);break;case"var":$.write(s.from([a.properties[V]])),b($,j);break;case"string":$.write(s.from([a.properties[V]])),T($,j);break;case"pair":Object.getOwnPropertyNames(j).forEach(k=>{const z=j[k];Array.isArray(z)?z.forEach(Y=>{$.write(s.from([a.properties[V]])),S($,k.toString(),Y.toString())}):($.write(s.from([a.properties[V]])),S($,k.toString(),z.toString()))});break;default:return $.emit("error",new Error(`Invalid property ${V} value: ${j}`)),!1}}function H($,V,j){b($,j);for(const k in V)if(Object.prototype.hasOwnProperty.call(V,k)&&V[k]!==null){const z=V[k];if(Array.isArray(z))for(let Y=0;Y=1.5*p;return Math.round(d/p)+" "+_+(m?"s":"")}i.exports=function(d,f){f=f||{};var p=typeof d;if(p==="string"&&d.length>0)return function(_){if(!((_=String(_)).length>100)){var m=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(_);if(m){var g=parseFloat(m[1]);switch((m[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return g*h;case"weeks":case"week":case"w":return g*l;case"days":case"day":case"d":return g*c;case"hours":case"hour":case"hrs":case"hr":case"h":return g*o;case"minutes":case"minute":case"mins":case"min":case"m":return g*a;case"seconds":case"second":case"secs":case"sec":case"s":return g*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return g;default:return}}}}(d);if(p==="number"&&isFinite(d))return f.long?function(_){var m=Math.abs(_);return m>=c?u(_,m,c,"day"):m>=o?u(_,m,o,"hour"):m>=a?u(_,m,a,"minute"):m>=s?u(_,m,s,"second"):_+" ms"}(d):function(_){var m=Math.abs(_);return m>=c?Math.round(_/c)+"d":m>=o?Math.round(_/o)+"h":m>=a?Math.round(_/a)+"m":m>=s?Math.round(_/s)+"s":_+"ms"}(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))}},{}],46:[function(t,i,r){const s=t("./lib/number-allocator.js");i.exports.NumberAllocator=s},{"./lib/number-allocator.js":47}],47:[function(t,i,r){const s=t("js-sdsl").Set,a=t("debug")("number-allocator:trace"),o=t("debug")("number-allocator:error");function c(h,u){this.low=h,this.high=u}function l(h,u){if(!(this instanceof l))return new l(h,u);this.min=h,this.max=u,this.ss=new s([],(d,f)=>d.compare(f)),a("Create"),this.clear()}c.prototype.equals=function(h){return this.low===h.low&&this.high===h.high},c.prototype.compare=function(h){return this.lowh)return!1;if(d.low===h)return++d.low,a("use():"+h),!0;if(d.high===h)return--d.high,a("use():"+h),!0;const f=d.low;return d.low=h+1,this.ss.insert(new c(f,h-1)),a("use():"+h),!0}return a("use():failed"),!1},l.prototype.free=function(h){if(hthis.max)return void o("free():"+h+" is out of range");const u=new c(h,h),d=this.ss.lowerBound(u);if(d){if(d.low<=h&&h<=d.high)return void o("free():"+h+" has already been vacant");if(d===this.ss.front())h+1===d.low?--d.low:this.ss.insert(u);else{const f=this.ss.reverseLowerBound(u);f.high+1===h?h+1===d.low?(this.ss.eraseElementByValue(f),d.low=f.low):f.high=h:h+1===d.low?d.low=h:this.ss.insert(u)}}else{if(d===this.ss.front())return void this.ss.insert(u);const f=this.ss.reverseLowerBound(u);f.high+1===h?f.high=h:this.ss.insert(u)}a("free():"+h)},l.prototype.clear=function(){a("clear()"),this.ss.clear(),this.ss.insert(new c(this.min,this.max))},l.prototype.intervalCount=function(){return this.ss.size()},l.prototype.dump=function(){console.log("length:"+this.ss.size());for(const h of this.ss)console.log(h)},i.exports=l},{debug:18,"js-sdsl":36}],48:[function(t,i,r){var s=t("wrappy");function a(c){var l=function(){return l.called?l.value:(l.called=!0,l.value=c.apply(this,arguments))};return l.called=!1,l}function o(c){var l=function(){if(l.called)throw new Error(l.onceError);return l.called=!0,l.value=c.apply(this,arguments)},h=c.name||"Function wrapped with `once`";return l.onceError=h+" shouldn't be called more than once",l.called=!1,l}i.exports=s(a),i.exports.strict=s(o),a.proto=a(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return a(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return o(this)},configurable:!0})})},{wrappy:79}],49:[function(t,i,r){(function(s){(function(){s===void 0||!s.version||s.version.indexOf("v0.")===0||s.version.indexOf("v1.")===0&&s.version.indexOf("v1.8.")!==0?i.exports={nextTick:function(a,o,c,l){if(typeof a!="function")throw new TypeError('"callback" argument must be a function');var h,u,d=arguments.length;switch(d){case 0:case 1:return s.nextTick(a);case 2:return s.nextTick(function(){a.call(null,o)});case 3:return s.nextTick(function(){a.call(null,o,c)});case 4:return s.nextTick(function(){a.call(null,o,c,l)});default:for(h=new Array(d-1),u=0;u1)for(var C=1;C= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=f-p,D=Math.floor,M=String.fromCharCode;function I(k){throw new RangeError(S[k])}function R(k,z){for(var Y=k.length,J=[];Y--;)J[Y]=z(k[Y]);return J}function O(k,z){var Y=k.split("@"),J="";return Y.length>1&&(J=Y[0]+"@",k=Y[1]),J+R((k=k.replace(T,".")).split("."),z).join(".")}function H(k){for(var z,Y,J=[],re=0,he=k.length;re=55296&&z<=56319&&re65535&&(Y+=M((z-=65536)>>>10&1023|55296),z=56320|1023&z),Y+=M(z)}).join("")}function Q(k,z){return k+22+75*(k<26)-((z!=0)<<5)}function $(k,z,Y){var J=0;for(k=Y?D(k/g):k>>1,k+=D(k/z);k>N*_>>1;J+=f)k=D(k/N);return D(J+(N+1)*k/(k+m))}function V(k){var z,Y,J,re,he,le,ue,L,F,W,te,oe=[],ne=k.length,pe=0,ye=x,Pe=v;for((Y=k.lastIndexOf(y))<0&&(Y=0),J=0;J=128&&I("not-basic"),oe.push(k.charCodeAt(J));for(re=Y>0?Y+1:0;re=ne&&I("invalid-input"),((L=(te=k.charCodeAt(re++))-48<10?te-22:te-65<26?te-65:te-97<26?te-97:f)>=f||L>D((d-pe)/le))&&I("overflow"),pe+=L*le,!(L<(F=ue<=Pe?p:ue>=Pe+_?_:ue-Pe));ue+=f)le>D(d/(W=f-F))&&I("overflow"),le*=W;Pe=$(pe-he,z=oe.length+1,he==0),D(pe/z)>d-ye&&I("overflow"),ye+=D(pe/z),pe%=z,oe.splice(pe++,0,ye)}return G(oe)}function j(k){var z,Y,J,re,he,le,ue,L,F,W,te,oe,ne,pe,ye,Pe=[];for(oe=(k=H(k)).length,z=x,Y=0,he=v,le=0;le=z&&teD((d-Y)/(ne=J+1))&&I("overflow"),Y+=(ue-z)*ne,z=ue,le=0;led&&I("overflow"),te==z){for(L=Y,F=f;!(L<(W=F<=he?p:F>=he+_?_:F-he));F+=f)ye=L-W,pe=f-W,Pe.push(M(Q(W+ye%pe,0))),L=D(ye/pe);Pe.push(M(Q(L,0))),he=$(Y,ne,J==re),Y=0,++J}++Y,++z}return Pe.join("")}if(h={version:"1.4.1",ucs2:{decode:H,encode:G},decode:V,encode:j,toASCII:function(k){return O(k,function(z){return b.test(z)?"xn--"+j(z):z})},toUnicode:function(k){return O(k,function(z){return C.test(z)?V(z.slice(4).toLowerCase()):z})}},o&&c)if(i.exports==o)c.exports=h;else for(u in h)h.hasOwnProperty(u)&&(o[u]=h[u]);else a.punycode=h})(this)}).call(this)}).call(this,typeof kt<"u"?kt:typeof self<"u"?self:typeof window<"u"?window:{})},{}],52:[function(t,i,r){function s(o,c){return Object.prototype.hasOwnProperty.call(o,c)}i.exports=function(o,c,l,h){c=c||"&",l=l||"=";var u={};if(typeof o!="string"||o.length===0)return u;var d=/\+/g;o=o.split(c);var f=1e3;h&&typeof h.maxKeys=="number"&&(f=h.maxKeys);var p=o.length;f>0&&p>f&&(p=f);for(var _=0;_=0?(m=y.substr(0,C),g=y.substr(C+1)):(m=y,g=""),v=decodeURIComponent(m),x=decodeURIComponent(g),s(u,v)?a(u[v])?u[v].push(x):u[v]=[u[v],x]:u[v]=x}return u};var a=Array.isArray||function(o){return Object.prototype.toString.call(o)==="[object Array]"}},{}],53:[function(t,i,r){var s=function(l){switch(typeof l){case"string":return l;case"boolean":return l?"true":"false";case"number":return isFinite(l)?l:"";default:return""}};i.exports=function(l,h,u,d){return h=h||"&",u=u||"=",l===null&&(l=void 0),typeof l=="object"?o(c(l),function(f){var p=encodeURIComponent(s(f))+u;return a(l[f])?o(l[f],function(_){return p+encodeURIComponent(s(_))}).join(h):p+encodeURIComponent(s(l[f]))}).join(h):d?encodeURIComponent(s(d))+u+encodeURIComponent(s(l)):""};var a=Array.isArray||function(l){return Object.prototype.toString.call(l)==="[object Array]"};function o(l,h){if(l.map)return l.map(h);for(var u=[],d=0;d2?"one of ".concat(l," ").concat(c.slice(0,h-1).join(", "),", or ")+c[h-1]:h===2?"one of ".concat(l," ").concat(c[0]," or ").concat(c[1]):"of ".concat(l," ").concat(c[0])}return"of ".concat(l," ").concat(String(c))}a("ERR_INVALID_OPT_VALUE",function(c,l){return'The value "'+l+'" is invalid for option "'+c+'"'},TypeError),a("ERR_INVALID_ARG_TYPE",function(c,l,h){var u,d,f;if(typeof l=="string"&&(d="not ",l.substr(0,d.length)===d)?(u="must not be",l=l.replace(/^not /,"")):u="must be",function(_,m,g){return(g===void 0||g>_.length)&&(g=_.length),_.substring(g-m.length,g)===m}(c," argument"))f="The ".concat(c," ").concat(u," ").concat(o(l,"type"));else{var p=function(_,m,g){return typeof g!="number"&&(g=0),!(g+m.length>_.length)&&_.indexOf(m,g)!==-1}(c,".")?"property":"argument";f='The "'.concat(c,'" ').concat(p," ").concat(u," ").concat(o(l,"type"))}return f+=". Received type ".concat(typeof h)},TypeError),a("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),a("ERR_METHOD_NOT_IMPLEMENTED",function(c){return"The "+c+" method is not implemented"}),a("ERR_STREAM_PREMATURE_CLOSE","Premature close"),a("ERR_STREAM_DESTROYED",function(c){return"Cannot call "+c+" after a stream was destroyed"}),a("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),a("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),a("ERR_STREAM_WRITE_AFTER_END","write after end"),a("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),a("ERR_UNKNOWN_ENCODING",function(c){return"Unknown encoding: "+c},TypeError),a("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),i.exports.codes=s},{}],56:[function(t,i,r){(function(s){(function(){var a=Object.keys||function(_){var m=[];for(var g in _)m.push(g);return m};i.exports=d;var o=t("./_stream_readable"),c=t("./_stream_writable");t("inherits")(d,o);for(var l=a(c.prototype),h=0;h0)if(typeof F=="string"||pe.objectMode||Object.getPrototypeOf(F)===h.prototype||(F=function(ye){return h.from(ye)}(F)),te)pe.endEmitted?N(L,new S):O(L,pe,F,!0);else if(pe.ended)N(L,new b);else{if(pe.destroyed)return!1;pe.reading=!1,pe.decoder&&!W?(F=pe.decoder.write(F),pe.objectMode||F.length!==0?O(L,pe,F,!1):V(L,pe)):O(L,pe,F,!1)}else te||(pe.reading=!1,V(L,pe));return!pe.ended&&(pe.lengthF.highWaterMark&&(F.highWaterMark=function(W){return W>=H?W=H:(W--,W|=W>>>1,W|=W>>>2,W|=W>>>4,W|=W>>>8,W|=W>>>16,W++),W}(L)),L<=F.length?L:F.ended?F.length:(F.needReadable=!0,0))}function Q(L){var F=L._readableState;d("emitReadable",F.needReadable,F.emittedReadable),F.needReadable=!1,F.emittedReadable||(d("emitReadable",F.flowing),F.emittedReadable=!0,s.nextTick($,L))}function $(L){var F=L._readableState;d("emitReadable_",F.destroyed,F.length,F.ended),F.destroyed||!F.length&&!F.ended||(L.emit("readable"),F.emittedReadable=!1),F.needReadable=!F.flowing&&!F.ended&&F.length<=F.highWaterMark,J(L)}function V(L,F){F.readingMore||(F.readingMore=!0,s.nextTick(j,L,F))}function j(L,F){for(;!F.reading&&!F.ended&&(F.length0,F.resumeScheduled&&!F.paused?F.flowing=!0:L.listenerCount("data")>0&&L.resume()}function z(L){d("readable nexttick read 0"),L.read(0)}function Y(L,F){d("resume",F.reading),F.reading||L.read(0),F.resumeScheduled=!1,L.emit("resume"),J(L),F.flowing&&!F.reading&&L.read(0)}function J(L){var F=L._readableState;for(d("flow",F.flowing);F.flowing&&L.read()!==null;);}function re(L,F){return F.length===0?null:(F.objectMode?W=F.buffer.shift():!L||L>=F.length?(W=F.decoder?F.buffer.join(""):F.buffer.length===1?F.buffer.first():F.buffer.concat(F.length),F.buffer.clear()):W=F.buffer.consume(L,F.decoder),W);var W}function he(L){var F=L._readableState;d("endReadable",F.endEmitted),F.endEmitted||(F.ended=!0,s.nextTick(le,F,L))}function le(L,F){if(d("endReadableNT",L.endEmitted,L.length),!L.endEmitted&&L.length===0&&(L.endEmitted=!0,F.readable=!1,F.emit("end"),L.autoDestroy)){var W=F._writableState;(!W||W.autoDestroy&&W.finished)&&F.destroy()}}function ue(L,F){for(var W=0,te=L.length;W=F.highWaterMark:F.length>0)||F.ended))return d("read: emitReadable",F.length,F.ended),F.length===0&&F.ended?he(this):Q(this),null;if((L=G(L,F))===0&&F.ended)return F.length===0&&he(this),null;var te,oe=F.needReadable;return d("need readable",oe),(F.length===0||F.length-L0?re(L,F):null)===null?(F.needReadable=F.length<=F.highWaterMark,L=0):(F.length-=L,F.awaitDrain=0),F.length===0&&(F.ended||(F.needReadable=!0),W!==L&&F.ended&&he(this)),te!==null&&this.emit("data",te),te},I.prototype._read=function(L){N(this,new T("_read()"))},I.prototype.pipe=function(L,F){var W=this,te=this._readableState;switch(te.pipesCount){case 0:te.pipes=L;break;case 1:te.pipes=[te.pipes,L];break;default:te.pipes.push(L)}te.pipesCount+=1,d("pipe count=%d opts=%j",te.pipesCount,F);var oe=(!F||F.end!==!1)&&L!==s.stdout&&L!==s.stderr?pe:gt;function ne(rt,ut){d("onunpipe"),rt===W&&ut&&ut.hasUnpiped===!1&&(ut.hasUnpiped=!0,d("cleanup"),L.removeListener("close",ot),L.removeListener("finish",Xe),L.removeListener("drain",ye),L.removeListener("error",He),L.removeListener("unpipe",ne),W.removeListener("end",pe),W.removeListener("end",gt),W.removeListener("data",Fe),Pe=!0,!te.awaitDrain||L._writableState&&!L._writableState.needDrain||ye())}function pe(){d("onend"),L.end()}te.endEmitted?s.nextTick(oe):W.once("end",oe),L.on("unpipe",ne);var ye=function(rt){return function(){var ut=rt._readableState;d("pipeOnDrain",ut.awaitDrain),ut.awaitDrain&&ut.awaitDrain--,ut.awaitDrain===0&&c(rt,"data")&&(ut.flowing=!0,J(rt))}}(W);L.on("drain",ye);var Pe=!1;function Fe(rt){d("ondata");var ut=L.write(rt);d("dest.write",ut),ut===!1&&((te.pipesCount===1&&te.pipes===L||te.pipesCount>1&&ue(te.pipes,L)!==-1)&&!Pe&&(d("false write response, pause",te.awaitDrain),te.awaitDrain++),W.pause())}function He(rt){d("onerror",rt),gt(),L.removeListener("error",He),c(L,"error")===0&&N(L,rt)}function ot(){L.removeListener("finish",Xe),gt()}function Xe(){d("onfinish"),L.removeListener("close",ot),gt()}function gt(){d("unpipe"),W.unpipe(L)}return W.on("data",Fe),function(rt,ut,Yt){if(typeof rt.prependListener=="function")return rt.prependListener(ut,Yt);rt._events&&rt._events[ut]?Array.isArray(rt._events[ut])?rt._events[ut].unshift(Yt):rt._events[ut]=[Yt,rt._events[ut]]:rt.on(ut,Yt)}(L,"error",He),L.once("close",ot),L.once("finish",Xe),L.emit("pipe",W),te.flowing||(d("pipe resume"),W.resume()),L},I.prototype.unpipe=function(L){var F=this._readableState,W={hasUnpiped:!1};if(F.pipesCount===0)return this;if(F.pipesCount===1)return L&&L!==F.pipes?this:(L||(L=F.pipes),F.pipes=null,F.pipesCount=0,F.flowing=!1,L&&L.emit("unpipe",this,W),this);if(!L){var te=F.pipes,oe=F.pipesCount;F.pipes=null,F.pipesCount=0,F.flowing=!1;for(var ne=0;ne0,te.flowing!==!1&&this.resume()):L==="readable"&&(te.endEmitted||te.readableListening||(te.readableListening=te.needReadable=!0,te.flowing=!1,te.emittedReadable=!1,d("on readable",te.length,te.reading),te.length?Q(this):te.reading||s.nextTick(z,this))),W},I.prototype.addListener=I.prototype.on,I.prototype.removeListener=function(L,F){var W=l.prototype.removeListener.call(this,L,F);return L==="readable"&&s.nextTick(k,this),W},I.prototype.removeAllListeners=function(L){var F=l.prototype.removeAllListeners.apply(this,arguments);return L!=="readable"&&L!==void 0||s.nextTick(k,this),F},I.prototype.resume=function(){var L=this._readableState;return L.flowing||(d("resume"),L.flowing=!L.readableListening,function(F,W){W.resumeScheduled||(W.resumeScheduled=!0,s.nextTick(Y,F,W))}(this,L)),L.paused=!1,this},I.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},I.prototype.wrap=function(L){var F=this,W=this._readableState,te=!1;for(var oe in L.on("end",function(){if(d("wrapped end"),W.decoder&&!W.ended){var pe=W.decoder.end();pe&&pe.length&&F.push(pe)}F.push(null)}),L.on("data",function(pe){d("wrapped data"),W.decoder&&(pe=W.decoder.write(pe)),(!W.objectMode||pe!=null)&&(W.objectMode||pe&&pe.length)&&(F.push(pe)||(te=!0,L.pause()))}),L)this[oe]===void 0&&typeof L[oe]=="function"&&(this[oe]=function(pe){return function(){return L[pe].apply(L,arguments)}}(oe));for(var ne=0;ne-1))throw new S(V);return this._writableState.defaultEncoding=V,this},Object.defineProperty(I.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(I.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),I.prototype._write=function(V,j,k){k(new v("_write()"))},I.prototype._writev=null,I.prototype.end=function(V,j,k){var z=this._writableState;return typeof V=="function"?(k=V,V=null,j=null):typeof j=="function"&&(k=j,j=null),V!=null&&this.write(V,j),z.corked&&(z.corked=1,this.uncork()),z.ending||function(Y,J,re){J.ending=!0,$(Y,J),re&&(J.finished?s.nextTick(re):Y.once("finish",re)),J.ended=!0,Y.writable=!1}(this,z,k),this},Object.defineProperty(I.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(V){this._writableState&&(this._writableState.destroyed=V)}}),I.prototype.destroy=p.destroy,I.prototype._undestroy=p.undestroy,I.prototype._destroy=function(V,j){j(V)}}).call(this)}).call(this,t("_process"),typeof kt<"u"?kt:typeof self<"u"?self:typeof window<"u"?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,inherits:24,"util-deprecate":78}],61:[function(t,i,r){(function(s){(function(){var a;function o(y,C,b){return C in y?Object.defineProperty(y,C,{value:b,enumerable:!0,configurable:!0,writable:!0}):y[C]=b,y}var c=t("./end-of-stream"),l=Symbol("lastResolve"),h=Symbol("lastReject"),u=Symbol("error"),d=Symbol("ended"),f=Symbol("lastPromise"),p=Symbol("handlePromise"),_=Symbol("stream");function m(y,C){return{value:y,done:C}}function g(y){var C=y[l];if(C!==null){var b=y[_].read();b!==null&&(y[f]=null,y[l]=null,y[h]=null,C(m(b,!1)))}}var v=Object.getPrototypeOf(function(){}),x=Object.setPrototypeOf((o(a={get stream(){return this[_]},next:function(){var y=this,C=this[u];if(C!==null)return Promise.reject(C);if(this[d])return Promise.resolve(m(void 0,!0));if(this[_].destroyed)return new Promise(function(N,D){s.nextTick(function(){y[u]?D(y[u]):N(m(void 0,!0))})});var b,T=this[f];if(T)b=new Promise(function(N,D){return function(M,I){N.then(function(){D[d]?M(m(void 0,!0)):D[p](M,I)},I)}}(T,this));else{var S=this[_].read();if(S!==null)return Promise.resolve(m(S,!1));b=new Promise(this[p])}return this[f]=b,b}},Symbol.asyncIterator,function(){return this}),o(a,"return",function(){var y=this;return new Promise(function(C,b){y[_].destroy(null,function(T){T?b(T):C(m(void 0,!0))})})}),a),v);i.exports=function(y){var C,b=Object.create(x,(o(C={},_,{value:y,writable:!0}),o(C,l,{value:null,writable:!0}),o(C,h,{value:null,writable:!0}),o(C,u,{value:null,writable:!0}),o(C,d,{value:y._readableState.endEmitted,writable:!0}),o(C,p,{value:function(T,S){var N=b[_].read();N?(b[f]=null,b[l]=null,b[h]=null,T(m(N,!1))):(b[l]=T,b[h]=S)},writable:!0}),C));return b[f]=null,c(y,function(T){if(T&&T.code!=="ERR_STREAM_PREMATURE_CLOSE"){var S=b[h];return S!==null&&(b[f]=null,b[l]=null,b[h]=null,S(T)),void(b[u]=T)}var N=b[l];N!==null&&(b[f]=null,b[l]=null,b[h]=null,N(m(void 0,!0))),b[d]=!0}),y.on("readable",(function(T){s.nextTick(g,T)}).bind(null,b)),b}}).call(this)}).call(this,t("_process"))},{"./end-of-stream":64,_process:50}],62:[function(t,i,r){function s(u,d){var f=Object.keys(u);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(u);d&&(p=p.filter(function(_){return Object.getOwnPropertyDescriptor(u,_).enumerable})),f.push.apply(f,p)}return f}function a(u,d,f){return d in u?Object.defineProperty(u,d,{value:f,enumerable:!0,configurable:!0,writable:!0}):u[d]=f,u}function o(u,d){for(var f=0;f0?this.tail.next=_:this.head=_,this.tail=_,++this.length}},{key:"unshift",value:function(p){var _={data:p,next:this.head};this.length===0&&(this.tail=_),this.head=_,++this.length}},{key:"shift",value:function(){if(this.length!==0){var p=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,p}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(p){if(this.length===0)return"";for(var _=this.head,m=""+_.data;_=_.next;)m+=p+_.data;return m}},{key:"concat",value:function(p){if(this.length===0)return c.alloc(0);for(var _,m,g,v=c.allocUnsafe(p>>>0),x=this.head,y=0;x;)_=x.data,m=v,g=y,c.prototype.copy.call(_,m,g),y+=x.data.length,x=x.next;return v}},{key:"consume",value:function(p,_){var m;return pv.length?v.length:p;if(x===v.length?g+=v:g+=v.slice(0,p),(p-=x)===0){x===v.length?(++m,_.next?this.head=_.next:this.head=this.tail=null):(this.head=_,_.data=v.slice(x));break}++m}return this.length-=m,g}},{key:"_getBuffer",value:function(p){var _=c.allocUnsafe(p),m=this.head,g=1;for(m.data.copy(_),p-=m.data.length;m=m.next;){var v=m.data,x=p>v.length?v.length:p;if(v.copy(_,_.length-p,0,x),(p-=x)===0){x===v.length?(++g,m.next?this.head=m.next:this.head=this.tail=null):(this.head=m,m.data=v.slice(x));break}++g}return this.length-=g,_}},{key:h,value:function(p,_){return l(this,function(m){for(var g=1;g0,function(C){_||(_=C),C&&g.forEach(h),y||(g.forEach(h),m(_))})});return f.reduce(u)}},{"../../../errors":55,"./end-of-stream":64}],67:[function(t,i,r){var s=t("../../../errors").codes.ERR_INVALID_OPT_VALUE;i.exports={getHighWaterMark:function(a,o,c,l){var h=function(u,d,f){return u.highWaterMark!=null?u.highWaterMark:d?u[f]:null}(o,l,c);if(h!=null){if(!isFinite(h)||Math.floor(h)!==h||h<0)throw new s(l?c:"highWaterMark",h);return Math.floor(h)}return a.objectMode?16:16384}}},{"../../../errors":55}],68:[function(t,i,r){i.exports=t("events").EventEmitter},{events:22}],69:[function(t,i,r){(r=i.exports=t("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=t("./lib/_stream_writable.js"),r.Duplex=t("./lib/_stream_duplex.js"),r.Transform=t("./lib/_stream_transform.js"),r.PassThrough=t("./lib/_stream_passthrough.js"),r.finished=t("./lib/internal/streams/end-of-stream.js"),r.pipeline=t("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(t,i,r){i.exports=function(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("interval needed");var s;if(arguments.length>0){s=new Array(arguments.length-2);for(var a=0;a>5==6?2:m>>4==14?3:m>>3==30?4:m>>6==2?-1:-2}function l(m){var g=this.lastTotal-this.lastNeed,v=function(x,y,C){if((192&y[0])!=128)return x.lastNeed=0,"�";if(x.lastNeed>1&&y.length>1){if((192&y[1])!=128)return x.lastNeed=1,"�";if(x.lastNeed>2&&y.length>2&&(192&y[2])!=128)return x.lastNeed=2,"�"}}(this,m);return v!==void 0?v:this.lastNeed<=m.length?(m.copy(this.lastChar,g,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(m.copy(this.lastChar,g,0,m.length),void(this.lastNeed-=m.length))}function h(m,g){if((m.length-g)%2==0){var v=m.toString("utf16le",g);if(v){var x=v.charCodeAt(v.length-1);if(x>=55296&&x<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1],v.slice(0,-1)}return v}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",g,m.length-1)}function u(m){var g=m&&m.length?this.write(m):"";if(this.lastNeed){var v=this.lastTotal-this.lastNeed;return g+this.lastChar.toString("utf16le",0,v)}return g}function d(m,g){var v=(m.length-g)%3;return v===0?m.toString("base64",g):(this.lastNeed=3-v,this.lastTotal=3,v===1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",g,m.length-v))}function f(m){var g=m&&m.length?this.write(m):"";return this.lastNeed?g+this.lastChar.toString("base64",0,3-this.lastNeed):g}function p(m){return m.toString(this.encoding)}function _(m){return m&&m.length?this.write(m):""}r.StringDecoder=o,o.prototype.write=function(m){if(m.length===0)return"";var g,v;if(this.lastNeed){if((g=this.fillLast(m))===void 0)return"";v=this.lastNeed,this.lastNeed=0}else v=0;return v=0?(S>0&&(y.lastNeed=S-1),S):--T=0?(S>0&&(y.lastNeed=S-2),S):--T=0?(S>0&&(S===2?S=0:y.lastNeed=S-3),S):0}(this,m,g);if(!this.lastNeed)return m.toString("utf8",g);this.lastTotal=v;var x=m.length-(v-this.lastNeed);return m.copy(this.lastChar,0,x),m.toString("utf8",g,x)},o.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length}},{"safe-buffer":73}],76:[function(t,i,r){var s=t("punycode"),a=t("./util");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}r.parse=C,r.resolve=function(b,T){return C(b,!1,!0).resolve(T)},r.resolveObject=function(b,T){return b?C(b,!1,!0).resolveObject(T):T},r.format=function(b){return a.isString(b)&&(b=C(b)),b instanceof o?b.format():o.prototype.format.call(b)},r.Url=o;var c=/^([a-z0-9.+-]+:)/i,l=/:[0-9]*$/,h=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,u=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r",` `," "]),d=["'"].concat(u),f=["%","/","?",";","#"].concat(d),p=["/","?","#"],_=/^[+a-z0-9A-Z_-]{0,63}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},v={javascript:!0,"javascript:":!0},x={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=t("querystring");function C(b,T,S){if(b&&a.isObject(b)&&b instanceof o)return b;var N=new o;return N.parse(b,T,S),N}o.prototype.parse=function(b,T,S){if(!a.isString(b))throw new TypeError("Parameter 'url' must be a string, not "+typeof b);var N=b.indexOf("?"),D=N!==-1&&N127?he+="x":he+=re[le];if(!he.match(_)){var L=Y.slice(0,j),F=Y.slice(j+1),W=re.match(m);W&&(L.push(W[1]),F.unshift(W[2])),F.length&&(I="/"+F.join(".")+I),this.hostname=L.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),z||(this.hostname=s.toASCII(this.hostname));var te=this.port?":"+this.port:"",oe=this.hostname||"";this.host=oe+te,this.href+=this.host,z&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),I[0]!=="/"&&(I="/"+I))}if(!g[H])for(j=0,J=d.length;j0)&&S.host.split("@"))&&(S.auth=W.shift(),S.host=S.hostname=W.shift())),S.search=b.search,S.query=b.query,a.isNull(S.pathname)&&a.isNull(S.search)||(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S;if(!re.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var le=re.slice(-1)[0],ue=(S.host||b.host||re.length>1)&&(le==="."||le==="..")||le==="",L=0,F=re.length;F>=0;F--)(le=re[F])==="."?re.splice(F,1):le===".."?(re.splice(F,1),L++):L&&(re.splice(F,1),L--);if(!Y&&!J)for(;L--;L)re.unshift("..");!Y||re[0]===""||re[0]&&re[0].charAt(0)==="/"||re.unshift(""),ue&&re.join("/").substr(-1)!=="/"&&re.push("");var W,te=re[0]===""||re[0]&&re[0].charAt(0)==="/";return he&&(S.hostname=S.host=te?"":re.length?re.shift():"",(W=!!(S.host&&S.host.indexOf("@")>0)&&S.host.split("@"))&&(S.auth=W.shift(),S.host=S.hostname=W.shift())),(Y=Y||S.host&&re.length)&&!te&&re.unshift(""),re.length?S.pathname=re.join("/"):(S.pathname=null,S.path=null),a.isNull(S.pathname)&&a.isNull(S.search)||(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=b.auth||S.auth,S.slashes=S.slashes||b.slashes,S.href=S.format(),S},o.prototype.parseHost=function(){var b=this.host,T=l.exec(b);T&&((T=T[0])!==":"&&(this.port=T.substr(1)),b=b.substr(0,b.length-T.length)),b&&(this.hostname=b)}},{"./util":77,punycode:51,querystring:54}],77:[function(t,i,r){i.exports={isString:function(s){return typeof s=="string"},isObject:function(s){return typeof s=="object"&&s!==null},isNull:function(s){return s===null},isNullOrUndefined:function(s){return s==null}}},{}],78:[function(t,i,r){(function(s){(function(){function a(o){try{if(!s.localStorage)return!1}catch{return!1}var c=s.localStorage[o];return c!=null&&String(c).toLowerCase()==="true"}i.exports=function(o,c){if(a("noDeprecation"))return o;var l=!1;return function(){if(!l){if(a("throwDeprecation"))throw new Error(c);a("traceDeprecation")?console.trace(c):console.warn(c),l=!0}return o.apply(this,arguments)}}}).call(this)}).call(this,typeof kt<"u"?kt:typeof self<"u"?self:typeof window<"u"?window:{})},{}],79:[function(t,i,r){i.exports=function s(a,o){if(a&&o)return s(a)(o);if(typeof a!="function")throw new TypeError("need wrapper function");return Object.keys(a).forEach(function(l){c[l]=a[l]}),c;function c(){for(var l=new Array(arguments.length),h=0;h0)for(var d=0,f=arguments.length;d1)d=u;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");f=this.head.next,d=this.head.value}for(var p=0;f!==null;p++)d=h(d,f.value,p),f=f.next;return d},s.prototype.reduceReverse=function(h,u){var d,f=this.tail;if(arguments.length>1)d=u;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");f=this.tail.prev,d=this.tail.value}for(var p=this.length-1;f!==null;p--)d=h(d,f.value,p),f=f.prev;return d},s.prototype.toArray=function(){for(var h=new Array(this.length),u=0,d=this.head;d!==null;u++)h[u]=d.value,d=d.next;return h},s.prototype.toArrayReverse=function(){for(var h=new Array(this.length),u=0,d=this.tail;d!==null;u++)h[u]=d.value,d=d.prev;return h},s.prototype.slice=function(h,u){(u=u||this.length)<0&&(u+=this.length),(h=h||0)<0&&(h+=this.length);var d=new s;if(uthis.length&&(u=this.length);for(var f=0,p=this.head;p!==null&&fthis.length&&(u=this.length);for(var f=this.length,p=this.tail;p!==null&&f>u;f--)p=p.prev;for(;p!==null&&f>h;f--,p=p.prev)d.push(p.value);return d},s.prototype.splice=function(h,u,...d){h>this.length&&(h=this.length-1),h<0&&(h=this.length+h);for(var f=0,p=this.head;p!==null&&f0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},_0=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],a;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},pu=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i":u=r[m]>+g;break;case">=":u=r[m]>=+g;break;case"<":u=r[m]<+g;break;case"<=":u=r[m]<=+g;break;case"=":case"==":u=r[m]==g;break;case"!=":u=r[m]!=g;break;case"[)":u=iV(+r[m],g);break;case"![)":u=!iV(+r[m],g);break;case"[]":u=rV(+r[m],g);break;case"![]":u=!rV(+r[m],g);break}}u&&i.events[c.action](r,c)}}),s==="valueUpdate"&&((o=r.realTimes)===null||o===void 0||o.forEach(function(c){var l;(l=c.triggers)===null||l===void 0||l.forEach(function(h){var u,d=!1;h.conditionType==="and"?d=h.conditions.every(function(f){return i.judgeCondition(r,c.key,f)}):h.conditionType==="or"&&(d=h.conditions.some(function(f){return i.judgeCondition(r,c.key,f)})),d&&((u=h.actions)===null||u===void 0||u.forEach(function(f){i.events[f.action](r,f)}))})})),i.doEvent(i.store.pens[r.parentId],s))},this.renderPenRaw=bz,this.setElemPosition=za,this.setLifeCycleFunc=DEe,this.store=Fbe(ns()),this.setOptions(t),this.setDatabyOptions(t),this.init(e),this.register(aSe()),this.registerCanvasDraw({cube:gTe}),this.registerAnchors(oSe()),globalThis.meta2d=this,this.initEventFns(),this.store.emitter.on("*",this.onEvent)}return Object.defineProperty(n.prototype,"beforeAddPen",{get:function(){return this.canvas.beforeAddPen},set:function(e){this.canvas.beforeAddPen=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"beforeAddPens",{get:function(){return this.canvas.beforeAddPens},set:function(e){this.canvas.beforeAddPens=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"beforeAddAnchor",{get:function(){return this.canvas.beforeAddAnchor},set:function(e){this.canvas.beforeAddAnchor=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"beforeRemovePens",{get:function(){return this.canvas.beforeRemovePens},set:function(e){this.canvas.beforeRemovePens=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"beforeRemoveAnchor",{get:function(){return this.canvas.beforeRemoveAnchor},set:function(e){this.canvas.beforeRemoveAnchor=e},enumerable:!1,configurable:!0}),n.prototype.setOptions=function(e){var t;e===void 0&&(e={}),(e.grid!==void 0||e.gridColor!==void 0||e.gridSize!==void 0)&&this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0),(e.rule!==void 0||e.ruleColor!==void 0||e.ruleOptions!==void 0)&&(this.store.patchFlagsTop=!0,e.ruleOptions&&!((t=this.store.options)===null||t===void 0)&&t.ruleOptions&&(Object.assign(this.store.options.ruleOptions,e.ruleOptions),e.ruleOptions=this.store.options.ruleOptions)),e.background!==void 0&&this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0),e.resizeMode!==void 0&&(e.resizeMode||(this.canvas.hotkeyType=un.None)),(e.width!==void 0||e.height!==void 0)&&this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0),this.store.options=Object.assign(this.store.options,e),this.canvas&&e.scroll!==void 0&&(e.scroll?(!this.canvas.scroll&&(this.canvas.scroll=new n_e(this.canvas)),this.canvas.scroll.show()):this.canvas.scroll&&this.canvas.scroll.hide())},n.prototype.getOptions=function(){return this.store.options},n.prototype.setDatabyOptions=function(e){e===void 0&&(e={});var t=e.color,i=e.activeColor,r=e.activeBackground,s=e.grid,a=e.gridColor,o=e.gridSize,c=e.fromArrow,l=e.toArrow,h=e.rule,u=e.ruleColor,d=e.textColor;this.setRule({rule:h,ruleColor:u}),this.setGrid({grid:s,gridColor:a,gridSize:o}),this.store.data=Object.assign(this.store.data,{textColor:d,color:t,activeColor:i,activeBackground:r,fromArrow:c,toArrow:l})},n.prototype.init=function(e){typeof e=="string"?this.canvas=new qhe(this,document.getElementById(e),this.store):this.canvas=new qhe(this,e,this.store),this.resize(),this.canvas.listen()},n.prototype.initEventFns=function(){var e=this;this.events[_l.Link]=function(t,i){var r;if(window&&i.value&&typeof i.value=="string"){window.open(i.value,(r=i.params)!==null&&r!==void 0?r:"_blank");return}console.warn("[meta2d] Link param is not a string")},this.events[_l.SetProps]=function(t,i){var r=i.value;if(r&&typeof r=="object"){var s=i.params?e.find(i.params):e.find(t.id);s.forEach(function(a){r.hasOwnProperty("visible")&&e.setVisible(a,r.visible),e.setValue(dd({id:a.id},r),{render:!1,doEvent:!1})}),e.render();return}console.warn("[meta2d] SetProps value is not an object")},this.events[_l.StartAnimate]=function(t,i){var r=t;if(i.value&&(r=e.findOne(i.value)),!(e.store.animates.has(r)&&!r.calculative.pause)){if(i.targetType&&i.params){e.startAnimate(i.value||[t],i.params);return}if(!i.value||typeof i.value=="string"){e.startAnimate(i.value||[t]);return}console.warn("[meta2d] StartAnimate value is not a string")}},this.events[_l.PauseAnimate]=function(t,i){if(!i.value||typeof i.value=="string"){e.pauseAnimate(i.value||[t]);return}console.warn("[meta2d] PauseAnimate value is not a string")},this.events[_l.StopAnimate]=function(t,i){if(!i.value||typeof i.value=="string"){e.stopAnimate(i.value||[t]);return}console.warn("[meta2d] StopAnimate event value is not a string")},this.events[_l.StartVideo]=function(t,i){if(!i.value||typeof i.value=="string"){e.startVideo(i.value||[t]);return}console.warn("[meta2d] StartVideo value is not a string")},this.events[_l.PauseVideo]=function(t,i){if(!i.value||typeof i.value=="string"){e.pauseVideo(i.value||[t]);return}console.warn("[meta2d] PauseVideo value is not a string")},this.events[_l.StopVideo]=function(t,i){if(!i.value||typeof i.value=="string"){e.stopVideo(i.value||[t]);return}console.warn("[meta2d] StopVideo event value is not a string")},this.events[_l.JS]=function(t,i){var r;if(i.value&&!i.fn)try{if(typeof i.value!="string")throw new Error("[meta2d] Function value must be string");var s=i.value;i.fn=new Function("pen","params","context",s)}catch(a){console.error("[meta2d]: Error on make a function:",a)}(r=i.fn)===null||r===void 0||r.call(i,t,i.params,{meta2d:e,eventName:i.name})},this.events[_l.GlobalFn]=function(t,i){if(typeof i.value!="string"){console.warn("[meta2d] GlobalFn value must be a string");return}globalThis[i.value]&&globalThis[i.value](t,i.params)},this.events[_l.Emit]=function(t,i){if(typeof i.value!="string"){console.warn("[meta2d] Emit value must be a string");return}e.store.emitter.emit(i.value,{pen:t,params:i.params,eventName:i.name})},this.events[_l.SendPropData]=function(t,i){var r=At(i.value);if(r&&typeof r=="object"){var s=i.params?e.findOne(i.params):t;for(var a in r)(r[a]===void 0||r[a]==="")&&(r[a]=s[a]);r.id=s.id,e.doSendDataEvent(r,i.extend);return}console.warn("[meta2d] SendPropData value is not an object")},this.events[_l.SendVarData]=function(t,i){var r=At(i.value);if(r&&typeof r=="object"){var s=i.params?e.findOne(i.params):t,a=[],o=function(l){var h={dataId:l,value:r[l]};if(!h.value){var u=s.form.find(function(d){return d.dataIds&&d.dataIds.dataId===h.dataId});u&&(h.value=s[u.key])}a.push(h)};for(var c in r)o(c);e.doSendDataEvent(a,i.extend);return}console.warn("[meta2d] SendVarData value is not an object")},this.events[_l.Navigator]=function(t,i){i.value&&typeof i.value=="string"&&e.navigatorTo(i.value)},this.events[_l.Dialog]=function(t,i){i.params&&typeof i.params=="string"&&i.value&&typeof i.value=="string"&&e.canvas.dialog.show(i.value,i.params)},this.events[_l.SendData]=function(t,i){var r=At(i.value);if(r&&typeof r=="object"&&i.targetType==="id"){var s=i.params?e.findOne(i.params):t;for(var a in r)(r[a]===void 0||r[a]==="")&&(r[a]=s[a]);r.id=s.id,e.sendDataToNetWork(r,i.network);return}},this.events[_l.PostMessage]=function(t,i){if(typeof i.value!="string"){console.warn("[meta2d] Emit value must be a string");return}var r=i.params?e.findOne(i.params):t;if(r.name!=="iframe"||!r.iframe){console.warn("不是嵌入页面");return}var s=Ehe(r.iframe.split("?")[1]);r.calculative.singleton.div.children[0].contentWindow.postMessage(JSON.stringify({name:i.value,id:s.id}),"*")},this.events[_l.PostMessageToParent]=function(t,i){if(typeof i.value!="string"){console.warn("[meta2d] Emit value must be a string");return}window.parent.postMessage(JSON.stringify(i.value),"*")}},n.prototype.navigatorTo=function(e){if(e){var t=window.location.href,i=t.split("id=");if(i.length>1){var r=i[1].indexOf("&");r===-1?window.location.href=i[0]+"id="+e:window.location.href=i[0]+"id="+e+i[1].slice(r)}}},n.prototype.doSendDataEvent=function(e,t){var i=this,r=JSON.stringify(e);this.mqttClient&&this.mqttClient.connected&&(t?t.split(",").forEach(function(s){i.mqttClient.publish(s,r)}):this.store.data.mqttTopics&&this.store.data.mqttTopics.split(",").forEach(function(s){i.mqttClient.publish(s,r)})),this.websocket&&this.websocket.readyState===1&&this.websocket.send(r),(this.store.data.https||this.store.data.http)&&this.sendDatabyHttp(r),this.store.emitter.emit("sendData",r)},n.prototype.sendDataToNetWork=function(e,t){return sh(this,void 0,void 0,function(){var i,r,s,a,o,c,l,h,u;return nh(this,function(d){switch(d.label){case 0:if(i=At(t),i.data&&(Object.assign(i,i.data),delete i.data),!i.url)return[2];if(i.protocol!=="http")return[3,2];if(typeof i.headers=="object")for(r in i.headers)s=i.headers[r].match(new RegExp("(?<=\\$\\{).*?(?=\\})","g")),s&&(i.headers[r]=i.headers[r].replace("${"+s[0]+"}",this.getDynamicParam(s[0])));return a=void 0,i.method==="GET"&&(a="?"+Object.keys(e).map(function(f){return f+"="+e[f]}).join("&")),[4,fetch(i.url+(a||""),{headers:i.headers||{},method:i.method,body:i.method==="POST"?JSON.stringify(e):void 0})];case 1:return o=d.sent(),o.ok&&console.info("http消息发送成功"),[3,3];case 2:i.protocol==="mqtt"?(c=this.mqttClients.filter(function(f){return f.options.href===i.url}),c&&c.length?c[0].connected&&i.topics.split(",").forEach(function(f){c[0].publish(f,e)}):(l=xX.connect(i.url,i.options),l.on("connect",function(){console.info("mqtt连接成功"),i.topics.split(",").forEach(function(f){l.publish(f,e),l==null||l.end()})}))):i.protocol==="websocket"&&(h=this.websockets.filter(function(f){return f.url===i.url}),h&&h.length?h[0].readyState===1&&h[0].send(e):(u=new WebSocket(i.url,i.protocols||void 0),u.onopen=function(){console.info("websocket连接成功"),u.send(e),setTimeout(function(){u.close()},100)})),d.label=3;case 3:return[2]}})})},n.prototype.resize=function(e,t){this.canvas.resize(e,t),this.render(),this.store.emitter.emit("resize",{width:e,height:t}),this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.init()},n.prototype.addPen=function(e,t,i){return i===void 0&&(i=!0),sh(this,void 0,void 0,function(){return nh(this,function(r){switch(r.label){case 0:return[4,this.canvas.addPen(e,t,i)];case 1:return[2,r.sent()]}})})},n.prototype.addPens=function(e,t){return sh(this,void 0,void 0,function(){return nh(this,function(i){switch(i.label){case 0:return[4,this.canvas.addPens(e,t)];case 1:return[2,i.sent()]}})})},n.prototype.render=function(e){var t;(t=this.canvas)===null||t===void 0||t.render(e)},n.prototype.setBackgroundImage=function(e,t){var i,r,s,a;return sh(this,void 0,void 0,function(){function o(d){return sh(this,void 0,void 0,function(){return nh(this,function(f){return[2,new Promise(function(p){var _=new Image;_.src=d,c.store.options.cdn&&!(d.startsWith("http")||d.startsWith("//")||d.startsWith("data:image"))&&(_.src=c.store.options.cdn+d),_.crossOrigin="anonymous",_.onload=function(){p(_)}})]})})}var c,l,h,u;return nh(this,function(d){switch(d.label){case 0:return c=this,this.store.data.bkImage=e,l=(t==null?void 0:t.width)||((i=this.store.data)===null||i===void 0?void 0:i.width)||((r=this.store.options)===null||r===void 0?void 0:r.width),h=(t==null?void 0:t.height)||((s=this.store.data)===null||s===void 0?void 0:s.height)||((a=this.store.options)===null||a===void 0?void 0:a.height),l&&h?(this.canvas.canvasTemplate.canvas.style.backgroundImage=null,this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0)):this.canvas.canvasTemplate.canvas.style.backgroundImage=e?"url('"+e+"')":"",e?[4,o(e)]:[3,2];case 1:return u=d.sent(),this.store.bkImg=u,l&&h&&this.canvas&&(this.canvas.canvasTemplate.init(),this.render()),[3,3];case 2:this.store.bkImg=null,d.label=3;case 3:return[2]}})})},n.prototype.setBackgroundColor=function(e){e===void 0&&(e=this.store.data.background),this.store.data.background=e,this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0)},n.prototype.setGrid=function(e){var t=e===void 0?{}:e,i=t.grid,r=i===void 0?this.store.data.grid:i,s=t.gridColor,a=s===void 0?this.store.data.gridColor:s,o=t.gridSize,c=o===void 0?this.store.data.gridSize:o,l=t.gridRotate,h=l===void 0?this.store.data.gridRotate:l;this.store.data.grid=r,this.store.data.gridColor=a,this.store.data.gridSize=c,this.store.data.gridRotate=h,this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0)},n.prototype.setRule=function(e){var t=e===void 0?{}:e,i=t.rule,r=i===void 0?this.store.data.rule:i,s=t.ruleColor,a=s===void 0?this.store.data.ruleColor:s;this.store.data.rule=r,this.store.data.ruleColor=a,this.store.patchFlagsTop=!0},n.prototype.open=function(e,t){var i,r,s,a,o,c,l,h,u=this;if(t===void 0&&(t=!0),this.clear(!1,e==null?void 0:e.template),this.canvas.autoPolylineFlag=!0,e){this.setBackgroundImage(e.bkImage,e),Object.assign(this.store.data,e),this.store.data.pens=[];try{for(var d=rc(e.pens),f=d.next();!f.done;f=d.next()){var p=f.value;p.id||(p.id=ns()),!p.calculative&&(p.calculative={canvas:this.canvas}),this.store.pens[p.id]=p}}catch(b){i={error:b}}finally{try{f&&!f.done&&(r=d.return)&&r.call(d)}finally{if(i)throw i.error}}try{for(var _=rc(e.pens),m=_.next();!m.done;m=_.next()){var p=m.value;this.canvas.makePen(p)}}catch(b){s={error:b}}finally{try{m&&!m.done&&(a=_.return)&&a.call(_)}finally{if(s)throw s.error}}try{for(var g=rc(e.pens),v=g.next();!v.done;v=g.next()){var p=v.value;this.canvas.updateLines(p)}}catch(b){o={error:b}}finally{try{v&&!v.done&&(c=g.return)&&c.call(g)}finally{if(o)throw o.error}}}if(this.canvas.patchFlagsLines.forEach(function(b){b.type&&u.canvas.initLineRect(b)}),this.store.data.template||(this.store.data.template=ns()),t||(this.canvas.opening=!0),this.initBindDatas(),this.initBinds(),this.initMessageEvents(),this.render(),this.listenSocket(),this.connectSocket(),this.connectNetwork(),this.startAnimate(),this.startVideo(),this.doInitJS(),this.store.data.iconUrls)try{for(var x=rc(this.store.data.iconUrls),y=x.next();!y.done;y=x.next()){var C=y.value;Ybe(C,function(){u.render()})}}catch(b){l={error:b}}finally{try{y&&!y.done&&(h=x.return)&&h.call(x)}finally{if(l)throw l.error}}this.canvas.autoPolylineFlag=!1,this.store.emitter.emit("opened"),this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.init()},n.prototype.cacheData=function(e){if(e&&this.store.options.cacheLength){var t=this.store.cacheDatas.findIndex(function(r){return r.data&&r.data._id===e});if(t===-1)this.store.cacheDatas.push({data:At(this.store.data,!0)}),this.store.cacheDatas.length>this.store.options.cacheLength&&this.store.cacheDatas.shift();else{var i=this.store.cacheDatas.splice(t,1)[0];this.store.cacheDatas.push(i)}}},n.prototype.loadCacheData=function(e){var t=this,i=this.store.cacheDatas.findIndex(function(r){return r.data&&r.data._id===e});i!==-1&&(this.store.data=this.store.cacheDatas[i].data,this.setBackgroundImage(this.store.data.bkImage),this.store.pens={},this.store.data.pens.forEach(function(r){r.calculative.canvas=t.canvas,t.store.pens[r.id]=r,mr.path2dDraws[r.name]&&t.store.path2dMap.set(r,mr.path2dDraws[r.name](r)),r.type&&t.store.path2dMap.set(r,mr.path2dDraws[r.name](r)),r.image&&(r.calculative.imageDrawed=!1,t.canvas.loadImage(r))}),this.render())},n.prototype.initBindDatas=function(){var e=this;this.store.bindDatas={},this.store.data.pens.forEach(function(t){var i;(i=t.form)===null||i===void 0||i.forEach(function(r){var s;r.dataIds&&(Array.isArray(r.dataIds)?s=r.dataIds:s=[r.dataIds]),s==null||s.forEach(function(a){e.store.bindDatas[a.dataId]||(e.store.bindDatas[a.dataId]=[]),e.store.bindDatas[a.dataId].push({id:t.id,formItem:r})})})})},n.prototype.initBinds=function(){var e=this;this.store.bind={},this.store.data.pens.forEach(function(t){var i;(i=t.realTimes)===null||i===void 0||i.forEach(function(r){r.bind&&r.bind.id&&(e.store.bind[r.bind.id]||(e.store.bind[r.bind.id]=[]),e.store.bind[r.bind.id].push({id:t.id,key:r.key}))})})},n.prototype.connectSocket=function(){this.connectWebsocket(),this.connectMqtt(),this.connectHttp()},n.prototype.doInitJS=function(){var e=this.store.data.initJs;if(e&&e.trim())try{var t=new Function("context",e);t({meta2d:this})}catch(i){console.warn("initJs error",i)}},n.prototype.drawLine=function(e){e&&a_e(this.store),this.canvas.drawingLineName=e},n.prototype.alignPenToGrid=function(e){this.canvas.alignPenToGrid(e)},n.prototype.drawingPencil=function(){this.canvas.drawingPencil()},n.prototype.stopPencil=function(){this.canvas.stopPencil()},n.prototype.lock=function(e){this.store.data.locked=e,this.finishDrawLine(!0),this.canvas.drawingLineName="",this.stopPencil(),this.store.data.pens.forEach(function(t){t.externElement===!0&&t.onMove&&t.onMove(t)}),e>0&&this.initMessageEvents()},n.prototype.finishDrawLine=function(e){return sh(this,void 0,void 0,function(){return nh(this,function(t){switch(t.label){case 0:return[4,this.canvas.finishDrawline(e)];case 1:return t.sent(),[2]}})})},n.prototype.finishPencil=function(){return sh(this,void 0,void 0,function(){return nh(this,function(e){switch(e.label){case 0:return[4,this.canvas.finishPencil()];case 1:return e.sent(),[2]}})})},n.prototype.updateLineType=function(e,t){if(!(!e||e.name!="line"||!t||!this.canvas[t])){e.lineName=t;var i=xo(e),r=nn(e);i.prev=void 0,i.next=void 0,r.prev=void 0,r.next=void 0,e.calculative.worldAnchors=[i,r],e.calculative.activeAnchor=i,this.canvas[t](this.store,e,r),e.lineName==="curve"&&(i.prev={penId:i.penId,x:i.x-50,y:i.y},i.next={penId:i.penId,x:i.x+50,y:i.y},r.prev={penId:r.penId,x:r.x-50,y:r.y},r.next={penId:r.penId,x:r.x+50,y:r.y}),e.calculative.activeAnchor=void 0,this.canvas.initLineRect(e),this.render()}},n.prototype.addDrawLineFn=function(e,t){this.canvas[e]=t,this.canvas.drawLineFns.push(e)},n.prototype.removeDrawLineFn=function(e){var t=this.canvas.drawLineFns.indexOf(e);t>-1&&this.canvas.drawLineFns.splice(t,1)},n.prototype.showMagnifier=function(){this.canvas.showMagnifier()},n.prototype.hideMagnifier=function(){this.canvas.hideMagnifier()},n.prototype.toggleMagnifier=function(){this.canvas.toggleMagnifier()},n.prototype.clear=function(e,t){var i,r,s;e===void 0&&(e=!0);try{for(var a=rc(this.store.data.pens),o=a.next();!o.done;o=a.next()){var c=o.value;(s=c.onDestroy)===null||s===void 0||s.call(c,c)}}catch(l){i={error:l}}finally{try{o&&!o.done&&(r=a.return)&&r.call(a)}finally{if(i)throw i.error}}Ube(this.store,t),this.hideInput(),this.canvas.tooltip.hide(),this.map&&this.map.isShow&&(this.map.show(),this.map.setView()),this.canvas.clearCanvas(),sessionStorage.removeItem("page"),this.store.clipboard=void 0,this.store.sameTemplate||(this.canvas.canvasTemplate.bgPatchFlags=!0),this.store.patchFlagsTop=!0,this.setBackgroundImage(void 0),e&&this.render()},n.prototype.emit=function(e,t){this.store.emitter.emit(e,t)},n.prototype.on=function(e,t){return this.store.emitter.on(e,t),this},n.prototype.off=function(e,t){return this.store.emitter.off(e,t),this},n.prototype.registerMoveDock=function(e){this.canvas.customMoveDock=e},n.prototype.registerResizeDock=function(e){this.canvas.customResizeDock=e},n.prototype.find=function(e){return this.canvas.find(e)},n.prototype.findOne=function(e){return this.canvas.findOne(e)},n.prototype.getPenRect=function(e){return this.canvas.getPenRect(e)},n.prototype.setPenRect=function(e,t,i){i===void 0&&(i=!0),this.canvas.setPenRect(e,t,i)},n.prototype.startAnimate=function(e,t){var i=this;this.stopAnimate(e);var r;e?typeof e=="string"?r=this.find(e):r=e:r=this.store.data.pens.filter(function(s){return(s.type||s.frames)&&s.autoPlay||s.animations&&s.animations.length&&s.animations.findIndex(function(a){return a.autoPlay})!==-1}),r.forEach(function(s){var a,o;if(s.calculative.pause){var c=Date.now()-s.calculative.pause;s.calculative.pause=void 0,s.calculative.frameStart+=c,s.calculative.frameEnd+=c}else{var l=-1;if(t!==void 0&&s.animations){if(typeof t=="string"){if(l=s.animations.findIndex(function(u){return u.name===t}),l===-1)return}else if(typeof t=="number")if(s.animations.length>t)l=t;else return}else t===void 0&&(l=(a=s.animations)===null||a===void 0?void 0:a.findIndex(function(u){return u.autoPlay}),l===-1&&(!((o=s.animations)===null||o===void 0)&&o.length)&&(l=0));if(l!==-1&&l!==void 0){var h=At(s.animations[l]);delete h.name,h.currentAnimation=l,!s.type&&h.frames&&(h.showDuration=i.calcAnimateDuration(h)),i.setValue(dd({id:s.id},h),{doEvent:!1,history:!1})}i.store.animates.add(s),s.type||i.store.animateMap.set(s,s.calculative.canvas.getFrameProps(s))}}),this.canvas.canvasImage.init(),this.canvas.canvasImageBottom.init(),this.canvas.animate()},n.prototype.pauseAnimate=function(e){var t=[];e?typeof e=="string"?t=this.find(e):t=e:this.store.animates.forEach(function(i){t.push(i)}),t.forEach(function(i){i.calculative.pause||(i.calculative.pause=Date.now())})},n.prototype.stopAnimate=function(e){var t=this,i=[];e?typeof e=="string"?i=this.find(e):i=e:this.store.animates.forEach(function(r){i.push(r)}),i.forEach(function(r){r.currentAnimation=void 0,r.calculative.pause=void 0,r.calculative.start=void 0,r.calculative.duration=void 0,r.calculative.animatePos=0,t.store.animates.delete(r),t.canvas.restoreNodeAnimate(r),t.canvas.updateLines(r),t.store.animateMap.delete(r)}),this.initImageCanvas(i),setTimeout(function(){var r;(r=t.canvas)===null||r===void 0||r.calcActiveRect(),t.render()},20)},n.prototype.startVideo=function(e){var t;e?typeof e=="string"?t=this.find(e):t=e:t=this.store.data.pens.filter(function(i){return(i.video||i.audio)&&i.autoPlay}),t.forEach(function(i){var r,s;(r=i.calculative.media)===null||r===void 0||r.play(),(s=i.onStartVideo)===null||s===void 0||s.call(i,i)})},n.prototype.pauseVideo=function(e){var t=[];e?typeof e=="string"?t=this.find(e):t=e:t=this.store.data.pens.filter(function(i){return(i.video||i.audio)&&i.autoPlay}),t.forEach(function(i){var r,s;(r=i.calculative.media)===null||r===void 0||r.pause(),(s=i.onPauseVideo)===null||s===void 0||s.call(i,i)})},n.prototype.stopVideo=function(e){var t=[];e?typeof e=="string"?t=this.find(e):t=e:t=this.store.data.pens.filter(function(i){return(i.video||i.audio)&&i.autoPlay}),t.forEach(function(i){var r;i.calculative.media&&(i.calculative.media.currentTime=0,i.calculative.media.pause()),(r=i.onStopVideo)===null||r===void 0||r.call(i,i)})},n.prototype.calcAnimateDuration=function(e){return e.frames.reduce(function(t,i){return t+i.duration},0)},n.prototype.combine=function(e,t){var i=this;if(e===void 0&&(e=this.store.active),!(!e||!e.length)){var r=At(e);if(e.length===1&&e[0].type){e[0].type=Xn.Node,this.canvas.active(e),this.pushHistory({type:sr.Update,initPens:r,pens:At(e,!0)}),this.render();return}var s=B0(e),a=dd(dd({id:ns(),name:"combine"},s),{children:[],showChild:t});this.canvas.makePen(a);var o=At(a),c=1/0;e.forEach(function(l){var h,u=i.store.data.pens.findIndex(function(f){return f.id===l.id});if(u0)},n.prototype.active=function(e,t){t===void 0&&(t=!0),this.canvas.active(e,t)},n.prototype.inactive=function(){this.canvas.inactive()},n.prototype.activeAll=function(){this.canvas.active(this.store.data.pens.filter(function(e){return!e.parentId&&e.locked!==js.Disable})),this.render()},n.prototype.delete=function(e,t,i){t===void 0&&(t=!1),i===void 0&&(i=!0),this.canvas.delete(e,t,i)},n.prototype.scale=function(e,t){t===void 0&&(t={x:0,y:0}),this.canvas.scale(e,t)},n.prototype.translate=function(e,t){this.canvas.translate(e,t)},n.prototype.translatePens=function(e,t,i){this.canvas.translatePens(e,t,i)},n.prototype.getParent=function(e,t){return xd(e,t)},n.prototype.data=function(){var e=At(this.store.data),t=this.store.data,i=t.pens,r=t.paths;e.version=M0e.version,e.paths={};var s=function(o){Object.prototype.hasOwnProperty.call(r,o)&&i.find(function(c){return c.pathId===o})&&(e.paths[o]=r[o])};for(var a in r)s(a);return e},n.prototype.copy=function(e){this.canvas.copy(e)},n.prototype.cut=function(e){this.canvas.cut(e)},n.prototype.paste=function(){this.canvas.paste()},n.prototype.undo=function(){this.canvas.undo()},n.prototype.redo=function(){this.canvas.redo()},n.prototype.listenSocket=function(){try{var e=void 0,t=this.store.data.socketCbJs;if(t&&(e=new Function("e","context",t)),!e)return this.socketFn=null,!1;this.socketFn=e}catch(i){return console.error("Create the function for socket:",i),!1}return!0},n.prototype.connectWebsocket=function(e){var t=this;this.closeWebsocket(),e&&(this.store.data.websocket=e),this.store.data.websocket&&(this.websocket=new WebSocket(this.store.data.websocket,this.store.data.websocketProtocols||void 0),this.websocket.onmessage=function(i){t.socketCallback(i.data,{type:"websocket",url:t.store.data.websocket})},this.websocket.onclose=function(){console.info("Canvas websocket closed and reconneting..."),t.connectWebsocket()})},n.prototype.closeWebsocket=function(){this.websocket&&(this.websocket.onclose=void 0,this.websocket.close(),this.websocket=void 0)},n.prototype.connectMqtt=function(e){var t=this;this.closeMqtt(),e&&(this.store.data.mqtt=e.mqtt,this.store.data.mqttTopics=e.mqttTopics,this.store.data.mqttOptions=e.mqttOptions),this.store.data.mqtt&&(this.store.data.mqttOptions.clientId&&!this.store.data.mqttOptions.customClientId&&(this.store.data.mqttOptions.clientId=ns()),this.mqttClient=xX.connect(this.store.data.mqtt,this.store.data.mqttOptions),this.mqttClient.on("message",function(i,r){t.socketCallback(r.toString(),{topic:i,type:"mqtt",url:t.store.data.mqtt})}),this.store.data.mqttTopics&&this.mqttClient.subscribe(this.store.data.mqttTopics.split(",")))},n.prototype.closeMqtt=function(){var e;(e=this.mqttClient)===null||e===void 0||e.end()},n.prototype.connectHttp=function(){var e=this;this.closeHttp();var t=this.store.data.https;if(t)this.store.data.cancelFirstConnect||t.forEach(function(o){return sh(e,void 0,void 0,function(){return nh(this,function(c){return this.oldRequestHttp(o),[2]})})}),t.forEach(function(o,c){o.http&&(e.httpTimerList[c]=setInterval(function(){return sh(e,void 0,void 0,function(){return nh(this,function(l){return this.oldRequestHttp(o),[2]})})},o.httpTimeInterval||1e3))});else{var i=this.store.data,r=i.http,s=i.httpTimeInterval,a=i.httpHeaders;r&&(this.httpTimer=setInterval(function(){return sh(e,void 0,void 0,function(){var o,c;return nh(this,function(l){switch(l.label){case 0:return[4,fetch(r,{headers:a})];case 1:return o=l.sent(),o.ok?[4,o.text()]:[3,3];case 2:c=l.sent(),this.socketCallback(c,{type:"http",url:r}),l.label=3;case 3:return[2]}})})},s||1e3))}},n.prototype.oldRequestHttp=function(e){return sh(this,void 0,void 0,function(){var t,i,r;return nh(this,function(s){switch(s.label){case 0:return t=At(e),t.http?[4,fetch(t.http,{headers:t.httpHeaders,method:t.method||"GET",body:t.method==="POST"?JSON.stringify(t.body):void 0})]:[3,3];case 1:return i=s.sent(),i.ok?[4,i.text()]:[3,3];case 2:r=s.sent(),this.socketCallback(r,{type:"http",url:t.http}),s.label=3;case 3:return[2]}})})},n.prototype.sendDatabyHttp=function(e){return sh(this,void 0,void 0,function(){var t,i,r,s,a,o=this;return nh(this,function(c){switch(c.label){case 0:return t=this.store.data.https,t?(t.forEach(function(l){return sh(o,void 0,void 0,function(){var h;return nh(this,function(u){switch(u.label){case 0:return l.http?[4,fetch(l.http,{method:"post",body:e,headers:l.httpHeaders})]:[3,2];case 1:h=u.sent(),h.ok&&console.info("http消息发送成功"),u.label=2;case 2:return[2]}})})}),[3,3]):[3,1];case 1:return i=this.store.data,r=i.http,s=i.httpHeaders,r?[4,fetch(r,{method:"post",body:e,headers:s})]:[3,3];case 2:a=c.sent(),a.ok&&console.info("http消息发送成功"),c.label=3;case 3:return[2]}})})},n.prototype.closeHttp=function(){clearInterval(this.httpTimer),this.httpTimer=void 0,this.httpTimerList&&this.httpTimerList.forEach(function(e){clearInterval(e),e=void 0})},n.prototype.connectNetwork=function(){var e=this;this.closeNetwork();var t=this.store.data.networks,i=[];if(t){var r=0;this.mqttClients=[];var s=0;this.websockets=[],t.forEach(function(a){a.type==="subscribe"&&(a.protocol==="mqtt"?(a.options.clientId&&!a.options.customClientId&&(a.options.clientId=ns()),e.mqttClients[r]=xX.connect(a.url,a.options),e.mqttClients[r].on("message",function(o,c){e.socketCallback(c.toString(),{topic:o,type:"mqtt",url:a.url})}),a.topics&&e.mqttClients[r].subscribe(a.topics.split(",")),r+=1):a.protocol==="websocket"?(e.websockets[s]=new WebSocket(a.url,a.protocols||void 0),e.websockets[s].onmessage=function(o){e.socketCallback(o.data,{type:"websocket",url:a.url})},s+=1):a.protocol==="http"&&i.push({url:a.url,headers:a.headers||void 0,method:a.method,body:a.body}))})}this.onNetworkConnect(i)},n.prototype.randomString=function(e){e=e||32;for(var t="ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",i=t.length,r="",s=0;s":h=d>+u;break;case">=":h=d>=+u;break;case"<":h=d<+u;break;case"<=":h=d<=+u;break;case"=":case"==":h=d==u;break;case"!=":h=d!=u;break;case"[)":h=iV(+d,u);break;case"![)":h=!iV(+d,u);break;case"[]":h=rV(+d,u);break;case"![]":h=!rV(+d,u);break}}return h},n.prototype.pushChildren=function(e,t){var i=this,r=[At(e,!0)],s=[];e.children||(e.children=[]);var a=[];t.forEach(function(c){var l,h=At(c,!0);if((!c.id||!i.store.pens[c.id])&&(i.canvas.makePen(c),h=null),c.parentId){var u=i.store.pens[c.parentId],d=u.children.findIndex(function(p){return p===c.id});r.push(At(u,!0)),u.children.splice(d,1),a.push(At(u,!0))}e.children.push(c.id),c.parentId=e.id;var f=KV(c.calculative.worldRect,e.calculative.worldRect);Object.assign(c,f),c.locked=(l=c.lockedOnCombine)!==null&&l!==void 0?l:js.DisableMove,h?(r.push(h),a.push(At(c,!0))):s.push(At(c,!0))}),a.push(At(e,!0));var o=1;s.length&&(o=2,this.pushHistory({type:sr.Add,pens:s,step:o})),this.pushHistory({type:sr.Update,initPens:r,pens:a,step:o})},n.prototype.toPng=function(e,t,i,r){return i===void 0&&(i=!1),this.canvas.toPng(e,t,i,r)},n.prototype.activeToPng=function(e){return this.canvas.activeToPng(e)},n.prototype.downloadPng=function(e,t,i){var r,s,a=this,o;try{for(var c=rc(this.store.data.pens),l=c.next();!l.done;l=c.next()){var h=l.value;(h.calculative.img||["iframe"].includes(h.name))&&((o=h.onRenderPenRaw)===null||o===void 0||o.call(h,h))}}catch(u){r={error:u}}finally{try{l&&!l.done&&(s=c.return)&&s.call(c)}finally{if(r)throw r.error}}setTimeout(function(){var u=document.createElement("a");u.setAttribute("download",(e||a.store.data.name||"le5le.meta2d")+".png"),u.setAttribute("href",a.toPng(t,void 0,!0,i));var d=document.createEvent("MouseEvents");d.initEvent("click",!0,!0),u.dispatchEvent(d)},1e3)},n.prototype.downloadSvg=function(){var e,t;if(!window.C2S)throw console.error("请先加载乐吾乐官网下的canvas2svg.js","https://assets.le5lecdn.com/2d/canvas2svg.js"),new Error("请先加载乐吾乐官网下的canvas2svg.js");var i=this.getRect();i.x-=10,i.y-=10;var r=new window.C2S(i.width+20,i.height+20);r.textBaseline="middle";try{for(var s=rc(this.store.data.pens),a=s.next();!a.done;a=s.next()){var o=a.value;o.visible==!1||!Ez(o,this.store)||bz(r,o,i,!0)}}catch(p){e={error:p}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}var c=r.getSerializedSvg();this.store.data.background?(c=c.replace("{{bk}}",""),c=c.replace("{{bkRect}}",'')):(c=c.replace("{{bk}}",""),c=c.replace("{{bkRect}}","")),c=c.replace(/--le5le--/g,"&#x");var l=window.URL,h=new Blob([c]),u=l.createObjectURL(h),d=document.createElement("a");d.setAttribute("download",(this.store.data.name||"le5le.meta2d")+".svg"),d.setAttribute("href",u);var f=document.createEvent("MouseEvents");f.initEvent("click",!0,!0),d.dispatchEvent(f)},n.prototype.getRect=function(e){return e===void 0&&(e=this.store.data.pens),B0(e)},n.prototype.hiddenTemplate=function(){this.canvas.canvasTemplate.hidden()},n.prototype.showTemplate=function(){this.canvas.canvasTemplate.show()},n.prototype.lockTemplate=function(e){this.store.data.pens.forEach(function(t){t.canvasLayer===Ts.CanvasTemplate&&(t.locked=e)})},n.prototype.fitView=function(e,t){if(e===void 0&&(e=!0),t===void 0&&(t=10),!!this.hasView()){var i=this.canvas.canvas,r=i.offsetWidth,s=i.offsetHeight;this.resize(r,s);var a=Em(t),o=this.getRect(),c=(r-a[1]-a[3])/o.width,l=(s-a[0]-a[2])/o.height,h=c;e?h=c>l?l:c:h=c>l?c:l,this.scale(h*this.store.data.scale),this.centerView()}},n.prototype.trimPens=function(){var e=this.store.data.pens.filter(function(t){return t.name==="line"&&t.anchors.length<2});this.delete(e)},n.prototype.fitTemplateView=function(e,t){var i=this;if(e===void 0&&(e=!0),t===void 0&&(t=10),!!this.hasView()){var r=this.canvas.canvas,s=r.offsetWidth,a=r.offsetHeight,o=Em(t),c=this.getRect(),l=(s-o[1]-o[3])/c.width,h=(a-o[0]-o[2])/c.height,u=l;e?u=l>h?h:l:u=l>h?l:h,this.canvas.templateScale(u*this.store.data.scale);var d=this.getRect(),f=this.store.data.pens.filter(function(p){return!p.parentId});this.canvas.templateTranslatePens(f,-d.x,-d.y),this.store.data.pens.forEach(function(p){p.type?i.canvas.initLineRect(p):i.canvas.updateLines(p)}),this.centerView()}},n.prototype.fitSizeView=function(e,t){e===void 0&&(e=!0),t===void 0&&(t=10);var i=this.canvas.canvas,r=i.offsetWidth,s=i.offsetHeight;this.resize(r,s);var a=Em(t),o=(this.store.data.width||this.store.options.width)*this.store.data.scale,c=(this.store.data.height||this.store.options.height)*this.store.data.scale,l=(r-a[1]-a[3])/o,h=(s-a[0]-a[2])/c,u=l;e==="width"?u=l:e==="height"?u=h:e?u=l>h?h:l:u=l>h?l:h,this.scale(u*this.store.data.scale),this.centerSizeView()},n.prototype.centerSizeView=function(){var e=this.getViewCenter(),t=this.store.data.width||this.store.options.width,i=this.store.data.height||this.store.options.height,r={x:0,y:0,width:t,height:i};To(r);var s=r.center,a=this.store.data,o=a.scale,c=a.origin,l=a.x,h=a.y;this.translate((e.x-c.x)/o-s.x-l/o,(e.y-c.y)/o-s.y-h/o);var u=this.canvas.canvas,d=(u.scrollWidth-u.offsetWidth)/2,f=(u.scrollHeight-u.offsetHeight)/2;u.scrollTo(d,f)},n.prototype.scrollView=function(e,t){if(e===void 0&&(e=10),t===void 0&&(t=!1),!!this.hasView()&&this.canvas.scroll){var i=this.canvas.canvas,r=i.offsetWidth,s=i.offsetHeight;this.resize(r,s);var a=Em(e),o=this.getRect(),c=(r-a[1]-a[3])/o.width;this.scale(c*this.store.data.scale),this.topView(a[0]),t&&this.canvas.scroll.changeMode()}},n.prototype.screenView=function(e,t){if(e===void 0&&(e=10),t===void 0&&(t=!0),!!this.hasView()){var i=this.canvas.canvas,r=i.offsetWidth,s=i.offsetHeight;this.resize(r,s);var a=Em(e),o=this.getRect(),c=(r-a[1]-a[3])/o.width;t||(c=(s-a[0]-a[2])/o.height),this.scale(c*this.store.data.scale),this.topView(a[0])}},n.prototype.topView=function(e){if(e===void 0&&(e=10),!!this.hasView()){var t=this.getRect(),i=this.getViewCenter(),r=this.getPenRect(t);To(r);var s=r.center,a=this.store.data,o=a.scale,c=a.origin,l=a.x,h=a.y;this.translate((i.x-c.x)/o-s.x-l/o,(e-c.y)/o-r.y-h/o);var u=this.canvas.canvas,d=(u.scrollWidth-u.offsetWidth)/2,f=(u.scrollHeight-u.offsetHeight)/2;u.scrollTo(d,f)}},n.prototype.centerView=function(){if(this.hasView()){var e=this.getRect(),t=this.getViewCenter(),i=this.getPenRect(e);To(i);var r=i.center,s=this.store.data,a=s.scale,o=s.origin,c=s.x,l=s.y;this.translate((t.x-o.x)/a-r.x-c/a,(t.y-o.y)/a-r.y-l/a);var h=this.canvas.canvas,u=(h.scrollWidth-h.offsetWidth)/2,d=(h.scrollHeight-h.offsetHeight)/2;h.scrollTo(u,d)}},n.prototype.hasView=function(){return!!this.store.data.pens.filter(function(e){return!e.isRuleLine}).length},n.prototype.getViewCenter=function(){var e=this.canvas,t=e.width,i=e.height;return{x:t/2,y:i/2}},n.prototype.beSameByFirst=function(e,t){e===void 0&&(e=this.store.data.pens);for(var i=At(e),r=e[0],s=this.getPenRect(r),a=s.width,o=s.height,c=1;c0){var r=t[0];eV.forEach(function(a){i[a]=r[a]||e.store.options.defaultFormat[a]||e.store.options[a]})}else{var s={};eV.forEach(function(a){s[a]=e.store.options.defaultFormat[a]||e.store.options[a]||void 0})}localStorage.setItem("meta2d-formatPainter",JSON.stringify(i))},n.prototype.formatPainter=function(){for(var e=this.store.active,t=At(e),i=JSON.parse(localStorage.getItem("meta2d-formatPainter")),r=0;ro&&(o=u.height)});var c=s.x,l=s.y;e.forEach(function(h,u){var d=r.getPenRect(h);if(d.x=c,d.y=l+o/2-d.height/2,r.setValue(dd({id:h.id},d),{render:!1,doEvent:!1}),u!==e.length-1){var f=c+d.width-s.x,p=r.getPenRect(e[u+1]);Math.round(t-f)>=Math.round(p.width+i)?c+=d.width+i:(c=s.x,l+=o+i)}}),this.render(),this.pushHistory({type:sr.Update,initPens:a,pens:e})},n.prototype.gotoView=function(e){var t=this.getViewCenter(),i=t.x-e.calculative.worldRect.x-e.calculative.worldRect.width/2,r=t.y-e.calculative.worldRect.y-e.calculative.worldRect.height/2;this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.translate(i-this.store.data.x,r-this.store.data.y),this.store.data.x=i,this.store.data.y=r,this.canvas.canvasImage.init(),this.canvas.canvasImageBottom.init(),this.render()},n.prototype.showMap=function(){this.map||(this.map=new pSe(this.canvas)),this.map.show()},n.prototype.hideMap=function(){this.map.hide()},n.prototype.onSizeUpdate=function(){var e=this;this.mapTimer&&(clearTimeout(this.mapTimer),this.mapTimer=void 0),this.mapTimer=setTimeout(function(){e.map&&e.map.isShow&&e.map.show(),e.canvas.scroll&&e.canvas.scroll.isShow&&e.canvas.scroll.resize()},500)},n.prototype.toggleAnchorMode=function(){this.canvas.toggleAnchorMode()},n.prototype.addAnchorHand=function(){this.canvas.addAnchorHand()},n.prototype.removeAnchorHand=function(){this.canvas.removeAnchorHand()},n.prototype.toggleAnchorHand=function(){this.canvas.toggleAnchorHand()},n.prototype.top=function(e){var t,i,r=this;e||(e=this.store.active),Array.isArray(e)||(e=[e]);var s=function(h){var u=a.store.data.pens,d=pu(pu([],_0(dy(h,a.store)),!1),[h],!1).map(function(p){return p.id}),f=u.filter(function(p){return d.includes(p.id)});f.forEach(function(p){var _=u.findIndex(function(m){return m.id===p.id});_>-1&&(u.push(u[_]),u.splice(_,1),r.initTemplateCanvas([p]),r.initImageCanvas([p])),r.specificLayerMove(p,"top")})},a=this;try{for(var o=rc(e),c=o.next();!c.done;c=o.next()){var l=c.value;s(l)}}catch(h){t={error:h}}finally{try{c&&!c.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}this.store.emitter.emit("layer",{type:"top",pens:e})},n.prototype.initImageCanvas=function(e){this.canvas.initImageCanvas(e)},n.prototype.initTemplateCanvas=function(e){this.canvas.initTemplateCanvas(e)},n.prototype.bottom=function(e){var t,i;e||(e=this.store.active),Array.isArray(e)||(e=[e]);var r=function(l){for(var h=s.store.data.pens,u=pu(pu([],_0(dy(l,s.store)),!1),[l],!1).map(function(_){return _.id}),d=h.filter(function(_){return u.includes(_.id)}),f=function(_){var m=d[_],g=h.findIndex(function(v){return v.id===m.id});g>-1&&(h.unshift(h[g]),h.splice(g+1,1),s.initTemplateCanvas([m]),s.initImageCanvas([m])),s.specificLayerMove(m,"bottom")},p=d.length-1;p>=0;p--)f(p)},s=this;try{for(var a=rc(e),o=a.next();!o.done;o=a.next()){var c=o.value;r(c)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(t)throw t.error}}this.store.emitter.emit("layer",{type:"bottom",pens:e})},n.prototype.upByArea=function(e){var t,i,r,s=this,a=this.store.data.pens.findIndex(function(g){return g.id===e.id});if(a===-1){console.warn("upByArea: pen not in canvas");return}var o=pu([e],_0(dy(e,this.store)),!1),c=o.map(function(g){return s.store.data.pens.findIndex(function(v){return v.id===g.id})});c.includes(-1)&&(console.warn("upByArea: pen children not in canvas"),c=c.filter(function(g){return g!==-1}));var l=Math.min.apply(Math,pu([],_0(c),!1)),h=e.calculative.worldRect,u=this.store.data.pens.findIndex(function(g,v){if(v<=l||g.id===e.id||qbe(g,e))return!1;var x=g.calculative.worldRect;return Tz(h,x)});if(u===-1){this.up(e);return}(t=this.store.data.pens).splice.apply(t,pu([u+1,0],_0(o),!1));var d=function(g){var v=f.store.data.pens.findIndex(function(x){return x.id===g.id});v>-1&&f.store.data.pens.splice(v,1)},f=this;try{for(var p=rc(o),_=p.next();!_.done;_=p.next()){var m=_.value;d(m)}}catch(g){i={error:g}}finally{try{_&&!_.done&&(r=p.return)&&r.call(p)}finally{if(i)throw i.error}}this.initImageCanvas([e])},n.prototype.specificLayerMove=function(e,t){var i;if(e.image&&e.name!=="gif"){var r=Ts.CanvasImageBottom;t==="top"?r=Ts.CanvasImage:(t==="up"||t==="down")&&(r=Ts.CanvasMain),this.setValue({id:e.id,canvasLayer:r},{render:!1,doEvent:!1,history:!1})}else if(e.externElement||e.name==="gif"){var s=1;t==="top"?(e.calculative.canvas.maxZindex+=1,s=e.calculative.canvas.maxZindex):t==="up"?s=e.calculative.zIndex===void 0?6:e.calculative.zIndex+1:t==="down"&&(s=e.calculative.zIndex===void 0?3:e.calculative.zIndex-1,s<1&&(s=1)),this.setValue({id:e.id,zIndex:s},{render:!1,doEvent:!1,history:!1}),!((i=e.calculative.singleton)===null||i===void 0)&&i.div&&za(e,e.calculative.singleton.div)}},n.prototype.up=function(e){var t,i,r=this;e||(e=this.store.active),Array.isArray(e)||(e=[e]);var s=function(h){var u=a.store.data.pens;if(h.children&&h.children.length){for(var d=pu(pu([],_0(dy(h,a.store)),!1),[h],!1),f=[],p=function(v){var x=u[v];d.findIndex(function(y){return y.id===x.id})!==-1&&(x.temIndex=v,f.push(x))},_=0;_-1&&_!==u.length-1&&(u.splice(_+2,0,u[_]),u.splice(_,1),a.initTemplateCanvas([h]),a.initImageCanvas([h])),a.specificLayerMove(h,"up")}},a=this;try{for(var o=rc(e),c=o.next();!c.done;c=o.next()){var l=c.value;s(l)}}catch(h){t={error:h}}finally{try{c&&!c.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}this.store.emitter.emit("layer",{type:"up",pens:e})},n.prototype.down=function(e){var t,i,r=this;e||(e=this.store.active),Array.isArray(e)||(e=[e]);var s=function(h){var u=a.store.data.pens;if(h.children&&h.children.length){for(var d=pu(pu([],_0(dy(h,a.store)),!1),[h],!1),f=[],p=function(v){var x=u[v];d.findIndex(function(y){return y.id===x.id})!==-1&&(x.temIndex=v,f.push(x))},_=0;_-1&&_!==0&&(u.splice(_-1,0,u[_]),u.splice(_+1,1),a.initTemplateCanvas([h]),a.initImageCanvas([h])),a.specificLayerMove(h,"down")}},a=this;try{for(var o=rc(e),c=o.next();!c.done;c=o.next()){var l=c.value;s(l)}}catch(h){t={error:h}}finally{try{c&&!c.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}this.store.emitter.emit("layer",{type:"down",pens:e})},n.prototype.setLayer=function(e,t,i){i===void 0&&(i=this.store.data.pens);var r=i.findIndex(function(s){return s.id===e.id});r>-1&&(r>t?(i.splice(t,0,i[r]),i.splice(r+1,1)):re.anchors.length&&(i=e.anchors.length),i<0&&(i=0),i==0&&e.anchors[0].connectTo||i==e.anchors.length&&e.anchors[i-1].connectTo)){console.warn("端点存在连接关系");return}var r=null,s=null;t.x<=1&&t.x>=0&&t.y<=1&&t.y>=0?(s={id:t.id||ns(),penId:e.id,x:e.calculative.worldRect.x+e.calculative.worldRect.width*t.x,y:e.calculative.worldRect.y+e.calculative.worldRect.height*t.y},e.calculative.worldRect&&e.rotate%360&&Yn(s,e.rotate,e.calculative.worldRect.center),r={id:s.id,penId:e.id,x:t.x,y:t.y}):(s={id:t.id||ns(),penId:e.id,x:t.x,y:t.y},e.calculative.worldRect&&(e.rotate%360&&Yn(t,-e.rotate,e.calculative.worldRect.center),r={id:s.id,penId:e.id,x:(t.x-e.calculative.worldRect.x)/e.calculative.worldRect.width,y:(t.y-e.calculative.worldRect.y)/e.calculative.worldRect.height})),e.type===Xn.Line?(e.calculative.worldAnchors.splice(i,0,s),e.anchors.splice(i,0,r),this.canvas.updateLines(e),this.canvas.initLineRect(e),this.render()):(e.calculative.worldAnchors.push(s),e.anchors.push(r))}},n.prototype.connectLine=function(e,t,i,r,s){if(s===void 0&&(s=!0),!i){var a=t.calculative.worldRect;i=OS(e,{x:a.x+a.width/2,y:a.y+a.height/2})}if(!r){var a=e.calculative.worldRect;r=OS(t,{x:a.x+a.width/2,y:a.y+a.height/2})}var o=Math.abs(i.x-r.x),c=Math.abs(i.y-r.y),l={height:c,lineName:"line",lineWidth:1,name:"line",type:1,width:o,x:Math.min(i.x,r.x),y:Math.min(i.y,r.y),anchors:[{x:i.x>r.x?1:0,y:i.y>r.y?1:0,id:ns()},{x:i.x>r.x?0:1,y:i.x>r.x?0:1,id:ns()}]};return this.addPens([l]),sc(e,i,l,l.calculative.worldAnchors[0]),sc(t,r,l,l.calculative.worldAnchors[1]),l.calculative.active=!1,this.canvas.updateLines(l),this.canvas.updateLines(e),this.canvas.updateLines(t),this.canvas.initLineRect(l),s&&this.render(),l},n.prototype.toComponent=function(e,t,i){if(e===void 0&&(e=this.store.data.pens),e.length===1){var r=At(e[0]);return r.type=Xn.Node,r.id=void 0,[r]}var s=At(e,!0),a=B0(s),o=dd(dd({id:ns(),name:"combine"},a),{children:[],showChild:t});i&&(o.anchors=[{id:"0",penId:o.id,x:.5,y:0},{id:"1",penId:o.id,x:1,y:.5},{id:"2",penId:o.id,x:.5,y:1},{id:"3",penId:o.id,x:0,y:.5}]);var c=s.filter(function(u){return!u.parentId}),l=s.find(function(u){return u.width===a.width&&u.height===a.height}),h=l&&t===void 0;return c.length===1?o=c[0]:h&&(l.children||(l.children=[]),o=l),s.forEach(function(u){var d;if(!(u===o||u.parentId===o.id)&&!u.parentId){o.children.push(u.id),u.parentId=o.id;var f=KV(u.calculative.worldRect,a);Object.assign(u,f),u.locked=(d=u.lockedOnCombine)!==null&&d!==void 0?d:js.DisableMove}}),h||c.length===1?At(s):At(pu([o],_0(s),!1))},n.prototype.installPenPlugins=function(e,t){var i=this;if(!(!e.tag&&!e.name&&!e.id)){var r;e.id?r="id":e.tag?r="tag":e.name&&(r="name"),t.forEach(function(s){var a,o,c=s.plugin,l=s.options;if(c&&OEe(c)&&r)if(c.install(e,l),!i.penPluginMap.has(c))i.penPluginMap.set(c,[(a={},a[r]=e[r],a.option=l,a)]);else{var h=i.penPluginMap.get(c).find(function(u){return u[r]===e[r]});h?h.option=l:i.penPluginMap.get(c).push((o={},o[r]=e[r],o.option=l,o))}})}},n.prototype.uninstallPenPlugins=function(e,t){var i=this,r;e.id?r="id":e.tag?r="tag":e.name&&(r="name"),r&&t.forEach(function(s){var a=s.plugin;a.uninstall(e,s.options);var o=i.penPluginMap.get(a),c=o.findIndex(function(l){return l[r]===e[r]});c!==-1&&(o.splice(c,1),o.length===0&&i.penPluginMap.delete(a))})},n.prototype.setVisible=function(e,t,i){var r,s;if(i===void 0&&(i=!0),this.onSizeUpdate(),this.setValue({id:e.id,visible:t},{render:!1,doEvent:!1}),e.children)try{for(var a=rc(e.children),o=a.next();!o.done;o=a.next()){var c=o.value,l=this.store.pens[c];l&&this.setVisible(l,t,!1)}}catch(h){r={error:h}}finally{try{o&&!o.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}i&&this.render()},n.prototype.clearHover=function(){this.canvas.clearHover()},n.prototype.closeSocket=function(){this.closeWebsocket(),this.closeMqtt(),this.closeHttp()},n.prototype.destroy=function(e){if(this.clear(!1),this.closeSocket(),this.closeNetwork(),this.store.emitter.all.clear(),this.canvas.destroy(),this.canvas=void 0,mr[this.store.id]=void 0,!e){for(var t in mr)delete mr[t];mr.path2dDraws={},mr.canvasDraws={},mr.anchors={},mr.htmlElements={}}},n}();function mSe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.ey,c=a/4;if(t.moveTo(r+c,s),t.lineTo(r,s),t.lineTo(r,o),t.lineTo(r+c,o),t instanceof Path2D)return t}function gSe(n){var e=[{x:.25,y:0},{x:.25,y:1},{x:0,y:.5}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:i+"",x:r,y:s,penId:n.id}})}function vSe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.ex,c=i.ey,l=n.offsetX,h=a/7;if(l>1?h=l:l>0&&(h=a*l),t.moveTo(r+h,s),t.lineTo(o,s),t.lineTo(r+a-h,c),t.lineTo(r,c),t.closePath(),t instanceof Path2D)return t}function xSe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=i.ex,l=i.ey,h=a/8;if(t.moveTo(r+h,s),t.lineTo(c-h,s),t.bezierCurveTo(c+h/3,s,c+h/3,l,c-h,l),t.lineTo(r+h,l),t.lineTo(r,s+o/2),t.closePath(),t instanceof Path2D)return t}function ySe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=i.ex,l=i.center,h=l.x,u=s+o*6/7,d=o/6;if(t.moveTo(r,s),t.lineTo(c,s),t.lineTo(c,u),t.bezierCurveTo(c-20,u-d,h+a/5,u-d,h,u),t.bezierCurveTo(h-a/5,u+d,r,u+d,r,u),t.closePath(),t instanceof Path2D)return t}function ASe(n){var e=[{x:.5,y:0},{x:1,y:.5},{x:.5,y:.8571428571428571},{x:0,y:.5}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:""+i,penId:n.id,x:r,y:s}})}function CSe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.ex,c=i.ey,l=a/10;if(t.moveTo(r+l*2,s),t.bezierCurveTo(r-l*2/3,s,r-l*2/3,c,r+l*2,c),t.lineTo(o,c),t.bezierCurveTo(o-l,c,o-l,s,o,s),t.closePath(),t instanceof Path2D)return t}function bSe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.ex,c=i.ey;t.moveTo(r,s),t.lineTo(o,s),t.lineTo(o,c),t.lineTo(r,c),t.closePath();var l=a/7;if(t.moveTo(r,s+l),t.lineTo(o,s+l),t.moveTo(r+l,s),t.lineTo(r+l,c),t instanceof Path2D)return t}function ESe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.height,o=i.ex,c=i.ey,l=a/4;if(t.moveTo(r,s+l),t.lineTo(o,s),t.lineTo(o,c),t.lineTo(r,c),t.closePath(),t instanceof Path2D)return t}function TSe(n){var e=[{x:.5,y:.125},{x:1,y:.5},{x:.5,y:1},{x:0,y:.5}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:""+i,penId:n.id,x:r,y:s}})}function SSe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.ex,o=i.ey;if(t.moveTo(r,s),t.lineTo(a,s),t.moveTo(r,o),t.lineTo(a,o),t instanceof Path2D)return t}function MSe(n){var e=[{x:.5,y:0},{x:.5,y:1}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:i+"",x:r,y:s,penId:n.id}})}function RSe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=i.ex,l=i.ey;if(t.ellipse(r+a/2,s+o/2,a/2,o/2,0,0,Math.PI*2),t.moveTo(r+a/2,l),t.lineTo(c,l),t.closePath(),t instanceof Path2D)return t}function ISe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.ex,c=i.ey,l=a/7;if(t.moveTo(r,s),t.lineTo(o,s),t.lineTo(o,c),t.lineTo(r,c),t.closePath(),t.moveTo(r+l,s),t.lineTo(r+l,c),t.moveTo(o-l,s),t.lineTo(o-l,c),t instanceof Path2D)return t}function PSe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.height,o=i.ex,c=i.ey,l=a/7;if(t.moveTo(r,s+l),t.bezierCurveTo(r,s-l/2|0,o,s-l/2|0,o,s+l),t.lineTo(o,c-l),t.bezierCurveTo(o,c+l/2|0,r,c+l/2|0,r,c-l),t.closePath(),t.moveTo(r,c-l),t.bezierCurveTo(r,c-l*2|0,o,c-l*2|0,o,c-l),t instanceof Path2D)return t}function wSe(){return{flowComment:mSe,flowData:vSe,flowDb:PSe,flowDisplay:xSe,flowDocument:ySe,flowExternStorage:CSe,flowInternalStorage:bSe,flowManually:ESe,flowParallel:SSe,flowQueue:RSe,flowSubprocess:ISe}}function DSe(){return{flowDocument:ASe,flowManually:TSe,flowParallel:MSe,flowComment:gSe}}function OSe(n,e){var t=e.calculative.worldRect,i=t.x,r=t.y,s=t.width,a=t.height;n.beginPath(),n.ellipse(i+s/2,r+a/2,s/2,a/2,0,0,Math.PI*2),n.stroke(),n.beginPath(),n.fillStyle=n.strokeStyle,n.ellipse(i+s/2,r+a/2,s/4,a/4,0,0,Math.PI*2),n.fill()}function LSe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=i.ey,l=n.calculative.lineLeft||.08,h=n.calculative.borderRadius||0,u=h;h<1&&(h=a*h,u=o*h);var d=h-1&&(e.data.pens.splice(i,1),e.pens[t]=void 0)}),n.children=void 0}function zSe(n,e){n.onDestroy||(n.onDestroy=GSe,n.onAdd=HSe);var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=i.ex,l=n.calculative.borderRadius||0,h=l;l<1&&(l=a*l,h=o*h);var u=l-1&&(e.data.pens.splice(i,1),e.pens[t]=void 0)}),n.children=[]}function KSe(){return{interfaceClass:USe,simpleClass:zSe}}function WSe(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height;if(t.rect(r,s,a,o),t.closePath(),t instanceof Path2D)return t}function jSe(n,e){var t,i=(t=e.headHeight)!==null&&t!==void 0?t:50,r=e.calculative.worldRect,s=r.x,a=r.y,o=r.width,c=r.height,l=r.ey,h=e.calculative.borderRadius||0,u=h;e.calculative.borderRadius<1&&(h*=o,u*=c);var d=h0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},AX=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i1&&console.warn("echarts 只支持单 x 轴,多 x 轴将被忽略");var S=Array.isArray(b)?b[0]:b,N=Array.isArray(T)?T[0]:T;if(m)if(m===cD.Replace){if(!S&&!N)v&&(y===1?(!Array.isArray(v)&&(v=[v]),v.forEach(function(R,O){var H=x[0].data.find(function(G){return G.name===R.name});H&&(H.value=R.value)})):x.forEach(function(R,O){Array.isArray(v[O])||(v[O]=[v[O]]),v[O].forEach(function(H,G){var Q=R.data.find(function($){return $.name===H.name});Q&&(Q.value=H.value)})}));else if((S.type==="category"||N.type==="category")&&g&&v){var I=S.type==="category"?S.data:N.data;!Array.isArray(g)&&(g=[g]),!Array.isArray(v)&&(v=[v]),y===1?v.forEach(function(R,O){var H=I.indexOf(g[O]);x[0].data[H]=R}):x.forEach(function(R,O){v[O].forEach(function(H,G){var Q=I.indexOf(g[G]);R.data[Q]=H})})}}else m===cD.ReplaceAll&&(g&&(S.data=g,S.data.splice(0,S.data.length-_)),v&&(y===1?(x[0].data=v,x[0].data.splice(0,x[0].data.length-_)):x.forEach(function(R,O){R.data=v[O],R.data.splice(0,R.data.length-_)})));else{if(g){!Array.isArray(g)&&(g=[g]);var D=S.data;D.push.apply(D,AX([],yX(g),!1)),D.splice(0,D.length-_)}if(v)if(y===1){!Array.isArray(v)&&(v=[v]);var M=x[0].data;M.push.apply(M,AX([],yX(v),!1)),M.splice(0,M.length-_)}else x.forEach(function(R,O){Array.isArray(v[O])||(v[O]=[v[O]]);var H=R.data;H.push.apply(H,AX([],yX(v[O]),!1)),H.splice(0,H.length-_)})}return delete e.dataX,delete e.dataY,Object.assign(e,{echarts:p})}function t8e(n,e,t){if(t.key==="dataY"){var i=n.echarts,r=i.option,s=r.xAxis,a=r.yAxis;Array.isArray(s)&&s.length>1&&console.warn("echarts 只支持单 x 轴,多 x 轴将被忽略");var o=Array.isArray(s)?s[0]:s,c=Array.isArray(a)?a[0]:a,l=i.option.series;if(!o&&!c){var h=[];if(Array.isArray(l)&&l.length===1)return l[0].data.forEach(function(g){var v=t.dataIds.find(function(y){return y.name===g.name}).dataId;if(v){var x=e.find(function(y){return y.dataId===v});x&&h.push({name:g.name,value:x.value})}}),{id:n.id,dataY:h}}else if(o.type==="category"||c.type==="category"){var u=[],d=[],f=o.type==="category"?o.data:c.data;return f==null||f.forEach(function(g){var v=t.dataIds.find(function(y){return y.name===g}).dataId;if(v){var x=e.find(function(y){return y.dataId===v});x&&(d.push(g),u.push(x.value))}}),{id:n.id,dataY:u,dataX:d}}else if(o.type==="time"){var p=[],_=+new Date,m=!1;if(l.forEach(function(g,v){var x=[],y=t.dataIds.find(function(b){return b.name===g.name}).dataId;if(y){var C=e.find(function(b){return b.dataId===y});C&&(x.push([_,C.value]),m=!0)}p[v]=x}),m)p.forEach(function(g,v){if(!g||g.length===0){var x=l[v].data[l[v].data.length-1];p[v]=[[_,x[1]]]}});else return;return{id:n.id,dataY:p.length===1?p[0]:p}}}}function bX(n){var e,t,i=new Image;i.src=(t=(e=n.calculative.singleton)===null||e===void 0?void 0:e.echart)===null||t===void 0?void 0:t.getDataURL({pixelRatio:2}),n.calculative.img=i}function Rz(n,e){var t=At(n);if(t.dataZoom)for(var i=["right","top","width","height","left","bottom"],r=function(a){t.dataZoom.forEach(function(o){isNaN(o[i[a]])||(o[i[a]]*=e)})},s=0;s0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},eue=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i=r&&(v=!0);var x=h||c[g]==null?m:[c[g],m];p.addPoint(x,!0,v)})})}}return delete e.dataX,delete e.dataY,delete e.overwrite,Object.assign(e,{highcharts:i})}function o8e(n){var e;if(!((e=n.calculative)===null||e===void 0)&&e.singleton){var t=n.calculative.singleton.highchart.getSVG(),i=new Image;i.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(t))),n.calculative.img=i}}var iue=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function l8e(n){var e=globalThis.lcjs;if(!(!n.lightningCharts||!e)){if(typeof n.lightningCharts=="string")try{n.lightningCharts=JSON.parse(n.lightningCharts)}catch{}if(n.lightningCharts){n.onDestroy||(n.onDestroy=h8e,n.onMove=rue,n.onResize=u8e,n.onRotate=rue,n.onValue=d8e,n.onRenderPenRaw=f8e);var t=new Path2D,i=n.calculative.worldRect;if(n.calculative.singleton||(n.calculative.singleton={}),!n.calculative.singleton.div){var r=document.createElement("div");r.style.position="absolute",r.style.outline="none",r.style.left="-9999px",r.style.top="-9999px",r.style.width=i.width+"px",r.style.height=i.height+"px",r.id=n.id,document.body.appendChild(r),n.calculative.singleton.div=r,setTimeout(function(){l_e(n)},100),setTimeout(function(){n.calculative.canvas.externalElements&&n.calculative.canvas.externalElements.parentElement.appendChild(r),za(n,r);var s=new Image;s.src=n.calculative.singleton.div.children[0].toDataURL(),n.calculative.img=s},400)}return n.calculative.patchFlags&&n.calculative.singleton.div&&za(n,n.calculative.singleton.div),t}}}function c8e(n){var e=n.toLowerCase(),t=/^#([0-9|a-f]{3}|[0-9|a-f]{6})$/,i=/rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;if(e&&t.test(e)){e.length==4&&(e="#"+e[1]+e[1]+e[2]+e[2]+e[3]+e[3]);for(var r=[],s=1;s<7;s+=2)r.push(parseInt("0x"+e.slice(s,s+2)));return r}else if(e&&i.test(e)){var a=e.match(/\(([^)]*)\)/)[1],o=a.split(",").map(function(c){return parseInt(c)});return o}return e}function l_e(n){var e=lcjs.lightningChart;lcjs.PieChartTypes;var t=lcjs.LegendBoxBuilders,i=lcjs.SliceLabelFormatters,r=lcjs.Themes;lcjs.GaugeChartTypes,lcjs.SolidLine;var s=lcjs.SolidFill,a=lcjs.ColorRGBA,o=lcjs.UIOrigins,c=lcjs.emptyLine,l=lcjs.AutoCursorModes,h=lcjs.AxisScrollStrategies,u=lcjs.AxisTickStrategies,d=lcjs.UIElementBuilders,f=n.lightningCharts.option.data,p=n.lightningCharts.option.title||"Title",_=r[n.lightningCharts.option.theme||"lightNew"];switch(n.calculative.singleton.lightningChart=e(),n.lightningCharts.option.type){case"line":var m=n.calculative.singleton.lightningChart.ChartXY({container:n.id}).setTitle(p);f.forEach(function(S){m.addLineSeries().setName(S.name).add(S.data)});break;case"bar":var g=n.calculative.singleton.lightningChart,v=void 0;v=function(S){var N=10,D=N*.25,M=D*3,I=[],R=[],O=g.ChartXY(S).setTitle(p).setAutoCursorMode(l.onHover).setMouseInteractions(!1).setPadding({bottom:30}),H=O.getDefaultAxisX().setMouseInteractions(!1).setScrollStrategy(void 0).setTickStrategy(u.Empty);O.getDefaultAxisY().setMouseInteractions(!1).setTitle(n.lightningCharts.option.yTitle).setInterval(0,70).setScrollStrategy(h.fitting),O.setAutoCursor(function(k){return k.disposePointMarker().disposeTickMarkerX().disposeTickMarkerY().setGridStrokeXStyle(c).setGridStrokeYStyle(c).setResultTable(function(z){z.setOrigin(o.CenterBottom)})});var G=function(k){var z=O.addRectangleSeries();return z.setCursorResultTableFormatter(function(Y,J,re){var he={name:k.name,value:k.data[k.figures.indexOf(re)]};return Y.addRow("Department:",he.name).addRow("# of employees:",String(he.value))}),z},Q=O.addLegendBox(t.VerticalLegendBox).setAutoDispose({type:"max-width",maxWidth:.2}),$=function(){for(var k,z,Y=0,J=0;J=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function g8e(n,e){e.onAdd||(e.onAdd=A8e,e.onMouseMove=E8e,e.onMouseLeave=T8e,e.onMouseDown=S8e,e.onShowInput=C8e,e.onInput=b8e,e.onValue=R8e,e.onBeforeValue=I8e);var t=e.calculative.canvas.store.data,i=e.calculative.canvas.store.options;e.color=e.color||t.color||i.color,e.activeColor=e.activeColor||i.activeColor,e.hoverColor=e.hoverColor||i.hoverColor,e.activeBackground=e.activeBackground||i.activeBackground,e.hoverBackground=e.hoverBackground||i.hoverBackground,x8e(n,e),y8e(n,e)}function v8e(n){var e,t,i,r,s=[],a=[];n.table.rowHeight||(n.table.rowHeight=40),n.table.colWidth||(n.table.colWidth=150);var o=0;try{for(var c=LD(n.table.header.data),l=c.next();!l.done;l=c.next()){var h=l.value;o+=h.width||n.table.colWidth,s.push(o)}}catch(p){e={error:p}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}var u=0;n.table.header.show!=!1&&(u+=n.table.header.height||n.table.rowHeight,a.push(u));try{for(var d=LD(n.table.data),f=d.next();!f.done;f=d.next()){var h=f.value;u+=h.height||n.table.rowHeight,a.push(u)}}catch(p){i={error:p}}finally{try{f&&!f.done&&(r=d.return)&&r.call(d)}finally{if(i)throw i.error}}n.colPos=s,n.rowPos=a,n.tableWidth=o,n.tableHeight=u,n.width||(n.width=o,n.height=u,n.calculative.width=o,n.calculative.height=u,n.calculative.worldRect={x:n.x,y:n.y,height:n.height,width:n.width},Mo(n.calculative.worldRect))}function x8e(n,e){var t,i;if(e.colPos){var r=e.calculative.worldRect;n.save(),n.strokeStyle=e.color,n.beginPath(),n.rect(r.x,r.y,r.width,r.height),e.background&&(n.fillStyle=e.background,n.fill()),n.stroke();var s=e.rowPos[e.rowPos.length-1];try{for(var a=LD(e.rowPos),o=a.next();!o.done;o=a.next()){var c=o.value;if(c!==s){var l=c*e.calculative.worldRect.height/e.tableHeight;n.beginPath(),n.moveTo(e.calculative.worldRect.x,e.calculative.worldRect.y+l),n.lineTo(e.calculative.worldRect.ex,e.calculative.worldRect.y+l),n.stroke()}}}catch(h){t={error:h}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(t)throw t.error}}s=e.colPos[e.colPos.length-1],e.colPos.forEach(function(h,u){if(h!==s){var d=h*e.calculative.worldRect.width/e.tableWidth;n.beginPath(),n.moveTo(e.calculative.worldRect.x+d,e.calculative.worldRect.y),n.lineTo(e.calculative.worldRect.x+d,e.calculative.worldRect.ey),n.stroke()}}),n.restore()}}function y8e(n,e){var t,i,r,s;if(e.colPos){e.calculative.texts||(e.calculative.texts=[]);for(var a=1,o=0;on.calculative.worldRect.x+n.colPos[s]*t&&(r.col=s+1);for(var s=0;sn.calculative.worldRect.y+n.rowPos[s]*i&&(r.row=s+1);return r}function h_e(n,e,t){if(!(!n.table.data||!Array.isArray(n.table.data))){if(n.table.header.show==!1){var i=n.table.data[e];return Array.isArray(i)?i[t]:!i.data||!Array.isArray(i.data)?void 0:i.data[t]}if(e===0){var r=n.table.header.data[t];return r.fontWeight=n.table.header.fontWeight,r}var s=n.table.data[e-1];if(s){if(Array.isArray(s))return s[t];if(!s.data||!Array.isArray(s.data))return}else return;return s.data[t]}}function u_e(n,e,t,i){if(!(!n.table.data||!Array.isArray(n.table.data))){n.calculative.texts=void 0;var r;n.table.header.show==!1?(r=n.table.data[e],Array.isArray(r)||r.data&&Array.isArray(r.data)&&(r=r.data)):e===0?r=n.table.header.data:(r=n.table.data[e-1],Array.isArray(r)||r.data&&Array.isArray(r.data)&&(r=r.data)),r&&(r[t]instanceof Object?r[t].text=i:r[t]=i,n.calculative.canvas.store.emitter.emit("valueUpdate",n))}}function d_e(n,e,t){var i=n.calculative.worldRect.width/n.tableWidth,r=n.calculative.worldRect.height/n.tableHeight,s=0,a=n.colPos[t]*i;t>0&&(s=n.colPos[t-1]*i);var o=0,c=n.rowPos[e]*r;return e>0&&(o=n.rowPos[e-1]*r),{x:n.calculative.worldRect.x+s,y:n.calculative.worldRect.y+o,ex:n.calculative.worldRect.x+a,ey:n.calculative.worldRect.y+c,width:a-s,height:c-o}}function M8e(n,e,t){var i,r,s,a,o=n.calculative.worldRect.width/n.tableWidth,c=n.calculative.worldRect.height/n.tableHeight,l=0,h=0,u=0;try{for(var d=LD(t),f=d.next();!f.done;f=d.next()){var p=f.value;h+p.width*o+20*o=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function P8e(n,e){e.onAdd||(e.onAdd=__e,(!e.rowPos||!e.colPos||!e.calculative.maxOffsetY)&&e.onAdd(e),e.onMouseMove=F8e,e.onMouseLeave=U8e,e.onMouseDown=k8e,e.onShowInput=N8e,e.onInput=B8e,e.onValue=H8e,e.onBeforeValue=G8e,e.onMouseEnter=Y8e,e.onWheel=K8e,e.onDestroy=j8e);var t=e.calculative.canvas.store.data,i=e.calculative.canvas.store.options;if(e.color=e.color||t.color||i.color,e.textColor=e.textColor||e.color||t.textColor||i.textColor,e.activeColor=e.activeColor||i.activeColor,e.hoverColor=e.hoverColor||i.hoverColor,e.activeBackground=e.activeBackground||i.activeBackground,e.hoverBackground=e.hoverBackground||i.hoverBackground,!e.hasHeader){n.save(),n.beginPath();var r=e.calculative.worldRect,s=r.x,a=r.y,o=r.width,c=r.height;n.fillStyle="#fff0",n.rect(s-1,a-1,o+2,c+2),n.fill(),n.clip()}O8e(n,e),L8e(n,e),w8e(n,e),n.restore(),e.isFirstTime=!1}function w8e(n,e){if(e.calculative.hover&&e.calculative.hoverCell&&!e.calculative.isInput&&e.calculative.isHover){var t=e.calculative.worldRect,i=e.calculative.canvas.mousePos;if(!(i.x>t.x&&i.xt.y&&i.ye.calculative.worldRect.height)continue}else if(v<0||v>e.calculative.worldRect.height)continue;n.beginPath(),n.moveTo(e.calculative.worldRect.x,e.calculative.worldRect.y+v),n.lineTo(e.calculative.worldRect.ex,e.calculative.worldRect.y+v),n.strokeStyle=e.borderColor||"#424B61",n.stroke()}}}catch(y){t={error:y}}finally{try{m&&!m.done&&(i=_.return)&&i.call(_)}finally{if(t)throw t.error}}}if(e.vLine!==!1){var x=e.colPos[e.colPos.length-1];e.colPos.forEach(function(y,C){if(y!==x){var b=y*e.calculative.worldRect.width/e.tableWidth;n.beginPath(),n.moveTo(e.calculative.worldRect.x+b,e.calculative.worldRect.y),n.lineTo(e.calculative.worldRect.x+b,e.calculative.worldRect.ey),n.strokeStyle=e.borderColor||"#424B61",n.stroke()}})}n.restore()}}function L8e(n,e){var t,i,r,s,a;if(e.colPos){e.calculative.texts||(e.calculative.texts=[]);for(var o=1,c=function(h){if(e.hasHeader&&h===1){n.save(),n.beginPath();var u=e.calculative.worldRect,d=u.x,f=u.y,p=u.width,_=u.height;n.fillStyle="#fff0",n.rect(d-1,f+e.rowPos[0]*e.calculative.worldRect.height/e.tableHeight-1,p+2,_-e.rowPos[0]*e.calculative.worldRect.height/e.tableHeight+2),n.fill(),n.clip()}for(var m=V8e(e,h).style,g=function(x){var y=g_e(e,h,x),C=y.value,b=y.style,T=!0;b.wheres&&Array.isArray(b.wheres)&&(T=!1,T=b.wheres.every(function(J){var re=new Function("attr","return attr "+J.comparison+" "+J.value);return re(C)}));var S=e.color,N=e.textColor||e.color,D=null,M=null,I=null,R=null;T&&(S=b.color||m.color||e.color,N=b.textColor||m.textColor||e.textColor,D=b.background||m.background,M=(b.fontSize||m.fontSize||0)*e.calculative.canvas.store.data.scale,I=b.fontWeight||m.fontWeight,R=b.fontStyle||m.fontStyle);var O=void 0;e.stripe&&(e.hasHeader!==!1?h%2===1&&(D=D||e.stripeColor||"#407FFF1F"):h%2===0&&(D=D||e.stripeColor||"#407FFF1F")),e.calculative.active&&((t=e.calculative.activeCell)===null||t===void 0?void 0:t.row)===h&&((i=e.calculative.activeCell)===null||i===void 0?void 0:i.col)===x&&(S=e.activeColor,D=e.activeBackground,O=S,N=e.activeTextColor||e.activeColor),e.calculative.hover&&((r=e.calculative.hoverCell)===null||r===void 0?void 0:r.row)===h&&((s=e.calculative.hoverCell)===null||s===void 0?void 0:s.col)===x&&(S=e.hoverColor,D=e.hoverBackground,N=e.hoverTextColor||e.hoverColor,O=S);var H=x_e(e,h,x);if(H.y+H.heighte.calculative.worldRect.height+e.calculative.worldRect.y)return"continue";D&&(n.save(),n.beginPath(),n.fillStyle=D,n.fillRect(H.x,H.y,H.width+.25*e.calculative.canvas.store.data.scale,H.height),n.restore()),O&&(n.save(),n.beginPath(),n.strokeStyle=O,n.strokeRect(H.x,H.y,H.width,H.height),n.restore()),e.calculative.worldTextRect=H;var G=e.calculative.texts[h];if(e.calculative.texts[h]||(G=[],e.calculative.texts.push(G)),G[x]==null){if(typeof C=="object"){var Q=e.styles&&e.styles.filter(function(J){return J.col===x&&J.row===void 0&&J.pens});if(Q.length>0){if(G[x]="",e.isFirstTime){e.maxNum&&e.hasHeader&&h>=e.maxNum&&(C.visible=!1);var $=JSON.parse(JSON.stringify(Q[0].pens));$.forEach(function(J){Object.assign(J,{row:h,col:x},C),J.activeBackground=J.background,J.hoverBackground=J.background,J.activeColor=J.color,J.hoverColor=J.color,J.activeTextColor=J.textColor,J.hoverTextColor=J.textColor,J.height*=e.calculative.canvas.store.data.scale,J.width*=e.calculative.canvas.store.data.scale}),z8e(e,H,$),e.calculative.canvas.parent.pushChildren(e,$)}return"continue"}}else C===void 0?G[x]="":G[x]=C.text||C+"";if(!G[x])return"continue";G[x]=M5(e,G[x])}if(!G[x])return"continue";n.save(),n.beginPath(),n.fillStyle=N,n.textAlign="center",n.textBaseline="middle",n.font=(R||e.calculative.fontStyle||"")+" normal "+(I||e.calculative.fontWeight||"")+" "+(M||e.calculative.fontSize||12)*o+"px "+e.calculative.fontFamily;var V=e.colStyle&&((a=e.colStyle[x])===null||a===void 0?void 0:a.textAlign);if(V&&(n.textAlign=V),G[x].length===1)V==="left"?n.fillText(G[x][0],H.x,H.y+H.height/2):V==="right"?n.fillText(G[x][0],H.x+H.width,H.y+H.height/2):n.fillText(G[x][0],H.x+H.width/2,H.y+H.height/2);else{var j=.55,k=(M||e.calculative.fontSize)*e.calculative.lineHeight*o,z=G[x].length*k,Y=(H.height-z)/2;V==="left"?G[x].forEach(function(J,re){n.fillText(J,H.x,H.y+Y+(re+j)*k)}):V==="right"?G[x].forEach(function(J,re){n.fillText(J,H.x+H.width,H.y+Y+(re+j)*k)}):G[x].forEach(function(J,re){n.fillText(J,H.x+H.width/2,H.y+Y+(re+j)*k)})}n.restore()},v=0;vn.calculative.worldRect.x+n.colPos[s]*t&&(r.col=s+1);for(var s=0;sn.calculative.worldRect.y+n.rowPos[s]*i-n.offsetY*n.calculative.canvas.store.data.scale&&(r.row=s+1);return r}function g_e(n,e,t){if(!(!n.data||!Array.isArray(n.data))){var i=n.data[e],r=n.styles&&n.styles.filter(function(s){return s.row===e&&s.col===t});if(Array.isArray(i))return{value:i[t],style:(r==null?void 0:r.length)>0?r[0]:{}};if(!i.data||!Array.isArray(i.data))return}}function V8e(n,e){if(!(!n.data||!Array.isArray(n.data))){var t=n.data[e],i=n.styles&&n.styles.filter(function(r){return r.row===e&&!r.col});if(Array.isArray(t))return{value:t,style:(i==null?void 0:i.length)>0?i[0]:{}};if(!t.data||!Array.isArray(t.data))return}}function v_e(n,e,t,i){if(!(!n.data||!Array.isArray(n.data))){n.isFirstTime=!1,n.calculative.texts=void 0;var r=n.data[e];r&&(r[t]instanceof Object||(r[t]=i),n.calculative.canvas.store.emitter.emit("valueUpdate",n))}}function x_e(n,e,t){var i=n.calculative.worldRect.width/n.tableWidth,r=n.calculative.worldRect.height/n.tableHeight,s=0,a=n.colPos[t]*i;t>0&&(s=n.colPos[t-1]*i);var o=0,c=n.rowPos[e]*r;e>0&&(o=n.rowPos[e-1]*r);var l=n.offsetY*n.calculative.canvas.store.data.scale;return e===0&&n.hasHeader&&(l=0),{x:n.calculative.worldRect.x+s,y:n.calculative.worldRect.y+o-l,ex:n.calculative.worldRect.x+a,ey:n.calculative.worldRect.y+c-l,width:a-s,height:c-o}}function z8e(n,e,t){var i,r,s,a,o=n.calculative.worldRect.width/n.tableWidth,c=n.calculative.worldRect.height/n.tableHeight,l=1,h=1;n.initWorldRect&&(n.calculative.worldRect.width!==n.initWorldRect.width&&(l=n.calculative.worldRect.width/n.initWorldRect.width),n.calculative.worldRect.height!==n.initWorldRect.height&&(h=n.calculative.worldRect.height/n.initWorldRect.height));var u=0,d=0,f=0,p=n.calculative.canvas.store.data.scale;if(t.length>1){try{for(var _=Pz(t),m=_.next();!m.done;m=_.next()){var g=m.value;d+g.width*o+20*p*o0?t=4:t=-4,A$(n,t)}}function A$(n,e){var t;n.offsetY||(n.offsetY=0),n.offsetY+=e,n.offsetY>n.calculative.maxOffsetY&&(n.offsetY=n.calculative.maxOffsetY),n.offsetY<0&&(n.offsetY=0),(t=n.children)===null||t===void 0||t.forEach(function(i){var r=n.calculative.canvas.store.pens[i];W8e(n,r)}),n.calculative.canvas.render()}function W8e(n,e){if(e){e.oldY||(e.oldY=e.y);var t=e.calculative.worldRect;t.y,t.height;var i=n.calculative.worldRect;i.y,i.height;var r=n.calculative.canvas.store.data.scale;n.calculative.worldRect.height/n.tableHeight;var s=n.rowHeight;e.y=e.oldY-n.offsetY*r/n.calculative.worldRect.height;var a=s*(n.initScale||1)/n.tableHeight*n.maxNum;if(n.calculative.canvas.updatePenRect(e),n.hasHeader)if(e.y1){if(e.calculative.visible=!1,e.visible=!1,e.y+e.height/2>1){e.oldY-=a;var o=e.row-n.maxNum;if(!n.data[o])return;var c=At(n.data[o][e.col]);c.background&&(c.activeBackground=c.background,c.hoverBackground=c.background),c.color&&(c.hoverColor=c.color,c.activeColor=c.color),c.textColor&&(c.activeTextColor=c.textColor,c.hoverTextColor=c.textColor),Object.assign(e,c,{row:o}),Object.assign(e.calculative,c,{row:o})}}else e.visible=!0,e.calculative.visible=!0;else if(e.y<0){if(e.calculative.visible=!1,e.visible=!1,e.y<-s/n.tableHeight/2){e.oldY+=a;var o=e.row+n.maxNum;if(!n.data[o])return;var c=At(n.data[o][e.col]);c.background&&(c.activeBackground=c.background,c.hoverBackground=c.background),c.color&&(c.hoverColor=c.color,c.activeColor=c.color),c.textColor&&(c.activeTextColor=c.textColor,c.hoverTextColor=c.textColor),Object.assign(e,c,{row:o}),Object.assign(e.calculative,c,{row:o})}}else if(e.y+e.height>1){if(e.calculative.visible=!1,e.visible=!1,e.y+e.height/2>1){e.oldY-=a;var o=e.row-n.maxNum;if(!n.data[o])return;var c=At(n.data[o][e.col]);c.background&&(c.activeBackground=c.background,c.hoverBackground=c.background),c.color&&(c.hoverColor=c.color,c.activeColor=c.color),c.textColor&&(c.activeTextColor=c.textColor,c.hoverTextColor=c.textColor),Object.assign(e,c,{row:o}),Object.assign(e.calculative,c,{row:o})}}else e.calculative.visible=!0,e.visible=!0}}function j8e(n){uJ(n)}function uJ(n){n.interval&&(globalThis.clearInterval(n.interval),n.interval=null)}function dJ(n){if(n.maxNum&&n.swiper){if(n.interval)return;n.interval=globalThis.setInterval(function(){n.offsetY>=n.calculative.maxOffsetY?(n.offsetY=0,X8e(n)):n.offsetY%n.rowHeight?A$(n,1):(n.calculative.stap||(n.calculative.stap=0),n.calculative.stap+=1,n.calculative.stap==12&&(n.calculative.stap=0,A$(n,1)))},50)}}function X8e(n){var e;(e=n.children)===null||e===void 0||e.forEach(function(t){var i=n.rowHeight,r=n.calculative.canvas.store.pens[t];if(r){var s=i*(n.initScale||1)/n.tableHeight*n.maxNum;r.oldY-=s;var a=r.row-n.maxNum;if(n.data[a]){var o=At(n.data[a][r.col]);o.background&&(o.activeBackground=o.background,o.hoverBackground=o.background),o.color&&(o.hoverColor=o.color,o.activeColor=o.color),o.textColor&&(o.activeTextColor=o.textColor,o.hoverTextColor=o.textColor),r.calculative.visible=!0,r.visible=!0,Object.assign(r,o,{row:a}),Object.assign(r.calculative,o,{row:a})}}}),n.calculative.canvas.render()}function Y8e(n){uJ(n)}function Q8e(n,e){e.onClick||(e.onClick=$8e);var t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,r=e.calculative.worldRect.width,s=e.calculative.worldRect.height;r2?s/2-2:1,0,Math.PI*2),n.fill()):(n.fillStyle=e.offColor,e.disable&&(n.fillStyle=e.disableOffColor),n.fill(),n.closePath(),n.beginPath(),n.fillStyle="#ffffff",n.moveTo(t+s,i+s/2),n.arc(t+s/2,i+s/2,s/2>2?s/2-2:1,0,Math.PI*2),n.fill()),n.closePath()}function $8e(n){n.disable||(n.checked=!n.checked,n.calculative.canvas.store.emitter.emit("valueUpdate",n),n.calculative.canvas.render())}function Z8e(n,e){e.onAdd||(e.onAdd=Qw,e.onResize=Qw,e.onMove=Qw,e.onMouseMove=q8e,e.onMouseDown=y_e,e.onValue=J8e,e.onBeforeValue=e5e),e.calculative.barRect||Qw(e),e.calculative.canvas.store.data;var t=e.calculative.canvas.store.options;n.fillStyle=e.background,n.beginPath();var i=e.calculative.worldRect.x+e.calculative.barRect.x,r=e.calculative.worldRect.y+e.calculative.barRect.y,s=e.calculative.barRect.width,a=e.calculative.barRect.height,o=a/2;n.moveTo(i+o,r),n.arcTo(i+s,r,i+s,r+a,o),n.arcTo(i+s,r+a,i,r+a,o),n.arcTo(i,r+a,e.x,e.y,o),n.arcTo(i,r,i+s,r,o),n.fill(),n.fillStyle=e.activeColor||t.activeColor,n.beginPath(),s=e.calculative.ballRect.x,n.moveTo(i+o,r),n.arcTo(i+s,r,i+s,r+a,o),n.arcTo(i+s,r+a,i,r+a,o),n.arcTo(i,r+a,e.x,e.y,o),n.arcTo(i,r,i+s,r,o),n.fill(),n.fillStyle=e.btnBackground||"#000000",n.strokeStyle=e.activeColor||t.activeColor,n.lineWidth=2,n.beginPath(),i=e.calculative.worldRect.x+e.calculative.ballRect.x,r=e.calculative.worldRect.y+e.calculative.ballRect.y+e.calculative.ballRect.height/2,n.lineWidth=e.calculative.ballRect.width/10,n.arc(i,r,e.calculative.ballRect.width/2,0,Math.PI*2),n.fill(),n.stroke()}function Qw(n){if(n._textWidth||(n._textWidth=n.textWidth||50,n._fontSize=n.fontSize||12),n.textWidth=n.calculative.worldRect.width,n.calculative.textWidth=n.textWidth,n.unit||(n.unit="%"),n.sliderWidth||(n.sliderWidth=n.width),n.sliderHeight||(n.sliderHeight=n.height),!!n.calculative.worldRect){var e=n.calculative.worldRect.width/n.sliderWidth,t=n.calculative.worldRect.height/n.sliderHeight,i=Math.min(e,t);n.fontSize=n._fontSize*i;var r=n.calculative.worldRect.width-n._textWidth*i;n.textLeft=r+10*i,n.calculative.textLeft=n.textLeft,n.calculative.barRect={x:0,y:(n.calculative.worldRect.height-n.barHeight*t)/2,width:r,height:n.barHeight*t},Mo(n.calculative.barRect),fJ(n)}}function fJ(n){var e=n.calculative.barRect.height*3.5,t=n.calculative.barRect.width*n.value/100;n.calculative.ballRect={x:t,y:(n.calculative.worldRect.height-e)/2,width:e,height:e},Mo(n.calculative.ballRect),n.calculative.text=n.value+n.unit,I0(n)}function y_e(n,e){var t=e.x-n.calculative.worldRect.x;if(!(t>n.calculative.barRect.width)){var i=Math.round(t/n.calculative.barRect.width*100);in.max||i<0||i>100||(n.value=i,fJ(n),n.calculative.text=n.value+n.unit,I0(n),n.calculative.canvas.store.emitter.emit("valueUpdate",n),n.calculative.canvas.render())}}function q8e(n,e){n.calculative.canvas.mouseDown&&y_e(n,e)}function J8e(n){n.calculative.isUpdateData&&(delete n.calculative.isUpdateData,Qw(n)),fJ(n)}function e5e(n,e){return n.calculative.isUpdateData=!1,(e.textWidth||e.barHeight)&&(e.textWidth&&(n._textWidth=0),n.calculative.isUpdateData=!0),e}function t5e(n,e){e.onMouseDown||(e.onMouseDown=i5e);var t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,r=e.calculative.worldRect.height;e.calculative.worldRect.width;var s=e.calculative,a=s.fontStyle,o=s.fontWeight,c=s.fontSize,l=s.fontFamily,h=s.lineHeight,u=2;n.beginPath(),n.moveTo(t,i),n.arcTo(t+r,i,t+r,i+r,u),n.arcTo(t+r,i+r,t,i+r,u),n.arcTo(t,i+r,t,i,u),n.arcTo(t,i,t+r,i,u),n.strokeStyle="#d9d9d9",n.fillStyle="#ffffff00",e.checked&&(n.fillStyle=e.background||"#1890ff",n.strokeStyle=e.background||"#1890ff"),e.isForbidden&&(n.fillStyle="#ebebeb",n.strokeStyle="#d9d9d9"),n.closePath(),n.fill(),n.stroke(),n.save(),e.checked&&(n.beginPath(),n.lineWidth=r/10,n.strokeStyle="#ffffff",n.moveTo(t+102/506*r,i+r/2),n.lineTo(t+220/506*r,i+346/460*r),n.lineTo(t+404/506*r,i+142/460*r),n.stroke()),n.restore(),n.save(),n.fillStyle=e.isForbidden?"#00000040":Qy(e,e.calculative.canvas.parent.store)||"#000000d9",n.textAlign="start",n.textBaseline="middle",n.font=Ld({fontStyle:a,fontWeight:o,fontFamily:l||e.calculative.canvas.parent.store.options.fontFamily,fontSize:c,lineHeight:h}),n.fillText(e.value+"",t+r+10,i+r/2),n.restore()}function i5e(n,e){n.isForbidden||(n.checked=!n.checked,n.calculative.canvas.store.emitter.emit("valueUpdate",n),n.calculative.canvas.render())}function r5e(n,e){e.onAdd||(e.onAdd=s5e,e.optionPos||(e.onAdd(e),e.calculative.canvas.parent.active([e])),e.onMouseDown=n5e,e.onValue=a5e);var t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,r=e.calculative.worldRect.height,s=e.calculative.worldRect.width;if(e.optionPos){var a=e.calculative,o=a.fontStyle,c=a.fontWeight;a.fontSize;var l=a.fontFamily,h=a.lineHeight;if(e.direction=="horizontal")for(var u=0;un.calculative.worldRect.x+n.optionPos[t]*n.calculative.worldRect.width/n.checkboxWidth&&e.xn.calculative.worldRect.y+n.optionPos[t]*i&&e.y=0&&(t=Number.parseFloat(t).toFixed(e)),Number.parseFloat(t)}function EX(n){return typeof n=="number"&&Number.isFinite(n)}function c5e(n){n=C$({max:null,min:null,splitNumber:4,symmetrical:!1,deviation:!1,preferZero:!1},n);var e=[10,15,20,25,30,40,50,60,70,80,90,100,150],t=n.max,i=n.min,r=n.splitNumber,s=n.symmetrical,a=n.deviation,o=n.preferZero;if(!EX(t)||!EX(i)||t0&&(t<0?t=0:i=0);var c=(t-i)/r,l=Math.floor(Math.log10(c)-1);l=Math.pow(10,l);var h=c/l,u=e[0]*l,d=-1,f;for(f=0;fh){u=e[f]*l;break}var p=t,_=i;function m(x){if(p=parseInt(""+(t/x+1))*x,_=parseInt(""+(i/x-1))*x,t===0&&(p=0),i===0&&(_=0),s&&p*_<0){var y=Math.max(Math.abs(p),Math.abs(_));p=y,_=-y}}if(m(u),a)return{max:ty(p),min:ty(_),interval:ty(u),splitNumber:Math.round((p-_)/u)};if(!s||p*_>0){var g=void 0;e:do{if(g=Math.round((p-_)/u),(f-d)*(g-r)<0){for(;g=e.length-1||f<=0||g===r)break;d=f,g>r?u=e[++f]*l:u=e[--f]*l,m(u)}while(g!==r)}p=ty(p),_=ty(_);var v=ty((p-_)/r);return{max:p,min:_,interval:v,splitNumber:r}}function A_e(n,e){var t,i,r,s,a,o,c,l,h,u,d,f,p,_,m,g,v,x,y,C,b,T,S,N,D,M,I,R,O=e.calculative.worldRect.x,H=e.calculative.worldRect.y,G=e.calculative.worldRect.width,Q=e.calculative.worldRect.height,$=e.calculative.canvas.store.data.scale,V=[];if(e.echarts)for(var j=0;j0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},uV=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i0)&&!(r=i.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s},nue=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;ib)return{value:void 0};var T=0,S=0;n.strokeStyle=l&&((t=m.itemStyle)===null||t===void 0?void 0:t.borderColor)||"#fff",n.lineWidth=(l&&((i=m.itemStyle)===null||i===void 0?void 0:i.borderWidth)||2)*r;var N=l?m.data:m;N.forEach(function(D,M){var I,R,O,H,G,Q,$,V,j,k,z,Y,J;S+=Math.PI*2*D.value/y,n.beginPath();var re=u+M;re>=e.chartsColor.length&&(re=re%e.chartsColor.length),n.fillStyle=l?e.echarts.option.color[re]:e.chartsColor[re],n.moveTo(v+C*Math.sin(S),x-C*Math.cos(S)),n.arc(v,x,C,-Math.PI/2+S,-Math.PI/2+T,!0),n.lineTo(v+b*Math.sin(T),x-b*Math.cos(T)),n.arc(v,x,b,-Math.PI/2+T,-Math.PI/2+S),n.lineTo(v+C*Math.sin(S),x-C*Math.cos(S)),n.stroke(),n.fill(),n.closePath();var he=(T+S)/2,le=v+(b+10*r)*Math.sin(he),ue=x-(b+10*r)*Math.cos(he),L=n.fillStyle;m.label||(m.label={position:"outside",show:!0}),l&&["inner","inside"].includes(m.label.position)?(n.fillStyle="#ffffff",le=v+(b-C)/2*Math.sin(he),ue=x-(b-C)/2*Math.cos(he)):l&&m.label.position=="outside",m.labelLine||(m.labelLine={show:!0}),(l&&m.labelLine.show!==!1||!l)&&(n.beginPath(),n.strokeStyle=l?e.echarts.option.color[u+M]:e.chartsColor[u+M],n.moveTo(v+b*Math.sin(he),x-b*Math.cos(he)),n.lineTo(le,ue));var F={fontStyle:((I=e.tickLabel)===null||I===void 0?void 0:I.fontStyle)||e.calculative.fontStyle,fontWeight:((R=e.tickLabel)===null||R===void 0?void 0:R.fontWeight)||e.calculative.fontWeight,fontFamily:((O=e.tickLabel)===null||O===void 0?void 0:O.fontFamily)||e.calculative.fontFamily,lineHeight:((H=e.tickLabel)===null||H===void 0?void 0:H.lineHeight)||e.calculative.lineHeight,fontSize:(((G=e.tickLabel)===null||G===void 0?void 0:G.fontSize)||e.calculative.fontSize)*r};n.font=Ld(F),n.textBaseline="middle",n.textAlign="center",he>Math.PI?((l&&m.label.position==="outside"||!l)&&(n.textAlign="end"),(l&&m.labelLine.show!==!1||!l&&(!((V=($=(Q=e.tickLabel)===null||Q===void 0?void 0:Q.labelLine)===null||$===void 0?void 0:$.show)!==null&&V!==void 0)||V))&&n.lineTo(le-5*r,ue),(l&&m.label.show!==!1||!l&&(!((k=(j=e.tickLabel)===null||j===void 0?void 0:j.show)!==null&&k!==void 0)||k))&&n.fillText(D.name,le-5*r,ue)):((l&&m.label.position==="outside"||!l)&&(n.textAlign="start"),(l&&m.labelLine.show!==!1||!l)&&n.lineTo(le+5*r,ue),(l&&m.label.show!==!1||!l&&(!((Y=(z=e.tickLabel)===null||z===void 0?void 0:z.show)!==null&&Y!==void 0)||Y))&&n.fillText(D.name,le+5*r,ue)),n.stroke(),n.closePath(),n.fillStyle=L,n.strokeStyle=l&&((J=m.itemStyle)===null||J===void 0?void 0:J.borderColor)||"#fff",T=S}),u+=N.length},f=0;f0&&(l[0].value=o.value)})}),r=t):i===k8.ReplaceAll&&(r=e.dataY):t.forEach(function(s,a){var o=nue(nue([],sue(s),!1),sue(e.dataY[a]),!1);r.push(o)}),delete e.dataX,delete e.dataY,Object.assign(e,{data:r})}function p5e(n,e){e.onBeforeValue||(e.onBeforeValue=C_e);var t=e.calculative.canvas.store.data.scale,i=e.calculative.worldRect.x,r=e.calculative.worldRect.y;e.calculative.worldRect.width;var s=e.calculative.worldRect.height,a=[];if(e.echarts&&!e.echarts.option.color&&(e.echarts.option.color=["#1890ff","#2FC25B","#FACC14","#c23531","#2f4554","#61a0a8","#d48265"]),e.echarts)for(var o=0;ox?x/2*9/10:v/2*9/10,S=m+v/2,N=g+x/2,D=e.echarts?e.echarts.option.series[0].data[0].value:e.value,M,I=e.startAngle-e.endAngle,R=e.background||"#E6EBF8";n.strokeStyle=R;var O=T/10;n.lineWidth=O,n.beginPath(),n.lineCap="round",n.arc(S,N,T,-e.startAngle/180*Math.PI,-e.endAngle/180*Math.PI),n.stroke(),n.closePath();var H=0;if(e.axisLine&&!e.isClock)for(var G=e.axisLine.length-1;G>=0;G--)e.axisLine[G][0]*(e.max-e.min).02?n.textAlign="end":te<-.02?n.textAlign="start":n.textAlign="center",oe>.02?n.textBaseline="top":oe<-.02?n.textBaseline="bottom":n.textBaseline="middle",n.fillText(h5e(ue*G+e.min,1),S+F*te,N-F*oe),n.fill()}n.closePath();var ne=1,pe=["value"];if(e.isClock&&(ne=3,pe=["hourvalue","minutevalue","secondvalue"]),e.isClock)for(var G=0;G0&&(ye=(e.startAngle-(e[pe[G]]-e.min)/(e.max*5-e.min)*I)/180*Math.PI);var Pe=4/5*T;pe[G]==="hourvalue"&&(Pe=3/5*T),pe[G]==="minutevalue"&&(Pe=3.5/5*T);var Fe=T*1/40;n.beginPath(),n.setLineDash([]),n.lineWidth=T/(G+1)/20,n.strokeStyle=e.color||"#999999",n.moveTo(S-Fe*3*Math.cos(ye),N+Fe*3*Math.sin(ye)),n.lineTo(S+Pe*Math.cos(ye),N-Pe*Math.sin(ye)),n.stroke()}else{var ye=(e.startAngle-(D-e.min)/(e.max-e.min)*I)/180*Math.PI,Pe=4/5*T,Fe=T*1/40;n.beginPath(),n.setLineDash([]),n.lineWidth=2,n.fillStyle=M,n.moveTo(S-Fe*3*Math.cos(ye),N+Fe*3*Math.sin(ye)),n.lineTo(S+Fe*Math.cos(ye-Math.PI/2),N-Fe*Math.sin(ye-Math.PI/2)),n.lineTo(S+Pe*Math.cos(ye),N-Pe*Math.sin(ye)),n.lineTo(S+Fe*Math.cos(ye+Math.PI/2),N-Fe*Math.sin(ye+Math.PI/2)),n.lineTo(S-Fe*3*Math.cos(ye),N+Fe*3*Math.sin(ye)),n.fill()}n.beginPath(),n.textAlign="center",n.textBaseline="middle";var He={fontStyle:((l=e.titleLabel)===null||l===void 0?void 0:l.fontStyle)||e.calculative.fontStyle,textDecoration:((h=e.titleLabel)===null||h===void 0?void 0:h.textDecoration)||e.textDecoration,fontWeight:((u=e.titleLabel)===null||u===void 0?void 0:u.fontWeight)||e.calculative.fontWeight,fontFamily:((d=e.titleLabel)===null||d===void 0?void 0:d.fontFamily)||e.calculative.fontFamily,fontSize:(((f=e.titleLabel)===null||f===void 0?void 0:f.fontSize)||e.calculative.fontSize)*y,lineHeight:((p=e.titleLabel)===null||p===void 0?void 0:p.lineHeight)||e.calculative.lineHeight};n.font=Ld(He),n.fillStyle=((_=e.titleLabel)===null||_===void 0?void 0:_.color)||M,e.isClock?n.fillText(("0"+parseInt(e.hourvalue)).slice(-2)+":"+("0"+parseInt(e.minutevalue)).slice(-2)+":"+("0"+parseInt(e.secondvalue)).slice(-2),S,N+T/2):n.fillText(D+" "+(e.unit||""),S,N+T/2),n.fill(),e.isClock&&(n.beginPath(),n.fillStyle=e.color||"#999999",n.strokeStyle="#ffffff",n.arc(S,N,T/20,0,Math.PI*2),n.stroke(),n.fill(),n.closePath())}function m5e(n){if(n.isClock)n.clockInterval=setInterval(function(){var t=new Date,i=t.getSeconds(),r=t.getMinutes()+i/60,s=t.getHours()%12+r/60;n.calculative.canvas.parent.setValue({id:n.id,hourvalue:s,minutevalue:r,secondvalue:i},{render:!0,doEvent:!1})},1e3);else{var e=n.value;n.value=0,n.frames=[{duration:2e3,value:e}],n.calculative.canvas.parent.startAnimate(n.id),setTimeout(function(){n.value=e},1e3)}}function g5e(n){n.clockInterval&&(clearInterval(n.clockInterval),n.clockInterval=void 0)}function v5e(n){n.isClock&&(n.onDestroy(n),n.onAdd(n))}function x5e(){return{lineChart:u5e,histogram:p5e,pieChart:d5e,gauge:_5e}}function y5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=o/6,l=a/4;if(t.moveTo(r+l*2,s+0),t.lineTo(r+l*2,s+c),t.moveTo(r,s+c+l*2),t.arc(r+l*2,s+c+l*2,l*2,Math.PI*1,Math.PI*2,!1),t.lineTo(r+l*4,s+c*5),t.lineTo(r,s+c*5),t.lineTo(r,s+c+l*2),t.moveTo(r+l,s+c*5),t.lineTo(r+l,s+c*6),t.moveTo(r+l*2,s+c*5),t.lineTo(r+l*2,s+c*6),t.moveTo(r+l*3,s+c*5),t.lineTo(r+l*3,s+c*6),t.closePath(),t instanceof Path2D)return t}function aue(n){var e=[{x:.5,y:0},{x:.25,y:1},{x:.5,y:1},{x:.75,y:1}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:""+i,penId:n.id,x:r,y:s}})}function A5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=o-a,l=.5*a;if(t.moveTo(r+a/2,s),t.lineTo(r+a/2,s+c),t.moveTo(r+a,s+l+c),t.arc(r+a/2,s+l+c,l,0,Math.PI*2,!1),t.closePath(),t instanceof Path2D)return t}function oue(n){var e=[{x:.5,y:0},{x:.5,y:1}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:""+i,penId:n.id,x:r,y:s}})}function C5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=o/2,l=a/5;if(t.moveTo(r,s+c),t.lineTo(r+l,s+c),t.moveTo(r+l*5,s+c),t.ellipse(r+l*3,s+c,2*l,c,0,0,Math.PI*2),t.closePath(),t instanceof Path2D)return t}function b5e(n){var e=[{x:.6,y:0},{x:1,y:.5},{x:.6,y:1},{x:0,y:.5}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:""+i,penId:n.id,x:r,y:s}})}function E5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=o/4,l=.5*a;if(t.moveTo(r+l,s),t.lineTo(r+l,s+c),t.moveTo(r,s+c),t.rect(r,s+c,l*2,c*2),t.moveTo(r+l,s+3*c),t.lineTo(r+l,s+4*c),t.closePath(),t instanceof Path2D)return t}function T5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=o/8,l=.25*a;if(t.moveTo(r+l*2,s),t.lineTo(r+l*2,s+c*2),t.lineTo(r+l*3,s+c*3),t.lineTo(r+l*3,s+c*5),t.lineTo(r+l*2,s+c*6),t.lineTo(r+l*1,s+c*5),t.lineTo(r+l*1,s+c*3),t.lineTo(r+l*2,s+c*2),t.moveTo(r+l*3,s+c*4),t.lineTo(r+l*4,s+c*4),t.moveTo(r+l*2,s+c*6),t.lineTo(r+l*2,s+c*8),t.closePath(),t instanceof Path2D)return t}function S5e(n){var e=[{x:.5,y:0},{x:1,y:.5},{x:.5,y:1}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:""+i,penId:n.id,x:r,y:s}})}function M5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=a/2,l=o/10;if(t.moveTo(r+c,s),t.lineTo(r+c,s+l),t.moveTo(r+c,s+l),t.quadraticCurveTo(r+c*2,s+l,r+c*2,s+l*9),t.moveTo(r+c,s+l),t.quadraticCurveTo(r,s+l,r,s+l*9),t.quadraticCurveTo(r+c,s+l*6,r+c*2,s+l*9),t.moveTo(r+c,s+o*3/4),t.lineTo(r+c,s+o),t.moveTo(r+c*2/5,s+o*201/250),t.lineTo(r+c*2/5,s+o),t.moveTo(r+c*8/5,s+o*201/250),t.lineTo(r+c*8/5,s+o),t.closePath(),t instanceof Path2D)return t}function lue(n){var e=[{x:.5,y:0},{x:.2,y:1},{x:.5,y:1},{x:.8,y:1}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:""+i,penId:n.id,x:r,y:s}})}function R5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=o/6,l=a/4;if(t.moveTo(r+l*2,s+0),t.lineTo(r+l*2,s+c),t.moveTo(r,s+c+l*2),t.arc(r+l*2,s+c+l*2,l*2,Math.PI*1,Math.PI*2,!1),t.lineTo(r+l*4,s+c*5),t.lineTo(r,s+c*5),t.lineTo(r,s+c+l*2),t.moveTo(r,s+c*5-c/3),t.lineTo(r+l*4,s+c*5-c/3),t.moveTo(r+l,s+c*5),t.lineTo(r+l,s+c*6),t.moveTo(r+l*2,s+c*5),t.lineTo(r+l*2,s+c*6),t.moveTo(r+l*3,s+c*5),t.lineTo(r+l*3,s+c*6),t.closePath(),t instanceof Path2D)return t}function I5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=o/4,l=.5*a;if(t.moveTo(r+l,s),t.lineTo(r+l,s+c),t.lineTo(r+l*2,s+c*2),t.lineTo(r+l*2,s+c*4),t.lineTo(r,s+c*4),t.lineTo(r,s+c*2),t.lineTo(r+l,s+c),t.closePath(),t instanceof Path2D)return t}function P5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=o/4,l=a/2;if(t.moveTo(r+l,s),t.lineTo(r+l,s+c),t.lineTo(r+l*2,s+c*4),t.lineTo(r,s+c*4),t.lineTo(r+l,s+c),t.closePath(),t instanceof Path2D)return t}function w5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=o/3,l=.5*a;if(t.moveTo(r+l,s),t.lineTo(r+l,s+c),t.lineTo(r+a,s+2*c),t.lineTo(r+l,s+o),t.lineTo(r,s+2*c),t.lineTo(r+l,s+c),t.closePath(),t instanceof Path2D)return t}function D5e(n){var e=[{x:.5,y:0},{x:1,y:.6666666666666666},{x:.5,y:1},{x:0,y:.6666666666666666}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:""+i,penId:n.id,x:r,y:s}})}function O5e(n,e){var t=e||new Path2D,i=n.calculative.worldRect,r=i.x,s=i.y,a=i.width,o=i.height,c=a/2,l=o/10;if(t.moveTo(r+c,s),t.lineTo(r+c,s+l),t.moveTo(r+c,s+l),t.quadraticCurveTo(r+c*2,s+l,r+c*2,s+l*9),t.moveTo(r+c,s+l),t.quadraticCurveTo(r,s+l,r,s+l*9),t.quadraticCurveTo(r+c,s+l*6,r+c*2,s+l*9),t.moveTo(r,s+l*10),t.quadraticCurveTo(r+c,s+l*7,r+c*2,s+l*10),t.moveTo(r+c*2/5,s+o*201/250+l),t.lineTo(r+c*2/5,s+o),t.moveTo(r+c*8/5,s+o*201/250+l),t.lineTo(r+c*8/5,s+o),t.closePath(),t instanceof Path2D)return t}function L5e(n){var e=[{x:.5,y:0},{x:.2,y:1},{x:.8,y:1}];n.anchors=e.map(function(t,i){var r=t.x,s=t.y;return{id:""+i,penId:n.id,x:r,y:s}})}function N5e(n,e){var t=e.calculative.worldRect,i=t.x,r=t.y,s=t.width,a=t.height,o=s/2,c=a/10;n.beginPath(),n.moveTo(i+o,r),n.lineTo(i+o,r+c),n.moveTo(i+o,r+c),n.quadraticCurveTo(i+o*2,r+c,i+o*2,r+c*9),n.moveTo(i+o,r+c),n.quadraticCurveTo(i,r+c,i,r+c*9),n.quadraticCurveTo(i+o,r+c*6,i+o*2,r+c*9),n.moveTo(i+o,r+a*3/4),n.lineTo(i+o,r+a*9/10),n.moveTo(i+o*2/5,r+a*201/250),n.lineTo(i+o*2/5,r+a*9/10),n.moveTo(i+o*8/5,r+a*201/250),n.lineTo(i+o*8/5,r+a*9/10),n.stroke(),n.closePath(),n.beginPath();var l=o*2>c*10?c:o/5;n.fillStyle="#333333",n.font=l+"px Arial",n.textBaseline="bottom",n.textAlign="center",n.fillText("o",i+o,r+a),n.fillText("m",i+o*2/5,r+a),n.fillText("o",i+o*8/5,r+a),n.closePath()}function B5e(){return{andGate:y5e,basicEvent:A5e,conditionalEvent:C5e,event:E5e,forbiddenGate:T5e,orGate:M5e,priorityAndGate:R5e,switchEvent:I5e,transferSymbol:P5e,unexpandedEvent:w5e,xorGate:O5e}}function F5e(){return{votingGate:N5e}}function U5e(){return{andGate:aue,orGate:lue,priorityAndGate:aue,votingGate:lue,xorGate:L5e,forbiddenGate:S5e,basicEvent:oue,unexpandedEvent:D5e,conditionalEvent:b5e,transferSymbol:oue}}var b_e={exports:{}},TX={exports:{}};const k5e={},V5e=Object.freeze(Object.defineProperty({__proto__:null,default:k5e},Symbol.toStringTag,{value:"Module"})),E_e=c0e(V5e);var cue;function zs(){return cue||(cue=1,function(n,e){(function(t,i){n.exports=i()})(kt,function(){var t=t||function(i,r){var s;if(typeof window<"u"&&window.crypto&&(s=window.crypto),typeof self<"u"&&self.crypto&&(s=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(s=globalThis.crypto),!s&&typeof window<"u"&&window.msCrypto&&(s=window.msCrypto),!s&&typeof kt<"u"&&kt.crypto&&(s=kt.crypto),!s&&typeof F0=="function")try{s=E_e}catch{}var a=function(){if(s){if(typeof s.getRandomValues=="function")try{return s.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof s.randomBytes=="function")try{return s.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||function(){function v(){}return function(x){var y;return v.prototype=x,y=new v,v.prototype=null,y}}(),c={},l=c.lib={},h=l.Base=function(){return{extend:function(v){var x=o(this);return v&&x.mixIn(v),(!x.hasOwnProperty("init")||this.init===x.init)&&(x.init=function(){x.$super.init.apply(this,arguments)}),x.init.prototype=x,x.$super=this,x},create:function(){var v=this.extend();return v.init.apply(v,arguments),v},init:function(){},mixIn:function(v){for(var x in v)v.hasOwnProperty(x)&&(this[x]=v[x]);v.hasOwnProperty("toString")&&(this.toString=v.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),u=l.WordArray=h.extend({init:function(v,x){v=this.words=v||[],x!=r?this.sigBytes=x:this.sigBytes=v.length*4},toString:function(v){return(v||f).stringify(this)},concat:function(v){var x=this.words,y=v.words,C=this.sigBytes,b=v.sigBytes;if(this.clamp(),C%4)for(var T=0;T>>2]>>>24-T%4*8&255;x[C+T>>>2]|=S<<24-(C+T)%4*8}else for(var N=0;N>>2]=y[N>>>2];return this.sigBytes+=b,this},clamp:function(){var v=this.words,x=this.sigBytes;v[x>>>2]&=4294967295<<32-x%4*8,v.length=i.ceil(x/4)},clone:function(){var v=h.clone.call(this);return v.words=this.words.slice(0),v},random:function(v){for(var x=[],y=0;y>>2]>>>24-b%4*8&255;C.push((T>>>4).toString(16)),C.push((T&15).toString(16))}return C.join("")},parse:function(v){for(var x=v.length,y=[],C=0;C>>3]|=parseInt(v.substr(C,2),16)<<24-C%8*4;return new u.init(y,x/2)}},p=d.Latin1={stringify:function(v){for(var x=v.words,y=v.sigBytes,C=[],b=0;b>>2]>>>24-b%4*8&255;C.push(String.fromCharCode(T))}return C.join("")},parse:function(v){for(var x=v.length,y=[],C=0;C>>2]|=(v.charCodeAt(C)&255)<<24-C%4*8;return new u.init(y,x)}},_=d.Utf8={stringify:function(v){try{return decodeURIComponent(escape(p.stringify(v)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(v){return p.parse(unescape(encodeURIComponent(v)))}},m=l.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new u.init,this._nDataBytes=0},_append:function(v){typeof v=="string"&&(v=_.parse(v)),this._data.concat(v),this._nDataBytes+=v.sigBytes},_process:function(v){var x,y=this._data,C=y.words,b=y.sigBytes,T=this.blockSize,S=T*4,N=b/S;v?N=i.ceil(N):N=i.max((N|0)-this._minBufferSize,0);var D=N*T,M=i.min(D*4,b);if(D){for(var I=0;I>>2]|=c[u]<<24-u%4*8;a.call(this,h,l)}else a.apply(this,arguments)};o.prototype=s}}(),t.lib.WordArray})}(MX)),MX.exports}var RX={exports:{}},due;function H5e(){return due||(due=1,function(n,e){(function(t,i){n.exports=i(zs())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.WordArray,a=i.enc;a.Utf16=a.Utf16BE={stringify:function(c){for(var l=c.words,h=c.sigBytes,u=[],d=0;d>>2]>>>16-d%4*8&65535;u.push(String.fromCharCode(f))}return u.join("")},parse:function(c){for(var l=c.length,h=[],u=0;u>>1]|=c.charCodeAt(u)<<16-u%2*16;return s.create(h,l*2)}},a.Utf16LE={stringify:function(c){for(var l=c.words,h=c.sigBytes,u=[],d=0;d>>2]>>>16-d%4*8&65535);u.push(String.fromCharCode(f))}return u.join("")},parse:function(c){for(var l=c.length,h=[],u=0;u>>1]|=o(c.charCodeAt(u)<<16-u%2*16);return s.create(h,l*2)}};function o(c){return c<<8&4278255360|c>>>8&16711935}}(),t.enc.Utf16})}(RX)),RX.exports}var IX={exports:{}},fue;function K6(){return fue||(fue=1,function(n,e){(function(t,i){n.exports=i(zs())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.WordArray,a=i.enc;a.Base64={stringify:function(c){var l=c.words,h=c.sigBytes,u=this._map;c.clamp();for(var d=[],f=0;f>>2]>>>24-f%4*8&255,_=l[f+1>>>2]>>>24-(f+1)%4*8&255,m=l[f+2>>>2]>>>24-(f+2)%4*8&255,g=p<<16|_<<8|m,v=0;v<4&&f+v*.75>>6*(3-v)&63));var x=u.charAt(64);if(x)for(;d.length%4;)d.push(x);return d.join("")},parse:function(c){var l=c.length,h=this._map,u=this._reverseMap;if(!u){u=this._reverseMap=[];for(var d=0;d>>6-f%4*2,m=p|_;u[d>>>2]|=m<<24-d%4*8,d++}return s.create(u,d)}}(),t.enc.Base64})}(IX)),IX.exports}var PX={exports:{}},pue;function G5e(){return pue||(pue=1,function(n,e){(function(t,i){n.exports=i(zs())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.WordArray,a=i.enc;a.Base64url={stringify:function(c,l){l===void 0&&(l=!0);var h=c.words,u=c.sigBytes,d=l?this._safe_map:this._map;c.clamp();for(var f=[],p=0;p>>2]>>>24-p%4*8&255,m=h[p+1>>>2]>>>24-(p+1)%4*8&255,g=h[p+2>>>2]>>>24-(p+2)%4*8&255,v=_<<16|m<<8|g,x=0;x<4&&p+x*.75>>6*(3-x)&63));var y=d.charAt(64);if(y)for(;f.length%4;)f.push(y);return f.join("")},parse:function(c,l){l===void 0&&(l=!0);var h=c.length,u=l?this._safe_map:this._map,d=this._reverseMap;if(!d){d=this._reverseMap=[];for(var f=0;f>>6-f%4*2,m=p|_;u[d>>>2]|=m<<24-d%4*8,d++}return s.create(u,d)}}(),t.enc.Base64url})}(PX)),PX.exports}var wX={exports:{}},_ue;function W6(){return _ue||(_ue=1,function(n,e){(function(t,i){n.exports=i(zs())})(kt,function(t){return function(i){var r=t,s=r.lib,a=s.WordArray,o=s.Hasher,c=r.algo,l=[];(function(){for(var _=0;_<64;_++)l[_]=i.abs(i.sin(_+1))*4294967296|0})();var h=c.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(_,m){for(var g=0;g<16;g++){var v=m+g,x=_[v];_[v]=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360}var y=this._hash.words,C=_[m+0],b=_[m+1],T=_[m+2],S=_[m+3],N=_[m+4],D=_[m+5],M=_[m+6],I=_[m+7],R=_[m+8],O=_[m+9],H=_[m+10],G=_[m+11],Q=_[m+12],$=_[m+13],V=_[m+14],j=_[m+15],k=y[0],z=y[1],Y=y[2],J=y[3];k=u(k,z,Y,J,C,7,l[0]),J=u(J,k,z,Y,b,12,l[1]),Y=u(Y,J,k,z,T,17,l[2]),z=u(z,Y,J,k,S,22,l[3]),k=u(k,z,Y,J,N,7,l[4]),J=u(J,k,z,Y,D,12,l[5]),Y=u(Y,J,k,z,M,17,l[6]),z=u(z,Y,J,k,I,22,l[7]),k=u(k,z,Y,J,R,7,l[8]),J=u(J,k,z,Y,O,12,l[9]),Y=u(Y,J,k,z,H,17,l[10]),z=u(z,Y,J,k,G,22,l[11]),k=u(k,z,Y,J,Q,7,l[12]),J=u(J,k,z,Y,$,12,l[13]),Y=u(Y,J,k,z,V,17,l[14]),z=u(z,Y,J,k,j,22,l[15]),k=d(k,z,Y,J,b,5,l[16]),J=d(J,k,z,Y,M,9,l[17]),Y=d(Y,J,k,z,G,14,l[18]),z=d(z,Y,J,k,C,20,l[19]),k=d(k,z,Y,J,D,5,l[20]),J=d(J,k,z,Y,H,9,l[21]),Y=d(Y,J,k,z,j,14,l[22]),z=d(z,Y,J,k,N,20,l[23]),k=d(k,z,Y,J,O,5,l[24]),J=d(J,k,z,Y,V,9,l[25]),Y=d(Y,J,k,z,S,14,l[26]),z=d(z,Y,J,k,R,20,l[27]),k=d(k,z,Y,J,$,5,l[28]),J=d(J,k,z,Y,T,9,l[29]),Y=d(Y,J,k,z,I,14,l[30]),z=d(z,Y,J,k,Q,20,l[31]),k=f(k,z,Y,J,D,4,l[32]),J=f(J,k,z,Y,R,11,l[33]),Y=f(Y,J,k,z,G,16,l[34]),z=f(z,Y,J,k,V,23,l[35]),k=f(k,z,Y,J,b,4,l[36]),J=f(J,k,z,Y,N,11,l[37]),Y=f(Y,J,k,z,I,16,l[38]),z=f(z,Y,J,k,H,23,l[39]),k=f(k,z,Y,J,$,4,l[40]),J=f(J,k,z,Y,C,11,l[41]),Y=f(Y,J,k,z,S,16,l[42]),z=f(z,Y,J,k,M,23,l[43]),k=f(k,z,Y,J,O,4,l[44]),J=f(J,k,z,Y,Q,11,l[45]),Y=f(Y,J,k,z,j,16,l[46]),z=f(z,Y,J,k,T,23,l[47]),k=p(k,z,Y,J,C,6,l[48]),J=p(J,k,z,Y,I,10,l[49]),Y=p(Y,J,k,z,V,15,l[50]),z=p(z,Y,J,k,D,21,l[51]),k=p(k,z,Y,J,Q,6,l[52]),J=p(J,k,z,Y,S,10,l[53]),Y=p(Y,J,k,z,H,15,l[54]),z=p(z,Y,J,k,b,21,l[55]),k=p(k,z,Y,J,R,6,l[56]),J=p(J,k,z,Y,j,10,l[57]),Y=p(Y,J,k,z,M,15,l[58]),z=p(z,Y,J,k,$,21,l[59]),k=p(k,z,Y,J,N,6,l[60]),J=p(J,k,z,Y,G,10,l[61]),Y=p(Y,J,k,z,T,15,l[62]),z=p(z,Y,J,k,O,21,l[63]),y[0]=y[0]+k|0,y[1]=y[1]+z|0,y[2]=y[2]+Y|0,y[3]=y[3]+J|0},_doFinalize:function(){var _=this._data,m=_.words,g=this._nDataBytes*8,v=_.sigBytes*8;m[v>>>5]|=128<<24-v%32;var x=i.floor(g/4294967296),y=g;m[(v+64>>>9<<4)+15]=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360,m[(v+64>>>9<<4)+14]=(y<<8|y>>>24)&16711935|(y<<24|y>>>8)&4278255360,_.sigBytes=(m.length+1)*4,this._process();for(var C=this._hash,b=C.words,T=0;T<4;T++){var S=b[T];b[T]=(S<<8|S>>>24)&16711935|(S<<24|S>>>8)&4278255360}return C},clone:function(){var _=o.clone.call(this);return _._hash=this._hash.clone(),_}});function u(_,m,g,v,x,y,C){var b=_+(m&g|~m&v)+x+C;return(b<>>32-y)+m}function d(_,m,g,v,x,y,C){var b=_+(m&v|g&~v)+x+C;return(b<>>32-y)+m}function f(_,m,g,v,x,y,C){var b=_+(m^g^v)+x+C;return(b<>>32-y)+m}function p(_,m,g,v,x,y,C){var b=_+(g^(m|~v))+x+C;return(b<>>32-y)+m}r.MD5=o._createHelper(h),r.HmacMD5=o._createHmacHelper(h)}(Math),t.MD5})}(wX)),wX.exports}var DX={exports:{}},mue;function T_e(){return mue||(mue=1,function(n,e){(function(t,i){n.exports=i(zs())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.WordArray,a=r.Hasher,o=i.algo,c=[],l=o.SHA1=a.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(h,u){for(var d=this._hash.words,f=d[0],p=d[1],_=d[2],m=d[3],g=d[4],v=0;v<80;v++){if(v<16)c[v]=h[u+v]|0;else{var x=c[v-3]^c[v-8]^c[v-14]^c[v-16];c[v]=x<<1|x>>>31}var y=(f<<5|f>>>27)+g+c[v];v<20?y+=(p&_|~p&m)+1518500249:v<40?y+=(p^_^m)+1859775393:v<60?y+=(p&_|p&m|_&m)-1894007588:y+=(p^_^m)-899497514,g=m,m=_,_=p<<30|p>>>2,p=f,f=y}d[0]=d[0]+f|0,d[1]=d[1]+p|0,d[2]=d[2]+_|0,d[3]=d[3]+m|0,d[4]=d[4]+g|0},_doFinalize:function(){var h=this._data,u=h.words,d=this._nDataBytes*8,f=h.sigBytes*8;return u[f>>>5]|=128<<24-f%32,u[(f+64>>>9<<4)+14]=Math.floor(d/4294967296),u[(f+64>>>9<<4)+15]=d,h.sigBytes=u.length*4,this._process(),this._hash},clone:function(){var h=a.clone.call(this);return h._hash=this._hash.clone(),h}});i.SHA1=a._createHelper(l),i.HmacSHA1=a._createHmacHelper(l)}(),t.SHA1})}(DX)),DX.exports}var OX={exports:{}},gue;function pJ(){return gue||(gue=1,function(n,e){(function(t,i){n.exports=i(zs())})(kt,function(t){return function(i){var r=t,s=r.lib,a=s.WordArray,o=s.Hasher,c=r.algo,l=[],h=[];(function(){function f(g){for(var v=i.sqrt(g),x=2;x<=v;x++)if(!(g%x))return!1;return!0}function p(g){return(g-(g|0))*4294967296|0}for(var _=2,m=0;m<64;)f(_)&&(m<8&&(l[m]=p(i.pow(_,1/2))),h[m]=p(i.pow(_,1/3)),m++),_++})();var u=[],d=c.SHA256=o.extend({_doReset:function(){this._hash=new a.init(l.slice(0))},_doProcessBlock:function(f,p){for(var _=this._hash.words,m=_[0],g=_[1],v=_[2],x=_[3],y=_[4],C=_[5],b=_[6],T=_[7],S=0;S<64;S++){if(S<16)u[S]=f[p+S]|0;else{var N=u[S-15],D=(N<<25|N>>>7)^(N<<14|N>>>18)^N>>>3,M=u[S-2],I=(M<<15|M>>>17)^(M<<13|M>>>19)^M>>>10;u[S]=D+u[S-7]+I+u[S-16]}var R=y&C^~y&b,O=m&g^m&v^g&v,H=(m<<30|m>>>2)^(m<<19|m>>>13)^(m<<10|m>>>22),G=(y<<26|y>>>6)^(y<<21|y>>>11)^(y<<7|y>>>25),Q=T+G+R+h[S]+u[S],$=H+O;T=b,b=C,C=y,y=x+Q|0,x=v,v=g,g=m,m=Q+$|0}_[0]=_[0]+m|0,_[1]=_[1]+g|0,_[2]=_[2]+v|0,_[3]=_[3]+x|0,_[4]=_[4]+y|0,_[5]=_[5]+C|0,_[6]=_[6]+b|0,_[7]=_[7]+T|0},_doFinalize:function(){var f=this._data,p=f.words,_=this._nDataBytes*8,m=f.sigBytes*8;return p[m>>>5]|=128<<24-m%32,p[(m+64>>>9<<4)+14]=i.floor(_/4294967296),p[(m+64>>>9<<4)+15]=_,f.sigBytes=p.length*4,this._process(),this._hash},clone:function(){var f=o.clone.call(this);return f._hash=this._hash.clone(),f}});r.SHA256=o._createHelper(d),r.HmacSHA256=o._createHmacHelper(d)}(Math),t.SHA256})}(OX)),OX.exports}var LX={exports:{}},vue;function K5e(){return vue||(vue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),pJ())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.WordArray,a=i.algo,o=a.SHA256,c=a.SHA224=o.extend({_doReset:function(){this._hash=new s.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var l=o._doFinalize.call(this);return l.sigBytes-=4,l}});i.SHA224=o._createHelper(c),i.HmacSHA224=o._createHmacHelper(c)}(),t.SHA224})}(LX)),LX.exports}var NX={exports:{}},xue;function S_e(){return xue||(xue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),ZH())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.Hasher,a=i.x64,o=a.Word,c=a.WordArray,l=i.algo;function h(){return o.create.apply(o,arguments)}var u=[h(1116352408,3609767458),h(1899447441,602891725),h(3049323471,3964484399),h(3921009573,2173295548),h(961987163,4081628472),h(1508970993,3053834265),h(2453635748,2937671579),h(2870763221,3664609560),h(3624381080,2734883394),h(310598401,1164996542),h(607225278,1323610764),h(1426881987,3590304994),h(1925078388,4068182383),h(2162078206,991336113),h(2614888103,633803317),h(3248222580,3479774868),h(3835390401,2666613458),h(4022224774,944711139),h(264347078,2341262773),h(604807628,2007800933),h(770255983,1495990901),h(1249150122,1856431235),h(1555081692,3175218132),h(1996064986,2198950837),h(2554220882,3999719339),h(2821834349,766784016),h(2952996808,2566594879),h(3210313671,3203337956),h(3336571891,1034457026),h(3584528711,2466948901),h(113926993,3758326383),h(338241895,168717936),h(666307205,1188179964),h(773529912,1546045734),h(1294757372,1522805485),h(1396182291,2643833823),h(1695183700,2343527390),h(1986661051,1014477480),h(2177026350,1206759142),h(2456956037,344077627),h(2730485921,1290863460),h(2820302411,3158454273),h(3259730800,3505952657),h(3345764771,106217008),h(3516065817,3606008344),h(3600352804,1432725776),h(4094571909,1467031594),h(275423344,851169720),h(430227734,3100823752),h(506948616,1363258195),h(659060556,3750685593),h(883997877,3785050280),h(958139571,3318307427),h(1322822218,3812723403),h(1537002063,2003034995),h(1747873779,3602036899),h(1955562222,1575990012),h(2024104815,1125592928),h(2227730452,2716904306),h(2361852424,442776044),h(2428436474,593698344),h(2756734187,3733110249),h(3204031479,2999351573),h(3329325298,3815920427),h(3391569614,3928383900),h(3515267271,566280711),h(3940187606,3454069534),h(4118630271,4000239992),h(116418474,1914138554),h(174292421,2731055270),h(289380356,3203993006),h(460393269,320620315),h(685471733,587496836),h(852142971,1086792851),h(1017036298,365543100),h(1126000580,2618297676),h(1288033470,3409855158),h(1501505948,4234509866),h(1607167915,987167468),h(1816402316,1246189591)],d=[];(function(){for(var p=0;p<80;p++)d[p]=h()})();var f=l.SHA512=s.extend({_doReset:function(){this._hash=new c.init([new o.init(1779033703,4089235720),new o.init(3144134277,2227873595),new o.init(1013904242,4271175723),new o.init(2773480762,1595750129),new o.init(1359893119,2917565137),new o.init(2600822924,725511199),new o.init(528734635,4215389547),new o.init(1541459225,327033209)])},_doProcessBlock:function(p,_){for(var m=this._hash.words,g=m[0],v=m[1],x=m[2],y=m[3],C=m[4],b=m[5],T=m[6],S=m[7],N=g.high,D=g.low,M=v.high,I=v.low,R=x.high,O=x.low,H=y.high,G=y.low,Q=C.high,$=C.low,V=b.high,j=b.low,k=T.high,z=T.low,Y=S.high,J=S.low,re=N,he=D,le=M,ue=I,L=R,F=O,W=H,te=G,oe=Q,ne=$,pe=V,ye=j,Pe=k,Fe=z,He=Y,ot=J,Xe=0;Xe<80;Xe++){var gt,rt,ut=d[Xe];if(Xe<16)rt=ut.high=p[_+Xe*2]|0,gt=ut.low=p[_+Xe*2+1]|0;else{var Yt=d[Xe-15],ki=Yt.high,ei=Yt.low,Xi=(ki>>>1|ei<<31)^(ki>>>8|ei<<24)^ki>>>7,Li=(ei>>>1|ki<<31)^(ei>>>8|ki<<24)^(ei>>>7|ki<<25),Yr=d[Xe-2],xi=Yr.high,Wi=Yr.low,Ti=(xi>>>19|Wi<<13)^(xi<<3|Wi>>>29)^xi>>>6,zi=(Wi>>>19|xi<<13)^(Wi<<3|xi>>>29)^(Wi>>>6|xi<<26),ji=d[Xe-7],Ei=ji.high,Si=ji.low,ir=d[Xe-16],Ot=ir.high,qt=ir.low;gt=Li+Si,rt=Xi+Ei+(gt>>>0
  • >>0?1:0),gt=gt+zi,rt=rt+Ti+(gt>>>0>>0?1:0),gt=gt+qt,rt=rt+Ot+(gt>>>0>>0?1:0),ut.high=rt,ut.low=gt}var Vt=oe&pe^~oe&Pe,Mi=ne&ye^~ne&Fe,er=re&le^re&L^le&L,lr=he&ue^he&F^ue&F,Fr=(re>>>28|he<<4)^(re<<30|he>>>2)^(re<<25|he>>>7),cs=(he>>>28|re<<4)^(he<<30|re>>>2)^(he<<25|re>>>7),Kt=(oe>>>14|ne<<18)^(oe>>>18|ne<<14)^(oe<<23|ne>>>9),Dr=(ne>>>14|oe<<18)^(ne>>>18|oe<<14)^(ne<<23|oe>>>9),hs=u[Xe],us=hs.high,ws=hs.low,ur=ot+Dr,Tt=He+Kt+(ur>>>0>>0?1:0),ur=ur+Mi,Tt=Tt+Vt+(ur>>>0>>0?1:0),ur=ur+ws,Tt=Tt+us+(ur>>>0>>0?1:0),ur=ur+gt,Tt=Tt+rt+(ur>>>0>>0?1:0),ti=cs+lr,Lt=Fr+er+(ti>>>0>>0?1:0);He=Pe,ot=Fe,Pe=pe,Fe=ye,pe=oe,ye=ne,ne=te+ur|0,oe=W+Tt+(ne>>>0>>0?1:0)|0,W=L,te=F,L=le,F=ue,le=re,ue=he,he=ur+ti|0,re=Tt+Lt+(he>>>0>>0?1:0)|0}D=g.low=D+he,g.high=N+re+(D>>>0>>0?1:0),I=v.low=I+ue,v.high=M+le+(I>>>0>>0?1:0),O=x.low=O+F,x.high=R+L+(O>>>0>>0?1:0),G=y.low=G+te,y.high=H+W+(G>>>0>>0?1:0),$=C.low=$+ne,C.high=Q+oe+($>>>0>>0?1:0),j=b.low=j+ye,b.high=V+pe+(j>>>0>>0?1:0),z=T.low=z+Fe,T.high=k+Pe+(z>>>0>>0?1:0),J=S.low=J+ot,S.high=Y+He+(J>>>0>>0?1:0)},_doFinalize:function(){var p=this._data,_=p.words,m=this._nDataBytes*8,g=p.sigBytes*8;_[g>>>5]|=128<<24-g%32,_[(g+128>>>10<<5)+30]=Math.floor(m/4294967296),_[(g+128>>>10<<5)+31]=m,p.sigBytes=_.length*4,this._process();var v=this._hash.toX32();return v},clone:function(){var p=s.clone.call(this);return p._hash=this._hash.clone(),p},blockSize:1024/32});i.SHA512=s._createHelper(f),i.HmacSHA512=s._createHmacHelper(f)}(),t.SHA512})}(NX)),NX.exports}var BX={exports:{}},yue;function W5e(){return yue||(yue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),ZH(),S_e())})(kt,function(t){return function(){var i=t,r=i.x64,s=r.Word,a=r.WordArray,o=i.algo,c=o.SHA512,l=o.SHA384=c.extend({_doReset:function(){this._hash=new a.init([new s.init(3418070365,3238371032),new s.init(1654270250,914150663),new s.init(2438529370,812702999),new s.init(355462360,4144912697),new s.init(1731405415,4290775857),new s.init(2394180231,1750603025),new s.init(3675008525,1694076839),new s.init(1203062813,3204075428)])},_doFinalize:function(){var h=c._doFinalize.call(this);return h.sigBytes-=16,h}});i.SHA384=c._createHelper(l),i.HmacSHA384=c._createHmacHelper(l)}(),t.SHA384})}(BX)),BX.exports}var FX={exports:{}},Aue;function j5e(){return Aue||(Aue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),ZH())})(kt,function(t){return function(i){var r=t,s=r.lib,a=s.WordArray,o=s.Hasher,c=r.x64,l=c.Word,h=r.algo,u=[],d=[],f=[];(function(){for(var m=1,g=0,v=0;v<24;v++){u[m+5*g]=(v+1)*(v+2)/2%64;var x=g%5,y=(2*m+3*g)%5;m=x,g=y}for(var m=0;m<5;m++)for(var g=0;g<5;g++)d[m+5*g]=g+(2*m+3*g)%5*5;for(var C=1,b=0;b<24;b++){for(var T=0,S=0,N=0;N<7;N++){if(C&1){var D=(1<>>24)&16711935|(C<<24|C>>>8)&4278255360,b=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;var T=v[y];T.high^=b,T.low^=C}for(var S=0;S<24;S++){for(var N=0;N<5;N++){for(var D=0,M=0,I=0;I<5;I++){var T=v[N+5*I];D^=T.high,M^=T.low}var R=p[N];R.high=D,R.low=M}for(var N=0;N<5;N++)for(var O=p[(N+4)%5],H=p[(N+1)%5],G=H.high,Q=H.low,D=O.high^(G<<1|Q>>>31),M=O.low^(Q<<1|G>>>31),I=0;I<5;I++){var T=v[N+5*I];T.high^=D,T.low^=M}for(var $=1;$<25;$++){var D,M,T=v[$],V=T.high,j=T.low,k=u[$];k<32?(D=V<>>32-k,M=j<>>32-k):(D=j<>>64-k,M=V<>>64-k);var z=p[d[$]];z.high=D,z.low=M}var Y=p[0],J=v[0];Y.high=J.high,Y.low=J.low;for(var N=0;N<5;N++)for(var I=0;I<5;I++){var $=N+5*I,T=v[$],re=p[$],he=p[(N+1)%5+5*I],le=p[(N+2)%5+5*I];T.high=re.high^~he.high&le.high,T.low=re.low^~he.low&le.low}var T=v[0],ue=f[S];T.high^=ue.high,T.low^=ue.low}},_doFinalize:function(){var m=this._data,g=m.words;this._nDataBytes*8;var v=m.sigBytes*8,x=this.blockSize*32;g[v>>>5]|=1<<24-v%32,g[(i.ceil((v+1)/x)*x>>>5)-1]|=128,m.sigBytes=g.length*4,this._process();for(var y=this._state,C=this.cfg.outputLength/8,b=C/8,T=[],S=0;S>>24)&16711935|(D<<24|D>>>8)&4278255360,M=(M<<8|M>>>24)&16711935|(M<<24|M>>>8)&4278255360,T.push(M),T.push(D)}return new a.init(T,C)},clone:function(){for(var m=o.clone.call(this),g=m._state=this._state.slice(0),v=0;v<25;v++)g[v]=g[v].clone();return m}});r.SHA3=o._createHelper(_),r.HmacSHA3=o._createHmacHelper(_)}(Math),t.SHA3})}(FX)),FX.exports}var UX={exports:{}},Cue;function X5e(){return Cue||(Cue=1,function(n,e){(function(t,i){n.exports=i(zs())})(kt,function(t){/** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */return function(i){var r=t,s=r.lib,a=s.WordArray,o=s.Hasher,c=r.algo,l=a.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),h=a.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),u=a.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),d=a.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),f=a.create([0,1518500249,1859775393,2400959708,2840853838]),p=a.create([1352829926,1548603684,1836072691,2053994217,0]),_=c.RIPEMD160=o.extend({_doReset:function(){this._hash=a.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(b,T){for(var S=0;S<16;S++){var N=T+S,D=b[N];b[N]=(D<<8|D>>>24)&16711935|(D<<24|D>>>8)&4278255360}var M=this._hash.words,I=f.words,R=p.words,O=l.words,H=h.words,G=u.words,Q=d.words,$,V,j,k,z,Y,J,re,he,le;Y=$=M[0],J=V=M[1],re=j=M[2],he=k=M[3],le=z=M[4];for(var ue,S=0;S<80;S+=1)ue=$+b[T+O[S]]|0,S<16?ue+=m(V,j,k)+I[0]:S<32?ue+=g(V,j,k)+I[1]:S<48?ue+=v(V,j,k)+I[2]:S<64?ue+=x(V,j,k)+I[3]:ue+=y(V,j,k)+I[4],ue=ue|0,ue=C(ue,G[S]),ue=ue+z|0,$=z,z=k,k=C(j,10),j=V,V=ue,ue=Y+b[T+H[S]]|0,S<16?ue+=y(J,re,he)+R[0]:S<32?ue+=x(J,re,he)+R[1]:S<48?ue+=v(J,re,he)+R[2]:S<64?ue+=g(J,re,he)+R[3]:ue+=m(J,re,he)+R[4],ue=ue|0,ue=C(ue,Q[S]),ue=ue+le|0,Y=le,le=he,he=C(re,10),re=J,J=ue;ue=M[1]+j+he|0,M[1]=M[2]+k+le|0,M[2]=M[3]+z+Y|0,M[3]=M[4]+$+J|0,M[4]=M[0]+V+re|0,M[0]=ue},_doFinalize:function(){var b=this._data,T=b.words,S=this._nDataBytes*8,N=b.sigBytes*8;T[N>>>5]|=128<<24-N%32,T[(N+64>>>9<<4)+14]=(S<<8|S>>>24)&16711935|(S<<24|S>>>8)&4278255360,b.sigBytes=(T.length+1)*4,this._process();for(var D=this._hash,M=D.words,I=0;I<5;I++){var R=M[I];M[I]=(R<<8|R>>>24)&16711935|(R<<24|R>>>8)&4278255360}return D},clone:function(){var b=o.clone.call(this);return b._hash=this._hash.clone(),b}});function m(b,T,S){return b^T^S}function g(b,T,S){return b&T|~b&S}function v(b,T,S){return(b|~T)^S}function x(b,T,S){return b&S|T&~S}function y(b,T,S){return b^(T|~S)}function C(b,T){return b<>>32-T}r.RIPEMD160=o._createHelper(_),r.HmacRIPEMD160=o._createHmacHelper(_)}(),t.RIPEMD160})}(UX)),UX.exports}var kX={exports:{}},bue;function _J(){return bue||(bue=1,function(n,e){(function(t,i){n.exports=i(zs())})(kt,function(t){(function(){var i=t,r=i.lib,s=r.Base,a=i.enc,o=a.Utf8,c=i.algo;c.HMAC=s.extend({init:function(l,h){l=this._hasher=new l.init,typeof h=="string"&&(h=o.parse(h));var u=l.blockSize,d=u*4;h.sigBytes>d&&(h=l.finalize(h)),h.clamp();for(var f=this._oKey=h.clone(),p=this._iKey=h.clone(),_=f.words,m=p.words,g=0;g>>2]&255;D.sigBytes-=M}};s.BlockCipher=f.extend({cfg:f.cfg.extend({mode:m,padding:v}),reset:function(){var D;f.reset.call(this);var M=this.cfg,I=M.iv,R=M.mode;this._xformMode==this._ENC_XFORM_MODE?D=R.createEncryptor:(D=R.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==D?this._mode.init(this,I&&I.words):(this._mode=D.call(R,this,I&&I.words),this._mode.__creator=D)},_doProcessBlock:function(D,M){this._mode.processBlock(D,M)},_doFinalize:function(){var D,M=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(M.pad(this._data,this.blockSize),D=this._process(!0)):(D=this._process(!0),M.unpad(D)),D},blockSize:128/32});var x=s.CipherParams=a.extend({init:function(D){this.mixIn(D)},toString:function(D){return(D||this.formatter).stringify(this)}}),y=r.format={},C=y.OpenSSL={stringify:function(D){var M,I=D.ciphertext,R=D.salt;return R?M=o.create([1398893684,1701076831]).concat(R).concat(I):M=I,M.toString(h)},parse:function(D){var M,I=h.parse(D),R=I.words;return R[0]==1398893684&&R[1]==1701076831&&(M=o.create(R.slice(2,4)),R.splice(0,4),I.sigBytes-=16),x.create({ciphertext:I,salt:M})}},b=s.SerializableCipher=a.extend({cfg:a.extend({format:C}),encrypt:function(D,M,I,R){R=this.cfg.extend(R);var O=D.createEncryptor(I,R),H=O.finalize(M),G=O.cfg;return x.create({ciphertext:H,key:I,iv:G.iv,algorithm:D,mode:G.mode,padding:G.padding,blockSize:D.blockSize,formatter:R.format})},decrypt:function(D,M,I,R){R=this.cfg.extend(R),M=this._parse(M,R.format);var O=D.createDecryptor(I,R).finalize(M.ciphertext);return O},_parse:function(D,M){return typeof D=="string"?M.parse(D,this):D}}),T=r.kdf={},S=T.OpenSSL={execute:function(D,M,I,R,O){if(R||(R=o.random(64/8)),O)var H=d.create({keySize:M+I,hasher:O}).compute(D,R);else var H=d.create({keySize:M+I}).compute(D,R);var G=o.create(H.words.slice(M),I*4);return H.sigBytes=M*4,x.create({key:H,iv:G,salt:R})}},N=s.PasswordBasedCipher=b.extend({cfg:b.cfg.extend({kdf:S}),encrypt:function(D,M,I,R){R=this.cfg.extend(R);var O=R.kdf.execute(I,D.keySize,D.ivSize,R.salt,R.hasher);R.iv=O.iv;var H=b.encrypt.call(this,D,M,O.key,R);return H.mixIn(O),H},decrypt:function(D,M,I,R){R=this.cfg.extend(R),M=this._parse(M,R.format);var O=R.kdf.execute(I,D.keySize,D.ivSize,M.salt,R.hasher);R.iv=O.iv;var H=b.decrypt.call(this,D,M,O.key,R);return H}})}()})}(HX)),HX.exports}var GX={exports:{}},Mue;function Q5e(){return Mue||(Mue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),mc())})(kt,function(t){return t.mode.CFB=function(){var i=t.lib.BlockCipherMode.extend();i.Encryptor=i.extend({processBlock:function(s,a){var o=this._cipher,c=o.blockSize;r.call(this,s,a,c,o),this._prevBlock=s.slice(a,a+c)}}),i.Decryptor=i.extend({processBlock:function(s,a){var o=this._cipher,c=o.blockSize,l=s.slice(a,a+c);r.call(this,s,a,c,o),this._prevBlock=l}});function r(s,a,o,c){var l,h=this._iv;h?(l=h.slice(0),this._iv=void 0):l=this._prevBlock,c.encryptBlock(l,0);for(var u=0;u>24&255)===255){var c=o>>16&255,l=o>>8&255,h=o&255;c===255?(c=0,l===255?(l=0,h===255?h=0:++h):++l):++c,o=0,o+=c<<16,o+=l<<8,o+=h}else o+=1<<24;return o}function s(o){return(o[0]=r(o[0]))===0&&(o[1]=r(o[1])),o}var a=i.Encryptor=i.extend({processBlock:function(o,c){var l=this._cipher,h=l.blockSize,u=this._iv,d=this._counter;u&&(d=this._counter=u.slice(0),this._iv=void 0),s(d);var f=d.slice(0);l.encryptBlock(f,0);for(var p=0;p>>2]|=o<<24-c%4*8,i.sigBytes+=o},unpad:function(i){var r=i.words[i.sigBytes-1>>>2]&255;i.sigBytes-=r}},t.pad.Ansix923})}(YX)),YX.exports}var QX={exports:{}},Oue;function tMe(){return Oue||(Oue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),mc())})(kt,function(t){return t.pad.Iso10126={pad:function(i,r){var s=r*4,a=s-i.sigBytes%s;i.concat(t.lib.WordArray.random(a-1)).concat(t.lib.WordArray.create([a<<24],1))},unpad:function(i){var r=i.words[i.sigBytes-1>>>2]&255;i.sigBytes-=r}},t.pad.Iso10126})}(QX)),QX.exports}var $X={exports:{}},Lue;function iMe(){return Lue||(Lue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),mc())})(kt,function(t){return t.pad.Iso97971={pad:function(i,r){i.concat(t.lib.WordArray.create([2147483648],1)),t.pad.ZeroPadding.pad(i,r)},unpad:function(i){t.pad.ZeroPadding.unpad(i),i.sigBytes--}},t.pad.Iso97971})}($X)),$X.exports}var ZX={exports:{}},Nue;function rMe(){return Nue||(Nue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),mc())})(kt,function(t){return t.pad.ZeroPadding={pad:function(i,r){var s=r*4;i.clamp(),i.sigBytes+=s-(i.sigBytes%s||s)},unpad:function(i){for(var r=i.words,s=i.sigBytes-1,s=i.sigBytes-1;s>=0;s--)if(r[s>>>2]>>>24-s%4*8&255){i.sigBytes=s+1;break}}},t.pad.ZeroPadding})}(ZX)),ZX.exports}var qX={exports:{}},Bue;function sMe(){return Bue||(Bue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),mc())})(kt,function(t){return t.pad.NoPadding={pad:function(){},unpad:function(){}},t.pad.NoPadding})}(qX)),qX.exports}var JX={exports:{}},Fue;function nMe(){return Fue||(Fue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),mc())})(kt,function(t){return function(i){var r=t,s=r.lib,a=s.CipherParams,o=r.enc,c=o.Hex,l=r.format;l.Hex={stringify:function(h){return h.ciphertext.toString(c)},parse:function(h){var u=c.parse(h);return a.create({ciphertext:u})}}}(),t.format.Hex})}(JX)),JX.exports}var eY={exports:{}},Uue;function aMe(){return Uue||(Uue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),K6(),W6(),l4(),mc())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.BlockCipher,a=i.algo,o=[],c=[],l=[],h=[],u=[],d=[],f=[],p=[],_=[],m=[];(function(){for(var x=[],y=0;y<256;y++)y<128?x[y]=y<<1:x[y]=y<<1^283;for(var C=0,b=0,y=0;y<256;y++){var T=b^b<<1^b<<2^b<<3^b<<4;T=T>>>8^T&255^99,o[C]=T,c[T]=C;var S=x[C],N=x[S],D=x[N],M=x[T]*257^T*16843008;l[C]=M<<24|M>>>8,h[C]=M<<16|M>>>16,u[C]=M<<8|M>>>24,d[C]=M;var M=D*16843009^N*65537^S*257^C*16843008;f[T]=M<<24|M>>>8,p[T]=M<<16|M>>>16,_[T]=M<<8|M>>>24,m[T]=M,C?(C=S^x[x[x[D^S]]],b^=x[x[b]]):C=b=1}})();var g=[0,1,2,4,8,16,32,64,128,27,54],v=a.AES=s.extend({_doReset:function(){var x;if(!(this._nRounds&&this._keyPriorReset===this._key)){for(var y=this._keyPriorReset=this._key,C=y.words,b=y.sigBytes/4,T=this._nRounds=b+6,S=(T+1)*4,N=this._keySchedule=[],D=0;D6&&D%b==4&&(x=o[x>>>24]<<24|o[x>>>16&255]<<16|o[x>>>8&255]<<8|o[x&255]):(x=x<<8|x>>>24,x=o[x>>>24]<<24|o[x>>>16&255]<<16|o[x>>>8&255]<<8|o[x&255],x^=g[D/b|0]<<24),N[D]=N[D-b]^x);for(var M=this._invKeySchedule=[],I=0;I>>24]]^p[o[x>>>16&255]]^_[o[x>>>8&255]]^m[o[x&255]]}}},encryptBlock:function(x,y){this._doCryptBlock(x,y,this._keySchedule,l,h,u,d,o)},decryptBlock:function(x,y){var C=x[y+1];x[y+1]=x[y+3],x[y+3]=C,this._doCryptBlock(x,y,this._invKeySchedule,f,p,_,m,c);var C=x[y+1];x[y+1]=x[y+3],x[y+3]=C},_doCryptBlock:function(x,y,C,b,T,S,N,D){for(var M=this._nRounds,I=x[y]^C[0],R=x[y+1]^C[1],O=x[y+2]^C[2],H=x[y+3]^C[3],G=4,Q=1;Q>>24]^T[R>>>16&255]^S[O>>>8&255]^N[H&255]^C[G++],V=b[R>>>24]^T[O>>>16&255]^S[H>>>8&255]^N[I&255]^C[G++],j=b[O>>>24]^T[H>>>16&255]^S[I>>>8&255]^N[R&255]^C[G++],k=b[H>>>24]^T[I>>>16&255]^S[R>>>8&255]^N[O&255]^C[G++];I=$,R=V,O=j,H=k}var $=(D[I>>>24]<<24|D[R>>>16&255]<<16|D[O>>>8&255]<<8|D[H&255])^C[G++],V=(D[R>>>24]<<24|D[O>>>16&255]<<16|D[H>>>8&255]<<8|D[I&255])^C[G++],j=(D[O>>>24]<<24|D[H>>>16&255]<<16|D[I>>>8&255]<<8|D[R&255])^C[G++],k=(D[H>>>24]<<24|D[I>>>16&255]<<16|D[R>>>8&255]<<8|D[O&255])^C[G++];x[y]=$,x[y+1]=V,x[y+2]=j,x[y+3]=k},keySize:256/32});i.AES=s._createHelper(v)}(),t.AES})}(eY)),eY.exports}var tY={exports:{}},kue;function oMe(){return kue||(kue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),K6(),W6(),l4(),mc())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.WordArray,a=r.BlockCipher,o=i.algo,c=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],l=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],h=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],u=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],d=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],f=o.DES=a.extend({_doReset:function(){for(var g=this._key,v=g.words,x=[],y=0;y<56;y++){var C=c[y]-1;x[y]=v[C>>>5]>>>31-C%32&1}for(var b=this._subKeys=[],T=0;T<16;T++){for(var S=b[T]=[],N=h[T],y=0;y<24;y++)S[y/6|0]|=x[(l[y]-1+N)%28]<<31-y%6,S[4+(y/6|0)]|=x[28+(l[y+24]-1+N)%28]<<31-y%6;S[0]=S[0]<<1|S[0]>>>31;for(var y=1;y<7;y++)S[y]=S[y]>>>(y-1)*4+3;S[7]=S[7]<<5|S[7]>>>27}for(var D=this._invSubKeys=[],y=0;y<16;y++)D[y]=b[15-y]},encryptBlock:function(g,v){this._doCryptBlock(g,v,this._subKeys)},decryptBlock:function(g,v){this._doCryptBlock(g,v,this._invSubKeys)},_doCryptBlock:function(g,v,x){this._lBlock=g[v],this._rBlock=g[v+1],p.call(this,4,252645135),p.call(this,16,65535),_.call(this,2,858993459),_.call(this,8,16711935),p.call(this,1,1431655765);for(var y=0;y<16;y++){for(var C=x[y],b=this._lBlock,T=this._rBlock,S=0,N=0;N<8;N++)S|=u[N][((T^C[N])&d[N])>>>0];this._lBlock=T,this._rBlock=b^S}var D=this._lBlock;this._lBlock=this._rBlock,this._rBlock=D,p.call(this,1,1431655765),_.call(this,8,16711935),_.call(this,2,858993459),p.call(this,16,65535),p.call(this,4,252645135),g[v]=this._lBlock,g[v+1]=this._rBlock},keySize:64/32,ivSize:64/32,blockSize:64/32});function p(g,v){var x=(this._lBlock>>>g^this._rBlock)&v;this._rBlock^=x,this._lBlock^=x<>>g^this._lBlock)&v;this._lBlock^=x,this._rBlock^=x<192.");var x=v.slice(0,2),y=v.length<4?v.slice(0,2):v.slice(2,4),C=v.length<6?v.slice(0,2):v.slice(4,6);this._des1=f.createEncryptor(s.create(x)),this._des2=f.createEncryptor(s.create(y)),this._des3=f.createEncryptor(s.create(C))},encryptBlock:function(g,v){this._des1.encryptBlock(g,v),this._des2.decryptBlock(g,v),this._des3.encryptBlock(g,v)},decryptBlock:function(g,v){this._des3.decryptBlock(g,v),this._des2.encryptBlock(g,v),this._des1.decryptBlock(g,v)},keySize:192/32,ivSize:64/32,blockSize:64/32});i.TripleDES=a._createHelper(m)}(),t.TripleDES})}(tY)),tY.exports}var iY={exports:{}},Vue;function lMe(){return Vue||(Vue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),K6(),W6(),l4(),mc())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.StreamCipher,a=i.algo,o=a.RC4=s.extend({_doReset:function(){for(var h=this._key,u=h.words,d=h.sigBytes,f=this._S=[],p=0;p<256;p++)f[p]=p;for(var p=0,_=0;p<256;p++){var m=p%d,g=u[m>>>2]>>>24-m%4*8&255;_=(_+f[p]+g)%256;var v=f[p];f[p]=f[_],f[_]=v}this._i=this._j=0},_doProcessBlock:function(h,u){h[u]^=c.call(this)},keySize:256/32,ivSize:0});function c(){for(var h=this._S,u=this._i,d=this._j,f=0,p=0;p<4;p++){u=(u+1)%256,d=(d+h[u])%256;var _=h[u];h[u]=h[d],h[d]=_,f|=h[(h[u]+h[d])%256]<<24-p*8}return this._i=u,this._j=d,f}i.RC4=s._createHelper(o);var l=a.RC4Drop=o.extend({cfg:o.cfg.extend({drop:192}),_doReset:function(){o._doReset.call(this);for(var h=this.cfg.drop;h>0;h--)c.call(this)}});i.RC4Drop=s._createHelper(l)}(),t.RC4})}(iY)),iY.exports}var rY={exports:{}},zue;function cMe(){return zue||(zue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),K6(),W6(),l4(),mc())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.StreamCipher,a=i.algo,o=[],c=[],l=[],h=a.Rabbit=s.extend({_doReset:function(){for(var d=this._key.words,f=this.cfg.iv,p=0;p<4;p++)d[p]=(d[p]<<8|d[p]>>>24)&16711935|(d[p]<<24|d[p]>>>8)&4278255360;var _=this._X=[d[0],d[3]<<16|d[2]>>>16,d[1],d[0]<<16|d[3]>>>16,d[2],d[1]<<16|d[0]>>>16,d[3],d[2]<<16|d[1]>>>16],m=this._C=[d[2]<<16|d[2]>>>16,d[0]&4294901760|d[1]&65535,d[3]<<16|d[3]>>>16,d[1]&4294901760|d[2]&65535,d[0]<<16|d[0]>>>16,d[2]&4294901760|d[3]&65535,d[1]<<16|d[1]>>>16,d[3]&4294901760|d[0]&65535];this._b=0;for(var p=0;p<4;p++)u.call(this);for(var p=0;p<8;p++)m[p]^=_[p+4&7];if(f){var g=f.words,v=g[0],x=g[1],y=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,C=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360,b=y>>>16|C&4294901760,T=C<<16|y&65535;m[0]^=y,m[1]^=b,m[2]^=C,m[3]^=T,m[4]^=y,m[5]^=b,m[6]^=C,m[7]^=T;for(var p=0;p<4;p++)u.call(this)}},_doProcessBlock:function(d,f){var p=this._X;u.call(this),o[0]=p[0]^p[5]>>>16^p[3]<<16,o[1]=p[2]^p[7]>>>16^p[5]<<16,o[2]=p[4]^p[1]>>>16^p[7]<<16,o[3]=p[6]^p[3]>>>16^p[1]<<16;for(var _=0;_<4;_++)o[_]=(o[_]<<8|o[_]>>>24)&16711935|(o[_]<<24|o[_]>>>8)&4278255360,d[f+_]^=o[_]},blockSize:128/32,ivSize:64/32});function u(){for(var d=this._X,f=this._C,p=0;p<8;p++)c[p]=f[p];f[0]=f[0]+1295307597+this._b|0,f[1]=f[1]+3545052371+(f[0]>>>0>>0?1:0)|0,f[2]=f[2]+886263092+(f[1]>>>0>>0?1:0)|0,f[3]=f[3]+1295307597+(f[2]>>>0>>0?1:0)|0,f[4]=f[4]+3545052371+(f[3]>>>0>>0?1:0)|0,f[5]=f[5]+886263092+(f[4]>>>0>>0?1:0)|0,f[6]=f[6]+1295307597+(f[5]>>>0>>0?1:0)|0,f[7]=f[7]+3545052371+(f[6]>>>0>>0?1:0)|0,this._b=f[7]>>>0>>0?1:0;for(var p=0;p<8;p++){var _=d[p]+f[p],m=_&65535,g=_>>>16,v=((m*m>>>17)+m*g>>>15)+g*g,x=((_&4294901760)*_|0)+((_&65535)*_|0);l[p]=v^x}d[0]=l[0]+(l[7]<<16|l[7]>>>16)+(l[6]<<16|l[6]>>>16)|0,d[1]=l[1]+(l[0]<<8|l[0]>>>24)+l[7]|0,d[2]=l[2]+(l[1]<<16|l[1]>>>16)+(l[0]<<16|l[0]>>>16)|0,d[3]=l[3]+(l[2]<<8|l[2]>>>24)+l[1]|0,d[4]=l[4]+(l[3]<<16|l[3]>>>16)+(l[2]<<16|l[2]>>>16)|0,d[5]=l[5]+(l[4]<<8|l[4]>>>24)+l[3]|0,d[6]=l[6]+(l[5]<<16|l[5]>>>16)+(l[4]<<16|l[4]>>>16)|0,d[7]=l[7]+(l[6]<<8|l[6]>>>24)+l[5]|0}i.Rabbit=s._createHelper(h)}(),t.Rabbit})}(rY)),rY.exports}var sY={exports:{}},Hue;function hMe(){return Hue||(Hue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),K6(),W6(),l4(),mc())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.StreamCipher,a=i.algo,o=[],c=[],l=[],h=a.RabbitLegacy=s.extend({_doReset:function(){var d=this._key.words,f=this.cfg.iv,p=this._X=[d[0],d[3]<<16|d[2]>>>16,d[1],d[0]<<16|d[3]>>>16,d[2],d[1]<<16|d[0]>>>16,d[3],d[2]<<16|d[1]>>>16],_=this._C=[d[2]<<16|d[2]>>>16,d[0]&4294901760|d[1]&65535,d[3]<<16|d[3]>>>16,d[1]&4294901760|d[2]&65535,d[0]<<16|d[0]>>>16,d[2]&4294901760|d[3]&65535,d[1]<<16|d[1]>>>16,d[3]&4294901760|d[0]&65535];this._b=0;for(var m=0;m<4;m++)u.call(this);for(var m=0;m<8;m++)_[m]^=p[m+4&7];if(f){var g=f.words,v=g[0],x=g[1],y=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,C=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360,b=y>>>16|C&4294901760,T=C<<16|y&65535;_[0]^=y,_[1]^=b,_[2]^=C,_[3]^=T,_[4]^=y,_[5]^=b,_[6]^=C,_[7]^=T;for(var m=0;m<4;m++)u.call(this)}},_doProcessBlock:function(d,f){var p=this._X;u.call(this),o[0]=p[0]^p[5]>>>16^p[3]<<16,o[1]=p[2]^p[7]>>>16^p[5]<<16,o[2]=p[4]^p[1]>>>16^p[7]<<16,o[3]=p[6]^p[3]>>>16^p[1]<<16;for(var _=0;_<4;_++)o[_]=(o[_]<<8|o[_]>>>24)&16711935|(o[_]<<24|o[_]>>>8)&4278255360,d[f+_]^=o[_]},blockSize:128/32,ivSize:64/32});function u(){for(var d=this._X,f=this._C,p=0;p<8;p++)c[p]=f[p];f[0]=f[0]+1295307597+this._b|0,f[1]=f[1]+3545052371+(f[0]>>>0>>0?1:0)|0,f[2]=f[2]+886263092+(f[1]>>>0>>0?1:0)|0,f[3]=f[3]+1295307597+(f[2]>>>0>>0?1:0)|0,f[4]=f[4]+3545052371+(f[3]>>>0>>0?1:0)|0,f[5]=f[5]+886263092+(f[4]>>>0>>0?1:0)|0,f[6]=f[6]+1295307597+(f[5]>>>0>>0?1:0)|0,f[7]=f[7]+3545052371+(f[6]>>>0>>0?1:0)|0,this._b=f[7]>>>0>>0?1:0;for(var p=0;p<8;p++){var _=d[p]+f[p],m=_&65535,g=_>>>16,v=((m*m>>>17)+m*g>>>15)+g*g,x=((_&4294901760)*_|0)+((_&65535)*_|0);l[p]=v^x}d[0]=l[0]+(l[7]<<16|l[7]>>>16)+(l[6]<<16|l[6]>>>16)|0,d[1]=l[1]+(l[0]<<8|l[0]>>>24)+l[7]|0,d[2]=l[2]+(l[1]<<16|l[1]>>>16)+(l[0]<<16|l[0]>>>16)|0,d[3]=l[3]+(l[2]<<8|l[2]>>>24)+l[1]|0,d[4]=l[4]+(l[3]<<16|l[3]>>>16)+(l[2]<<16|l[2]>>>16)|0,d[5]=l[5]+(l[4]<<8|l[4]>>>24)+l[3]|0,d[6]=l[6]+(l[5]<<16|l[5]>>>16)+(l[4]<<16|l[4]>>>16)|0,d[7]=l[7]+(l[6]<<8|l[6]>>>24)+l[5]|0}i.RabbitLegacy=s._createHelper(h)}(),t.RabbitLegacy})}(sY)),sY.exports}var nY={exports:{}},Gue;function uMe(){return Gue||(Gue=1,function(n,e){(function(t,i,r){n.exports=i(zs(),K6(),W6(),l4(),mc())})(kt,function(t){return function(){var i=t,r=i.lib,s=r.BlockCipher,a=i.algo;const o=16,c=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],l=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var h={pbox:[],sbox:[]};function u(m,g){let v=g>>24&255,x=g>>16&255,y=g>>8&255,C=g&255,b=m.sbox[0][v]+m.sbox[1][x];return b=b^m.sbox[2][y],b=b+m.sbox[3][C],b}function d(m,g,v){let x=g,y=v,C;for(let b=0;b1;--b)x=x^m.pbox[b],y=u(m,x)^y,C=x,x=y,y=C;return C=x,x=y,y=C,y=y^m.pbox[1],x=x^m.pbox[0],{left:x,right:y}}function p(m,g,v){for(let T=0;T<4;T++){m.sbox[T]=[];for(let S=0;S<256;S++)m.sbox[T][S]=l[T][S]}let x=0;for(let T=0;T=v&&(x=0);let y=0,C=0,b=0;for(let T=0;T{window.meta2d&&window.meta2d.render(),window.meta3d&&window.meta3d.render()}),document.head.appendChild(i)}var Wue=performance.now();function iy(n){let e="/view/";e==="/"&&(e=""),location.host.indexOf(".le5le.")===-1&&(e="/view");const i=document.createElement("script");i.type="text/javascript",i.defer=!0,i.src=e+n+"?r="+new Date().getTime(),i.addEventListener("load",()=>{const r=performance.now();(r>Wue+500||r>33)&&(window.meta2d&&window.meta2d.render(),window.meta3d&&window.meta3d.render(),Wue=r)}),document.body.appendChild(i)}function fMe(n){const e="blrtP0ilBMMMYtAt",t=dS.enc.Utf8.parse(e);return dS.AES.decrypt(n,dS.enc.Utf8.parse(e),{iv:t,mode:dS.mode.CBC,padding:dS.pad.Pkcs7}).toString(dS.enc.Utf8)}function M_e(n,e){const t=new _Se("app");pMe(),Kue("/css/t/font_2395018_nng9x1qhat.css"),Kue("/css/t/font_2073009_teagntehxt.css"),iy("/js/r.js"),setTimeout(()=>{if(location.host.indexOf(".le5le.com")===-1)iy("/js/1.js"),setTimeout(async()=>{window.registerIot(window.userId,"/view/js/2d-components.js"),window.meta2dTools&®isterToolsNew&®isterToolsNew(),t.render()},1e3);else{for(let a=1;a<10;a++)iy("/js/"+a+".js");for(let a=97;a<110;a++)iy("/js/"+String.fromCharCode(a)+".js");iy("/js/2d-components.js")}const s=["/js/marked.min.js","/js/echarts.min.js","/js/highcharts.js","/js/lcjs.iife.js","/js/mycharts.js"];for(let a=0;a{iy("/js/highcharts-more.js")},1e3);const i=setInterval(()=>{!window.meta2dTools||window.meta2dTools.length<1450||registerToolsNew&&(registerToolsNew(),clearInterval(i))},200);n.locked=1,window.userId=n.userId,setTimeout(()=>{t.open(n),t.fitView(!0,0)},1e3),setTimeout(()=>{t.fitView(!0,0)},5e3)}function pMe(){bm(wSe()),a$(DSe()),bm(BSe()),MS(FSe()),bm(KSe()),bm(XSe()),MS(YSe()),p8e(),_8e(),m8e(),MS(o5e()),MS(x5e()),bm(B5e()),MS(F5e()),a$(U5e())}class da{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,r){for(const s in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,s)&&this._BabylonFileParsers[s](e,t,i,r)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}}da._BabylonFileParsers={};da._IndividualBabylonFileParsers={};class Kh{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in Kh.Triggers)if(Object.prototype.hasOwnProperty.call(Kh.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in Kh.Triggers)if(Object.prototype.hasOwnProperty.call(Kh.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in Kh.Triggers)if(Object.prototype.hasOwnProperty.call(Kh.Triggers,t)&&parseInt(t)===e)return!0;return!1}}Kh.Triggers={};class mJ{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}}class R_e{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class Ae{static FromPromise(e,t){const i=new Ae;return e.then(r=>{i.notifyObservers(r)}).catch(r=>{if(t)t.notifyObservers(r);else throw r}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new mJ(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,s=!1){if(!e)return null;const a=new R_e(e,t,r);return a.unregisterOnNextCall=s,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(a,this._lastNotifiedValue),a._remove=()=>{this.remove(a)},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return e?(e._remove=null,this._observers.indexOf(e)!==-1?(this._deferUnregister(e),!0):!1):!1}removeCallback(e,t){for(let i=0;i{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return i!==-1?(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0):!1}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const a=this._eventState;a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.lastReturnValue=e,a.userInfo=s;for(const o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?a.lastReturnValue=o.callback.apply(o.scope,[e,a]):a.lastReturnValue=o.callback(e,a)),a.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new Ae;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const ZS=1/2.2,hD=2.2,Ba=(1+Math.sqrt(5))/2,ni=.001;class Va{static BuildArray(e,t){const i=[];for(let r=0;r{const s=r.previous;if(!s)return;const a=r.next;a?(s.next=a,a.previous=s):(s.next=void 0,n[e]=s),r.next=void 0,r.previous=void 0}}const mMe=["push","splice","pop","shift","unshift"];function I_e(n,e){const t=mMe.map(i=>_Me(n,i,e));return()=>{t.forEach(i=>{i==null||i()})}}const P_e={};function xe(n,e){P_e[n]=e}function gn(n){return P_e[n]}class bo{static SetMatrixPrecision(e){if(bo.MatrixTrackPrecisionChange=!1,e&&!bo.MatrixUse64Bits&&bo.MatrixTrackedMatrices)for(let t=0;tparseInt(n.toString().replace(/\W/g,""));class Be{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){const e=Xh(this.x),t=Xh(this.y);let i=e;return i=i*397^t,i}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return Be.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new this.constructor(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new this.constructor(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new this.constructor(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.copyFromFloats(this.x-e,this.y-t)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(this.x*-1,this.y*-1)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new this.constructor(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=ni){return e&&Hl(this.x,e.x,t)&&Hl(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),r=Math.sin(e),s=i*this.x-r*this.y,a=r*this.x+i*this.y;return t.x=s,t.y=a,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new Be(0,0)}static One(){return new Be(1,1)}static Random(e=0,t=1){return new Be(Xr(e,t),Xr(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Xr(e,t),Xr(e,t))}static get ZeroReadOnly(){return Be._ZeroReadOnly}static FromArray(e,t=0){return new Be(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,r,s){const a=s*s,o=s*a,c=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-r.x)*a+(-e.x+3*t.x-3*i.x+r.x)*o),l=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-r.y)*a+(-e.y+3*t.y-3*i.y+r.y)*o);return new e.constructor(c,l)}static ClampToRef(e,t,i,r){return r.x=Nn(e.x,t.x,i.x),r.y=Nn(e.y,t.y,i.y),r}static Clamp(e,t,i){const r=Nn(e.x,t.x,i.x),s=Nn(e.y,t.y,i.y);return new e.constructor(r,s)}static Hermite(e,t,i,r,s){const a=s*s,o=s*a,c=2*o-3*a+1,l=-2*o+3*a,h=o-2*a+s,u=o-a,d=e.x*c+i.x*l+t.x*h+r.x*u,f=e.y*c+i.y*l+t.y*h+r.y*u;return new e.constructor(d,f)}static Hermite1stDerivative(e,t,i,r,s){const a=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){const o=s*s;return a.x=(o-s)*6*e.x+(3*o-4*s+1)*t.x+(-o+s)*6*i.x+(3*o-2*s)*r.x,a.y=(o-s)*6*e.y+(3*o-4*s+1)*t.y+(-o+s)*6*i.y+(3*o-2*s)*r.y,a}static Lerp(e,t,i){const r=e.x+(t.x-e.x)*i,s=e.y+(t.y-e.y)*i;return new e.constructor(r,s)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){const t=new e.constructor;return Be.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,r=e.y>t.y?e.y:t.y;return new e.constructor(i,r)}static Transform(e,t){const i=new e.constructor;return Be.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){const r=t.m,s=e.x*r[0]+e.y*r[4]+r[12],a=e.x*r[1]+e.y*r[5]+r[13];return i.x=s,i.y=a,i}static PointInTriangle(e,t,i,r){const s=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),a=s<0?-1:1,o=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*a,c=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*a;return o>0&&c>0&&o+c<2*s*a}static Distance(e,t){return Math.sqrt(Be.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y;return i*i+r*r}static Center(e,t){const i=new e.constructor;return Be.CenterToRef(e,t,i)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const r=Be.DistanceSquared(t,i);if(r===0)return Be.Distance(e,t);const s=i.subtract(t),a=Math.max(0,Math.min(1,Be.Dot(e.subtract(t),s)/r)),o=t.add(s.multiplyByFloats(a,a));return Be.Distance(e,o)}}Be._ZeroReadOnly=Be.Zero();Object.defineProperties(Be.prototype,{dimension:{value:[2]},rank:{value:1}});class P{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){const e=Xh(this._x),t=Xh(this._y),i=Xh(this._z);let r=e;return r=r*397^t,r=r*397^i,r}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return P.FromArrayToRef(e,t,this),this}toQuaternion(){return we.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,r){return r.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new this.constructor(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(this._x*-1,this._y*-1,this._z*-1)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const r=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const s=t*Math.sin(i)*Math.cos(r),a=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(r);return e.set(s,a,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,r=this._y,s=this._z,a=e._x,o=e._y,c=e._z,l=e._w,h=2*(o*s-c*r),u=2*(c*i-a*s),d=2*(a*r-o*i);return t._x=i+l*h+o*d-c*u,t._y=r+l*u+c*h-a*d,t._z=s+l*d+a*u-o*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new this.constructor)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){const i=new this.constructor;return this.projectOnPlaneToRef(e,t,i),i}projectOnPlaneToRef(e,t,i){const r=e.normal,s=e.d,a=Wt.Vector3[0];this.subtractToRef(t,a),a.normalize();const o=P.Dot(a,r);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const c=-(P.Dot(t,r)+s)/o,l=a.scaleInPlace(c);t.addToRef(l,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=ni){return e&&Hl(this._x,e._x,t)&&Hl(this._y,e._y,t)&&Hl(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new this.constructor(this._x*e,this._y*t,this._z*i)}divide(e){return new this.constructor(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!Hl(t,i,e))return!0;const r=Math.abs(this._z);return!Hl(t,r,e)||!Hl(i,r,e)}get isNonUniform(){const e=Math.abs(this._x),t=Math.abs(this._y);if(e!==t)return!0;const i=Math.abs(this._z);return e!==i}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new this.constructor(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;const t=Wt.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(Wt.Matrix[0]),P.TransformCoordinatesToRef(this,Wt.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,Wt.Vector3[0]),Wt.Vector3[0].rotateByQuaternionToRef(e,Wt.Vector3[0]),t.addToRef(Wt.Vector3[0],i),i}cross(e){const t=new this.constructor;return P.CrossToRef(this,e,t)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,r){const s=P.Dot(e,i),a=P.Dot(t,i);return(s-r)/(s-a)}static GetAngleBetweenVectors(e,t,i){const r=e.normalizeToRef(Wt.Vector3[1]),s=t.normalizeToRef(Wt.Vector3[2]);let a=P.Dot(r,s);a=Nn(a,-1,1);const o=Math.acos(a),c=Wt.Vector3[3];return P.CrossToRef(r,s,c),P.Dot(c,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(a)}static GetAngleBetweenVectorsOnPlane(e,t,i){Wt.Vector3[0].copyFrom(e);const r=Wt.Vector3[0];Wt.Vector3[1].copyFrom(t);const s=Wt.Vector3[1];Wt.Vector3[2].copyFrom(i);const a=Wt.Vector3[2],o=Wt.Vector3[3],c=Wt.Vector3[4];r.normalize(),s.normalize(),a.normalize(),P.CrossToRef(a,r,o),P.CrossToRef(o,a,c);const l=Math.atan2(P.Dot(s,o),P.Dot(s,c));return w_e(l)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const r=ie.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(r.x**2+r.z**2),r.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=P.Zero();return P.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,r){i=Nn(i,0,1);const s=Wt.Vector3[0],a=Wt.Vector3[1];s.copyFrom(e);const o=s.length();s.normalizeFromLength(o),a.copyFrom(t);const c=a.length();a.normalizeFromLength(c);const l=P.Dot(s,a);let h,u;if(l<1-ni){const d=Math.acos(l),f=1/Math.sin(d);h=Math.sin((1-i)*d)*f,u=Math.sin(i*d)*f}else h=1-i,u=i;return s.scaleInPlace(h),a.scaleInPlace(u),r.copyFrom(s).addInPlace(a),r.scaleInPlace(_u(o,c,i)),r}static SmoothToRef(e,t,i,r,s){return P.SlerpToRef(e,t,r===0?1:i/r,s),s}static FromArray(e,t=0){return new P(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return P.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return P.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,r){return r.copyFromFloats(e,t,i),r}static Zero(){return new P(0,0,0)}static One(){return new P(1,1,1)}static Up(){return new P(0,1,0)}static get UpReadOnly(){return P._UpReadOnly}static get DownReadOnly(){return P._DownReadOnly}static get RightReadOnly(){return P._RightReadOnly}static get LeftReadOnly(){return P._LeftReadOnly}static get LeftHandedForwardReadOnly(){return P._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return P._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return P._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return P._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return P._ZeroReadOnly}static get OneReadOnly(){return P._OneReadOnly}static Down(){return new P(0,-1,0)}static Forward(e=!1){return new P(0,0,e?-1:1)}static Backward(e=!1){return new P(0,0,e?1:-1)}static Right(){return new P(1,0,0)}static Left(){return new P(-1,0,0)}static Random(e=0,t=1){return new P(Xr(e,t),Xr(e,t),Xr(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Xr(e,t),Xr(e,t),Xr(e,t))}static TransformCoordinates(e,t){const i=P.Zero();return P.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return P.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){const a=r.m,o=e*a[0]+t*a[4]+i*a[8]+a[12],c=e*a[1]+t*a[5]+i*a[9]+a[13],l=e*a[2]+t*a[6]+i*a[10]+a[14],h=1/(e*a[3]+t*a[7]+i*a[11]+a[15]);return s._x=o*h,s._y=c*h,s._z=l*h,s._isDirty=!0,s}static TransformNormal(e,t){const i=P.Zero();return P.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,r,s){const a=r.m;return s._x=e*a[0]+t*a[4]+i*a[8],s._y=e*a[1]+t*a[5]+i*a[9],s._z=e*a[2]+t*a[6]+i*a[10],s._isDirty=!0,s}static CatmullRom(e,t,i,r,s){const a=s*s,o=s*a,c=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-r._x)*a+(-e._x+3*t._x-3*i._x+r._x)*o),l=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-r._y)*a+(-e._y+3*t._y-3*i._y+r._y)*o),h=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-r._z)*a+(-e._z+3*t._z-3*i._z+r._z)*o);return new e.constructor(c,l,h)}static Clamp(e,t,i){const r=new e.constructor;return P.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){let s=e._x;s=s>i._x?i._x:s,s=si._y?i._y:a,a=ai._z?i._z:o,o=o0&&D<0?(I.copyFrom(a),R=t,O=i):D>0&&M<0?(I.copyFrom(c),R=i,O=r):(I.copyFrom(o).scaleInPlace(-1),R=r,O=t);const H=Wt.Vector3[9],G=Wt.Vector3[4];if(R.subtractToRef(v,b),O.subtractToRef(v,H),P.CrossToRef(b,H,G),!(P.Dot(G,l)<0))return s.copyFrom(v),Math.abs(_*m);const $=Wt.Vector3[5];P.CrossToRef(I,G,$),$.normalize();const V=Wt.Vector3[9];V.copyFrom(R).subtractInPlace(v);const j=V.length();if(jthis.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}minimizeInPlaceFromFloats(e,t,i,r){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(r,this.w),this}maximizeInPlaceFromFloats(e,t,i,r){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(r,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFrom(this):this.scaleToRef(1/t,e)}toVector3(){return new P(this.x,this.y,this.z)}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new Ct(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return Ct.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,r,s){return s.x=e,s.y=t,s.z=i,s.w=r,s}static Zero(){return new Ct(0,0,0,0)}static One(){return new Ct(1,1,1,1)}static Random(e=0,t=1){return new Ct(Xr(e,t),Xr(e,t),Xr(e,t),Xr(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Xr(e,t),Xr(e,t),Xr(e,t),Xr(e,t))}static Clamp(e,t,i){const r=new e.constructor;return Ct.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){return r.copyFromFloats(Nn(e.x,t.x,i.x),Nn(e.y,t.y,i.y),Nn(e.z,t.z,i.z),Nn(e.w,t.w,i.w))}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return Ct._ZeroReadOnly}static Normalize(e){const t=Ct.Zero();return Ct.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(Ct.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+r*r+s*s+a*a}static Center(e,t){return Ct.CenterToRef(e,t,Ct.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}static TransformCoordinates(e,t){const i=Ct.Zero();return Ct.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return Ct.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){const a=r.m,o=e*a[0]+t*a[4]+i*a[8]+a[12],c=e*a[1]+t*a[5]+i*a[9]+a[13],l=e*a[2]+t*a[6]+i*a[10]+a[14],h=e*a[3]+t*a[7]+i*a[11]+a[15];return s.x=o,s.y=c,s.z=l,s.w=h,s}static TransformNormal(e,t){const i=new e.constructor;return Ct.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){const r=t.m,s=e.x*r[0]+e.y*r[4]+e.z*r[8],a=e.x*r[1]+e.y*r[5]+e.z*r[9],o=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=s,i.y=a,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,r,s,a){const o=s.m;return a.x=e*o[0]+t*o[4]+i*o[8],a.y=e*o[1]+t*o[5]+i*o[9],a.z=e*o[2]+t*o[6]+i*o[10],a.w=r,a}static FromVector3(e,t=0){return new Ct(e._x,e._y,e._z,t)}static Dot(e,t){return e.dot(t)}}Ct._ZeroReadOnly=Ct.Zero();Object.defineProperties(Ct.prototype,{dimension:{value:[4]},rank:{value:1}});class we{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,r=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){const e=Xh(this._x),t=Xh(this._y),i=Xh(this._z),r=Xh(this._w);let s=e;return s=s*397^t,s=s*397^i,s=s*397^r,s}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return we.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=ni){return e&&Hl(this._x,e._x,t)&&Hl(this._y,e._y,t)&&Hl(this._z,e._z,t)&&Hl(this._w,e._w,t)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,r){return this._x+=e,this._y+=t,this._z+=i,this._w+=r,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,r){return this.subtractFromFloatsToRef(e,t,i,r,new this.constructor)}subtractFromFloatsToRef(e,t,i,r,s){return s._x=this._x-e,s._y=this._y-t,s._z=this._z-i,s._w=this._w-r,s._isDirty=!0,s}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new this.constructor(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,a=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,r,s,a),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,r){return this._x*=e,this._y*=t,this._z*=i,this._w*=r,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new this.constructor)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,r){return this._x===e&&this._y===t&&this._z===i&&this._w===r}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return t==0||t==1||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return e==0||e==1?this:(this.scaleInPlace(1/e),this)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=P.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,r=this._y,s=this._w,a=r*t-i*s,o=.4999999;if(a<-o)e._y=2*Math.atan2(r,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(a>o)e._y=2*Math.atan2(r,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const c=s*s,l=t*t,h=i*i,u=r*r;e._z=Math.atan2(2*(i*r+t*s),-l-h+u+c),e._x=Math.asin(-2*a),e._y=Math.atan2(2*(t*i+r*s),l-h-u+c),e._isDirty=!0}return e}toRotationMatrix(e){return ce.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return we.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new we;return we.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,r=i[0],s=i[4],a=i[8],o=i[1],c=i[5],l=i[9],h=i[2],u=i[6],d=i[10],f=r+c+d;let p;return f>0?(p=.5/Math.sqrt(f+1),t._w=.25/p,t._x=(u-l)*p,t._y=(a-h)*p,t._z=(o-s)*p,t._isDirty=!0):r>c&&r>d?(p=2*Math.sqrt(1+r-c-d),t._w=(u-l)/p,t._x=.25*p,t._y=(s+o)/p,t._z=(a+h)/p,t._isDirty=!0):c>d?(p=2*Math.sqrt(1+c-r-d),t._w=(a-h)/p,t._x=(s+o)/p,t._y=.25*p,t._z=(l+u)/p,t._isDirty=!0):(p=2*Math.sqrt(1+d-r-c),t._w=(o-s)/p,t._x=(a+h)/p,t._y=(l+u)/p,t._z=.25*p,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const r=we.Dot(e,t);return 1-r*r<=i}static SmoothToRef(e,t,i,r,s){let a=r===0?1:i/r;return a=Nn(a,0,1),we.SlerpToRef(e,t,a,s),s}static Zero(){return new we(0,0,0,0)}static Inverse(e){return new e.constructor(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new we(0,0,0,1)}static IsIdentity(e){return e&&e._x===0&&e._y===0&&e._z===0&&e._w===1}static RotationAxis(e,t){return we.RotationAxisToRef(e,t,new we)}static RotationAxisToRef(e,t,i){const r=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new we(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,r,s){return s.copyFromFloats(e,t,i,r),s}static FromEulerAngles(e,t,i){const r=new we;return we.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerAnglesToRef(e,t,i,r){return we.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerVector(e){const t=new we;return we.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return we.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,r=ni){const s=P.Dot(e,t)+1;return sMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(P.CrossToRef(e,t,ie.Vector3[0]),i.set(ie.Vector3[0].x,ie.Vector3[0].y,ie.Vector3[0].z,s)),i.normalize()}static RotationYawPitchRoll(e,t,i){const r=new we;return we.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){const s=i*.5,a=t*.5,o=e*.5,c=Math.sin(s),l=Math.cos(s),h=Math.sin(a),u=Math.cos(a),d=Math.sin(o),f=Math.cos(o);return r._x=f*h*l+d*u*c,r._y=d*u*l-f*h*c,r._z=f*u*c-d*h*l,r._w=f*u*l+d*h*c,r._isDirty=!0,r}static RotationAlphaBetaGamma(e,t,i){const r=new we;return we.RotationAlphaBetaGammaToRef(e,t,i,r),r}static RotationAlphaBetaGammaToRef(e,t,i,r){const s=(i+e)*.5,a=(i-e)*.5,o=t*.5;return r._x=Math.cos(a)*Math.sin(o),r._y=Math.sin(a)*Math.sin(o),r._z=Math.sin(s)*Math.cos(o),r._w=Math.cos(s)*Math.cos(o),r._isDirty=!0,r}static RotationQuaternionFromAxis(e,t,i){const r=new we(0,0,0,0);return we.RotationQuaternionFromAxisToRef(e,t,i,r),r}static RotationQuaternionFromAxisToRef(e,t,i,r){const s=Wt.Matrix[0];return ce.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),s),we.FromRotationMatrixToRef(s,r),r}static FromLookDirectionLH(e,t){const i=new we;return we.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const r=Wt.Matrix[0];return ce.LookDirectionLHToRef(e,t,r),we.FromRotationMatrixToRef(r,i),i}static FromLookDirectionRH(e,t){const i=new we;return we.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const r=Wt.Matrix[0];return ce.LookDirectionRHToRef(e,t,r),we.FromRotationMatrixToRef(r,i)}static Slerp(e,t,i){const r=we.Identity();return we.SlerpToRef(e,t,i,r),r}static SlerpToRef(e,t,i,r){let s,a,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,c=!1;if(o<0&&(c=!0,o=-o),o>.999999)a=1-i,s=c?-i:i;else{const l=Math.acos(o),h=1/Math.sin(l);a=Math.sin((1-i)*l)*h,s=c?-Math.sin(i*l)*h:Math.sin(i*l)*h}return r._x=a*e._x+s*t._x,r._y=a*e._y+s*t._y,r._z=a*e._z+s*t._z,r._w=a*e._w+s*t._w,r._isDirty=!0,r}static Hermite(e,t,i,r,s){const a=s*s,o=s*a,c=2*o-3*a+1,l=-2*o+3*a,h=o-2*a+s,u=o-a,d=e._x*c+i._x*l+t._x*h+r._x*u,f=e._y*c+i._y*l+t._y*h+r._y*u,p=e._z*c+i._z*l+t._z*h+r._z*u,_=e._w*c+i._w*l+t._w*h+r._w*u;return new e.constructor(d,f,p,_)}static Hermite1stDerivative(e,t,i,r,s){const a=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){const o=s*s;return a._x=(o-s)*6*e._x+(3*o-4*s+1)*t._x+(-o+s)*6*i._x+(3*o-2*s)*r._x,a._y=(o-s)*6*e._y+(3*o-4*s+1)*t._y+(-o+s)*6*i._y+(3*o-2*s)*r._y,a._z=(o-s)*6*e._z+(3*o-4*s+1)*t._z+(-o+s)*6*i._z+(3*o-2*s)*r._z,a._w=(o-s)*6*e._w+(3*o-4*s+1)*t._w+(-o+s)*6*i._w+(3*o-2*s)*r._w,a._isDirty=!0,a}static Normalize(e){const t=we.Zero();return we.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const r=new e.constructor;return we.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){return r.copyFromFloats(Nn(e.x,t.x,i.x),Nn(e.y,t.y,i.y),Nn(e.z,t.z,i.z),Nn(e.w,t.w,i.w))}static Random(e=0,t=1){return new we(Xr(e,t),Xr(e,t),Xr(e,t),Xr(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Xr(e,t),Xr(e,t),Xr(e,t),Xr(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(we.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+r*r+s*s+a*a}static Center(e,t){return we.CenterToRef(e,t,we.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(we.prototype,{dimension:{value:[4]},rank:{value:1}});class ce{static get Use64Bits(){return bo.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=ce._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,r=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:r}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,bo.MatrixTrackPrecisionChange&&bo.MatrixTrackedMatrices.push(this),this._m=new bo.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=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}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,this._m[0]!==1||this._m[5]!==1||this._m[15]!==1?this._isIdentity3x2=!1:this._m[1]!==0||this._m[2]!==0||this._m[3]!==0||this._m[4]!==0||this._m[6]!==0||this._m[7]!==0||this._m[8]!==0||this._m[9]!==0||this._m[10]!==0||this._m[11]!==0||this._m[12]!==0||this._m[13]!==0||this._m[14]!==0?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(this._isIdentity===!0)return 1;const e=this._m,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8],u=e[9],d=e[10],f=e[11],p=e[12],_=e[13],m=e[14],g=e[15],v=d*g-m*f,x=u*g-_*f,y=u*m-_*d,C=h*g-p*f,b=h*m-d*p,T=h*_-p*u,S=+(o*v-c*x+l*y),N=-(a*v-c*C+l*b),D=+(a*x-o*C+l*T),M=-(a*y-o*b+c*T);return t*S+i*N+r*D+s*M}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} ${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]} ${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]} ${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let r=0;r<16;r++)e[t+r]=i[r];return this}asArray(){return this._m}fromArray(e,t=0){return ce.FromArrayToRef(e,t,this)}copyFromFloats(...e){return ce.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return ce.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new this.constructor;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,r=t._m,s=e.m;for(let a=0;a<16;a++)r[a]=i[a]+s[a];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]+=i[r];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]+=i[r];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,r=e.m,s=t._m;for(let a=0;a<16;a++)s[a]=i[a]-r[a];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new this.constructor)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,r=t._m,s=e;for(let a=0;a<16;a++)r[a]=i[a]-s[a];return t.markAsUpdated(),t}invertToRef(e){if(this._isIdentity===!0)return ce.IdentityToRef(e),e;const t=this._m,i=t[0],r=t[1],s=t[2],a=t[3],o=t[4],c=t[5],l=t[6],h=t[7],u=t[8],d=t[9],f=t[10],p=t[11],_=t[12],m=t[13],g=t[14],v=t[15],x=f*v-g*p,y=d*v-m*p,C=d*g-m*f,b=u*v-_*p,T=u*g-f*_,S=u*m-_*d,N=+(c*x-l*y+h*C),D=-(o*x-l*b+h*T),M=+(o*y-c*b+h*S),I=-(o*C-c*T+l*S),R=i*N+r*D+s*M+a*I;if(R===0)return e.copyFrom(this),e;const O=1/R,H=l*v-g*h,G=c*v-m*h,Q=c*g-m*l,$=o*v-_*h,V=o*g-_*l,j=o*m-_*c,k=l*p-f*h,z=c*p-d*h,Y=c*f-d*l,J=o*p-u*h,re=o*f-u*l,he=o*d-u*c,le=-(r*x-s*y+a*C),ue=+(i*x-s*b+a*T),L=-(i*y-r*b+a*S),F=+(i*C-r*T+s*S),W=+(r*H-s*G+a*Q),te=-(i*H-s*$+a*V),oe=+(i*G-r*$+a*j),ne=-(i*Q-r*V+s*j),pe=-(r*k-s*z+a*Y),ye=+(i*k-s*J+a*re),Pe=-(i*z-r*J+a*he),Fe=+(i*Y-r*re+s*he);return ce.FromValuesToRef(N*O,le*O,W*O,pe*O,D*O,ue*O,te*O,ye*O,M*O,L*O,oe*O,Pe*O,I*O,F*O,ne*O,Fe*O,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new P(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return ce.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new this.constructor;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]*=i[r];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,r=t._m,s=e;for(let a=0;a<16;a++)r[a]=i[a]*s[a];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const r=this._m,s=e.m,a=r[0],o=r[1],c=r[2],l=r[3],h=r[4],u=r[5],d=r[6],f=r[7],p=r[8],_=r[9],m=r[10],g=r[11],v=r[12],x=r[13],y=r[14],C=r[15],b=s[0],T=s[1],S=s[2],N=s[3],D=s[4],M=s[5],I=s[6],R=s[7],O=s[8],H=s[9],G=s[10],Q=s[11],$=s[12],V=s[13],j=s[14],k=s[15];return t[i]=a*b+o*D+c*O+l*$,t[i+1]=a*T+o*M+c*H+l*V,t[i+2]=a*S+o*I+c*G+l*j,t[i+3]=a*N+o*R+c*Q+l*k,t[i+4]=h*b+u*D+d*O+f*$,t[i+5]=h*T+u*M+d*H+f*V,t[i+6]=h*S+u*I+d*G+f*j,t[i+7]=h*N+u*R+d*Q+f*k,t[i+8]=p*b+_*D+m*O+g*$,t[i+9]=p*T+_*M+m*H+g*V,t[i+10]=p*S+_*I+m*G+g*j,t[i+11]=p*N+_*R+m*Q+g*k,t[i+12]=v*b+x*D+y*O+C*$,t[i+13]=v*T+x*M+y*H+C*V,t[i+14]=v*S+x*I+y*G+C*j,t[i+15]=v*N+x*R+y*Q+C*k,this}divide(e){return this.divideToRef(e,new this.constructor)}divideToRef(e,t){const i=this._m,r=e.m,s=t._m;for(let a=0;a<16;a++)s[a]=i[a]/r[a];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]/=i[r];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new this.constructor)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=-t[r];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,r=t.m;return i[0]===r[0]&&i[1]===r[1]&&i[2]===r[2]&&i[3]===r[3]&&i[4]===r[4]&&i[5]===r[5]&&i[6]===r[6]&&i[7]===r[7]&&i[8]===r[8]&&i[9]===r[9]&&i[10]===r[10]&&i[11]===r[11]&&i[12]===r[12]&&i[13]===r[13]&&i[14]===r[14]&&i[15]===r[15]}equalsWithEpsilon(e,t=0){const i=this._m,r=e.m;for(let s=0;s<16;s++)if(!Hl(i[s],r[s],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new this.constructor)}floorToRef(e){const t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=Math.floor(t[r]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new this.constructor)}fractToRef(e){const t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=t[r]-Math.floor(t[r]);return e.markAsUpdated(),e}clone(){const e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=Xh(this._m[0]);for(let t=1;t<16;t++)e=e*397^Xh(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new we,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,r,s=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const a=this._m;if(i&&i.copyFromFloats(a[12],a[13],a[14]),e=e||Wt.Vector3[0],e.x=Math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]),e.y=Math.sqrt(a[4]*a[4]+a[5]*a[5]+a[6]*a[6]),e.z=Math.sqrt(a[8]*a[8]+a[9]*a[9]+a[10]*a[10]),r){const o=(s?r.absoluteScaling.x:r.scaling.x)<0?-1:1,c=(s?r.absoluteScaling.y:r.scaling.y)<0?-1:1,l=(s?r.absoluteScaling.z:r.scaling.z)<0?-1:1;e.x*=o,e.y*=c,e.z*=l}else this.determinant()<=0&&(e.y*=-1);if(e._x===0||e._y===0||e._z===0)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const o=1/e._x,c=1/e._y,l=1/e._z;ce.FromValuesToRef(a[0]*o,a[1]*o,a[2]*o,0,a[4]*c,a[5]*c,a[6]*c,0,a[8]*l,a[9]*l,a[10]*l,0,0,0,0,1,Wt.Matrix[0]),we.FromRotationMatrixToRef(Wt.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new Ct(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const i=e*4;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new this.constructor;return ce.TransposeToRef(this,e),e}transposeToRef(e){return ce.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,r,s){if(e<0||e>3)return this;const a=e*4;return this._m[a+0]=t,this._m[a+1]=i,this._m[a+2]=r,this._m[a+3]=s,this.markAsUpdated(),this}scale(e){const t=new this.constructor;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=Wt.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return ce.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new this.constructor;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=Wt.Vector3[0];if(!this.decompose(t))return ce.IdentityToRef(e),e;const i=this._m,r=1/t._x,s=1/t._y,a=1/t._z;return ce.FromValuesToRef(i[0]*r,i[1]*r,i[2]*r,0,i[4]*s,i[5]*s,i[6]*s,0,i[8]*a,i[9]*a,i[10]*a,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new ce;return ce.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,r){for(let s=0;s<16;s++)r._m[s]=e[s+t]*i;return r.markAsUpdated(),r}static get IdentityReadOnly(){return ce._IdentityReadOnly}static FromValuesToRef(e,t,i,r,s,a,o,c,l,h,u,d,f,p,_,m,g){const v=g._m;v[0]=e,v[1]=t,v[2]=i,v[3]=r,v[4]=s,v[5]=a,v[6]=o,v[7]=c,v[8]=l,v[9]=h,v[10]=u,v[11]=d,v[12]=f,v[13]=p,v[14]=_,v[15]=m,g.markAsUpdated()}static FromValues(e,t,i,r,s,a,o,c,l,h,u,d,f,p,_,m){const g=new ce,v=g._m;return v[0]=e,v[1]=t,v[2]=i,v[3]=r,v[4]=s,v[5]=a,v[6]=o,v[7]=c,v[8]=l,v[9]=h,v[10]=u,v[11]=d,v[12]=f,v[13]=p,v[14]=_,v[15]=m,g.markAsUpdated(),g}static Compose(e,t,i){const r=new ce;return ce.ComposeToRef(e,t,i,r),r}static ComposeToRef(e,t,i,r){const s=r._m,a=t._x,o=t._y,c=t._z,l=t._w,h=a+a,u=o+o,d=c+c,f=a*h,p=a*u,_=a*d,m=o*u,g=o*d,v=c*d,x=l*h,y=l*u,C=l*d,b=e._x,T=e._y,S=e._z;return s[0]=(1-(m+v))*b,s[1]=(p+C)*b,s[2]=(_-y)*b,s[3]=0,s[4]=(p-C)*T,s[5]=(1-(f+v))*T,s[6]=(g+x)*T,s[7]=0,s[8]=(_+y)*S,s[9]=(g-x)*S,s[10]=(1-(f+m))*S,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,r.markAsUpdated(),r}static Identity(){const e=ce.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return ce.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=ce.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new ce;return ce.RotationXToRef(e,t),t}static Invert(e){const t=new e.constructor;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return ce.FromValuesToRef(1,0,0,0,0,r,i,0,0,-i,r,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationY(e){const t=new ce;return ce.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return ce.FromValuesToRef(r,0,-i,0,0,1,0,0,i,0,r,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationZ(e){const t=new ce;return ce.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return ce.FromValuesToRef(r,i,0,0,-i,r,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationAxis(e,t){const i=new ce;return ce.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const r=Math.sin(-t),s=Math.cos(-t),a=1-s;e.normalize();const o=i._m;return o[0]=e._x*e._x*a+s,o[1]=e._x*e._y*a-e._z*r,o[2]=e._x*e._z*a+e._y*r,o[3]=0,o[4]=e._y*e._x*a+e._z*r,o[5]=e._y*e._y*a+s,o[6]=e._y*e._z*a-e._x*r,o[7]=0,o[8]=e._z*e._x*a-e._y*r,o[9]=e._z*e._y*a+e._x*r,o[10]=e._z*e._z*a+s,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,r=!1){const s=P.Dot(t,e),a=i._m;if(s<-1+ni)a[0]=-1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=r?1:-1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=r?-1:1,a[11]=0;else{const o=P.Cross(t,e),c=1/(1+s);a[0]=o._x*o._x*c+s,a[1]=o._y*o._x*c-o._z,a[2]=o._z*o._x*c+o._y,a[3]=0,a[4]=o._x*o._y*c+o._z,a[5]=o._y*o._y*c+s,a[6]=o._z*o._y*c-o._x,a[7]=0,a[8]=o._x*o._z*c-o._y,a[9]=o._y*o._z*c+o._x,a[10]=o._z*o._z*c+s,a[11]=0}return a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const r=new ce;return ce.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){return we.RotationYawPitchRollToRef(e,t,i,Wt.Quaternion[0]),Wt.Quaternion[0].toRotationMatrix(r),r}static Scaling(e,t,i){const r=new ce;return ce.ScalingToRef(e,t,i,r),r}static ScalingToRef(e,t,i,r){return ce.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,r),r._updateIdentityStatus(e===1&&t===1&&i===1),r}static Translation(e,t,i){const r=new ce;return ce.TranslationToRef(e,t,i,r),r}static TranslationToRef(e,t,i,r){return ce.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,r),r._updateIdentityStatus(e===0&&t===0&&i===0),r}static Lerp(e,t,i){const r=new e.constructor;return ce.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){const s=r._m,a=e.m,o=t.m;for(let c=0;c<16;c++)s[c]=a[c]*(1-i)+o[c]*i;return r.markAsUpdated(),r}static DecomposeLerp(e,t,i){const r=new e.constructor;return ce.DecomposeLerpToRef(e,t,i,r),r}static DecomposeLerpToRef(e,t,i,r){const s=Wt.Vector3[0],a=Wt.Quaternion[0],o=Wt.Vector3[1];e.decompose(s,a,o);const c=Wt.Vector3[2],l=Wt.Quaternion[1],h=Wt.Vector3[3];t.decompose(c,l,h);const u=Wt.Vector3[4];P.LerpToRef(s,c,i,u);const d=Wt.Quaternion[2];we.SlerpToRef(a,l,i,d);const f=Wt.Vector3[5];return P.LerpToRef(o,h,i,f),ce.ComposeToRef(u,d,f,r),r}static LookAtLH(e,t,i){const r=new ce;return ce.LookAtLHToRef(e,t,i,r),r}static LookAtLHToRef(e,t,i,r){const s=Wt.Vector3[0],a=Wt.Vector3[1],o=Wt.Vector3[2];t.subtractToRef(e,o),o.normalize(),P.CrossToRef(i,o,s);const c=s.lengthSquared();c===0?s.x=1:s.normalizeFromLength(Math.sqrt(c)),P.CrossToRef(o,s,a),a.normalize();const l=-P.Dot(s,e),h=-P.Dot(a,e),u=-P.Dot(o,e);return ce.FromValuesToRef(s._x,a._x,o._x,0,s._y,a._y,o._y,0,s._z,a._z,o._z,0,l,h,u,1,r),r}static LookAtRH(e,t,i){const r=new ce;return ce.LookAtRHToRef(e,t,i,r),r}static LookAtRHToRef(e,t,i,r){const s=Wt.Vector3[0],a=Wt.Vector3[1],o=Wt.Vector3[2];e.subtractToRef(t,o),o.normalize(),P.CrossToRef(i,o,s);const c=s.lengthSquared();c===0?s.x=1:s.normalizeFromLength(Math.sqrt(c)),P.CrossToRef(o,s,a),a.normalize();const l=-P.Dot(s,e),h=-P.Dot(a,e),u=-P.Dot(o,e);return ce.FromValuesToRef(s._x,a._x,o._x,0,s._y,a._y,o._y,0,s._z,a._z,o._z,0,l,h,u,1,r),r}static LookDirectionLH(e,t){const i=new ce;return ce.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const r=Wt.Vector3[0];r.copyFrom(e),r.scaleInPlace(-1);const s=Wt.Vector3[1];return P.CrossToRef(t,r,s),ce.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new ce;return ce.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const r=Wt.Vector3[2];return P.CrossToRef(t,e,r),ce.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,r,s){const a=new ce;return ce.OrthoLHToRef(e,t,i,r,a,s),a}static OrthoLHToRef(e,t,i,r,s,a){const o=i,c=r,l=2/e,h=2/t,u=2/(c-o),d=-(c+o)/(c-o);return ce.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,u,0,0,0,d,1,s),a&&s.multiplyToRef(ry,s),s._updateIdentityStatus(l===1&&h===1&&u===1&&d===0),s}static OrthoOffCenterLH(e,t,i,r,s,a,o){const c=new ce;return ce.OrthoOffCenterLHToRef(e,t,i,r,s,a,c,o),c}static OrthoOffCenterLHToRef(e,t,i,r,s,a,o,c){const l=s,h=a,u=2/(t-e),d=2/(r-i),f=2/(h-l),p=-(h+l)/(h-l),_=(e+t)/(e-t),m=(r+i)/(i-r);return ce.FromValuesToRef(u,0,0,0,0,d,0,0,0,0,f,0,_,m,p,1,o),c&&o.multiplyToRef(ry,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,r,s,a,o,c,l,h,u){const d=-o*Math.cos(c),f=-o*Math.sin(c);return ce.TranslationToRef(0,0,-l,Wt.Matrix[1]),ce.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,Wt.Matrix[0]),Wt.Matrix[1].multiplyToRef(Wt.Matrix[0],Wt.Matrix[0]),ce.TranslationToRef(0,0,l,Wt.Matrix[1]),Wt.Matrix[0].multiplyToRef(Wt.Matrix[1],Wt.Matrix[0]),ce.OrthoOffCenterLHToRef(e,t,i,r,s,a,h,u),Wt.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,r,s,a,o){const c=new ce;return ce.OrthoOffCenterRHToRef(e,t,i,r,s,a,c,o),c}static OrthoOffCenterRHToRef(e,t,i,r,s,a,o,c){return ce.OrthoOffCenterLHToRef(e,t,i,r,s,a,o,c),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,r,s,a,o,c,l,h,u){const d=o*Math.cos(c),f=o*Math.sin(c);return ce.TranslationToRef(0,0,l,Wt.Matrix[1]),ce.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,Wt.Matrix[0]),Wt.Matrix[1].multiplyToRef(Wt.Matrix[0],Wt.Matrix[0]),ce.TranslationToRef(0,0,-l,Wt.Matrix[1]),Wt.Matrix[0].multiplyToRef(Wt.Matrix[1],Wt.Matrix[0]),ce.OrthoOffCenterRHToRef(e,t,i,r,s,a,h,u),Wt.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,r,s,a=0){const o=new ce,c=i,l=r,h=2*c/e,u=2*c/t,d=(l+c)/(l-c),f=-2*l*c/(l-c),p=Math.tan(a);return ce.FromValuesToRef(h,0,0,0,0,u,0,p,0,0,d,1,0,0,f,0,o),s&&o.multiplyToRef(ry,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,r,s,a=0,o=!1){const c=new ce;return ce.PerspectiveFovLHToRef(e,t,i,r,c,!0,s,a,o),c}static PerspectiveFovLHToRef(e,t,i,r,s,a=!0,o,c=0,l=!1){const h=i,u=r,d=1/Math.tan(e*.5),f=a?d/t:d,p=a?d:d*t,_=l&&h===0?-1:u!==0?(u+h)/(u-h):1,m=l&&h===0?2*u:u!==0?-2*u*h/(u-h):-2*h,g=Math.tan(c);return ce.FromValuesToRef(f,0,0,0,0,p,0,g,0,0,_,1,0,0,m,0,s),o&&s.multiplyToRef(ry,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,r,s,a=!0,o,c=0){const l=1/Math.tan(e*.5),h=a?l/t:l,u=a?l:l*t,d=Math.tan(c);return ce.FromValuesToRef(h,0,0,0,0,u,0,d,0,0,-i,1,0,0,1,0,s),o&&s.multiplyToRef(ry,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,r,s,a=0,o=!1){const c=new ce;return ce.PerspectiveFovRHToRef(e,t,i,r,c,!0,s,a,o),c}static PerspectiveFovRHToRef(e,t,i,r,s,a=!0,o,c=0,l=!1){const h=i,u=r,d=1/Math.tan(e*.5),f=a?d/t:d,p=a?d:d*t,_=l&&h===0?1:u!==0?-(u+h)/(u-h):-1,m=l&&h===0?2*u:u!==0?-2*u*h/(u-h):-2*h,g=Math.tan(c);return ce.FromValuesToRef(f,0,0,0,0,p,0,g,0,0,_,-1,0,0,m,0,s),o&&s.multiplyToRef(ry,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,r,s,a=!0,o,c=0){const l=1/Math.tan(e*.5),h=a?l/t:l,u=a?l:l*t,d=Math.tan(c);return ce.FromValuesToRef(h,0,0,0,0,u,0,d,0,0,-i,-1,0,0,-1,0,s),o&&s.multiplyToRef(ry,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(e,t,i,r,s,a){const o=e.width,c=e.height,l=e.x,h=e.y,u=ce.FromValues(o/2,0,0,0,0,-c/2,0,0,0,0,a-s,0,l+o/2,c/2+h,s,1),d=new t.constructor;return t.multiplyToRef(i,d),d.multiplyToRef(r,d),d.multiplyToRef(u,d)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return bo.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return bo.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return ce.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,r=i[0],s=i[4],a=i[8],o=i[12],c=i[1],l=i[5],h=i[9],u=i[13],d=i[2],f=i[6],p=i[10],_=i[14],m=i[3],g=i[7],v=i[11],x=i[15],y=t._m;return y[0]=r,y[1]=s,y[2]=a,y[3]=o,y[4]=c,y[5]=l,y[6]=h,y[7]=u,y[8]=d,y[9]=f,y[10]=p,y[11]=_,y[12]=m,y[13]=g,y[14]=v,y[15]=x,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new ce;return ce.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,r=e.normal.y,s=e.normal.z,a=-2*i,o=-2*r,c=-2*s;return ce.FromValuesToRef(a*i+1,o*i,c*i,0,a*r,o*r+1,c*r,0,a*s,o*s,c*s+1,0,a*e.d,o*e.d,c*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,r){return ce.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static FromQuaternionToRef(e,t){const i=e._x*e._x,r=e._y*e._y,s=e._z*e._z,a=e._x*e._y,o=e._z*e._w,c=e._z*e._x,l=e._y*e._w,h=e._y*e._z,u=e._x*e._w;return t._m[0]=1-2*(r+s),t._m[1]=2*(a+o),t._m[2]=2*(c-l),t._m[3]=0,t._m[4]=2*(a-o),t._m[5]=1-2*(s+i),t._m[6]=2*(h+u),t._m[7]=0,t._m[8]=2*(c+l),t._m[9]=2*(h-u),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}ce._UpdateFlagSeed=0;ce._IdentityReadOnly=ce.Identity();Object.defineProperties(ce.prototype,{dimension:{value:[4,4]},rank:{value:2}});class Wt{}Wt.Vector3=Va.BuildTuple(11,P.Zero);Wt.Matrix=Va.BuildTuple(2,ce.Identity);Wt.Quaternion=Va.BuildTuple(3,we.Zero);class ie{}ie.Vector2=Va.BuildTuple(3,Be.Zero);ie.Vector3=Va.BuildTuple(13,P.Zero);ie.Vector4=Va.BuildTuple(3,Ct.Zero);ie.Quaternion=Va.BuildTuple(2,we.Zero);ie.Matrix=Va.BuildTuple(8,ce.Identity);xe("BABYLON.Vector2",Be);xe("BABYLON.Vector3",P);xe("BABYLON.Vector4",Ct);xe("BABYLON.Matrix",ce);const ry=ce.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class _t{static Sign(e){return e=+e,e===0||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(e===0)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e=e*2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=_t.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=_t.Repeat(e,t*2);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let r=_t.Clamp(i);return r=-2*r*r*r+3*r*r,t*r+e*(1-r)}static MoveTowards(e,t,i){let r=0;return Math.abs(t-e)<=i?r=t:r=e+_t.Sign(t-e)*i,r}static MoveTowardsAngle(e,t,i){const r=_t.DeltaAngle(e,t);let s=0;return-i180&&(r-=360),e+r*Nn(i)}static InverseLerp(e,t,i){let r=0;return e!=t?r=Nn((i-e)/(t-e)):r=0,r}static Hermite(e,t,i,r,s){const a=s*s,o=s*a,c=2*o-3*a+1,l=-2*o+3*a,h=o-2*a+s,u=o-a;return e*c+i*l+t*h+r*u}static Hermite1stDerivative(e,t,i,r,s){const a=s*s;return(a-s)*6*e+(3*a-4*s+1)*t+(-a+s)*6*i+(3*a-2*s)*r}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return i===0?t:_t.HCF(t,i)}}_t.TwoPi=Math.PI*2;_t.WithinEpsilon=Hl;_t.ToHex=Fp;_t.Clamp=Nn;_t.Lerp=_u;_t.RandomRange=Xr;_t.NormalizeRadians=w_e;function qS(n){return Math.pow(n,hD)}function JS(n){return n<=.04045?.0773993808*n:Math.pow(.947867299*(n+.055),2.4)}function e8(n){return Math.pow(n,ZS)}function t8(n){return n<=.0031308?12.92*n:1.055*Math.pow(n,.41666)-.055}class Me{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Me.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Ze(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return this.r*.3+this.g*.59+this.b*.11}multiply(e){return new this.constructor(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new this.constructor(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=ni){return _t.WithinEpsilon(this.r,e.r,t)&&_t.WithinEpsilon(this.g,e.g,t)&&_t.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new this.constructor(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=Nn(this.r,e,t),i.g=Nn(this.g,e,t),i.b=Nn(this.b,e,t),i}add(e){return new this.constructor(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new this.constructor(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new this.constructor(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,r){return r.copyFromFloats(this.r-e,this.g-t,this.b-i)}clone(){return new this.constructor(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+Fp(e)+Fp(t)+Fp(i)}toHSV(){const e=new this.constructor;return this.toHSVToRef(e),e}toHSVToRef(e){const t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),a=Math.min(t,i,r);let o=0,c=0;const l=s,h=s-a;s!==0&&(c=h/s),s!=a&&(s==t?(o=(i-r)/h,i=0&&a<=1?(c=s,l=o):a>=1&&a<=2?(c=o,l=s):a>=2&&a<=3?(l=s,h=o):a>=3&&a<=4?(l=o,h=s):a>=4&&a<=5?(c=o,h=s):a>=5&&a<=6&&(c=s,h=o);const u=i-s;r.set(c+u,l+u,h+u)}static FromHSV(e,t,i){const r=new Me(0,0,0);return Me.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==7)return new Me(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16);return Me.FromInts(t,i,r)}static FromArray(e,t=0){return new Me(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new Me(e/255,t/255,i/255)}static Lerp(e,t,i){const r=new Me(0,0,0);return Me.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){const a=s*s,o=s*a,c=2*o-3*a+1,l=-2*o+3*a,h=o-2*a+s,u=o-a,d=e.r*c+i.r*l+t.r*h+r.r*u,f=e.g*c+i.g*l+t.g*h+r.g*u,p=e.b*c+i.b*l+t.b*h+r.b*u;return new Me(d,f,p)}static Hermite1stDerivative(e,t,i,r,s){const a=Me.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){const o=s*s;a.r=(o-s)*6*e.r+(3*o-4*s+1)*t.r+(-o+s)*6*i.r+(3*o-2*s)*r.r,a.g=(o-s)*6*e.g+(3*o-4*s+1)*t.g+(-o+s)*6*i.g+(3*o-2*s)*r.g,a.b=(o-s)*6*e.b+(3*o-4*s+1)*t.b+(-o+s)*6*i.b+(3*o-2*s)*r.b}static Red(){return new Me(1,0,0)}static Green(){return new Me(0,1,0)}static Blue(){return new Me(0,0,1)}static Black(){return new Me(0,0,0)}static get BlackReadOnly(){return Me._BlackReadOnly}static White(){return new Me(1,1,1)}static Purple(){return new Me(.5,0,.5)}static Magenta(){return new Me(1,0,1)}static Yellow(){return new Me(1,1,0)}static Gray(){return new Me(.5,.5,.5)}static Teal(){return new Me(0,1,1)}static Random(){return new Me(Math.random(),Math.random(),Math.random())}}Me._BlackReadOnly=Me.Black();Object.defineProperties(Me.prototype,{dimension:{value:[3]},rank:{value:1}});class Ze{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new this.constructor(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,r){return this.r+=e,this.g+=t,this.b+=i,this.a+=r,this}subtract(e){return new this.constructor(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,r){return new this.constructor(this.r-e,this.g-t,this.b-i,this.a-r)}subtractFromFloatsToRef(e,t,i,r,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s.a=this.a-r,s}scale(e){return new this.constructor(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=Nn(this.r,e,t),i.g=Nn(this.g,e,t),i.b=Nn(this.b,e,t),i.a=Nn(this.a,e,t),i}multiply(e){return new this.constructor(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,r){return new this.constructor(this.r*e,this.g*t,this.b*i,this.a*r)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,r){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(r,this.a),this}maximizeInPlaceFromFloats(e,t,i,r){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(r,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=ni){return _t.WithinEpsilon(this.r,e.r,t)&&_t.WithinEpsilon(this.g,e.g,t)&&_t.WithinEpsilon(this.b,e.b,t)&&_t.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,r){return this.r===e&&this.g===t&&this.b===i&&this.a===r}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e=e*397^(this.a*255|0),e}clone(){return new this.constructor().copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(this.r*255),i=Math.round(this.g*255),r=Math.round(this.b*255);if(e)return"#"+Fp(t)+Fp(i)+Fp(r);const s=Math.round(this.a*255);return"#"+Fp(t)+Fp(i)+Fp(r)+Fp(s)}toLinearSpace(e=!1){const t=new Ze;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=JS(this.r),e.g=JS(this.g),e.b=JS(this.b)):(e.r=qS(this.r),e.g=qS(this.g),e.b=qS(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ze;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=t8(this.r),e.g=t8(this.g),e.b=t8(this.b)):(e.r=e8(this.r),e.g=e8(this.g),e.b=e8(this.b)),e.a=this.a,this}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==9&&e.length!==7)return new Ze(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16),s=e.length===9?parseInt(e.substring(7,9),16):255;return Ze.FromInts(t,i,r,s)}static Lerp(e,t,i){const r=new Ze(0,0,0,0);return Ze.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,r,s){const a=s*s,o=s*a,c=2*o-3*a+1,l=-2*o+3*a,h=o-2*a+s,u=o-a,d=e.r*c+i.r*l+t.r*h+r.r*u,f=e.g*c+i.g*l+t.g*h+r.g*u,p=e.b*c+i.b*l+t.b*h+r.b*u,_=e.a*c+i.a*l+t.a*h+r.a*u;return new Ze(d,f,p,_)}static Hermite1stDerivative(e,t,i,r,s){const a=new Ze;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){const o=s*s;a.r=(o-s)*6*e.r+(3*o-4*s+1)*t.r+(-o+s)*6*i.r+(3*o-2*s)*r.r,a.g=(o-s)*6*e.g+(3*o-4*s+1)*t.g+(-o+s)*6*i.g+(3*o-2*s)*r.g,a.b=(o-s)*6*e.b+(3*o-4*s+1)*t.b+(-o+s)*6*i.b+(3*o-2*s)*r.b,a.a=(o-s)*6*e.a+(3*o-4*s+1)*t.a+(-o+s)*6*i.a+(3*o-2*s)*r.a}static FromColor3(e,t=1){return new Ze(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ze(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new Ze(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let r=0;rnew Ze(0,0,0,0));xe("BABYLON.Color3",Me);xe("BABYLON.Color4",Ze);class Ms{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new Ae,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){return null}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const r=this._condition.serialize();return r.children.push(i),t&&t.children.push(r),r}return t&&t.children.push(i),i}}Ms._SerializeValueAsString=n=>typeof n=="number"?n.toString():typeof n=="boolean"?n?"true":"false":n instanceof Be?n.x+", "+n.y:n instanceof P?n.x+", "+n.y+", "+n.z:n instanceof Me?n.r+", "+n.g+", "+n.b:n instanceof Ze?n.r+", "+n.g+", "+n.b+", "+n.a:n;Ms._GetTargetProperty=n=>({name:"target",targetType:n._isMesh?"MeshProperties":n._isLight?"LightProperties":n._isCamera?"CameraProperties":n._isMaterial?"MaterialProperties":"SceneProperties",value:n._isScene?"Scene":n.name});xe("BABYLON.Action",Ms);class pn{constructor(e,t,i,r,s,a){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=a}static CreateNew(e,t,i){const r=e.getScene();return new pn(e,r.pointerX,r.pointerY,r.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,r){return new pn(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,r)}static CreateNewFromScene(e,t){return new pn(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,r){return new pn(e,t.x,t.y,null,i,r)}}class V8{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class vo extends V8{static get IsEqual(){return vo._IsEqual}static get IsDifferent(){return vo._IsDifferent}static get IsGreater(){return vo._IsGreater}static get IsLesser(){return vo._IsLesser}constructor(e,t,i,r,s=vo.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case vo.IsGreater:return this._effectiveTarget[this._property]>this.value;case vo.IsLesser:return this._effectiveTarget[this._property]r<10?"0"+r:""+r,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const r=Array.isArray(t)?t[0]:t;if(i!==void 0&&!de._CheckLimit(r,i))return;const s=de._FormatMessage(r),a=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];a.logFunc&&a.logFunc("BJS - "+s,...o);const c=`
    ${s}

    `;de._AddLogEntry(c),de._GenerateLimitMessage(r,e)}static get LogCache(){return de._LogCache}static ClearLogCache(){de._LogCache="",de._LogLimitOutputs={},de.errorsCount=0}static set LogLevels(e){de.Log=de._LogDisabled,de.Warn=de._LogDisabled,de.Error=de._LogDisabled,[de.MessageLogLevel,de.WarningLogLevel,de.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];de[i.name]=de._LogEnabled.bind(de,t)}})}}de.NoneLogLevel=0;de.MessageLogLevel=1;de.WarningLogLevel=2;de.ErrorLogLevel=4;de.AllLogLevel=7;de.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";de._LogCache="";de._LogLimitOutputs={};de._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];de.errorsCount=0;de.Log=de._LogEnabled.bind(de,de.MessageLogLevel);de.Warn=de._LogEnabled.bind(de,de.WarningLogLevel);de.Error=de._LogEnabled.bind(de,de.ErrorLogLevel);class L_e extends Ms{constructor(e,t,i,r){super(e,r),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[Ms._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class N_e extends Ms{constructor(e,t,i,r){super(e,r),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[Ms._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class B_e extends Ms{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[Ms._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ms._SerializeValueAsString(this.value)}]},e)}}class F_e extends Ms{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),typeof this._effectiveTarget[this._property]!="number"&&de.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[Ms._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ms._SerializeValueAsString(this.value)}]},e)}}class U_e extends Ms{constructor(e,t,i,r,s,a){super(e,a),this.from=i,this.to=r,this.loop=s,this._target=t}_prepare(){}execute(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[Ms._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Ms._SerializeValueAsString(this.loop)||!1}]},e)}}class k_e extends Ms{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){this._actionManager.getScene().stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[Ms._GetTargetProperty(this._target)]},e)}}class gJ extends Ms{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class V_e extends Ms{constructor(e,t,i,r=!0){super(e,i),this.children=t,this.enableChildrenConditions=r}_prepare(){for(let e=0;e!n||n.getClassName&&n.getClassName()==="Mesh"?null:n.getClassName&&(n.getClassName()==="SubMesh"||n.getClassName()==="PhysicsBody")?n.clone(e):n.clone?n.clone():Array.isArray(n)?n.slice():t&&typeof n=="object"?{...n}:null;function gMe(n){const e=[];do Object.getOwnPropertyNames(n).forEach(function(t){e.indexOf(t)===-1&&e.push(t)});while(n=Object.getPrototypeOf(n));return e}class ol{static DeepCopy(e,t,i,r,s=!1){const a=gMe(e);for(const o of a){if(o[0]==="_"&&(!r||r.indexOf(o)===-1)||o.endsWith("Observable")||i&&i.indexOf(o)!==-1)continue;const c=e[o],l=typeof c;if(l!=="function")try{if(l==="object")if(c instanceof Uint8Array)t[o]=Uint8Array.from(c);else if(c instanceof Array){if(t[o]=[],c.length>0)if(typeof c[0]=="object")for(let h=0;h-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter(i=>i.actionManager===this);for(const i of t)i.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=kr.OnPickTrigger&&t.trigger<=kr.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=kr.OnPickTrigger&&t.trigger<=kr.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===kr.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(de.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,kr.Triggers[e.trigger]?kr.Triggers[e.trigger]++:kr.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return t!==-1?(this.actions.splice(t,1),kr.Triggers[e.trigger]-=1,kr.Triggers[e.trigger]===0&&delete kr.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0):!1}processTrigger(e,t){for(let i=0;i{const h=gn("BABYLON."+c);return h&&new h(...l)},a=(c,l,h,u)=>{if(u===null){const _=parseFloat(l);return l==="true"||l==="false"?l==="true":isNaN(_)?l:_}const d=u.split("."),f=l.split(",");for(let _=0;_{if(c.detached)return;const f=[];let p=null,_=null;const m=c.combine&&c.combine.length>0;if(c.type===2?f.push(r):f.push(l),m){const v=[];for(let x=0;x0){const u=h.properties[0].value,d=h.properties[0].targetType===null?u:i.getMeshByName(u);d._meshId&&(d.mesh=i.getMeshById(d._meshId)),l={trigger:kr[h.name],parameter:d}}else l=kr[h.name];for(let u=0;u=0;o--)(a=n[o])&&(s=(r<3?a(s):r>3?a(e,t,s):a(e,t))||s);return r>3&&s&&Object.defineProperty(e,t,s),s}const dV={},WV={};function vMe(n){const e=n.getClassName();return WV[e]||(WV[e]={}),WV[e]}function b$(n){const e=n.getClassName();if(dV[e])return dV[e];dV[e]={};const t=dV[e];let i=n,r=e;for(;r;){const s=WV[r];for(const c in s)t[c]=s[c];let a,o=!1;do{if(a=Object.getPrototypeOf(i),!a.getClassName){o=!0;break}if(a.getClassName()!==r)break;i=a}while(a);if(o)break;r=a.getClassName(),i=a}return t}function Fd(n,e){return(t,i)=>{const r=vMe(t);r[i]||(r[i]={type:n,sourceName:e})}}function xMe(n,e=null){return(t,i)=>{const r=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[r]},set:function(s){typeof this.equals=="function"&&this.equals(s)||this[r]!==s&&(this[r]=s,t[n].apply(this))},enumerable:!0,configurable:!0})}}function ze(n,e=null){return xMe(n,e)}function K(n){return Fd(0,n)}function $t(n){return Fd(1,n)}function or(n){return Fd(2,n)}function R5(n){return Fd(3,n)}function LO(n){return Fd(4,n)}function Js(n){return Fd(5,n)}function I5(n){return Fd(6,n)}function K_e(n){return Fd(7,n)}function P5(n){return Fd(8,n)}function xJ(n){return Fd(9,n)}function W_e(n){return Fd(10,n)}function qH(n){return Fd(12,n)}function j_e(n){return Fd(11,n)}function e2(n,e,t,i){const r=t.value;t.value=(...s)=>{let a=r;if(typeof _native<"u"&&_native[e]){const o=_native[e];i?a=(...c)=>i(...c)?o(...c):r(...c):a=o}return n[e]=a,a(...s)}}e2.filter=function(n){return(e,t,i)=>e2(e,t,i,n)};const Xue={};function ci(n,e=!1){if(!(e&&Xue[n]))return Xue[n]=!0,`${n} needs to be imported before as it contains a side-effect required by your code.`}class x3{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),x3._HandleParenthesisContent(i,t))):e=x3._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:x3.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(s=>s==="true");let i;const r=e.split("||");for(const s in r)if(Object.prototype.hasOwnProperty.call(r,s)){let a=x3._SimplifyNegation(r[s].trim());const o=a.split("&&");if(o.length>1)for(let c=0;c(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}class vr{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>vr.HasTags(e),e.addTags=t=>vr.AddTagsTo(e,t),e.removeTags=t=>vr.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>vr.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const i=[];for(const r in e._tags)Object.prototype.hasOwnProperty.call(e._tags,r)&&e._tags[r]===!0&&i.push(r);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;t.split(" ").forEach(function(r){vr._AddTagTo(e,r)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(vr.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!vr.HasTags(e))return;const i=t.split(" ");for(const r in i)vr._RemoveTagFrom(e,i[r])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?vr.HasTags(e):x3.Eval(t,i=>vr.HasTags(e)&&e._tags[i])}}const Yue=function(n,e,t,i={}){const r=n();vr&&vr.HasTags(e)&&vr.AddTagsTo(r,vr.GetTags(e,!0));const s=b$(r),a={};for(const o in s){const c=s[o],l=e[o],h=c.type;if(l!=null&&(o!=="uniqueId"||Qe.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[o]=l;break;case 1:i.cloneTexturesOnlyOnce&&a[l.uniqueId]?r[o]=a[l.uniqueId]:(r[o]=t||l.isRenderTarget?l:l.clone(),a[l.uniqueId]=r[o]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[o]=t?l:l.clone();break}}return r};class Qe{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw ci("ImageProcessingConfiguration")};Qe._FresnelParametersParser=n=>{throw ci("FresnelParameters")};Qe._ColorCurvesParser=n=>{throw ci("ColorCurves")};Qe._TextureParser=(n,e,t)=>{throw ci("Texture")};class yMe{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new Ae,this._onClonedObservable=new Ae}}let Lr=class E${static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){const s=this._NodeConstructors[e];return s?s(t,i,r):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return this._nodeDataStorage._doNotSerialize?!0:this._parentNode?this._parentNode.doNotSerialize:!1}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&this._parentNode._children!==void 0&&this._parentNode._children!==null){const i=this._parentNode._children.indexOf(this);i!==-1&&this._parentNode._children.splice(i,1),!e&&!this._nodeDataStorage._isDisposed&&this._addToSceneRootNodes()}this._parentNode=e,this._parentNode&&((this._parentNode._children===void 0||this._parentNode._children===null)&&(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){this._nodeDataStorage._sceneRootNodesIndex===-1&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(this._nodeDataStorage._sceneRootNodesIndex!==-1){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null){this._isDirty=!1,this._nodeDataStorage=new yMe,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new Ae,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=ce.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new Ae,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||bt.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return this._behaviors.indexOf(e)!==-1?this:(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{e.attach(this)}):e.attach(this),this._behaviors.push(e),this)}removeBehavior(e){const t=this._behaviors.indexOf(e);return t===-1?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,this._updateCache())}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return this._parentNode?this._parentNode._isDirty||this._parentUpdateId!==this._parentNode._childUpdateId?!1:this._parentNode.isSynchronized():!0}isSynchronized(){return this._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):this._parentNode&&!this.isSynchronizedWithParent()?!1:this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return e===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,this._children&&this._children.forEach(e=>{e._syncParentEnabledState()})}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return this.parent?this.parent===e?!0:this.parent.isDescendantOf(e):!1}_getDescendants(e,t=!1,i){if(this._children)for(let r=0;r(!t||t(r))&&r.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew E$(e,this.getScene()),this);if(t&&(r.parent=t),!i){const s=this.getDescendants(!0);for(let a=0;a{throw ci("AnimationRange")};Lr._NodeConstructors={};B([K()],Lr.prototype,"name",void 0);B([K()],Lr.prototype,"id",void 0);B([K()],Lr.prototype,"uniqueId",void 0);B([K()],Lr.prototype,"state",void 0);B([K()],Lr.prototype,"metadata",void 0);class lc{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=this.width|0;return e=e*397^(this.height|0),e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new lc(this.width*e,this.height*t)}clone(){return new lc(this.width,this.height)}equals(e){return e?this.width===e.width&&this.height===e.height:!1}get surface(){return this.width*this.height}static Zero(){return new lc(0,0)}add(e){return new lc(this.width+e.width,this.height+e.height)}subtract(e){return new lc(this.width-e.width,this.height-e.height)}scale(e){return new lc(this.width*e,this.height*e)}static Lerp(e,t,i){const r=e.width+(t.width-e.width)*i,s=e.height+(t.height-e.height)*i;return new lc(r,s)}}function AMe(){return typeof _native<"u"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}class on{constructor(){this._xhr=AMe(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(on.CustomRequestHeaders).length>0||on.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in on.CustomRequestHeaders){const t=on.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return on.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){on.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of on.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;i(this._xhr,t)}t=t.replace("file:http:","http:"),t=t.replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}on.CustomRequestHeaders={};on.CustomRequestModifiers=new Array;on.SkipRequestModificationForBabylonCDN=!0;const yJ=Object.freeze(new we(0,0,0,0)),AJ=Object.freeze(P.Zero()),CJ=Object.freeze(Be.Zero()),bJ=Object.freeze(lc.Zero()),EJ=Object.freeze(Me.Black()),TJ=Object.freeze(new Ze(0,0,0,0)),Pp={key:0,repeatCount:0,loopMode:2};class ke{static _PrepareAnimation(e,t,i,r,s,a,o,c){let l;if(!isNaN(parseFloat(s))&&isFinite(s)?l=ke.ANIMATIONTYPE_FLOAT:s instanceof we?l=ke.ANIMATIONTYPE_QUATERNION:s instanceof P?l=ke.ANIMATIONTYPE_VECTOR3:s instanceof Be?l=ke.ANIMATIONTYPE_VECTOR2:s instanceof Me?l=ke.ANIMATIONTYPE_COLOR3:s instanceof Ze?l=ke.ANIMATIONTYPE_COLOR4:s instanceof lc&&(l=ke.ANIMATIONTYPE_SIZE),l==null)return null;const h=new ke(e,t,i,l,o),u=[{frame:0,value:s},{frame:r,value:a}];return h.setKeys(u),c!==void 0&&h.setEasingFunction(c),h}static CreateAnimation(e,t,i,r){const s=new ke(e+"Animation",e,i,t,ke.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,a,o,c,l,h,u){const d=ke._PrepareAnimation(e,i,r,s,a,o,c,l);return!d||(t.getScene&&(u=t.getScene()),!u)?null:u.beginDirectAnimation(t,[d],0,s,d.loopMode===1,1,h)}static CreateAndStartHierarchyAnimation(e,t,i,r,s,a,o,c,l,h,u){const d=ke._PrepareAnimation(e,r,s,a,o,c,l,h);return d?t.getScene().beginDirectHierarchyAnimation(t,i,[d],0,a,d.loopMode===1,1,u):null}static CreateMergeAndStartAnimation(e,t,i,r,s,a,o,c,l,h){const u=ke._PrepareAnimation(e,i,r,s,a,o,c,l);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,s,u.loopMode===1,1,h)):null}static MakeAnimationAdditive(e,t,i,r=!1,s){let a;typeof t=="object"?a=t:a={referenceFrame:t??0,range:i,cloneOriginalAnimation:r,clonedAnimationName:s};let o=e;if(a.cloneOriginalAnimation&&(o=e.clone(),o.name=a.clonedAnimationName||o.name),!o._keys.length)return o;const c=a.referenceFrame&&a.referenceFrame>=0?a.referenceFrame:0;let l=0;const h=o._keys[0];let u=o._keys.length-1;const d=o._keys[u],f={referenceValue:h.value,referencePosition:ie.Vector3[0],referenceQuaternion:ie.Quaternion[0],referenceScaling:ie.Vector3[1],keyPosition:ie.Vector3[2],keyQuaternion:ie.Quaternion[1],keyScaling:ie.Vector3[3]};let p=h.frame,_=d.frame;if(a.range){const v=o.getRange(a.range);v&&(p=v.from,_=v.to)}else p=a.fromFrame??p,_=a.toFrame??_;if(p!==h.frame&&(l=o.createKeyForFrame(p)),_!==d.frame&&(u=o.createKeyForFrame(_)),o._keys.length===1){const v=o._getKeyValue(o._keys[0]);f.referenceValue=v.clone?v.clone():v}else if(c<=h.frame){const v=o._getKeyValue(h.value);f.referenceValue=v.clone?v.clone():v}else if(c>=d.frame){const v=o._getKeyValue(d.value);f.referenceValue=v.clone?v.clone():v}else{Pp.key=0;const v=o._interpolate(c,Pp);f.referenceValue=v.clone?v.clone():v}o.dataType===ke.ANIMATIONTYPE_QUATERNION?f.referenceValue.normalize().conjugateInPlace():o.dataType===ke.ANIMATIONTYPE_MATRIX&&(f.referenceValue.decompose(f.referenceScaling,f.referenceQuaternion,f.referencePosition),f.referenceQuaternion.normalize().conjugateInPlace());let m=Number.MAX_VALUE;const g=a.clipKeys?[]:null;for(let v=l;v<=u;v++){let x=o._keys[v];if(g&&(x={frame:x.frame,value:x.value.clone?x.value.clone():x.value,inTangent:x.inTangent,outTangent:x.outTangent,interpolation:x.interpolation,lockedTangent:x.lockedTangent},m===Number.MAX_VALUE&&(m=x.frame),x.frame-=m,g.push(x)),!(v&&o.dataType!==ke.ANIMATIONTYPE_FLOAT&&x.value===h.value))switch(o.dataType){case ke.ANIMATIONTYPE_MATRIX:x.value.decompose(f.keyScaling,f.keyQuaternion,f.keyPosition),f.keyPosition.subtractInPlace(f.referencePosition),f.keyScaling.divideInPlace(f.referenceScaling),f.referenceQuaternion.multiplyToRef(f.keyQuaternion,f.keyQuaternion),ce.ComposeToRef(f.keyScaling,f.keyQuaternion,f.keyPosition,x.value);break;case ke.ANIMATIONTYPE_QUATERNION:f.referenceValue.multiplyToRef(x.value,x.value);break;case ke.ANIMATIONTYPE_VECTOR2:case ke.ANIMATIONTYPE_VECTOR3:case ke.ANIMATIONTYPE_COLOR3:case ke.ANIMATIONTYPE_COLOR4:x.value.subtractToRef(f.referenceValue,x.value);break;case ke.ANIMATIONTYPE_SIZE:x.value.width-=f.referenceValue.width,x.value.height-=f.referenceValue.height;break;default:x.value-=f.referenceValue}}return g&&o.setKeys(g,!0),o}static TransitionTo(e,t,i,r,s,a,o,c=null){if(o<=0)return i[e]=t,c&&c(),null;const l=s*(o/1e3);a.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(a);const h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=c,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,a){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=a,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=s===void 0?ke.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=ke._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let i=!0;for(const r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((t,i)=>t.frame-i.frame)}removeEvents(e){for(let t=0;t=0;a--)this._keys[a].frame>=r&&this._keys[a].frame<=s&&this._keys.splice(a,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const r=this._keys,s=r.length;let a=t.key;for(;a>=0&&e=r[a+1].frame;)++a;if(t.key=a,a<0)return i?void 0:this._getKeyValue(r[0].value);if(a+1>s-1)return i?void 0:this._getKeyValue(r[s-1].value);const o=r[a],c=r[a+1];if(i&&(e===o.frame||e===c.frame))return;const l=this._getKeyValue(o.value),h=this._getKeyValue(c.value);if(o.interpolation===ND.STEP)return c.frame>e?l:h;const u=o.outTangent!==void 0&&c.inTangent!==void 0,d=c.frame-o.frame;let f=(e-o.frame)/d;const p=o.easingFunction||this.getEasingFunction();switch(p!==null&&(f=p.ease(f)),this.dataType){case ke.ANIMATIONTYPE_FLOAT:{const _=u?this.floatInterpolateFunctionWithTangents(l,o.outTangent*d,h,c.inTangent*d,f):this.floatInterpolateFunction(l,h,f);switch(t.loopMode){case ke.ANIMATIONLOOPMODE_CYCLE:case ke.ANIMATIONLOOPMODE_CONSTANT:case ke.ANIMATIONLOOPMODE_YOYO:return _;case ke.ANIMATIONLOOPMODE_RELATIVE:case ke.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+_}break}case ke.ANIMATIONTYPE_QUATERNION:{const _=u?this.quaternionInterpolateFunctionWithTangents(l,o.outTangent.scale(d),h,c.inTangent.scale(d),f):this.quaternionInterpolateFunction(l,h,f);switch(t.loopMode){case ke.ANIMATIONLOOPMODE_CYCLE:case ke.ANIMATIONLOOPMODE_CONSTANT:case ke.ANIMATIONLOOPMODE_YOYO:return _;case ke.ANIMATIONLOOPMODE_RELATIVE:case ke.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.addInPlace((t.offsetValue||yJ).scale(t.repeatCount))}return _}case ke.ANIMATIONTYPE_VECTOR3:{const _=u?this.vector3InterpolateFunctionWithTangents(l,o.outTangent.scale(d),h,c.inTangent.scale(d),f):this.vector3InterpolateFunction(l,h,f);switch(t.loopMode){case ke.ANIMATIONLOOPMODE_CYCLE:case ke.ANIMATIONLOOPMODE_CONSTANT:case ke.ANIMATIONLOOPMODE_YOYO:return _;case ke.ANIMATIONLOOPMODE_RELATIVE:case ke.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||AJ).scale(t.repeatCount))}break}case ke.ANIMATIONTYPE_VECTOR2:{const _=u?this.vector2InterpolateFunctionWithTangents(l,o.outTangent.scale(d),h,c.inTangent.scale(d),f):this.vector2InterpolateFunction(l,h,f);switch(t.loopMode){case ke.ANIMATIONLOOPMODE_CYCLE:case ke.ANIMATIONLOOPMODE_CONSTANT:case ke.ANIMATIONLOOPMODE_YOYO:return _;case ke.ANIMATIONLOOPMODE_RELATIVE:case ke.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||CJ).scale(t.repeatCount))}break}case ke.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case ke.ANIMATIONLOOPMODE_CYCLE:case ke.ANIMATIONLOOPMODE_CONSTANT:case ke.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,f);case ke.ANIMATIONLOOPMODE_RELATIVE:case ke.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,h,f).add((t.offsetValue||bJ).scale(t.repeatCount))}break}case ke.ANIMATIONTYPE_COLOR3:{const _=u?this.color3InterpolateFunctionWithTangents(l,o.outTangent.scale(d),h,c.inTangent.scale(d),f):this.color3InterpolateFunction(l,h,f);switch(t.loopMode){case ke.ANIMATIONLOOPMODE_CYCLE:case ke.ANIMATIONLOOPMODE_CONSTANT:case ke.ANIMATIONLOOPMODE_YOYO:return _;case ke.ANIMATIONLOOPMODE_RELATIVE:case ke.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||EJ).scale(t.repeatCount))}break}case ke.ANIMATIONTYPE_COLOR4:{const _=u?this.color4InterpolateFunctionWithTangents(l,o.outTangent.scale(d),h,c.inTangent.scale(d),f):this.color4InterpolateFunction(l,h,f);switch(t.loopMode){case ke.ANIMATIONLOOPMODE_CYCLE:case ke.ANIMATIONLOOPMODE_CONSTANT:case ke.ANIMATIONLOOPMODE_YOYO:return _;case ke.ANIMATIONLOOPMODE_RELATIVE:case ke.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||TJ).scale(t.repeatCount))}break}case ke.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case ke.ANIMATIONLOOPMODE_CYCLE:case ke.ANIMATIONLOOPMODE_CONSTANT:case ke.ANIMATIONLOOPMODE_YOYO:return ke.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,f,t.workValue):l;case ke.ANIMATIONLOOPMODE_RELATIVE:case ke.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}break}}return 0}matrixInterpolateFunction(e,t,i,r){return ke.AllowMatrixDecomposeForInterpolation?r?(ce.DecomposeLerpToRef(e,t,i,r),r):ce.DecomposeLerp(e,t,i):r?(ce.LerpToRef(e,t,i,r),r):ce.Lerp(e,t,i)}clone(){const e=new ke(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){Pp.key=0;const t=this._interpolate(e,Pp,!0);if(!t)return this._keys[Pp.key].frame===e?Pp.key:Pp.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Pp.key+1,0,i),Pp.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let r=0;r=2&&(c=o.values[1]),o.values.length>=3&&(l=o.values[2]),o.values.length>=4&&(h=o.values[3]);break;case ke.ANIMATIONTYPE_QUATERNION:if(s=we.FromArray(o.values),o.values.length>=8){const d=we.FromArray(o.values.slice(4,8));d.equals(we.Zero())||(c=d)}if(o.values.length>=12){const d=we.FromArray(o.values.slice(8,12));d.equals(we.Zero())||(l=d)}o.values.length>=13&&(h=o.values[12]);break;case ke.ANIMATIONTYPE_MATRIX:s=ce.FromArray(o.values),o.values.length>=17&&(h=o.values[16]);break;case ke.ANIMATIONTYPE_COLOR3:s=Me.FromArray(o.values),o.values[3]&&(c=Me.FromArray(o.values[3])),o.values[4]&&(l=Me.FromArray(o.values[4])),o.values[5]&&(h=o.values[5]);break;case ke.ANIMATIONTYPE_COLOR4:s=Ze.FromArray(o.values),o.values[4]&&(c=Ze.FromArray(o.values[4])),o.values[5]&&(l=Ze.FromArray(o.values[5])),o.values[6]&&(h=Ze.FromArray(o.values[6]));break;case ke.ANIMATIONTYPE_VECTOR3:default:s=P.FromArray(o.values),o.values[3]&&(c=P.FromArray(o.values[3])),o.values[4]&&(l=P.FromArray(o.values[4])),o.values[5]&&(h=o.values[5]);break}const u={};u.frame=o.frame,u.value=s,c!=null&&(u.inTangent=c),l!=null&&(u.outTangent=l),h!=null&&(u.interpolation=h),r.push(u)}if(t.setKeys(r),e.ranges)for(a=0;a{const s=new on;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){let a=JSON.parse(s.responseText);if(a.animations&&(a=a.animations),a.length){const o=[];for(const c of a)o.push(this.Parse(c));i(o)}else{const o=this.Parse(a);e&&(o.name=e),i(o)}}else r("Unable to load the animation")}),s.open("GET",t),s.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{const r=new on;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){const s=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(s.animations){const a=JSON.parse(s.animations),o=[];for(const c of a.animations){const l=this.Parse(c);l.snippetId=e,o.push(l)}t(o)}else{const a=JSON.parse(s.animation),o=this.Parse(a);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}}ke._UniqueIdGenerator=0;ke.AllowMatricesInterpolation=!1;ke.AllowMatrixDecomposeForInterpolation=!0;ke.SnippetUrl="https://snippet.babylonjs.com";ke.ANIMATIONTYPE_FLOAT=0;ke.ANIMATIONTYPE_VECTOR3=1;ke.ANIMATIONTYPE_QUATERNION=2;ke.ANIMATIONTYPE_MATRIX=3;ke.ANIMATIONTYPE_COLOR3=4;ke.ANIMATIONTYPE_COLOR4=7;ke.ANIMATIONTYPE_VECTOR2=5;ke.ANIMATIONTYPE_SIZE=6;ke.ANIMATIONLOOPMODE_RELATIVE=0;ke.ANIMATIONLOOPMODE_CYCLE=1;ke.ANIMATIONLOOPMODE_CONSTANT=2;ke.ANIMATIONLOOPMODE_YOYO=4;ke.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;ke.CreateFromSnippetAsync=ke.ParseFromSnippetAsync;xe("BABYLON.Animation",ke);Lr._AnimationRangeFactory=(n,e,t)=>new $y(n,e,t);class X_e extends Ms{constructor(e,t,i,r,s=1e3,a,o,c){super(e,a),this.duration=1e3,this.onInterpolationDoneObservable=new Ae,this.propertyPath=i,this.value=r,this.duration=s,this.stopOtherAnimations=o,this.onInterpolationDone=c,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if(typeof this.value=="number")i=ke.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Me)i=ke.ANIMATIONTYPE_COLOR3;else if(this.value instanceof P)i=ke.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof ce)i=ke.ANIMATIONTYPE_MATRIX;else if(this.value instanceof we)i=ke.ANIMATIONTYPE_QUATERNION;else{de.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}const r=new ke("InterpolateValueAction",this._property,100*(1e3/this.duration),i,ke.ANIMATIONLOOPMODE_CONSTANT);r.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget);const s=()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()};e.beginDirectAnimation(this._effectiveTarget,[r],0,100,!1,1,s)}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Ms._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ms._SerializeValueAsString(this.value)},{name:"duration",value:Ms._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Ms._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}xe("BABYLON.InterpolateValueAction",X_e);class Y_e{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,r){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===ke.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=ce.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,this._minFrame!==0){const a={frame:0,value:this._minValue};this._keys.splice(0,0,a)}if(this._target instanceof Array){let a=0;for(const o of this._target)this._preparePath(o,a),this._getOriginalValues(a),a++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const s=t.getEvents();s&&s.length>0&&s.forEach(a=>{this._events.push(a._clone())}),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let r=e[i[0]];for(let s=1;s-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let s=0;sthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let u,d=e*(o.framePerSecond*s)/1e3+this._absoluteFrameOffset,f=0;if(r&&this._animationState.loopMode===ke.ANIMATIONLOOPMODE_YOYO){const g=(d-t)/h;d=Math.abs(Math.sin(g*Math.PI))*h+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&(d>=h&&s>0||d<=0&&s<0))l=!1,f=o._getKeyValue(this._maxValue);else if(!r&&t>=i&&(d<=h&&s<0||d>=0&&s>0))l=!1,f=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==ke.ANIMATIONLOOPMODE_CYCLE){const g=i.toString()+t.toString();if(!this._offsetsCache[g]){this._animationState.repeatCount=0,this._animationState.loopMode=ke.ANIMATIONLOOPMODE_CYCLE;const v=o._interpolate(t,this._animationState),x=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case ke.ANIMATIONTYPE_FLOAT:this._offsetsCache[g]=x-v;break;case ke.ANIMATIONTYPE_QUATERNION:this._offsetsCache[g]=x.subtract(v);break;case ke.ANIMATIONTYPE_VECTOR3:this._offsetsCache[g]=x.subtract(v);break;case ke.ANIMATIONTYPE_VECTOR2:this._offsetsCache[g]=x.subtract(v);break;case ke.ANIMATIONTYPE_SIZE:this._offsetsCache[g]=x.subtract(v);break;case ke.ANIMATIONTYPE_COLOR3:this._offsetsCache[g]=x.subtract(v);break}this._highLimitsCache[g]=x}f=this._highLimitsCache[g],u=this._offsetsCache[g]}if(u===void 0)switch(o.dataType){case ke.ANIMATIONTYPE_FLOAT:u=0;break;case ke.ANIMATIONTYPE_QUATERNION:u=yJ;break;case ke.ANIMATIONTYPE_VECTOR3:u=AJ;break;case ke.ANIMATIONTYPE_VECTOR2:u=CJ;break;case ke.ANIMATIONTYPE_SIZE:u=bJ;break;case ke.ANIMATIONTYPE_COLOR3:u=EJ;break;case ke.ANIMATIONTYPE_COLOR4:u=TJ;break}let p;if(this._host&&this._host.syncRoot){const g=this._host.syncRoot,v=(g.masterFrame-g.fromFrame)/(g.toFrame-g.fromFrame);p=t+h*v}else d>0&&t>i||d<0&&t0&&this.currentFrame>p||s<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=p,this._animationState.repeatCount=h===0?0:d/h>>0,this._animationState.highLimitValue=f,this._animationState.offsetValue=u;const m=o._interpolate(p,this._animationState);if(this.setValue(m,a),_.length){for(let g=0;g<_.length;g++)if(h>=0&&p>=_[g].frame&&_[g].frame>=t||h<0&&p<=_[g].frame&&_[g].frame<=t){const v=_[g];v.isDone||(v.onlyOnce&&(_.splice(g,1),g--),v.isDone=!0,v.action(p))}}return l||(this._stopped=!0),l}}function io(){return typeof window<"u"}function xy(){return typeof navigator<"u"}function Ny(){return typeof document<"u"}function NO(n){let e="",t=n.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}const CMe={IsWindowObjectExist:io,IsNavigatorAvailable:xy,IsDocumentAvailable:Ny,GetDOMTextContent:NO};class gr{static get Now(){return io()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class By{}By.FilesToLoad={};class Q_e{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>r.status!==0||s>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,s)*t}}class Zy extends Error{}Zy._setPrototypeOf=Object.setPrototypeOf||((n,e)=>(n.__proto__=e,n));const z0={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class kf extends Zy{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Zy._setPrototypeOf(this,kf.prototype)}}const $_e=(n,e)=>n.endsWith(e),Z_e=(n,e)=>n?n.startsWith(e):!1,SJ=n=>{if(typeof TextDecoder<"u")return new TextDecoder().decode(n);let e="";for(let t=0;t{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,r,s,a,o,c,l,h=0;const u=ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);for(;h>2,o=(i&3)<<4|r>>4,c=(r&15)<<2|s>>6,l=s&63,isNaN(r)?c=l=64:isNaN(s)&&(l=64),t+=e.charAt(a)+e.charAt(o)+e.charAt(c)+e.charAt(l);return t},JH=n=>atob(n),FO=n=>{const e=JH(n),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let r=0;r{let t=String(n);for(;t.length{i+=h.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class SMe{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{const s=t.split(";");for(let a=0;a{h=h.trim(),h!==""&&(i.push(h),h="")},a=u=>{raa._Stack[r],c=()=>r===-1?"!!INVALID EXPRESSION!!":aa._Stack[r--];let l=0,h="";for(;l1){for(s();r!==-1&&aa._OperatorPriority[o()]>=aa._OperatorPriority[d];)i.push(c());a(d),l++}else h+=u;l++}for(s();r!==-1;)o()==="("?c():i.push(c());return aa._InfixToPostfixCache.size>=aa.InfixToPostfixCacheLimitSize&&aa.ClearCache(),aa._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(aa._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t":i=r>s;break;case"<":i=r=":i=r>=s;break;case"==":i=r===s;break;case"!=":i=r!==s;break}return i}}var Vs;(function(n){n[n.GLSL=0]="GLSL",n[n.WGSL=1]="WGSL"})(Vs||(Vs={}));const wMe=/defined\s*?\((.+?)\)/g,oY=/defined\s*?\[(.+?)\]/g,DMe=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,OMe=/__decl__/,Que=/light\{X\}.(\w*)/g,$ue=/\{X\}/g,pV=[];class Cd{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,r){var s;(s=t.processor)!=null&&s.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,a=>{t.processCodeAfterIncludes&&(a=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",a));const o=this._ProcessShaderConversion(a,t,r);i(o,a)})}static PreProcess(e,t,i,r){var s;(s=t.processor)!=null&&s.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,a=>{t.processCodeAfterIncludes&&(a=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",a));const o=this._ApplyPreProcessing(a,t,r);i(o,a)})}static Finalize(e,t,i){return!i.processor||!i.processor.finalizeShaders?{vertexCode:e,fragmentCode:t}:i.processor.finalizeShaders(e,t,i.processingContext)}static _ProcessPrecision(e,t){var r;if((r=t.processor)!=null&&r.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return e.indexOf("precision highp float")===-1?i?e=`precision highp float; `+e:e=`precision mediump float; `+e:i||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){const i=/defined\((.+)\)/.exec(e);if(i&&i.length)return new fV(i[1].trim(),e[0]==="!");const r=["==","!=",">=","<=","<",">"];let s="",a=0;for(s of r)if(a=e.indexOf(s),a>-1)break;if(a===-1)return new fV(e);const o=e.substring(0,a).trim(),c=e.substring(a+s.length).trim();return new PMe(o,s,c)}static _BuildSubExpression(e){e=e.replace(wMe,"defined[$1]");const t=aa.infixToPostfix(e),i=[];for(const s of t)if(s!=="||"&&s!=="&&")i.push(s);else if(i.length>=2){let a=i[i.length-1],o=i[i.length-2];i.length-=2;const c=s=="&&"?new IMe:new RMe;typeof a=="string"&&(a=a.replace(oY,"defined($1)")),typeof o=="string"&&(o=o.replace(oY,"defined($1)")),c.leftOperand=typeof o=="string"?this._ExtractOperation(o):o,c.rightOperand=typeof a=="string"?this._ExtractOperation(a):a,i.push(c)}let r=i[i.length-1];return typeof r=="string"&&(r=r.replace(oY,"defined($1)")),typeof r=="string"?this._ExtractOperation(r):r}static _BuildExpression(e,t){const i=new MMe,r=e.substring(0,t);let s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),r==="#ifdef"?i.testExpression=new fV(s):r==="#ifndef"?i.testExpression=new fV(s,!0):i.testExpression=this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let r=e.currentLine;for(;this._MoveCursor(e,i);){r=e.currentLine;const s=r.substring(0,5).toLowerCase();if(s==="#else"){const a=new uD;t.children.push(a),this._MoveCursor(e,a);return}else if(s==="#elif"){const a=this._BuildExpression(r,5);t.children.push(a),i=a}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const s=Cd._MoveCursorRegex.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{const o=new aY;t.children.push(o);const c=this._BuildExpression(i,6);o.children.push(c),this._MoveCursorWithinIf(e,o,c);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const o=new aY;t.children.push(o);const c=this._BuildExpression(i,7);o.children.push(c),this._MoveCursorWithinIf(e,o,c);break}case"#if":{const o=new aY,c=this._BuildExpression(i,3);t.children.push(o),o.children.push(c),this._MoveCursorWithinIf(e,o,c);break}}continue}}const r=new uD;if(r.line=i,t.children.push(r),i[0]==="#"&&i[1]==="d"){const s=i.replace(";","").split(" ");r.additionalDefineKey=s[1],s.length===3&&(r.additionalDefineValue=s[2])}}return!1}static _EvaluatePreProcessors(e,t,i){const r=new uD,s=new SMe;return s.lineIndex=-1,s.lines=e.split(` `),this._MoveCursor(s,r),r.process(t,i)}static _PreparePreProcessors(e,t){var s;const i=e.defines,r={};for(const a of i){const c=a.replace("#define","").replace(";","").trim().split(" ");r[c[0]]=c.length>1?c[1]:""}return((s=e.processor)==null?void 0:s.shaderLanguage)===Vs.GLSL&&(r.GL_ES="true"),r.__VERSION__=e.version,r[e.platformName]="true",t._getGlobalDefines(r),r}static _ProcessShaderConversion(e,t,i){let r=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===Vs.GLSL&&r.indexOf("#version 3")!==-1&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;const s=t.defines,a=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,s,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,a,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ApplyPreProcessing(e,t,i){var o,c;let r=e;const s=t.defines,a=this._PreparePreProcessors(t,i);return(o=t.processor)!=null&&o.preProcessor&&(r=t.processor.preProcessor(r,s,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,a,t),(c=t.processor)!=null&&c.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ProcessIncludes(e,t,i){pV.length=0;let r;for(;(r=DMe.exec(e))!==null;)pV.push(r);let s=String(e),a=[e],o=!1;for(const c of pV){let l=c[1];if(l.indexOf("__decl__")!==-1&&(l=l.replace(OMe,""),t.supportsUniformBuffers&&(l=l.replace("Vertex","Ubo").replace("Fragment","Ubo")),l=l+"Declaration"),t.includesShadersStore[l]){let h=t.includesShadersStore[l];if(c[2]){const d=c[3].split(",");for(let f=0;fx+"{X}")),h+=m.replace($ue,g.toString())+` `}else t.supportsUniformBuffers||(h=h.replace(Que,(f,p)=>p+"{X}")),h=h.replace($ue,d)}const u=[];for(const d of a){const f=d.split(c[0]);for(let p=0;p=0||h.indexOf("#include <")>=0}else{const h=t.shadersRepository+"ShadersInclude/"+l+".fx";Cd._FileToolsLoadFile(h,u=>{t.includesShadersStore[l]=u,this._ProcessIncludes(a.join(""),t,i)});return}}pV.length=0,s=a.join(""),o?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,r,s,a){throw ci("FileTools")}}Cd._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;class Re{static GetShadersRepository(e=Vs.GLSL){return e===Vs.GLSL?Re.ShadersRepository:Re.ShadersRepositoryWGSL}static GetShadersStore(e=Vs.GLSL){return e===Vs.GLSL?Re.ShadersStore:Re.ShadersStoreWGSL}static GetIncludesShadersStore(e=Vs.GLSL){return e===Vs.GLSL?Re.IncludesShadersStore:Re.IncludesShadersStoreWGSL}}Re.ShadersRepository="src/Shaders/";Re.ShadersStore={};Re.IncludesShadersStore={};Re.ShadersRepositoryWGSL="src/ShadersWGSL/";Re.ShadersStoreWGSL={};Re.IncludesShadersStoreWGSL={};class bi{static get ShadersRepository(){return Re.ShadersRepository}static set ShadersRepository(e){Re.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new Ae),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r=null,s,a=null,o=null,c=null,l=null,h,u="",d=Vs.GLSL){if(this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new Ae,this.onErrorObservable=new Ae,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=u,t.attributes){const f=t;if(this._engine=i,this._attributesNames=f.attributes,this._uniformsNames=f.uniformsNames.concat(f.samplers),this._samplerList=f.samplers.slice(),this.defines=f.defines,this.onError=f.onError,this.onCompiled=f.onCompiled,this._fallbacks=f.fallbacks,this._indexParameters=f.indexParameters,this._transformFeedbackVaryings=f.transformFeedbackVaryings||null,this._multiTarget=!!f.multiTarget,this._shaderLanguage=f.shaderLanguage??Vs.GLSL,f.uniformBuffersNames){this._uniformBuffersNamesList=f.uniformBuffersNames.slice();for(let p=0;p{if(c[0]&&c[1]){o.isFragment=!0;const[h,u]=c;Cd.Process(u,o,(d,f)=>{this._fragmentSourceCodeBeforeMigration=f,this._processFinalCode&&(d=this._processFinalCode("fragment",d));const p=Cd.Finalize(h,d,o);o=null,this._useFinalCode(p.vertexCode,p.fragmentCode,s,t)},this._engine)}};this._loadShader(i,"Vertex","",h=>{Cd.Initialize(o),Cd.Process(h,o,(u,d)=>{this._rawVertexSourceCode=h,this._vertexSourceCodeBeforeMigration=d,this._processFinalCode&&(u=this._processFinalCode("vertex",u)),c[0]=u,l()},this._engine)}),this._loadShader(r,"Fragment","Pixel",h=>{this._rawFragmentSourceCode=h,c[1]=h,l()})}_useFinalCode(e,t,i,r=!1){if(i){const s=i.vertexElement||i.vertex||i.spectorName||i,a=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===Vs.WGSL?"//":"")+"#define SHADER_NAME vertex:"+s+` `+e,this._fragmentSourceCode=(this._shaderLanguage===Vs.WGSL?"//":"")+"#define SHADER_NAME fragment:"+a+` `+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect(r)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){if(typeof HTMLElement<"u"&&e instanceof HTMLElement){const o=NO(e);r(o);return}if(e.substr(0,7)==="source:"){r(e.substr(7));return}if(e.substr(0,7)==="base64:"){const o=window.atob(e.substr(7));r(o);return}const s=Re.GetShadersStore(this._shaderLanguage);if(s[e+t+"Shader"]){r(s[e+t+"Shader"]);return}if(i&&s[e+i+"Shader"]){r(s[e+i+"Shader"]);return}let a;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?a=e:a=Re.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(a+"."+t.toLowerCase()+".fx",r)}get vertexSourceCode(){var e;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:((e=this._pipelineContext)==null?void 0:e._getVertexShaderCode())??this._vertexSourceCode}get fragmentSourceCode(){var e;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:((e=this._pipelineContext)==null?void 0:e._getFragmentShaderCode())??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(s,a)=>{r&&r(a)},this.onCompiled=()=>{var a,o;const s=this.getEngine().scenes;if(s)for(let c=0;cthis._rebuildProgram(o,c,l,h);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?s._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,a,null,this._transformFeedbackVaryings,this._key):s._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,a,i,this._transformFeedbackVaryings,this._key),s._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,t,this._attributes),t)for(let o=0;o=o&&(s=`Offending line [${o}] in ${i?"fragment":"vertex"} code: ${c[o-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var a,o,c;this._compilationError=e.message;const i=this._attributesNames,r=this._fallbacks;if(de.Error("Unable to compile effect:"),de.Error("Uniforms: "+this._uniformsNames.map(function(l){return" "+l})),de.Error("Attributes: "+i.map(function(l){return" "+l})),de.Error(`Defines: `+this.defines),bi.LogShaderCodeOnCompilationError){let l=null,h=null,u=null;(a=this._pipelineContext)!=null&&a._getVertexShaderCode()&&([u,l]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),u&&(de.Error("Vertex code:"),de.Error(u))),(o=this._pipelineContext)!=null&&o._getFragmentShaderCode()&&([u,h]=this._getShaderCodeAndErrorLine((c=this._pipelineContext)==null?void 0:c._getFragmentShaderCode(),this._compilationError,!0),u&&(de.Error("Fragment code:"),de.Error(u))),l&&de.Error(l),h&&de.Error(h)}de.Error("Error: "+this._compilationError);const s=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,s()),r?(this._pipelineContext=null,r.hasMoreFallbacks?(this._allFallbacksProcessed=!1,de.Error("Trying next fallback."),this.defines=r.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,s(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||s())}get isSupported(){return this._compilationError===""}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(this._samplerList.indexOf(i+"0")===-1){const r=this._samplerList.indexOf(e);for(let a=1;a{r._swapAndDie(this,!1),this.isReady=t.isReady};t.isAsync?t.proxy.then(i):i(t.proxy);return}let e;switch(this.source){case mi.Temp:break;case mi.Url:e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,t=>{t._swapAndDie(this,!1),this.isReady=!0},null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer);return;case mi.Raw:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case mi.Raw3D:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case mi.Raw2DArray:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case mi.Dynamic:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case mi.Cube:e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer);return;case mi.CubeRaw:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case mi.CubeRawRGBD:return;case mi.CubePrefiltered:e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,t=>{t&&t._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),e._sphericalPolynomial=this._sphericalPolynomial;return;case mi.DepthStencil:case mi.Depth:break}}_swapAndDie(e,t=!0){var s;(s=this._hardwareTexture)==null||s.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let r=i.indexOf(this);r!==-1&&i.splice(r,1),r=i.indexOf(e),r===-1&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._references===0&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}Ar._Counter=0;class LMe{constructor(){this.shaderLanguage=Vs.GLSL}postProcessor(e,t,i,r,s){if(!s.getCaps().drawBuffersExtension){const a=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(a,"")}return e}}const NMe=/(flat\s)?\s*varying\s*.*/;class IJ{constructor(){this.shaderLanguage=Vs.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return NMe.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const r=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,s=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(s,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){const a=e.search(/layout *\(location *= *0\) *out/g)!==-1;e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/void\s+?main\s*\(/g,(r||a?"":`layout(location = 0) out vec4 glFragColor; `)+"void main(")}else if(t.indexOf("#define MULTIVIEW")!==-1)return`#extension GL_OVR_multiview2 : require layout (num_views = 2) in; `+e;return e}}class Jp{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=Jp._Counter++}}Jp._Counter=0;class z8 extends Jp{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class eme{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return this.program?this.isParallelCompiled?this.engine._isRenderingStateCompiled(this):!0:!1}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,r,s,a,o,c){const l=this.engine;if(l.supportsUniformBuffers)for(const d in t)e.bindUniformBlock(d,t[d]);this.engine.getUniforms(this,i).forEach((d,f)=>{r[i[f]]=d}),this._uniforms=r;let u;for(u=0;u{a[d]=f});for(const d of l.getAttributes(this,o))c.push(d)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],r=t.updateFlag;return i!==void 0&&i===r?!1:(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||r.length!==2)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||s.length!==3)return s=[t,i,r],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==r&&(s[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,s){let a=this._valueCache[e];if(!a||a.length!==4)return a=[t,i,r,s],this._valueCache[e]=a,!0;let o=!1;return a[0]!==t&&(a[0]=t,o=!0),a[1]!==i&&(a[1]=i,o=!0),a[2]!==r&&(a[2]=r,o=!0),a[3]!==s&&(a[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setUInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setFloat4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}class j6{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&(e=t.createTexture(),!e))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t;return((t=this._MSAARenderBuffers)==null?void 0:t[e])??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class Sn{static IsWrapper(e){return e.getPipelineContext===void 0}static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var r;this.effect=e,t!==void 0&&(this.defines=t),i&&((r=this.drawContext)==null||r.reset())}dispose(){var e;(e=this.drawContext)==null||e.dispose()}}class PJ{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){var e;this.stencilMaterial=void 0,(e=this.stencilGlobal)==null||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var i;if(!e)return;const t=!this.useStencilGlobalOnly&&!!((i=this.stencilMaterial)!=null&&i.enabled);this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}class BMe{}class yt{static get NpmPackage(){return"babylonjs@6.48.1"}static get Version(){return"6.48.1"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return bi.ShadersRepository}static set ShadersRepository(e){bi.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if(typeof document>"u")return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return yt._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,r){var l,h;this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new Ae,this._frameId=0,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._activeRenderLoops=new Array,this.onContextLostObservable=new Ae,this.onContextRestoredObservable=new Ae,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new MJ,this._stencilStateComposer=new PJ,this._stencilState=new U0,this._alphaState=new J_e,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=new Array,this._renderTargetWrapperCache=new Array,this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._currentRenderTarget=null,this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._boundRenderFunction=()=>this._renderLoop(),this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._frameHandler=0,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=new Array,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new Ae,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=gr.Now;let s=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=r??!1,this._stencilStateComposer.stencilGlobal=this._stencilState,bo.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=t??i.antialias,i.deterministicLockstep=i.deterministicLockstep??!1,i.lockstepMaxSteps=i.lockstepMaxSteps??4,i.timeStep=i.timeStep??1/60,i.audioEngine=i.audioEngine??!0,i.stencil=i.stencil??!0,this._audioContext=((l=i.audioEngineOptions)==null?void 0:l.audioContext)??null,this._audioDestination=((h=i.audioEngineOptions)==null?void 0:h.audioDestination)??null,this.premultipliedAlpha=i.premultipliedAlpha??!0,this.useExactSrgbConversions=i.useExactSrgbConversions??!1,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,r=r||i.adaptToDeviceRatio||!1;const a=io()&&window.devicePixelRatio||1,o=i.limitDeviceRatio||a;if(this._hardwareScalingLevel=r?1/Math.min(o,a):1,this._lastDevicePixelRatio=a,!e)return;if(e.getContext){if(s=e,this._renderingCanvas=s,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const u=navigator.userAgent;for(const d of yt.ExceptionList){const f=d.key,p=d.targets;if(new RegExp(f).test(u)){if(d.capture&&d.captureConstraint){const m=d.capture,g=d.captureConstraint,x=new RegExp(m).exec(u);if(x&&x.length>0&&parseInt(x[x.length-1])>=g)continue}for(const m of p)switch(m){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1;break}}}}if(this._doNotHandleContextLost||(this._onContextLost=u=>{u.preventDefault(),this._contextWasLost=!0,de.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},s.addEventListener("webglcontextlost",this._onContextLost,!1),s.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=s.getContext("webgl2",i)||s.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch{}if(!this._gl){if(!s)throw new Error("The provided canvas is null or undefined.");try{this._gl=s.getContext("webgl",i)||s.getContext("experimental-webgl",i)}catch{throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const u=this._gl.getContextAttributes();u&&(i.stencil=u.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),i.useHighPrecisionFloats!==void 0&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let u=0;u1?new IJ:new LMe,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const c=`Babylon.js v${yt.Version}`;de.Log(c+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",c)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&Ny()&&"ontouchend"in document},this._checkForMobile(),io()&&window.addEventListener("resize",this._checkForMobile))}_clearEmptyResources(){this._dummyFramebuffer=null,this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}_rebuildGraphicsResources(){var e;this.wipeCaches(!0),this._rebuildEffects(),(e=this._rebuildComputeEffects)==null||e.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){de.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout(async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=s,this._flagContextRestored()},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}bi.ResetCache()}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}_rebuildTextures(){}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||this._gl.getExtension("OES_standard_derivatives")!==null,maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:this._webGLVersion!==1,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(e!=null&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const t=this._gl.getExtension("WEBGL_draw_buffers");if(t!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=t.drawBuffersWEBGL.bind(t),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let i=0;i<16;i++)this._gl["COLOR_ATTACHMENT"+i+"_WEBGL"]=t["COLOR_ATTACHMENT"+i+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const t=this._gl.getExtension("WEBGL_depth_texture");t!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=t.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const t=this._gl.getExtension("OES_vertex_array_object");t!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=t.createVertexArrayOES.bind(t),this._gl.bindVertexArray=t.bindVertexArrayOES.bind(t),this._gl.deleteVertexArray=t.deleteVertexArrayOES.bind(t))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const t=this._gl.getExtension("ANGLE_instanced_arrays");t!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=t.drawArraysInstancedANGLE.bind(t),this._gl.drawElementsInstanced=t.drawElementsInstancedANGLE.bind(t),this._gl.vertexAttribDivisor=t.vertexAttribDivisorANGLE.bind(t)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const t=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),i=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);t&&i&&(this._caps.highPrecisionShaderSupported=t.precision!==0&&i.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const t=this._gl.getExtension("EXT_blend_minmax");t!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=t.MAX_EXT,this._gl.MIN=t.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const t=this._gl.getExtension("EXT_sRGB");t!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:t.SRGB_EXT,SRGB8:t.SRGB_ALPHA_EXT,SRGB8_ALPHA8:t.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!!(this._creationOptions&&this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let t=0;t"u",supportRenderAndCopyToLodForFloatTextures:this._webGLVersion!==1,supportDepthStencilTexture:this._webGLVersion!==1,supportShadowSamplers:this._webGLVersion!==1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:this._webGLVersion!==1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:this._webGLVersion!==1,basisNeedsPOT:this._webGLVersion===1,support3DTextures:this._webGLVersion!==1,needTypeSuffixInShaderConstants:this._webGLVersion!==1,supportMSAA:this._webGLVersion!==1,supportSSAO2:this._webGLVersion!==1,supportExtendedTextureFormats:this._webGLVersion!==1,supportSwitchCaseInShader:this._webGLVersion!==1,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}get isStencilEnable(){return this._isStencilEnable}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);const e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}getLoadedTexturesCache(){return this._internalTexturesCache}getCaps(){return this._caps}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._frameHandler!==0){const e=this._frameHandler;if(this._frameHandler=0,io()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if(typeof t=="function")return t(e)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(e);return clearTimeout(e)}}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let t=0;t=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const r=e.program,s=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,s,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,r,s,a,o){const c=this._currentBufferPointers[t];if(!c)return;let l=!1;c.active?(c.buffer!==e&&(c.buffer=e,l=!0),c.size!==i&&(c.size=i,l=!0),c.type!==r&&(c.type=r,l=!0),c.normalized!==s&&(c.normalized=s,l=!0),c.stride!==a&&(c.stride=a,l=!0),c.offset!==o&&(c.offset=o,l=!0)):(l=!0,c.active=!0,c.index=t,c.size=i,c.type=r,c.normalized=s,c.stride=a,c.offset=o,c.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,a,o):this._gl.vertexAttribPointer(t,i,r,s,a,o))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){const o=r[s];let c=null;if(i&&(c=i[o]),c||(c=e[o]),!c)continue;this._gl.enableVertexAttribArray(a),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[a]=!0);const l=c.getBuffer();l&&(this._vertexAttribPointer(l,a,c.getSize(),c.type,c.normalized,c.byteStride,c.byteOffset),c.getIsInstanced()&&(this._gl.vertexAttribDivisor(a,c.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(a),this._currentInstanceBuffers.push(l))))}}}recordVertexArrayObject(e,t,i,r){const s=this._gl.createVertexArray();if(!s)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=t!=null&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,r,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;const a=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let o=0;for(let c=0;c=0&&(this._gl.enableVertexAttribArray(l),this._vertexAttribArraysEnabled[l]=!0,this._vertexAttribPointer(e,l,i[c],this._gl.FLOAT,!1,r,o)),o+=i[c]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,r){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1?`#version 300 es #define WEBGL2 `:"",c=this._compileShader(t,"vertex",r,o),l=this._compileShader(i,"fragment",r,o);return this._createShaderProgram(e,c,l,s,a)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new eme;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,r,s=null){const a=r.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");return r.attachShader(a,t),r.attachShader(a,i),r.linkProgram(a),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),a}_finalizePipelineContext(e){const t=e.context,i=e.vertexShader,r=e.fragmentShader,s=e.program;if(!t.getProgramParameter(s,t.LINK_STATUS)){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){const c=this._gl.getShaderInfoLog(i);if(c)throw e.vertexCompilationError=c,new Error("VERTEX SHADER "+c)}if(!this._gl.getShaderParameter(r,this._gl.COMPILE_STATUS)){const c=this._gl.getShaderInfoLog(r);if(c)throw e.fragmentCompilationError=c,new Error("FRAGMENT SHADER "+c)}const o=t.getProgramInfoLog(s);if(o)throw e.programLinkError=o,new Error(o)}if(this.validateShaderPrograms&&(t.validateProgram(s),!t.getProgramParameter(s,t.VALIDATE_STATUS))){const c=t.getProgramInfoLog(s);if(c)throw e.programValidationError=c,new Error(c)}t.deleteShader(i),t.deleteShader(r),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,r,s,a,o,c,l,h){const u=e;r?u.program=this.createRawShaderProgram(u,t,i,void 0,l):u.program=this.createShaderProgram(u,t,i,c,void 0,l),u.program.__SPECTOR_rebuildProgram=o}_isRenderingStateCompiled(e){const t=e;return this._isDisposed||t._isDisposed?!1:this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)?(this._finalizePipelineContext(t),!0):!1}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!i.isParallelCompiled){t();return}const r=i.onCompiled;r?i.onCompiled=()=>{r(),t()}:i.onCompiled=t}getUniforms(e,t){const i=new Array,r=e;for(let s=0;s1||this.isWebGPU)),(a===1&&!this._caps.textureFloatLinearFiltering||a===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),a===1&&!this._caps.textureFloat&&(a=0,de.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=this._gl,f=new Ar(this,r),p=e.width||e,_=e.height||e,m=e.layers||0,g=this._getSamplingParameters(o,s),v=m!==0?d.TEXTURE_2D_ARRAY:d.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(a,c,l),y=this._getInternalFormat(c),C=this._getWebGLTextureType(a);return this._bindTextureDirectly(v,f),m!==0?(f.is2DArray=!0,d.texImage3D(v,0,x,p,_,m,0,y,C,null)):d.texImage2D(v,0,x,p,_,0,y,C,null),d.texParameteri(v,d.TEXTURE_MAG_FILTER,g.mag),d.texParameteri(v,d.TEXTURE_MIN_FILTER,g.min),d.texParameteri(v,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(v,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),s&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),f._useSRGBBuffer=l,f.baseWidth=p,f.baseHeight=_,f.width=p,f.height=_,f.depth=m,f.isReady=!0,f.samples=h,f.generateMipMaps=s,f.samplingMode=o,f.type=a,f.format=c,f.label=u,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,r,s=3,a=null,o=null,c,l,h=null,u=null,d=null,f=null,p,_,m){e=e||"";const g=e.substr(0,5)==="data:",v=e.substr(0,5)==="blob:",x=g&&e.indexOf(";base64,")!==-1,y=u||new Ar(this,mi.Url);y!==u&&(y.label=e.substring(0,60));const C=e;this._transformTextureUrl&&!x&&!u&&!h&&(e=this._transformTextureUrl(e)),C!==e&&(y._originalUrl=C);const b=e.lastIndexOf(".");let T=f||(b>-1?e.substring(b).toLowerCase():""),S=null;T.indexOf("?")>-1&&(T=T.split("?")[0]);for(const I of yt._TextureLoaders)if(I.canLoad(T,p)){S=I;break}r&&r.addPendingData(y),y.url=e,y.generateMipMaps=!t,y.samplingMode=s,y.invertY=i,y._useSRGBBuffer=this._getUseSRGBBuffer(!!m,t),this._doNotHandleContextLost||(y._buffer=h);let D=null;a&&!u&&(D=y.onLoadedObservable.add(a)),u||this._internalTexturesCache.push(y);const M=(I,R)=>{r&&r.removePendingData(y),e===C?(D&&y.onLoadedObservable.remove(D),bt.UseFallbackTexture&&e!==bt.FallbackTexture&&this._createTextureBase(bt.FallbackTexture,t,y.invertY,r,s,null,o,c,l,h,y),I=(I||"Unknown error")+(bt.UseFallbackTexture?" - Fallback texture was used":""),y.onErrorObservable.notifyObservers({message:I,exception:R}),o&&o(I,R)):(de.Warn(`Failed to load ${e}, falling back to ${C}`),this._createTextureBase(C,t,y.invertY,r,s,a,o,c,l,h,y,d,f,p,_,m))};if(S){const I=R=>{S.loadData(R,y,(O,H,G,Q,$,V)=>{V?M("TextureLoader failed to load data"):c(y,T,r,{width:O,height:H},y.invertY,!G,Q,()=>($(),!1),s)},_)};h?h instanceof ArrayBuffer?I(new Uint8Array(h)):ArrayBuffer.isView(h)?I(h):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,R=>I(new Uint8Array(R)),void 0,r?r.offlineProvider:void 0,!0,(R,O)=>{M("Unable to load "+(R&&R.responseURL,O))})}else{const I=R=>{v&&!this._doNotHandleContextLost&&(y._buffer=R),c(y,T,r,R,y.invertY,t,!1,l,s)};!g||x?h&&(typeof h.decoding=="string"||h.close)?I(h):yt._FileToolsLoadImage(e,I,M,r?r.offlineProvider:null,p,y.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof h=="string"||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?yt._FileToolsLoadImage(h,I,M,r?r.offlineProvider:null,p,y.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&I(h)}return y}createTexture(e,t,i,r,s=3,a=null,o=null,c=null,l=null,h=null,u=null,d,f,p,_){return this._createTextureBase(e,t,i,r,s,a,o,this._prepareWebGLTexture.bind(this),(m,g,v,x,y,C)=>{const b=this._gl,T=v.width===m&&v.height===g;y._creationFlags=p??0;const S=this._getTexImageParametersForCreateTexture(h,x,y._useSRGBBuffer);if(T)return b.texImage2D(b.TEXTURE_2D,0,S.internalFormat,S.format,S.type,v),!1;const N=this._caps.maxTextureSize;if(v.width>N||v.height>N||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=m,this._workingCanvas.height=g,this._workingContext.drawImage(v,0,0,v.width,v.height,0,0,m,g),b.texImage2D(b.TEXTURE_2D,0,S.internalFormat,S.format,S.type,this._workingCanvas),y.width=m,y.height=g),!1;{const D=new Ar(this,mi.Temp);this._bindTextureDirectly(b.TEXTURE_2D,D,!0),b.texImage2D(b.TEXTURE_2D,0,S.internalFormat,S.format,S.type,v),this._rescaleTexture(D,y,r,S.format,()=>{this._releaseTexture(D),this._bindTextureDirectly(b.TEXTURE_2D,y,!0),C()})}return!0},c,l,h,u,d,f,_)}_getTexImageParametersForCreateTexture(e,t,i){e==null&&(e=t===".jpg"&&!i?4:5);let r,s;return this.webGLVersion===1?(r=this._getInternalFormat(e,i),s=r):(r=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,i)),{internalFormat:s,format:r,type:this._gl.UNSIGNED_BYTE}}static _FileToolsLoadImage(e,t,i,r,s,a){throw ci("FileTools")}_rescaleTexture(e,t,i,r,s){}createRawTexture(e,t,i,r,s,a,o,c=null,l=0,h=0,u=!1){throw ci("Engine.RawTexture")}createRawCubeTexture(e,t,i,r,s,a,o,c=null){throw ci("Engine.RawTexture")}createRawTexture3D(e,t,i,r,s,a,o,c,l=null,h=0){throw ci("Engine.RawTexture")}createRawTexture2DArray(e,t,i,r,s,a,o,c,l=null,h=0){throw ci("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const r=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,s.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e}updateTextureDimensions(e,t,i,r=1){}updateTextureWrappingMode(e,t,i=null,r=null){const s=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&r!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(s,null)}_setupDepthStencilTexture(e,t,i,r,s,a=1){const o=t.width||t,c=t.height||t,l=t.layers||0;e.baseWidth=o,e.baseHeight=c,e.width=o,e.height=c,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=a,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=0,e._comparisonFunction=s;const h=this._gl,u=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(u,h.TEXTURE_MAG_FILTER,d.mag),h.texParameteri(u,h.TEXTURE_MIN_FILTER,d.min),h.texParameteri(u,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(u,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(s===0?(h.texParameteri(u,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(u,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(u,h.TEXTURE_COMPARE_FUNC,s),h.texParameteri(u,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,o=0){const c=this._gl;let l=c.TEXTURE_2D;if(e.isCube&&(l=c.TEXTURE_CUBE_MAP_POSITIVE_X+a),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=c.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=c.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=c.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=c.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=c.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=c.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=c.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}this._gl.compressedTexImage2D(l,o,t,i,r,0,s)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,a=!1){const o=this._gl,c=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=s===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let u=o.TEXTURE_2D;e.isCube&&(u=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const d=Math.round(Math.log(e.width)*Math.LOG2E),f=Math.round(Math.log(e.height)*Math.LOG2E),p=a?e.width:Math.pow(2,Math.max(d-r,0)),_=a?e.height:Math.pow(2,Math.max(f-r,0));o.texImage2D(u,r,h,p,_,0,l,c,t)}updateTextureData(e,t,i,r,s,a,o=0,c=0,l=!1){const h=this._gl,u=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let f=h.TEXTURE_2D,p=h.TEXTURE_2D;e.isCube&&(p=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,f=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(f,e,!0),h.texSubImage2D(p,c,i,r,s,a,d,u,t),l&&this._gl.generateMipmap(p),this._bindTextureDirectly(f,null)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){const s=this._gl,a=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(a,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(a,null,!0)}_prepareWebGLTextureContinuation(e,t,i,r,s){const a=this._gl;if(!a)return;const o=this._getSamplingParameters(s,!i);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,o.mag),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,o.min),!i&&!r&&a.generateMipmap(a.TEXTURE_2D),this._bindTextureDirectly(a.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,r,s,a,o,c,l=3){const h=this.getCaps().maxTextureSize,u=Math.min(h,this.needPOTTextures?yt.GetExponentOfTwo(r.width,h):r.width),d=Math.min(h,this.needPOTTextures?yt.GetExponentOfTwo(r.height,h):r.height),f=this._gl;if(f){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(f.TEXTURE_2D,e,!0),this._unpackFlipY(s===void 0?!0:!!s),e.baseWidth=r.width,e.baseHeight=r.height,e.width=u,e.height=d,e.isReady=!0,e.type=e.type!==-1?e.type:0,e.format=e.format!==-1?e.format:t===".jpg"&&!e._useSRGBBuffer?4:5,!c(u,d,r,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,a,o,l)})&&this._prepareWebGLTextureContinuation(e,i,a,o,l)}}_setupFramebufferDepthAttachments(e,t,i,r,s=1){const a=this._gl;if(e&&t)return this._createRenderBuffer(i,r,s,a.DEPTH_STENCIL,a.DEPTH24_STENCIL8,a.DEPTH_STENCIL_ATTACHMENT);if(t){let o=a.DEPTH_COMPONENT16;return this._webGLVersion>1&&(o=a.DEPTH_COMPONENT32F),this._createRenderBuffer(i,r,s,o,o,a.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,r,s,a.STENCIL_INDEX8,a.STENCIL_INDEX8,a.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,r,s,a,o=!0){const l=this._gl.createRenderbuffer();return this._updateRenderBuffer(l,e,t,i,r,s,a,o)}_updateRenderBuffer(e,t,i,r,s,a,o,c=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),r>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,r,a,t,i):l.renderbufferStorage(l.RENDERBUFFER,s,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),c&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){var i;this._deleteTexture((i=e._hardwareTexture)==null?void 0:i.underlyingResource),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);t!==-1&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);t!==-1&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let r=0;r-1;if(i&&a&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw de.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,((c=t==null?void 0:t._hardwareTexture)==null?void 0:c.underlyingResource)??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(s=!0,this._activateCurrentTexture());return a&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),s}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;const r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,r){e!==void 0&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];!i||i._currentState===t||(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,r=!1,s=""){if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const l=t.getInternalTexture();l&&(l._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let a;r?a=t.depthStencilTexture:t.isReady()?a=t.getInternalTexture():t.isCube?a=this.emptyCubeTexture:t.is3D?a=this.emptyTexture3D:t.is2DArray?a=this.emptyTexture2DArray:a=this.emptyTexture,!i&&a&&(a._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===a&&(i||this._bindSamplerUniformToChannel(a._associatedChannel,e),o=!1),this._activeChannel=e;const c=this._getTextureTarget(a);if(o&&this._bindTextureDirectly(c,a,i),a&&!a.isMultiview){if(a.isCube&&a._cachedCoordinatesMode!==t.coordinatesMode){a._cachedCoordinatesMode=t.coordinatesMode;const l=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=l,t.wrapV=l}a._cachedWrapU!==t.wrapU&&(a._cachedWrapU=t.wrapU,this._setTextureParameterInteger(c,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),a)),a._cachedWrapV!==t.wrapV&&(a._cachedWrapV=t.wrapV,this._setTextureParameterInteger(c,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),a)),a.is3D&&a._cachedWrapR!==t.wrapR&&(a._cachedWrapR=t.wrapR,this._setTextureParameterInteger(c,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),a)),this._setAnisotropicLevel(c,a,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,r){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let s=0;s=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e,t;this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),(e=this.releaseComputeEffects)==null||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},io()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,bi.ResetCache();for(const i of this._activeRequests)i.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._creationOptions.loseContextOnDispose&&((t=this._gl.getExtension("WEBGL_lose_context"))==null||t.loseContext())}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);const a=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&a===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const o=t.RGBA,c=t.UNSIGNED_BYTE,l=new Uint8Array(4);t.readPixels(0,0,1,1,o,c,l),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(this._webGLVersion===1){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;break}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER;break}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(this._webGLVersion===1){if(t!==void 0)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;case 11:return this._gl.RGBA16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;case 11:return this._gl.RGBA16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;case 11:return this._gl.RGBA32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;case 11:return this._gl.RGBA32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;case 5:return this._gl.RGBA32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;case 5:return this._gl.RGBA16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_loadFile(e,t,i,r,s,a){const o=yt._FileToolsLoadFile(e,t,i,r,s,a);return this._activeRequests.push(o),o.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),o}static _FileToolsLoadFile(e,t,i,r,s,a){throw ci("FileTools")}readPixels(e,t,i,r,s=!0,a=!0){const o=s?4:3,c=s?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(r*i*o);return a&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,r,c,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(this._HasMajorPerformanceCaveat!==null)return!this._HasMajorPerformanceCaveat;if(this._IsSupported===null)try{const e=this._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=t!=null&&!!window.WebGLRenderingContext}catch{this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(this._HasMajorPerformanceCaveat===null)try{const e=this._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch{this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}static FloorPOT(e){return e=e|e>>1,e=e|e>>2,e=e|e>>4,e=e|e>>8,e=e|e>>16,e-(e>>1)}static NearestPOT(e){const t=yt.CeilingPOT(e),i=yt.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let r;switch(i){case 1:r=yt.FloorPOT(e);break;case 2:r=yt.NearestPOT(e);break;case 3:default:r=yt.CeilingPOT(e);break}return Math.min(r,t)}static QueueNewFrame(e,t){if(io()){const{requestAnimationFrame:i}=t||window;if(typeof i=="function")return i(e)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:Ny()?document:null}}yt._TempClearColorUint32=new Uint32Array(4);yt._TempClearColorInt32=new Int32Array(4);yt.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}];yt._TextureLoaders=[];yt.CollisionsEpsilon=.001;yt._IsSupported=null;yt._HasMajorPerformanceCaveat=null;class H8{static SetImmediate(e){io()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const tme=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class G8 extends kf{constructor(e,t){super(e,z0.LoadFileError),this.name="LoadFileError",Zy._setPrototypeOf(this,G8.prototype),t instanceof on?this.request=t:this.file=t}}class BD extends kf{constructor(e,t){super(e,z0.RequestFileError),this.request=t,this.name="RequestFileError",Zy._setPrototypeOf(this,BD.prototype)}}class eG extends kf{constructor(e,t){super(e,z0.ReadFileError),this.file=t,this.name="ReadFileError",Zy._setPrototypeOf(this,eG.prototype)}}const eo={DefaultRetryStrategy:Q_e.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:n=>n,ScriptBaseUrl:"",ScriptPreprocessUrl:n=>n},ime=n=>(n=n.replace(/#/gm,"%23"),n),tG=(n,e)=>{if(!(n&&n.indexOf("data:")===0)&&eo.CorsBehavior)if(typeof eo.CorsBehavior=="string"||eo.CorsBehavior instanceof String)e.crossOrigin=eo.CorsBehavior;else{const t=eo.CorsBehavior(n);t&&(e.crossOrigin=t)}},w5=(n,e,t,i,r="",s)=>{const a=bt.LastCreatedEngine;if(typeof HTMLImageElement>"u"&&!(a!=null&&a._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let o,c=!1;n instanceof ArrayBuffer||ArrayBuffer.isView(n)?typeof Blob<"u"&&typeof URL<"u"?(o=URL.createObjectURL(new Blob([n],{type:r})),c=!0):o=`data:${r};base64,`+BO(n):n instanceof Blob?(o=URL.createObjectURL(n),c=!0):(o=ime(n),o=eo.PreprocessUrl(n));const l=C=>{if(t){const b=o||n.toString();t(`Error while trying to load image: ${b.indexOf("http")===0||b.length<=128?b:b.slice(0,128)+"..."}`,C)}};if(a!=null&&a._features.forceBitmapOverHTMLImageElement)return t2(o,C=>{a.createImageBitmap(new Blob([C],{type:r}),{premultiplyAlpha:"none",...s}).then(b=>{e(b),c&&URL.revokeObjectURL(o)}).catch(b=>{t&&t("Error while trying to load image: "+n,b)})},void 0,i||void 0,!0,(C,b)=>{l(b)}),null;const h=new Image;tG(o,h);const u=[],d=()=>{u.forEach(C=>{C.target.addEventListener(C.name,C.handler)})},f=()=>{u.forEach(C=>{C.target.removeEventListener(C.name,C.handler)}),u.length=0},p=()=>{f(),e(h),c&&h.src&&URL.revokeObjectURL(h.src)},_=C=>{f(),l(C),c&&h.src&&URL.revokeObjectURL(h.src)},m=C=>{if(C.blockedURI!==h.src)return;f();const b=new Error(`CSP violation of policy ${C.effectiveDirective} ${C.blockedURI}. Current policy is ${C.originalPolicy}`);bt.UseFallbackTexture=!1,l(b),c&&h.src&&URL.revokeObjectURL(h.src),h.src=""};u.push({target:h,name:"load",handler:p}),u.push({target:h,name:"error",handler:_}),u.push({target:document,name:"securitypolicyviolation",handler:m}),d();const g=o.substring(0,5)==="blob:",v=o.substring(0,5)==="data:",x=()=>{g||v||!on.IsCustomRequestAvailable?h.src=o:t2(o,(C,b,T)=>{const S=!r&&T?T:r,N=new Blob([C],{type:S}),D=URL.createObjectURL(N);c=!0,h.src=D},void 0,i||void 0,!0,(C,b)=>{l(b)})},y=()=>{i&&i.loadImage(o,h)};if(!g&&!v&&i&&i.enableTexturesOffline)i.open(y,x);else{if(o.indexOf("file:")!==-1){const C=decodeURIComponent(o.substring(5).toLowerCase());if(By.FilesToLoad[C]&&typeof URL<"u"){try{let b;try{b=URL.createObjectURL(By.FilesToLoad[C])}catch{b=URL.createObjectURL(By.FilesToLoad[C])}h.src=b,c=!0}catch{h.src=""}return h}}x()}return h},K8=(n,e,t,i,r)=>{const s=new FileReader,a={onCompleteObservable:new Ae,abort:()=>s.abort()};return s.onloadend=()=>a.onCompleteObservable.notifyObservers(a),r&&(s.onerror=()=>{r(new eG(`Unable to read ${n.name}`,n))}),s.onload=o=>{e(o.target.result)},t&&(s.onprogress=t),i?s.readAsArrayBuffer(n):s.readAsText(n),a},t2=(n,e,t,i,r,s,a)=>{if(n.name)return K8(n,e,t,r,s?h=>{s(void 0,h)}:void 0);const o=n;if(o.indexOf("file:")!==-1){let h=decodeURIComponent(o.substring(5).toLowerCase());h.indexOf("./")===0&&(h=h.substring(2));const u=By.FilesToLoad[h];if(u)return K8(u,e,t,r,s?d=>s(void 0,new G8(d.message,d.file)):void 0)}const{match:c,type:l}=rme(o);if(c){const h={onCompleteObservable:new Ae,abort:()=>()=>{}};try{const u=r?D5(o):DJ(o);e(u,void 0,l)}catch(u){s?s(void 0,u):de.Error(u.message||"Failed to parse the Data URL")}return H8.SetImmediate(()=>{h.onCompleteObservable.notifyObservers(h)}),h}return iG(o,(h,u)=>{e(h,u==null?void 0:u.responseURL,u==null?void 0:u.getResponseHeader("content-type"))},t,i,r,s?h=>{s(h.request,new G8(h.message,h.request))}:void 0,a)},iG=(n,e,t,i,r,s,a)=>{n=ime(n),n=eo.PreprocessUrl(n);const o=eo.BaseUrl+n;let c=!1;const l={onCompleteObservable:new Ae,abort:()=>c=!0},h=()=>{let u=new on,d=null,f;const p=()=>{u&&(t&&u.removeEventListener("progress",t),f&&u.removeEventListener("readystatechange",f),u.removeEventListener("loadend",_))};let _=()=>{p(),l.onCompleteObservable.notifyObservers(l),l.onCompleteObservable.clear(),t=void 0,f=null,_=null,s=void 0,a=void 0,e=void 0};l.abort=()=>{c=!0,_&&_(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),d!==null&&(clearTimeout(d),d=null),u=null};const m=v=>{const x=v.message||"Unknown error";s&&u?s(new BD(x,u)):de.Error(x)},g=v=>{if(u){if(u.open("GET",o),a)try{a(u)}catch(x){m(x);return}r&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),_&&u.addEventListener("loadend",_),f=()=>{if(!(c||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(f&&u.removeEventListener("readystatechange",f),u.status>=200&&u.status<300||u.status===0&&(!io()||wJ())){try{e&&e(r?u.response:u.responseText,u)}catch(C){m(C)}return}const x=eo.DefaultRetryStrategy;if(x){const C=x(o,u,v);if(C!==-1){p(),u=new on,d=setTimeout(()=>g(v+1),C);return}}const y=new BD("Error status: "+u.status+" "+u.statusText+" - Unable to load "+o,u);s&&s(y)}},u.addEventListener("readystatechange",f),u.send()}};g(0)};if(i&&i.enableSceneOffline){const u=f=>{f&&f.status>400?s&&s(f):h()},d=()=>{i&&i.loadFile(eo.BaseUrl+n,f=>{!c&&e&&e(f),l.onCompleteObservable.notifyObservers(l)},t?f=>{!c&&t&&t(f)}:void 0,u,r)};i.open(d,u)}else h();return l},wJ=()=>typeof location<"u"&&location.protocol==="file:",UO=n=>tme.test(n),rme=n=>{const e=tme.exec(n);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function D5(n){return FO(n.split(",")[1])}const DJ=n=>JH(n.split(",")[1]),FMe=()=>{yt._FileToolsLoadImage=w5,yt._FileToolsLoadFile=t2,Cd._FileToolsLoadFile=t2};FMe();let IS;const sme=(n,e,t,i,r,s,a,o,c,l)=>{IS={DecodeBase64UrlToBinary:n,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:r,LoadFile:s,LoadImage:a,ReadFile:o,RequestFile:c,SetCorsBehavior:l},Object.defineProperty(IS,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(h){t.DefaultRetryStrategy=h}}),Object.defineProperty(IS,"BaseUrl",{get:function(){return t.BaseUrl},set:function(h){t.BaseUrl=h}}),Object.defineProperty(IS,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(h){t.PreprocessUrl=h}}),Object.defineProperty(IS,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(h){t.CorsBehavior=h}})};sme(D5,DJ,eo,UO,wJ,t2,w5,K8,iG,tG);class dD{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=gn(e);if(t)return t;de.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let r=window||this;for(let s=0,a=i.length;s{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}const UMe={RandomId:mh};function FD(n){let e=1;do e*=2;while(ee.indexOf("/")?!1:e.indexOf("://"){t2(e,s=>{i(s)},void 0,void 0,t,(s,a)=>{r(a)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(Ee.ScriptBaseUrl&&e.startsWith(Ee._DefaultCdnUrl)){const i=Ee.ScriptBaseUrl[Ee.ScriptBaseUrl.length-1]==="/"?Ee.ScriptBaseUrl.substring(0,Ee.ScriptBaseUrl.length-1):Ee.ScriptBaseUrl;e=e.replace(Ee._DefaultCdnUrl,i)}return e=Ee.ScriptPreprocessUrl(e),t&&(e=Ee.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=Ee.GetBabylonScriptURL(e),Ee.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Ee.GetBabylonScriptURL(e),Ee.LoadScriptAsync(e)}static LoadScript(e,t,i,r){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(o){i==null||i(`Unable to load script '${e}' in worker`,o)}return}else if(!io()){i==null||i(`Cannot load script '${e}' outside of a window or a worker`);return}const s=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),r&&(a.id=r),a.onload=()=>{t&&t()},a.onerror=o=>{i&&i(`Unable to load script '${e}'`,o)},s.appendChild(a)}static LoadScriptAsync(e,t){return new Promise((i,r)=>{this.LoadScript(e,()=>{i()},(s,a)=>{r(a||new Error(s))},t)})}static ReadFileAsDataURL(e,t,i){const r=new FileReader,s={onCompleteObservable:new Ae,abort:()=>r.abort()};return r.onloadend=()=>{s.onCompleteObservable.notifyObservers(s)},r.onload=a=>{t(a.target.result)},r.onprogress=i,r.readAsDataURL(e),s}static ReadFile(e,t,i,r,s){return K8(e,t,i,r,s)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){ol.DeepCopy(e,t,i,r)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const c=atob(this.toDataURL(a,o).split(",")[1]),l=c.length,h=new Uint8Array(l);for(let u=0;ut(s)):e.toBlob(function(s){t(s)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const i=new Date;t="screenshot_"+((i.getFullYear()+"-"+(i.getMonth()+1)).slice(2)+"-"+i.getDate()+"_"+i.getHours()+"-"+("0"+i.getMinutes()).slice(-2))+".png"}Ee.Download(e,t)}else if(e&&typeof URL<"u"){const i=URL.createObjectURL(e),r=window.open("");if(!r)return;const s=r.document.createElement("img");s.onload=function(){URL.revokeObjectURL(i)},s.src=i,r.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if(typeof r=="string"||!t)this.ToBlob(e,function(a){a&&Ee.DownloadBlob(a,r),t&&t("")},i,s);else if(t){if(Ee._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(o=>{const c=new FileReader;c.readAsDataURL(o),c.onloadend=()=>{const l=c.result;t(l)}});return}const a=e.toDataURL(i,s);t(a)}}static Download(e,t){if(typeof URL>"u")return;const i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return typeof e[0]=="boolean"?e[0]:typeof e[1]=="boolean"?e[1]:!1}static CreateScreenshot(e,t,i,r,s="image/png",a=!1,o){throw ci("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",s){throw ci("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",a=1,o=!1,c,l=!1,h=!1,u=!0,d){throw ci("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,a=!1,o,c=!1,l=!1,h=!0,u){throw ci("ScreenshotTools")}static RandomId(){return mh()}static IsBase64(e){return UO(e)}static DecodeBase64(e){return D5(e)}static get errorsCount(){return de.errorsCount}static Log(e){de.Log(e)}static Warn(e){de.Warn(e)}static Error(e){de.Error(e)}static get LogCache(){return de.LogCache}static ClearLogCache(){de.ClearLogCache()}static set LogLevels(e){de.LogLevels=e}static set PerformanceLogLevel(e){if((e&Ee.PerformanceUserMarkLogLevel)===Ee.PerformanceUserMarkLogLevel){Ee.StartPerformanceCounter=Ee._StartUserMark,Ee.EndPerformanceCounter=Ee._EndUserMark;return}if((e&Ee.PerformanceConsoleLogLevel)===Ee.PerformanceConsoleLogLevel){Ee.StartPerformanceCounter=Ee._StartPerformanceConsole,Ee.EndPerformanceCounter=Ee._EndPerformanceConsole;return}Ee.StartPerformanceCounter=Ee._StartPerformanceCounterDisabled,Ee.EndPerformanceCounter=Ee._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Ee._Performance){if(!io())return;Ee._Performance=window.performance}!t||!Ee._Performance.mark||Ee._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!Ee._Performance.mark||(Ee._Performance.mark(e+"-End"),Ee._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Ee._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Ee._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return gr.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(r!=null?r+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return xy()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}Ee.UseCustomRequestHeaders=!1;Ee.CustomRequestHeaders=on.CustomRequestHeaders;Ee.GetDOMTextContent=NO;Ee._DefaultCdnUrl="https://cdn.babylonjs.com";Ee.GetAbsoluteUrl=typeof document=="object"?n=>{const e=document.createElement("a");return e.href=n,e.href}:typeof URL=="function"&&typeof location=="object"?n=>new URL(n,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};Ee.NoneLogLevel=de.NoneLogLevel;Ee.MessageLogLevel=de.MessageLogLevel;Ee.WarningLogLevel=de.WarningLogLevel;Ee.ErrorLogLevel=de.ErrorLogLevel;Ee.AllLogLevel=de.AllLogLevel;Ee.IsWindowObjectExist=io;Ee.PerformanceNoneLogLevel=0;Ee.PerformanceUserMarkLogLevel=1;Ee.PerformanceConsoleLogLevel=2;Ee.StartPerformanceCounter=Ee._StartPerformanceCounterDisabled;Ee.EndPerformanceCounter=Ee._EndPerformanceCounterDisabled;function kMe(n,e){return t=>{t.__bjsclassName__=n,t.__bjsmoduleName__=e??null}}class md{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?o.breakLoop():setTimeout(()=>{for(let c=0;c=e)break;if(i(l),s&&s()){o.breakLoop();break}}o.executeNext()},a)},r)}}Ee.Mix=T$;Ee.IsExponentOfTwo=FD;bt.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class ba{constructor(e){this.length=0,this.data=new Array(e),this._id=ba._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}}ba._GlobalId=0;class pm extends ba{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId?!1:(this.push(e),!0)}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;tthis.add(t,i))}get(e){const t=this._data[e];if(t!==void 0)return t}getOrAddWithFactory(e,t){let i=this.get(e);return i!==void 0||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return i!==void 0?i:(this.add(e,t),t)}contains(e){return this._data[e]!==void 0}add(e,t){return this._data[e]!==void 0?!1:(this._data[e]=t,++this._count,!0)}set(e,t){return this._data[e]===void 0?!1:(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return t!==void 0?(delete this._data[e],--this._count,t):null}remove(e){return this.contains(e)?(delete this._data[e],--this._count,!0):!1}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data){const i=this._data[t];e(t,i)}}first(e){for(const t in this._data){const i=this._data[t],r=e(t,i);if(r)return r}return null}}function nme(n){n.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class an{constructor(){this._dirty=!0,this._tempColor=new Ze(0,0,0,0),this._globalCurve=new Ze(0,0,0,0),this._highlightsCurve=new Ze(0,0,0,0),this._midtonesCurve=new Ze(0,0,0,0),this._shadowsCurve=new Ze(0,0,0,0),this._positiveCurve=new Ze(0,0,0,0),this._negativeCurve=new Ze(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",r="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,r,s){e!=null&&(e=an._Clamp(e,0,360),t=an._Clamp(t,-100,100),i=an._Clamp(i,-100,100),r=an._Clamp(r,-100,100),t=an._ApplyColorGradingSliderNonlinear(t),t*=.5,r=an._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),an._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,r){let s=an._Clamp(e,0,360);const a=an._Clamp(t/100,0,1),o=an._Clamp(i/100,0,1);if(a===0)r.r=o,r.g=o,r.b=o;else{s/=60;const c=Math.floor(s),l=s-c,h=o*(1-a),u=o*(1-a*l),d=o*(1-a*(1-l));switch(c){case 0:r.r=o,r.g=d,r.b=h;break;case 1:r.r=u,r.g=o,r.b=h;break;case 2:r.r=h,r.g=o,r.b=d;break;case 3:r.r=h,r.g=u,r.b=o;break;case 4:r.r=d,r.g=h,r.b=o;break;default:r.r=o,r.g=h,r.b=u;break}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return Qe.Clone(()=>new an,this)}serialize(){return Qe.Serialize(this)}static Parse(e){return Qe.Parse(()=>new an,e,null,null)}}an.PrepareUniforms=nme;B([K()],an.prototype,"_globalHue",void 0);B([K()],an.prototype,"_globalDensity",void 0);B([K()],an.prototype,"_globalSaturation",void 0);B([K()],an.prototype,"_globalExposure",void 0);B([K()],an.prototype,"_highlightsHue",void 0);B([K()],an.prototype,"_highlightsDensity",void 0);B([K()],an.prototype,"_highlightsSaturation",void 0);B([K()],an.prototype,"_highlightsExposure",void 0);B([K()],an.prototype,"_midtonesHue",void 0);B([K()],an.prototype,"_midtonesDensity",void 0);B([K()],an.prototype,"_midtonesSaturation",void 0);B([K()],an.prototype,"_midtonesExposure",void 0);Qe._ColorCurvesParser=an.Parse;function ame(n,e){e.EXPOSURE&&n.push("exposureLinear"),e.CONTRAST&&n.push("contrast"),e.COLORGRADING&&n.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&n.push("vInverseScreenSize"),e.VIGNETTE&&(n.push("vignetteSettings1"),n.push("vignetteSettings2")),e.COLORCURVES&&nme(n),e.DITHER&&n.push("ditherIntensity")}function ome(n,e){e.COLORGRADING&&n.push("txColorTransform")}class Ji{constructor(){this.colorCurves=new an,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Ji.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Ze(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Ji.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new Ae}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}switch(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===Ji._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType){case Ji.TONEMAPPING_ACES:e.TONEMAPPING_ACES=!0;break;default:e.TONEMAPPING_ACES=!1;break}e.CONTRAST=this.contrast!==1,e.EXPOSURE=this.exposure!==1,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&an.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),r=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const s=t??r/i;let a=Math.tan(this.vignetteCameraFov*.5),o=a*s;const c=Math.sqrt(o*a);o=T$(o,c,this.vignetteStretch),a=T$(a,c,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,a,-o*this.vignetteCenterX,-a*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return Qe.Clone(()=>new Ji,this)}serialize(){return Qe.Serialize(this)}static Parse(e){const t=Qe.Parse(()=>new Ji,e,null,null);return e.vignetteCentreX!==void 0&&(t.vignetteCenterX=e.vignetteCentreX),e.vignetteCentreY!==void 0&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}Ji.TONEMAPPING_STANDARD=0;Ji.TONEMAPPING_ACES=1;Ji.PrepareUniforms=ame;Ji.PrepareSamplers=ome;Ji._VIGNETTEMODE_MULTIPLY=0;Ji._VIGNETTEMODE_OPAQUE=1;B([K_e()],Ji.prototype,"colorCurves",void 0);B([K()],Ji.prototype,"_colorCurvesEnabled",void 0);B([$t("colorGradingTexture")],Ji.prototype,"_colorGradingTexture",void 0);B([K()],Ji.prototype,"_colorGradingEnabled",void 0);B([K()],Ji.prototype,"_colorGradingWithGreenDepth",void 0);B([K()],Ji.prototype,"_colorGradingBGR",void 0);B([K()],Ji.prototype,"_exposure",void 0);B([K()],Ji.prototype,"_toneMappingEnabled",void 0);B([K()],Ji.prototype,"_toneMappingType",void 0);B([K()],Ji.prototype,"_contrast",void 0);B([K()],Ji.prototype,"vignetteStretch",void 0);B([K()],Ji.prototype,"vignetteCenterX",void 0);B([K()],Ji.prototype,"vignetteCenterY",void 0);B([K()],Ji.prototype,"vignetteWeight",void 0);B([P5()],Ji.prototype,"vignetteColor",void 0);B([K()],Ji.prototype,"vignetteCameraFov",void 0);B([K()],Ji.prototype,"_vignetteBlendMode",void 0);B([K()],Ji.prototype,"_vignetteEnabled",void 0);B([K()],Ji.prototype,"_ditheringEnabled",void 0);B([K()],Ji.prototype,"_ditheringIntensity",void 0);B([K()],Ji.prototype,"_skipFinalColorClamp",void 0);B([K()],Ji.prototype,"_applyByPostProcess",void 0);B([K()],Ji.prototype,"_isEnabled",void 0);Qe._ImageProcessingConfigurationParser=Ji.Parse;yt.prototype.createUniformBuffer=function(n,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new z8(t);return this.bindUniformBuffer(i),n instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,n,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(n),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};yt.prototype.createDynamicUniformBuffer=function(n,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new z8(t);return this.bindUniformBuffer(i),n instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,n,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(n),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};yt.prototype.updateUniformBuffer=function(n,e,t,i){this.bindUniformBuffer(n),t===void 0&&(t=0),i===void 0?e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,e):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,new Float32Array(e)):e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,e.subarray(t,t+i)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(e).subarray(t,t+i)),this.bindUniformBuffer(null)};yt.prototype.bindUniformBuffer=function(n){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,n?n.underlyingResource:null)};yt.prototype.bindUniformBufferBase=function(n,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,n?n.underlyingResource:null)};yt.prototype.bindUniformBlock=function(n,e,t){const i=n.program,r=this._gl.getUniformBlockIndex(i,e);r!==4294967295&&this._gl.uniformBlockBinding(i,r,t)};class Ft{constructor(e,t,i,r,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=r??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return this._dynamic!==void 0}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(e<=2?t=e:t=4,this._uniformLocationPointer%t!==0){const i=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const r=this._uniformLocationPointer-i;for(let s=0;s0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},t==16)t=t*i;else{const a=(4-t)*i;t=t*i+a}r=[];for(let s=0;s1&&this._buffers[this._bufferIndex][1])if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}else this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1]);this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(Ft._UpdatedUbosInFrame[this._name]||(Ft._UpdatedUbosInFrame[this._name]=0),Ft._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._needSync=this._bufferIndex!==0,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(r===void 0){if(this._buffer){de.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let s=0;s0){this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label);return}de.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),t===0&&i===void 0?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}};class Z{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,r,s,a,o,c,l,h,u=!1,d=!1,f=1,p=!1){this._isDisposed=!1;let _=!1;if(this.engine=e,typeof r=="object"&&r!==null?(_=r.updatable??!1,s=r.postponeInternalCreation,a=r.stride,o=r.instanced,c=r.offset,l=r.size,h=r.type,u=r.normalized??!1,d=r.useBytes??!1,f=r.divisor??1,p=r.takeBufferOwnership??!1,this._label=r.label):_=!!r,t instanceof no?(this._buffer=t,this._ownsBuffer=p):(this._buffer=new no(e,t,_,a,s,o,d,f,this._label),this._ownsBuffer=!0),this.uniqueId=Z._Counter++,this._kind=i,h===void 0){const g=this.getData();this.type=g?Z.GetDataType(g):Z.FLOAT}else this.type=h;const m=Z.GetTypeByteLength(this.type);d?(this._size=l||(a?a/m:Z.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*m,this.byteOffset=c||0):(this._size=l||a||Z.DeduceStride(i),this.byteStride=a?a*m:this._buffer.byteStride||this._size*m,this.byteOffset=(c||0)*m),this.normalized=u,this._instanced=o!==void 0?o:!1,this._instanceDivisor=o?f:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){var e;(e=this._buffer)==null||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?Z.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Z.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/Z.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*Z.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){Z.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case Z.UVKind:case Z.UV2Kind:case Z.UV3Kind:case Z.UV4Kind:case Z.UV5Kind:case Z.UV6Kind:return 2;case Z.NormalKind:case Z.PositionKind:return 3;case Z.ColorKind:case Z.ColorInstanceKind:case Z.MatricesIndicesKind:case Z.MatricesIndicesExtraKind:case Z.MatricesWeightsKind:case Z.MatricesWeightsExtraKind:case Z.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?Z.BYTE:e instanceof Uint8Array?Z.UNSIGNED_BYTE:e instanceof Int16Array?Z.SHORT:e instanceof Uint16Array?Z.UNSIGNED_SHORT:e instanceof Int32Array?Z.INT:e instanceof Uint32Array?Z.UNSIGNED_INT:Z.FLOAT}static GetTypeByteLength(e){switch(e){case Z.BYTE:case Z.UNSIGNED_BYTE:return 1;case Z.SHORT:case Z.UNSIGNED_SHORT:return 2;case Z.INT:case Z.UNSIGNED_INT:case Z.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,r,s,a,o,c){if(e instanceof Array){let l=t/4;const h=i/4;for(let u=0;uu[f]=d),u}if(!(e instanceof Array||e instanceof Float32Array)||r!==0||e.length!==h)if(e instanceof Array){const u=r/4;return e.slice(u,u+h)}else{if(e instanceof ArrayBuffer)return new Float32Array(e,r,h);{let u=e.byteOffset+r;if(c){const f=new Float32Array(h),p=new Float32Array(e.buffer,u,h);return f.set(p),f}const d=u%4;return d&&(u=Math.max(0,u-d)),new Float32Array(e.buffer,u,h)}}return c?e.slice():e}}Z._Counter=0;Z.BYTE=5120;Z.UNSIGNED_BYTE=5121;Z.SHORT=5122;Z.UNSIGNED_SHORT=5123;Z.INT=5124;Z.UNSIGNED_INT=5125;Z.FLOAT=5126;Z.PositionKind="position";Z.NormalKind="normal";Z.TangentKind="tangent";Z.UVKind="uv";Z.UV2Kind="uv2";Z.UV3Kind="uv3";Z.UV4Kind="uv4";Z.UV5Kind="uv5";Z.UV6Kind="uv6";Z.ColorKind="color";Z.ColorInstanceKind="instanceColor";Z.MatricesIndicesKind="matricesIndices";Z.MatricesWeightsKind="matricesWeights";Z.MatricesIndicesExtraKind="matricesIndicesExtra";Z.MatricesWeightsExtraKind="matricesWeightsExtra";class Ro{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(Z.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let r;const s=ie.Vector3[0],a=ie.Vector3[1],o=ie.Vector3[2];if(t){const l=this.pickedMesh.getVerticesData(Z.NormalKind);let h=i?P.FromArrayToRef(l,i[this.faceId*3]*3,s):s.copyFromFloats(l[this.faceId*3*3],l[this.faceId*3*3+1],l[this.faceId*3*3+2]),u=i?P.FromArrayToRef(l,i[this.faceId*3+1]*3,a):a.copyFromFloats(l[(this.faceId*3+1)*3],l[(this.faceId*3+1)*3+1],l[(this.faceId*3+1)*3+2]),d=i?P.FromArrayToRef(l,i[this.faceId*3+2]*3,o):o.copyFromFloats(l[(this.faceId*3+2)*3],l[(this.faceId*3+2)*3+1],l[(this.faceId*3+2)*3+2]);h=h.scale(this.bu),u=u.scale(this.bv),d=d.scale(1-this.bu-this.bv),r=new P(h.x+u.x+d.x,h.y+u.y+d.y,h.z+u.z+d.z)}else{const l=this.pickedMesh.getVerticesData(Z.PositionKind),h=i?P.FromArrayToRef(l,i[this.faceId*3]*3,s):s.copyFromFloats(l[this.faceId*3*3],l[this.faceId*3*3+1],l[this.faceId*3*3+2]),u=i?P.FromArrayToRef(l,i[this.faceId*3+1]*3,a):a.copyFromFloats(l[(this.faceId*3+1)*3],l[(this.faceId*3+1)*3+1],l[(this.faceId*3+1)*3+2]),d=i?P.FromArrayToRef(l,i[this.faceId*3+2]*3,o):o.copyFromFloats(l[(this.faceId*3+2)*3],l[(this.faceId*3+2)*3+1],l[(this.faceId*3+2)*3+2]),f=h.subtract(u),p=d.subtract(u);r=P.Cross(f,p)}const c=(l,h)=>{let u=l.getWorldMatrix();l.nonUniformScaling&&(ie.Matrix[0].copyFrom(u),u=ie.Matrix[0],u.setTranslationFromFloats(0,0,0),u.invert(),u.transposeToRef(ie.Matrix[1]),u=ie.Matrix[1]),P.TransformNormalToRef(h,u,h)};if(e&&c(this.pickedMesh,r),this.ray){const l=ie.Vector3[0].copyFrom(r);e||c(this.pickedMesh,l),P.Dot(l,this.ray.direction)>0&&r.negateInPlace()}return r.normalize(),r}getTextureCoordinates(e=Z.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let r=Be.FromArray(i,t[this.faceId*3]*2),s=Be.FromArray(i,t[this.faceId*3+1]*2),a=Be.FromArray(i,t[this.faceId*3+2]*2);return r=r.scale(this.bu),s=s.scale(this.bv),a=a.scale(1-this.bu-this.bv),new Be(r.x+s.x+a.x,r.y+s.y+a.y)}}class UD{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[Z.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[Z.PositionKind]=new Z(this._scene.getEngine(),e,Z.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_rebuild(){const e=this._vertexBuffers[Z.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!i||(t=t||i._postProcesses.filter(r=>r!=null),!t||t.length===0||!this._scene.postProcessesEnabled)?!1:(t[0].activate(i,e,t!=null),!0)}directRender(e,t=null,i=!1,r=0,s=0,a=!1){var c;const o=this._scene.getEngine();for(let l=0;ll!=null),r.length===0||!this._scene.postProcessesEnabled))return;const o=this._scene.getEngine();for(let l=0,h=r.length;lt._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),i===void 0&&(i=e.getMaterial()),i!=null&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(this._particleSystems.length===0)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i=yi.LeftClick&&i<=yi.RightClick&&(c.type=r===1?"pointerdown":"pointerup",c.button=i-2),c}static _CreateWheelEvent(e,t,i,r,s,a){const o=this._CreateMouseEvent(e,t,i,r,s,a);switch(o.pointerId=1,o.type="wheel",o.deltaMode=X6.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case yi.MouseWheelX:o.deltaX=r;break;case yi.MouseWheelY:o.deltaY=r;break;case yi.MouseWheelZ:o.deltaZ=r;break}return o}static _CreateMouseEvent(e,t,i,r,s,a){const o=this._CreateEvent(a),c=s.pollInput(e,t,yi.Horizontal),l=s.pollInput(e,t,yi.Vertical);return a?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-a.getBoundingClientRect().x,o.offsetY=o.movementY-a.getBoundingClientRect().y):(o.movementX=s.pollInput(e,t,kD.DeltaHorizontal),o.movementY=s.pollInput(e,t,kD.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,s),o.clientX=c,o.clientY=l,o.x=c,o.y=l,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,r){const s=this._CreateEvent(r);return this._CheckNonCharacterKeys(s,i),s.deviceType=ii.Keyboard,s.deviceSlot=0,s.inputIndex=e,s.type=t===1?"keydown":"keyup",s.key=String.fromCharCode(e),s.keyCode=e,s}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(ii.Keyboard),r=i&&t.pollInput(ii.Keyboard,0,18)===1,s=i&&t.pollInput(ii.Keyboard,0,17)===1,a=i&&(t.pollInput(ii.Keyboard,0,91)===1||t.pollInput(ii.Keyboard,0,92)===1||t.pollInput(ii.Keyboard,0,93)===1),o=i&&t.pollInput(ii.Keyboard,0,16)===1;e.altKey=r,e.ctrlKey=s,e.metaKey=a,e.shiftKey=o}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class VMe{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(r,s,a,o)=>{const c=ly.CreateDeviceEvent(r,s,a,o,this);i(r,s,c)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===ii.Mouse||e===ii.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const Zue=255,que=Object.keys(yi).length/2;class zMe{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Ee.IsSafari(),this._usingMacOS=xy()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=s=>{},this._keyboardUpEvent=s=>{},this._keyboardBlurEvent=s=>{},this._pointerMoveEvent=s=>{},this._pointerDownEvent=s=>{},this._pointerUpEvent=s=>{},this._pointerCancelEvent=s=>{},this._pointerWheelEvent=s=>{},this._pointerBlurEvent=s=>{},this._pointerMacOSChromeOutEvent=s=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=xy()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=xy()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=s=>{},this._gamepadDisconnectedEvent=s=>{},this._eventPrefix=Ee.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const r=this._inputs[e][t];if(!r)throw`Unable to find device ${ii[e]}`;e>=ii.DualShock&&e<=ii.DualSense&&this._updateDevice(e,t,i);const s=r[i];if(s===void 0)throw`Unable to find input ${i} for device ${ii[e]} in slot ${t}`;return i===yi.Move&&Ee.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),s}isDeviceAvailable(e){return this._inputs[e]!==void 0}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this==null?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(const t of this._inputs)if(t)for(const i in t){const r=+i,s=t[r];if(s)for(let a=0;a{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ii.Keyboard,0,Zue));const t=this._inputs[ii.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&e.key!=="Meta"&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(ii.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ii.Keyboard,0,Zue));const t=this._inputs[ii.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&e.key==="Meta"&&this._metaKeys.length>0){for(const r of this._metaKeys){const s=ly.CreateDeviceEvent(ii.Keyboard,0,r,0,this,this._elementToAttachTo);t[r]=0,this._onInputChanged(ii.Keyboard,0,s)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(ii.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[ii.Keyboard][0];for(let t=0;t{const r=this._getPointerType(i);let s=r===ii.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(r===ii.Touch&&s===-1){const o=this._activeTouchIds.indexOf(-1);if(o>=0)s=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(r,s);else{Ee.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[r]||(this._inputs[r]={}),this._inputs[r][s]||this._addPointerDevice(r,s,i.clientX,i.clientY);const a=this._inputs[r][s];if(a){const o=i;o.inputIndex=yi.Move,a[yi.Horizontal]=i.clientX,a[yi.Vertical]=i.clientY,r===ii.Touch&&a[yi.LeftClick]===0&&(a[yi.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(r,s,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,a[i.button+2]=a[i.button+2]?0:1,this._onInputChanged(r,s,o))}},this._pointerDownEvent=i=>{const r=this._getPointerType(i);let s=r===ii.Mouse?0:i.pointerId;if(r===ii.Touch){const o=this._activeTouchIds.indexOf(-1);if(o>=0)s=o,this._activeTouchIds[o]=i.pointerId;else{Ee.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[r]||(this._inputs[r]={}),this._inputs[r][s]?r===ii.Touch&&this._onDeviceConnected(r,s):this._addPointerDevice(r,s,i.clientX,i.clientY);const a=this._inputs[r][s];if(a){const o=a[yi.Horizontal],c=a[yi.Vertical];if(r===ii.Mouse){if(i.pointerId===void 0&&(i.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch{}}else if(i.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(i.pointerId)}catch{}a[yi.Horizontal]=i.clientX,a[yi.Vertical]=i.clientY,a[i.button+2]=1;const l=i;l.inputIndex=i.button+2,this._onInputChanged(r,s,l),(o!==i.clientX||c!==i.clientY)&&(l.inputIndex=yi.Move,this._onInputChanged(r,s,l))}},this._pointerUpEvent=i=>{var o,c,l,h,u;const r=this._getPointerType(i),s=r===ii.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(r===ii.Touch){if(s===-1)return;this._activeTouchIds[s]=-1}const a=(o=this._inputs[r])==null?void 0:o[s];if(a&&a[i.button+2]!==0){const d=a[yi.Horizontal],f=a[yi.Vertical];a[yi.Horizontal]=i.clientX,a[yi.Vertical]=i.clientY,a[i.button+2]=0;const p=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(d!==i.clientX||f!==i.clientY)&&(p.inputIndex=yi.Move,this._onInputChanged(r,s,p)),p.inputIndex=i.button+2,r===ii.Mouse&&this._mouseId>=0&&((l=(c=this._elementToAttachTo).hasPointerCapture)!=null&&l.call(c,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&((u=(h=this._elementToAttachTo).hasPointerCapture)!=null&&u.call(h,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(r,s,p),r===ii.Touch&&this._onDeviceDisconnected(r,s)}},this._pointerCancelEvent=i=>{var r,s,a,o;if(i.pointerType==="mouse"){const c=this._inputs[ii.Mouse][0];this._mouseId>=0&&((s=(r=this._elementToAttachTo).hasPointerCapture)!=null&&s.call(r,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let l=yi.LeftClick;l<=yi.BrowserForward;l++)if(c[l]===1){c[l]=0;const h=ly.CreateDeviceEvent(ii.Mouse,0,l,0,this,this._elementToAttachTo);this._onInputChanged(ii.Mouse,0,h)}}else{const c=this._activeTouchIds.indexOf(i.pointerId);if(c===-1)return;(o=(a=this._elementToAttachTo).hasPointerCapture)!=null&&o.call(a,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[ii.Touch][c][yi.LeftClick]=0;const l=ly.CreateDeviceEvent(ii.Touch,c,yi.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(ii.Touch,c,l),this._activeTouchIds[c]=-1,this._onDeviceDisconnected(ii.Touch,c)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":document.onmousewheel!==void 0?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch{}this._pointerBlurEvent=()=>{var i,r,s,a,o;if(this.isDeviceAvailable(ii.Mouse)){const c=this._inputs[ii.Mouse][0];this._mouseId>=0&&((r=(i=this._elementToAttachTo).hasPointerCapture)!=null&&r.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let l=yi.LeftClick;l<=yi.BrowserForward;l++)if(c[l]===1){c[l]=0;const h=ly.CreateDeviceEvent(ii.Mouse,0,l,0,this,this._elementToAttachTo);this._onInputChanged(ii.Mouse,0,h)}}if(this.isDeviceAvailable(ii.Touch)){const c=this._inputs[ii.Touch];for(let l=0;l{const r=ii.Mouse,s=0;this._inputs[r]||(this._inputs[r]=[]),this._inputs[r][s]||(this._pointerActive=!0,this._registerDevice(r,s,que));const a=this._inputs[r][s];if(a){a[yi.MouseWheelX]=i.deltaX||0,a[yi.MouseWheelY]=i.deltaY||i.wheelDelta||0,a[yi.MouseWheelZ]=i.deltaZ||0;const o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),a[yi.MouseWheelX]!==0&&(o.inputIndex=yi.MouseWheelX,this._onInputChanged(r,s,o)),a[yi.MouseWheelY]!==0&&(o.inputIndex=yi.MouseWheelY,this._onInputChanged(r,s,o)),a[yi.MouseWheelZ]!==0&&(o.inputIndex=yi.MouseWheelZ,this._onInputChanged(r,s,o))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=i=>{i.buttons>1&&this._pointerCancelEvent(i)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,e?{passive:!1}:!1),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(ii.Mouse)){const i=this._inputs[ii.Mouse][0];i[yi.MouseWheelX]=0,i[yi.MouseWheelY]=0,i[yi.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){const s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?ii.DualSense:ii.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?ii.Xbox:e.indexOf("057e")!==-1?ii.Switch:ii.Generic}_getPointerType(e){let t=ii.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=ii.Touch),t}}class D${constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new Ae,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class HMe{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=a=>{for(let o=0;o{const o=this._registeredManagers.indexOf(a);o>-1&&this._registeredManagers.splice(o,1)};const t=Object.keys(ii).length/2;this._devices=new Array(t);const i=(a,o)=>{this._devices[a]||(this._devices[a]=new Array),this._devices[a][o]||(this._devices[a][o]=o);for(const c of this._registeredManagers){const l=new D$(this._deviceInputSystem,a,o);c._addDevice(l)}},r=(a,o)=>{var c;(c=this._devices[a])!=null&&c[o]&&delete this._devices[a][o];for(const l of this._registeredManagers)l._removeDevice(a,o)},s=(a,o,c)=>{if(c)for(const l of this._registeredManagers)l._onInputChanged(a,o,c)};typeof _native<"u"?this._deviceInputSystem=new VMe(i,r,s):this._deviceInputSystem=new zMe(e,i,r,s)}dispose(){this._deviceInputSystem.dispose()}}class hme{getDeviceSource(e,t){if(t===void 0){if(this._firstDevice[e]===void 0)return null;t=this._firstDevice[e]}return!this._devices[e]||this._devices[e][t]===void 0?null:this._devices[e][t]}getDeviceSources(e){return this._devices[e]?this._devices[e].filter(t=>!!t):[]}constructor(e){const t=Object.keys(ii).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new HMe(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new Ae(i=>{for(const r of this._devices)if(r)for(const s of r)s&&this.onDeviceConnectedObservable.notifyObserver(i,s)}),this.onDeviceDisconnectedObservable=new Ae,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var r,s;const i=(r=this._devices[e])==null?void 0:r[t];this.onDeviceDisconnectedObservable.notifyObservers(i),(s=this._devices[e])!=null&&s[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;(s=(r=this._devices[e])==null?void 0:r[t])==null||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case ii.Keyboard:case ii.Mouse:this._firstDevice[e]=0;break;case ii.Touch:case ii.DualSense:case ii.DualShock:case ii.Xbox:case ii.Switch:case ii.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i=yi.MouseWheelX&&t.inputIndex<=yi.MouseWheelZ?ft.POINTERWHEEL:ft.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,a));let o;e?(o=new pd(a,t,e),this._setRayOnPointerInfo(e,t)):(o=new pd(a,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,a)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,ce.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const r=this._scene,s=new cme(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,t.pointerType==="xr-near"&&e.originMesh&&(s.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const s=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const a=this._pointerOverMesh._getActionManagerForTrigger();a&&a.hasPointerTriggers&&(s.style.cursor=a.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=yi.Move,!this._checkPrePointerObservable(e,i,ft.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,ft.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e!=null&&e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const a=e.pickedMesh._getActionManagerForTrigger();if(a){if(a.hasPickTriggers)switch(a.processTrigger(5,pn.CreateNew(e.pickedMesh,t,e)),t.button){case 0:a.processTrigger(2,pn.CreateNew(e.pickedMesh,t,e));break;case 1:a.processTrigger(4,pn.CreateNew(e.pickedMesh,t,e));break;case 2:a.processTrigger(3,pn.CreateNew(e.pickedMesh,t,e));break}a.hasSpecificTrigger(8)&&window.setTimeout(()=>{const o=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,c=>c.isPickable&&c.isVisible&&c.isReady()&&c.actionManager&&c.actionManager.hasSpecificTrigger(8)&&c===this._pickedDownMesh,!1,i.cameraToUseForPointers);o!=null&&o.pickedMesh&&a&&this._totalPointersPressed!==0&&Date.now()-this._startingPointerTime>Ca.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,a.processTrigger(8,pn.CreateNew(o.pickedMesh,t)))},Ca.LongPressDelay)}}else for(const a of i._pointerDownStage)e=a.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let r;const s=ft.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,s),r=new pd(s,t,e),this._setRayOnPointerInfo(e,t)):r=new pd(s,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(r,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const r=new PointerEvent("pointerup",t);r.inputIndex=yi.Move;const s=new Jue;i?s.doubleClick=!0:s.singleClick=!0,!this._checkPrePointerObservable(e,r,ft.POINTERUP)&&this._processPointerUp(e,r,s)}_processPointerUp(e,t,i){const r=this._scene;if(e!=null&&e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){const a=ft.POINTERPICK,o=new pd(a,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(o,a)}const s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,pn.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,pn.CreateNew(e.pickedMesh,t,e));const a=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&a&&a.processTrigger(6,pn.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const s of r._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const s=this._pickedDownMesh._getActionManagerForTrigger(16);s&&s.processTrigger(16,pn.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const s=new pd(ft.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,ft.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,ft.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let a=0;if(i.singleClick?a=ft.POINTERTAP:i.doubleClick&&(a=ft.POINTERDOUBLETAP),a){const o=new pd(a,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(a)&&r.onPointerObservable.notifyObservers(o,a)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,r=null){const s=this._scene,a=s.getEngine();r||(r=a.getInputElement()),this._alreadyAttached&&this.detachControl(),r&&(this._alreadyAttachedTo=r),this._deviceSourceManager=new hme(a),this._initActionManager=o=>{if(!this._meshPickProceed){const c=s.skipPointerUpPicking||s._registeredActions===0&&!this._checkForPicking()&&!s.onPointerUp?null:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,s.pointerUpFastCheck,s.cameraToUseForPointers,s.pointerUpTrianglePredicate);this._currentPickResult=c,c&&(o=c.hit&&c.pickedMesh?c.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,c,l)=>{if((Date.now()-this._previousStartingPointerTime>Ca.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,c.singleClick=!0,c.ignore=!1,this._delayedClicks[o])){const h=this._delayedClicks[o].evt,u=ft.POINTERTAP,d=new pd(u,h,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(u)&&s.onPointerObservable.notifyObservers(d,u),this._delayedClicks[o]=null}},this._initClickEvent=(o,c,l,h)=>{var _,m;const u=new Jue;this._currentPickResult=null;let d=null,f=o.hasSpecificMask(ft.POINTERPICK)||c.hasSpecificMask(ft.POINTERPICK)||o.hasSpecificMask(ft.POINTERTAP)||c.hasSpecificMask(ft.POINTERTAP)||o.hasSpecificMask(ft.POINTERDOUBLETAP)||c.hasSpecificMask(ft.POINTERDOUBLETAP);!f&&Kh&&(d=this._initActionManager(d,u),d&&(f=d.hasPickTriggers));let p=!1;if(f){const g=l.button;if(u.hasSwiped=this._isPointerSwiping(),!u.hasSwiped){let v=!Ca.ExclusiveDoubleClickMode;if(v||(v=!o.hasSpecificMask(ft.POINTERDOUBLETAP)&&!c.hasSpecificMask(ft.POINTERDOUBLETAP),v&&!Kh.HasSpecificTrigger(6)&&(d=this._initActionManager(d,u),d&&(v=!d.hasSpecificTrigger(6)))),v)(Date.now()-this._previousStartingPointerTime>Ca.DoubleClickDelay||g!==this._previousButtonPressed)&&(u.singleClick=!0,h(u,this._currentPickResult),p=!0);else{const y={evt:l,clickInfo:u,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,g,u,h),Ca.DoubleClickDelay)};this._delayedClicks[g]=y}let x=o.hasSpecificMask(ft.POINTERDOUBLETAP)||c.hasSpecificMask(ft.POINTERDOUBLETAP);!x&&Kh.HasSpecificTrigger(6)&&(d=this._initActionManager(d,u),d&&(x=d.hasSpecificTrigger(6))),x&&(g===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>Ca.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>Ca.DragMovementThreshold),a.isPointerLock&&a._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=yi.MouseWheelX&&o.inputIndex<=yi.MouseWheelZ?ft.POINTERWHEEL:ft.POINTERMOVE)||!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking){this._processPointerMove(new Ro,o);return}s.pointerMovePredicate||(s.pointerMovePredicate=l=>l.isPickable&&l.isVisible&&l.isReady()&&l.isEnabled()&&(l.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||l._getActionManagerForTrigger()!==null)&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&l.layerMask)!==0));const c=s._registeredActions>0||s.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(c,o)},this._onPointerDown=o=>{var l;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,Ca.ExclusiveDoubleClickMode){for(let h=0;hh.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&h.layerMask)!==0)),this._pickedDownMesh=null;let c;s.skipPointerDownPicking||s._registeredActions===0&&!this._checkForPicking()&&!s.onPointerDown?c=new Ro:c=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,s.pointerDownFastCheck,s.cameraToUseForPointers,s.pointerDownTrianglePredicate),this._processPointerDown(c,o)},this._onPointerUp=o=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),s.preventDefaultOnPointerUp&&r&&(o.preventDefault(),r.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,o,(c,l)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!c.ignore)){if(this._checkPrePointerObservable(null,o,ft.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}c.hasSwiped||(c.singleClick&&s.onPrePointerObservable.hasSpecificMask(ft.POINTERTAP)&&this._checkPrePointerObservable(null,o,ft.POINTERTAP)&&(this._skipPointerTap=!0),c.doubleClick&&s.onPrePointerObservable.hasSpecificMask(ft.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,ft.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[o.pointerId]){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1),!(!s.cameraToUseForPointers&&!s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=h=>h.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&h.layerMask)!==0)),!this._meshPickProceed&&(Kh&&Kh.HasTriggers||this._checkForPicking()||s.onPointerUp)&&this._initActionManager(null,c),l||(l=this._currentPickResult),this._processPointerUp(l,o,c),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{const c=Z0.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){const l=new S$(c,o);if(s.onPreKeyboardObservable.notifyObservers(l,c),l.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const l=new Oz(c,o);s.onKeyboardObservable.notifyObservers(l,c)}s.actionManager&&s.actionManager.processTrigger(14,pn.CreateNewFromScene(s,o))},this._onKeyUp=o=>{const c=Z0.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){const l=new S$(c,o);if(s.onPreKeyboardObservable.notifyObservers(l,c),l.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const l=new Oz(c,o);s.onKeyboardObservable.notifyObservers(l,c)}s.actionManager&&s.actionManager.processTrigger(15,pn.CreateNewFromScene(s,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===ii.Mouse?o.onInputChangedObservable.add(c=>{c.inputIndex===yi.LeftClick||c.inputIndex===yi.MiddleClick||c.inputIndex===yi.RightClick||c.inputIndex===yi.BrowserBack||c.inputIndex===yi.BrowserForward?t&&o.getInput(c.inputIndex)===1?this._onPointerDown(c):e&&o.getInput(c.inputIndex)===0&&this._onPointerUp(c):i&&(c.inputIndex===yi.Move?this._onPointerMove(c):(c.inputIndex===yi.MouseWheelX||c.inputIndex===yi.MouseWheelY||c.inputIndex===yi.MouseWheelZ)&&this._onPointerMove(c))}):o.deviceType===ii.Touch?o.onInputChangedObservable.add(c=>{c.inputIndex===yi.LeftClick&&(t&&o.getInput(c.inputIndex)===1?(this._onPointerDown(c),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&o.getInput(c.inputIndex)===0&&(this._onPointerUp(c),this._totalPointersPressed===0&&(this._isMultiTouchGesture=!1))),i&&c.inputIndex===yi.Move&&this._onPointerMove(c)}):o.deviceType===ii.Keyboard&&o.onInputChangedObservable.add(c=>{c.type==="keydown"?this._onKeyDown(c):c.type==="keyup"&&this._onKeyUp(c)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,r){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const s=this._meshUnderPointerId[t];let a;s&&(a=s._getActionManagerForTrigger(10),a&&a.processTrigger(10,pn.CreateNew(s,r,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,a=e._getActionManagerForTrigger(9),a&&a.processTrigger(9,pn.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}Ca.DragMovementThreshold=10;Ca.LongPressDelay=500;Ca.DoubleClickDelay=300;Ca.ExclusiveDoubleClickMode=!1;class Fa{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){Fa.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){Fa.Enabled&&(this._startMonitoringTime=gr.Now)}endMonitoring(e=!0){if(!Fa.Enabled)return;e&&this.fetchNewFrame();const t=gr.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=gr.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}Fa.Enabled=!0;class yl{constructor(e,t,i,r){this.normal=new P(e,t,i),this.d=r}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new yl(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=e*397^(this.d|0),e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return e!==0&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=yl._TmpMatrix;e.invertToRef(t);const i=t.m,r=this.normal.x,s=this.normal.y,a=this.normal.z,o=this.d,c=r*i[0]+s*i[1]+a*i[2]+o*i[3],l=r*i[4]+s*i[5]+a*i[6]+o*i[7],h=r*i[8]+s*i[9]+a*i[10]+o*i[11],u=r*i[12]+s*i[13]+a*i[14]+o*i[15];return new yl(c,l,h,u)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const r=t.x-e.x,s=t.y-e.y,a=t.z-e.z,o=i.x-e.x,c=i.y-e.y,l=i.z-e.z,h=s*l-a*c,u=a*o-r*l,d=r*c-s*o,f=Math.sqrt(h*h+u*u+d*d);let p;return f!==0?p=1/f:p=0,this.normal.x=h*p,this.normal.y=u*p,this.normal.z=d*p,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return P.Dot(this.normal,e)<=t}signedDistanceTo(e){return P.Dot(e,this.normal)+this.d}static FromArray(e){return new yl(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const r=new yl(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){const i=new yl(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const r=-(t.x*e.x+t.y*e.y+t.z*e.z);return P.Dot(i,t)+r}}yl._TmpMatrix=ce.Identity();class Tu{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new yl(0,0,0,0));return Tu.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){Tu.GetNearPlaneToRef(e,t[0]),Tu.GetFarPlaneToRef(e,t[1]),Tu.GetLeftPlaneToRef(e,t[2]),Tu.GetRightPlaneToRef(e,t[3]),Tu.GetTopPlaneToRef(e,t[4]),Tu.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class kO{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}kO._UniqueIdCounter=1;class os{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}os.FALLOFF_DEFAULT=0;os.FALLOFF_PHYSICAL=1;os.FALLOFF_GLTF=2;os.FALLOFF_STANDARD=3;os.LIGHTMAP_DEFAULT=0;os.LIGHTMAP_SPECULAR=1;os.LIGHTMAP_SHADOWSONLY=2;os.INTENSITYMODE_AUTOMATIC=0;os.INTENSITYMODE_LUMINOUSPOWER=1;os.INTENSITYMODE_LUMINOUSINTENSITY=2;os.INTENSITYMODE_ILLUMINANCE=3;os.INTENSITYMODE_LUMINANCE=4;os.LIGHTTYPEID_POINTLIGHT=0;os.LIGHTTYPEID_DIRECTIONALLIGHT=1;os.LIGHTTYPEID_SPOTLIGHT=2;os.LIGHTTYPEID_HEMISPHERICLIGHT=3;class GMe{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var $p;(function(n){n[n.BackwardCompatible=0]="BackwardCompatible",n[n.Intermediate=1]="Intermediate",n[n.Aggressive=2]="Aggressive"})($p||($p={}));class pt extends da{static DefaultMaterialFactory(e){throw ci("StandardMaterial")}static CollisionCoordinatorFactory(){throw ci("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case $p.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case $p.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case $p.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1;break}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return Ca.DragMovementThreshold}static set DragMovementThreshold(e){Ca.DragMovementThreshold=e}static get LongPressDelay(){return Ca.LongPressDelay}static set LongPressDelay(e){Ca.LongPressDelay=e}static get DoubleClickDelay(){return Ca.DoubleClickDelay}static set DoubleClickDelay(e){Ca.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return Ca.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){Ca.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,s=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return ie.Vector4[0].set(r.x,r.y,r.z,s?-1:1),e&&(i?e.setFloat3(t,ie.Vector4[0].x,ie.Vector4[0].y,ie.Vector4[0].z):e.setVector4(t,ie.Vector4[0])),ie.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=I_e(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=pt.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=pt.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new Ca(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new Ze(.2,.2,.3,1),this.ambientColor=new Me(0,0,0),this.environmentIntensity=1,this._performancePriority=$p.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new Ae,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new Ae,this._onDisposeObserver=null,this.onBeforeRenderObservable=new Ae,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new Ae,this.onAfterRenderCameraObservable=new Ae,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new Ae,this.onAfterAnimationsObservable=new Ae,this.onBeforeDrawPhaseObservable=new Ae,this.onAfterDrawPhaseObservable=new Ae,this.onReadyObservable=new Ae,this.onBeforeCameraRenderObservable=new Ae,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new Ae,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new Ae,this.onAfterActiveMeshesEvaluationObservable=new Ae,this.onBeforeParticlesRenderingObservable=new Ae,this.onAfterParticlesRenderingObservable=new Ae,this.onDataLoadedObservable=new Ae,this.onNewCameraAddedObservable=new Ae,this.onCameraRemovedObservable=new Ae,this.onNewLightAddedObservable=new Ae,this.onLightRemovedObservable=new Ae,this.onNewGeometryAddedObservable=new Ae,this.onGeometryRemovedObservable=new Ae,this.onNewTransformNodeAddedObservable=new Ae,this.onTransformNodeRemovedObservable=new Ae,this.onNewMeshAddedObservable=new Ae,this.onMeshRemovedObservable=new Ae,this.onNewSkeletonAddedObservable=new Ae,this.onSkeletonRemovedObservable=new Ae,this.onNewMaterialAddedObservable=new Ae,this.onNewMultiMaterialAddedObservable=new Ae,this.onMaterialRemovedObservable=new Ae,this.onMultiMaterialRemovedObservable=new Ae,this.onNewTextureAddedObservable=new Ae,this.onTextureRemovedObservable=new Ae,this.onBeforeRenderTargetsRenderObservable=new Ae,this.onAfterRenderTargetsRenderObservable=new Ae,this.onBeforeStepObservable=new Ae,this.onAfterStepObservable=new Ae,this.onActiveCameraChanged=new Ae,this.onActiveCamerasChanged=new Ae,this.onBeforeRenderingGroupObservable=new Ae,this.onAfterRenderingGroupObservable=new Ae,this.onMeshImportedObservable=new Ae,this.onAnimationFileImportedObservable=new Ae,this._registeredForLateAnimationBindings=new pm(256),this._pointerPickingConfiguration=new GMe,this.onPrePointerObservable=new Ae,this.onPointerObservable=new Ae,this.onPreKeyboardObservable=new Ae,this.onKeyboardObservable=new Ae,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=pt.FOGMODE_NONE,this.fogColor=new Me(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new P(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new pm(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Fa,this._activeIndices=new Fa,this._activeParticles=new Fa,this._activeBones=new Fa,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=new Array,this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new ba(256),this._processedMaterials=new ba(256),this._renderTargets=new pm(256),this._materialsRenderTargets=new pm(256),this._activeParticleSystems=new ba(256),this._activeSkeletons=new pm(32),this._softwareSkinnedMeshes=new pm(32),this._activeAnimatables=new Array,this._transformMatrix=ce.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=na.Create(),this._beforeClearStage=na.Create(),this._beforeRenderTargetClearStage=na.Create(),this._gatherRenderTargetsStage=na.Create(),this._gatherActiveCameraRenderTargetsStage=na.Create(),this._isReadyForMeshStage=na.Create(),this._beforeEvaluateActiveMeshStage=na.Create(),this._evaluateSubMeshStage=na.Create(),this._preActiveMeshStage=na.Create(),this._cameraDrawRenderTargetStage=na.Create(),this._beforeCameraDrawStage=na.Create(),this._beforeRenderTargetDrawStage=na.Create(),this._beforeRenderingGroupDrawStage=na.Create(),this._beforeRenderingMeshStage=na.Create(),this._afterRenderingMeshStage=na.Create(),this._afterRenderingGroupDrawStage=na.Create(),this._afterCameraDrawStage=na.Create(),this._afterCameraPostProcessStage=na.Create(),this._afterRenderTargetDrawStage=na.Create(),this._afterRenderTargetPostProcessStage=na.Create(),this._afterRenderStage=na.Create(),this._pointerMoveStage=na.Create(),this._pointerDownStage=na.Create(),this._pointerUpStage=na.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||bt.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(bt._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new rl(this),UD&&(this.postProcessManager=new UD(this)),io()&&this.attachControl(),this._createUbo(),Ji&&(this._imageProcessingConfiguration=new Ji),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return this._animationRatio!==void 0?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var a,o;if(this._isDisposed)return!1;let t;const i=this.getEngine(),r=i.currentRenderPassId;i.currentRenderPassId=((a=this.activeCamera)==null?void 0:a.renderPassId)??r;let s=!0;for(this._pendingData.length>0&&(s=!1),(o=this.prePassRenderer)==null||o.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&s&&(s=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const u of this._isReadyForMeshStage)u.action(c,l)||(s=!1);if(!e)continue;const h=c.material||this.defaultMaterial;if(h)if(h._storeEffectOnSubMeshes)for(const u of c.subMeshes){const d=u.getMaterial();d&&d.hasRenderTargetTextures&&d.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(d)===-1&&(this._processedMaterials.push(d),this._materialsRenderTargets.concatWithNoDuplicate(d.getRenderTargetTextures()))}else h.hasRenderTargetTextures&&h.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(h)===-1&&(this._processedMaterials.push(h),this._materialsRenderTargets.concatWithNoDuplicate(h.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const c of this.activeCameras)c.isReady(!0)||(s=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(s=!1));for(const c of this.particleSystems)c.isReady()||(s=!1);if(this.layers)for(const c of this.layers)c.isReady()||(s=!1);return i.areAllEffectsReady()||(s=!1),i.currentRenderPassId=r,s}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(t)})};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){t!==void 0?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,i=this._pendingData.indexOf(e);i!==-1&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),this._executeWhenReadyTimeoutId===null&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_checkIsReady(e=!1){if(this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=gr.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,r){!i&&!r&&this._multiviewSceneUbo&&(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),!(this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag)&&(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?Tu.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Tu.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new Ft(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return kO.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(i=>{this.addMesh(i)}))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return i!==-1&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(r=>{this.removeMesh(r)}),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneTransformNodesArray!==-1||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(t!==-1){if(t!==this.transformNodes.length-1){const i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return t!==-1&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return t!==-1&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(t!==-1){for(const i of this.meshes)i._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(t!==-1&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const i=this.activeCameras.indexOf(e);i!==-1&&this.activeCameras.splice(i,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return t!==-1&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return t!==-1&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return t!==-1&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return t!==-1&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(t!==-1&&ti.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,i=>i.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,i=>i.name===e)}getLastMaterialById(e,t=!1){for(let i=this.materials.length-1;i>=0;i--)if(this.materials[i].id===e)return this.materials[i];if(t){for(let i=this.multiMaterials.length-1;i>=0;i--)if(this.multiMaterials[i].id===e)return this.multiMaterials[i]}return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const r=this.getLightById(e);if(r)return r;const s=this.getCameraById(e);if(s)return s;const a=this.getBoneById(e);return a||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const r=this.getLightByName(e);if(r)return r;const s=this.getCameraByName(e);if(s)return s;const a=this.getBoneByName(e);return a||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,r)for(let a=0;ae.dispose())}_evaluateActiveMeshes(){var i;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((i=this.activeCamera)==null||i._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const r=this._activeMeshes.length;for(let s=0;s0&&s.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),a!==s&&a._activate(this._renderId,!1);for(const o of this._preActiveMeshStage)o.action(s);s._activate(this._renderId,!1)&&(s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(a=s):a._internalAbstractMeshDataInfo._onlyForInstances=!1,a._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,a)),s._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let r=0;r0){const r=this.getActiveSubMeshCandidates(t),s=r.length;i=i||s===1;for(let a=0;a0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const o of this._gatherActiveCameraRenderTargetsStage)o.action(this._renderTargets);let s=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Ee.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let o=0;o0),this._renderId++}for(const o of this._cameraDrawRenderTargetStage)s=o.action(this.activeCamera)||s;this._intermediateRendering=!1}this._engine.currentRenderPassId=((a=e.outputRenderTarget)==null?void 0:a.renderPassId)??e.renderPassId??0,s&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(const o of this._beforeCameraDrawStage)o.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),r.snapshotRendering&&r.snapshotRenderingMode===1&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const o of this._afterCameraDrawStage)o.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const o=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,o)}for(const o of this._afterCameraPostProcessStage)o.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===0||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let i=0;i-1&&(r.trigger===13&&r._executeCurrent(pn.CreateNew(t,void 0,a)),(!t.actionManager.hasSpecificTrigger(13,l=>{const h=l.mesh?l.mesh:l;return a===h})||r.trigger===13)&&t._intersectionsInProgress.splice(c,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(pt.MinDeltaTime,Math.min(this._engine.getDeltaTime(),pt.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let r=0;const s=this._engine.getLockstepMaxSteps();let a=Math.floor(e/t);for(a=Math.min(a,s);e>0&&r0)for(let o=0;o0),this._intermediateRendering=!0;for(let o=0;o0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(r==null?void 0:r.renderPassId)??0,this.activeCamera=r,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const o of this._beforeClearStage)o.action();this._clearFrameBuffer(this.activeCamera);for(const o of this._gatherRenderTargetsStage)o.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let o=0;o0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const o of this._afterRenderStage)o.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let o=0;o{s.onAnimationEndObservable.clear(),s.onAnimationEnd=null}),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const s of e)s.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(s){de.Error("An error occurred while calling onDisposeObservable!",s)}if(this.detachControl(),this._engine.getInputElement())for(let s=0;ss.dispose(!0)),this._disposeList(this.transformNodes,s=>s.dispose(!0));const i=this.cameras;this._disposeList(i),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let r=this._engine.scenes.indexOf(this);r>-1&&this._engine.scenes.splice(r,1),bt._LastCreatedScene===this&&(this._engine.scenes.length>0?bt._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:bt._LastCreatedScene=null),r=this._engine._virtualScenes.indexOf(this),r>-1&&this._engine._virtualScenes.splice(r,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(r=>r.dispose());for(const r of i)t(r);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach(r=>{if(r.computeWorldMatrix(!0),!r.subMeshes||r.subMeshes.length===0||r.infiniteDistance)return;const s=r.getBoundingInfo(),a=s.boundingBox.minimumWorld,o=s.boundingBox.maximumWorld;P.CheckExtends(a,t,i),P.CheckExtends(o,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,r,s=!1){throw ci("Ray")}createPickingRayToRef(e,t,i,r,s,a=!1,o=!1){throw ci("Ray")}createPickingRayInCameraSpace(e,t,i){throw ci("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,r){throw ci("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,r,s,a){const o=ci("Ray",!0);return o&&de.Warn(o),new Ro}pickWithBoundingInfo(e,t,i,r,s){const a=ci("Ray",!0);return a&&de.Warn(a),new Ro}pickWithRay(e,t,i,r){throw ci("Ray")}multiPick(e,t,i,r,s){throw ci("Ray")}multiPickWithRay(e,t,i){throw ci("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;const r=[];for(const s in e){const a=e[s];vr&&vr.MatchesQuery(a,t)&&(!i||i(a))&&r.push(a)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,r,s,a,o){const c=t2(e,t,i,r?this.offlineProvider:void 0,s,a,o);return this._activeRequests.push(c),c.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),c}_loadFileAsync(e,t,i,r,s){return new Promise((a,o)=>{this._loadFile(e,c=>{a(c)},t,i,r,(c,l)=>{o(l)},s)})}_requestFile(e,t,i,r,s,a,o){const c=iG(e,t,i,r?this.offlineProvider:void 0,s,a,o);return this._activeRequests.push(c),c.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),c}_requestFileAsync(e,t,i,r,s){return new Promise((a,o)=>{this._requestFile(e,c=>{a(c)},t,i,r,c=>{o(c)},s)})}_readFile(e,t,i,r,s){const a=K8(e,t,i,r,s);return this._activeRequests.push(a),a.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),a}_readFileAsync(e,t,i){return new Promise((r,s)=>{this._readFile(e,a=>{r(a)},t,i,a=>{s(a)})})}getPerfCollector(){throw ci("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}pt.FOGMODE_NONE=0;pt.FOGMODE_EXP=1;pt.FOGMODE_EXP2=2;pt.FOGMODE_LINEAR=3;pt.MinDeltaTime=1;pt.MaxDeltaTime=1e3;var Ci;(function(n){n[n.LOCAL=0]="LOCAL",n[n.WORLD=1]="WORLD",n[n.BONE=2]="BONE"})(Ci||(Ci={}));class $n{}$n.X=new P(1,0,0);$n.Y=new P(0,1,0);$n.Z=new P(0,0,1);var y3;(function(n){n[n.X=0]="X",n[n.Y=1]="Y",n[n.Z=2]="Z"})(y3||(y3={}));class _s extends Lr{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){e.updateFlag===this._localMatrix.updateFlag&&!this._needToCompose||(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,r=null,s=null,a=null,o=null){super(e,t.getScene()),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=(r==null?void 0:r.clone())??ce.Identity(),this._restMatrix=s??this._localMatrix.clone(),this._bindMatrix=a??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new ce,this._absoluteBindMatrix=new ce,this._absoluteInverseBindMatrix=new ce,this._finalMatrix=new ce,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return this._index===null?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const i=this.parent.children.indexOf(this);i!==-1&&this.parent.children.splice(i,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=ie.Vector3[0],t=ie.Quaternion[0],i=ie.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??we.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=P.Zero(),this._localRotation=we.Zero(),this._localPosition=P.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,ce.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let i=0;i-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const s=this._runtimeAnimations;for(let a=s.length-1;a>=0;a--){const o=s[a];e&&o.animation.name!=e||t&&!t(o.target)||(o.dispose(),s.splice(a,1))}s.length==0&&(i||this._scene._activeAnimatables.splice(r,1),this._raiseOnAnimationEnd())}}else{const r=this._scene._activeAnimatables.indexOf(this);if(r>-1){i||this._scene._activeAnimatables.splice(r,1);const s=this._runtimeAnimations;for(let a=0;a{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){if(this._paused)return this.animationStarted=!1,this._pausedDelay===null&&(this._pausedDelay=e),!0;if(this._localDelayOffset===null?(this._localDelayOffset=e,this._pausedDelay=null):this._pausedDelay!==null&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),this._manualJumpDelay!==null&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,this._weight===0)return!0;let t=!1;const i=this._runtimeAnimations;let r;for(r=0;r0)return;this._animationTimeLast=e}this.deltaTime=n!==void 0?n:this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;const t=this._activeAnimatables;if(t.length===0)return;this._animationTime+=this.deltaTime;const i=this._animationTime;for(let r=0;rn.playOrder-e.playOrder)};pt.prototype.beginWeightedAnimation=function(n,e,t,i=1,r,s=1,a,o,c,l,h=!1){const u=this.beginAnimation(n,e,t,r,s,a,o,!1,c,l,h);return u.weight=i,u};pt.prototype.beginAnimation=function(n,e,t,i,r=1,s,a,o=!0,c,l,h=!1){e>t&&r>0&&(r*=-1),o&&this.stopAnimation(n,void 0,c),a||(a=new LJ(this,n,e,t,i,r,s,void 0,l,h));const u=c?c(n):!0;if(n.animations&&u&&a.appendAnimations(n,n.animations),n.getAnimatables){const d=n.getAnimatables();for(let f=0;fi&&s>0)s*=-1;else if(i>t&&s<0){const h=i;i=t,t=h}return new LJ(this,n,t,i,r,s,a,e,o,c)};pt.prototype.beginDirectHierarchyAnimation=function(n,e,t,i,r,s,a,o,c,l=!1){const h=n.getDescendants(e),u=[];u.push(this.beginDirectAnimation(n,t,i,r,s,a,o,c,l));for(const d of h)u.push(this.beginDirectAnimation(d,t,i,r,s,a,o,c,l));return u};pt.prototype.getAnimatableByTarget=function(n){for(let e=0;e0?c:-c,r),f.scaleAndAddToRef(c,t)}r.normalize()}for(let u=0;u0)r.copyFrom(i);else if(n.animations.length===1){if(we.SlerpToRef(i,t.currentValue,Math.min(1,n.totalWeight),r),n.totalAdditiveWeight===0)return r}else if(n.animations.length>1){let s=1,a,o;if(n.totalWeight<1){const l=1-n.totalWeight;a=[],o=[],a.push(i),o.push(l)}else{if(n.animations.length===2&&(we.SlerpToRef(n.animations[0].currentValue,n.animations[1].currentValue,n.animations[1].weight/n.totalWeight,e),n.totalAdditiveWeight===0))return e;a=[],o=[],s=n.totalWeight}for(let l=0;l=a&&m.frame<=o&&(i?(v=m.value.clone(),d?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(f))):p&&r?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(r))):v=m.value):v=m.value,_.push({frame:m.frame+t,value:v}));return this.animations[0].createRange(e,a+t,o+t),!0};class KMe{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=ke.ANIMATIONLOOPMODE_CYCLE}}var Fy;(function(n){n[n.CW=0]="CW",n[n.CCW=1]="CCW"})(Fy||(Fy={}));class ume{static Interpolate(e,t,i,r,s){const a=1-3*r+3*t,o=3*r-6*t,c=3*t;let l=e;for(let h=0;h<5;h++){const u=l*l,d=u*l,f=a*d+o*u+c*l,p=1/(3*a*u+2*o*l+c);l-=(f-e)*p,l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*s+Math.pow(l,3)}}class jp{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return this._radians*180/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),r=Math.atan2(i.y,i.x);return new jp(r)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new jp(Math.PI/2);i=Math.sqrt(i);let r=e.dot(t)/i;r=_t.Clamp(r,-1,1);const s=Math.acos(r);return new jp(s)}static FromRadians(e){return new jp(e)}static FromDegrees(e){return new jp(e*Math.PI/180)}}class dme{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,a=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new Be((s*(t.y-i.y)-a*(e.y-t.y))/o,((e.x-t.x)*a-(t.x-i.x)*s)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=jp.BetweenTwoPoints(this.centerPoint,this.startPoint);const c=this.startAngle.degrees();let l=jp.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=jp.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-c>180&&(l-=360),l-c<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-c<0?Fy.CW:Fy.CCW,this.angle=jp.FromDegrees(this.orientation===Fy.CW?c-h:h-c)}}class O5{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new Be(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new Be(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;const a=this._points[this._points.length-1],o=new Be(e,t),c=new Be(i,r),l=new dme(a,o,c);let h=l.angle.radians()/s;l.orientation===Fy.CW&&(h*=-1);let u=l.startAngle.radians()+h;for(let d=0;d(1-c)*(1-c)*l+2*c*(1-c)*h+c*c*u,o=this._points[this._points.length-1];for(let c=0;c<=s;c++){const l=c/s,h=a(l,o.x,e,i),u=a(l,o.y,t,r);this.addLineTo(h,u)}return this}addBezierCurveTo(e,t,i,r,s,a,o=36){if(this.closed)return this;const c=(h,u,d,f,p)=>(1-h)*(1-h)*(1-h)*u+3*h*(1-h)*(1-h)*d+3*h*h*(1-h)*f+h*h*h*p,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const u=h/o,d=c(u,l.x,e,i,s),f=c(u,l.y,t,r,a);this.addLineTo(d,f)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let r=i-1,s=0;sNumber.EPSILON){if(l<0&&(a=this._points[s],c=-c,o=this._points[r],l=-l),e.yo.y)continue;if(e.y===a.y&&e.x===a.x)return!0;{const h=l*(e.x-a.x)-c*(e.y-a.y);if(h===0)return!0;if(h<0)continue;t=!t}}else{if(e.y!==a.y)continue;if(o.x<=e.x&&e.x<=a.x||a.x<=e.x&&e.x<=o.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,r=0;r1)return Be.Zero();const t=e*this.length();let i=0;for(let r=0;r=i&&t<=l){const h=c.normalize(),u=t-i;return new Be(a.x+h.x*u,a.y+h.y*u)}i=l}return Be.Zero()}static StartingAt(e,t){return new O5(e,t)}}class qy{constructor(e,t=null,i,r=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:P.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:ce.Identity()};for(let s=0;st){const l=e;e=t,t=l}const i=this.getCurve(),r=this.getPointAt(e);let s=this.getPreviousPointIndexAt(e);const a=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,c=[];return e!==0&&(s++,c.push(r)),c.push(...i.slice(s,o)),(t!==1||e===1)&&c.push(a),new qy(c,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let r=0;rt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,r=e.length();if(r===0&&(r=1),t==null){let s;_t.WithinEpsilon(Math.abs(e.y)/r,1,ni)?_t.WithinEpsilon(Math.abs(e.x)/r,1,ni)?_t.WithinEpsilon(Math.abs(e.z)/r,1,ni)?s=P.Zero():s=new P(0,0,1):s=new P(1,0,0):s=new P(0,-1,0),i=P.Cross(e,s)}else i=P.Cross(e,t),P.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let r=i[0],s,a=0;const o=e*this.length();for(let c=1;co){const u=(a-o)/l,d=r.subtract(s),f=s.add(d.scaleInPlace(u));return this._setPointAtData(e,1-u,f,c-1,t)}r=s}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=ce.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),a=this._tangents[t].clone(),o=this._normals[t].clone(),c=this._binormals[t].clone(),l=we.RotationQuaternionFromAxis(r,s,i),h=we.RotationQuaternionFromAxis(o,c,a);we.Slerp(l,h,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class Cf{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;const s=[],a=(o,c,l,h)=>(1-o)*(1-o)*c+2*o*(1-o)*l+o*o*h;for(let o=0;o<=r;o++)s.push(new P(a(o/r,e.x,t.x,i.x),a(o/r,e.y,t.y,i.y),a(o/r,e.z,t.z,i.z)));return new Cf(s)}static CreateCubicBezier(e,t,i,r,s){s=s>3?s:4;const a=[],o=(c,l,h,u,d)=>(1-c)*(1-c)*(1-c)*l+3*c*(1-c)*(1-c)*h+3*c*c*(1-c)*u+c*c*c*d;for(let c=0;c<=s;c++)a.push(new P(o(c/s,e.x,t.x,i.x,r.x),o(c/s,e.y,t.y,i.y,r.y),o(c/s,e.z,t.z,i.z,r.z)));return new Cf(a)}static CreateHermiteSpline(e,t,i,r,s){const a=[],o=1/s;for(let c=0;c<=s;c++)a.push(P.Hermite(e,t,i,r,c*o));return new Cf(a)}static CreateCatmullRomSpline(e,t,i){const r=[],s=1/t;let a=0;if(i){const o=e.length;for(let c=0;c=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}}Un.EASINGMODE_EASEIN=0;Un.EASINGMODE_EASEOUT=1;Un.EASINGMODE_EASEINOUT=2;class fme extends Un{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class pme extends Un{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}class WMe extends Un{constructor(e=3,t=2){super(),this.bounces=e,this.bounciness=t}easeInCore(e){const t=Math.max(0,this.bounces);let i=this.bounciness;i<=1&&(i=1.001);const r=Math.pow(i,t),s=1-i,a=(1-r)/s+r*.5,o=e*a,c=Math.log(-o*(1-i)+1)/Math.log(i),l=Math.floor(c),h=l+1,u=(1-Math.pow(i,l))/(s*a),d=(1-Math.pow(i,h))/(s*a),f=(u+d)*.5,p=e-f,_=f-u;return-Math.pow(1/i,t-l)/(_*_)*(p-_)*(p+_)}}class jMe extends Un{easeInCore(e){return e*e*e}}class XMe extends Un{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),r=Math.max(0,this.springiness);return r==0?t=e:t=(Math.exp(r*e)-1)/(Math.exp(r)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class _me extends Un{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}class YMe extends Un{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class NJ extends Un{easeInCore(e){return e*e}}class QMe extends Un{easeInCore(e){return e*e*e*e}}class $Me extends Un{easeInCore(e){return e*e*e*e*e}}class BJ extends Un{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class ZMe extends Un{constructor(e=0,t=0,i=1,r=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=r}easeInCore(e){return ume.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}class rG{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new rG(this.frame,this.action,this.onlyOnce)}}class mme{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class Up{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(!this.mask&&!e){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let t=0;t0)){for(let t=0;ta&&(a=c.to);const o=new Up(e[0].name+"_merged",e[0]._scene,r);for(const c of e){i&&c.normalize(s,a);for(const l of c.targetedAnimations)o.addTargetedAnimation(l.animation,l.target);t&&c.dispose()}return o}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new Ae,this.onAnimationLoopObservable=new Ae,this.onAnimationGroupLoopObservable=new Ae,this.onAnimationGroupEndObservable=new Ae,this.onAnimationGroupPauseObservable=new Ae,this.onAnimationGroupPlayObservable=new Ae,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||bt.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new mme;i.animation=e,i.target=t;const r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){e==null&&(e=this._from),t==null&&(t=this._to);for(let i=0;ie){const c={frame:e,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};s.splice(0,0,c)}if(o.frame{this.onAnimationLoopObservable.notifyObservers(t),!this._animationLoopFlags[i]&&(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||this._targetedAnimations.length===0)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let a=0;a{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(c)},this._processLoop(c,o,a),this._animatables.push(c)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0&&(this._scene._activeAnimatables[t++]=r)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const t=this._parentContainer.animationGroups.indexOf(this);t>-1&&this._parentContainer.animationGroups.splice(t,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),this._animatables.length===0&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const r=new Up(e||this.name,this._scene,this._weight,this._playOrder);r._from=this.from,r._to=this.to,r._speedRatio=this.speedRatio,r._loopAnimation=this.loopAnimation,r._isAdditive=this.isAdditive,r._enableBlending=this.enableBlending,r._blendingSpeed=this.blendingSpeed,r.metadata=this.metadata,r.mask=this.mask;for(const s of this._targetedAnimations)r.addTargetedAnimation(i?s.animation.clone():s.animation,t?t(s.target):s.target);return r}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;t_[0].frame&&(l=_[0].frame),h<_[_.length-1].frame&&(h=_[_.length-1].frame)}o._from=l,o._to=h}return o}static ClipKeys(e,t,i,r,s){const a=e.clone(r||e.name);return Up.ClipKeysInPlace(a,t,i,s)}static ClipKeysInPlace(e,t,i,r){return Up.ClipInPlace(e,t,i,r,!1)}static ClipFrames(e,t,i,r,s){const a=e.clone(r||e.name);return Up.ClipFramesInPlace(a,t,i,s)}static ClipFramesInPlace(e,t,i,r){return Up.ClipInPlace(e,t,i,r,!0)}static ClipInPlace(e,t,i,r,s=!1){let a=Number.MAX_VALUE,o=-Number.MAX_VALUE;const c=e.targetedAnimations;for(let l=0;l=t&&_<=i||s&&m.frame>=t&&m.frame<=i){const g={frame:m.frame,value:m.value.clone?m.value.clone():m.value,inTangent:m.inTangent,outTangent:m.outTangent,interpolation:m.interpolation,lockedTangent:m.lockedTangent};p===Number.MAX_VALUE&&(p=g.frame),g.frame-=p,f.push(g)}}if(f.length===0){c.splice(l,1),l--;continue}a>f[0].frame&&(a=f[0].frame),o1)throw"step size should be less than 1.";return this.value+=e,this._ensureLimits(),this._raiseOnChange(),this}_ensureLimits(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this}_raiseOnChange(){return this._onchange.forEach(e=>e(this)),this}onchange(e){return this._onchange.push(e),this}}var VD;(function(n){n[n.Include=0]="Include",n[n.Exclude=1]="Exclude"})(VD||(VD={}));class JMe{constructor(e,t=VD.Include){this.mode=t,this.disabled=!1,this._targetNames=new Set,e&&this.addTargetName(e)}addTargetName(e){if(Array.isArray(e)){for(const t of e)this._targetNames.add(t);return}this._targetNames.add(e)}removeTargetName(e){if(Array.isArray(e)){for(const t of e)this._targetNames.delete(t);return}this._targetNames.delete(e)}hasTarget(e){return this._targetNames.has(e)}retainsTarget(e){return this._targetNames.has(e)===(this.mode===VD.Include)}}function zD(n,e,t){try{const i=n.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function gme(n=25){let e;return(t,i,r)=>{const s=performance.now();e===void 0||s-e>n?(e=s,setTimeout(()=>{zD(t,i,r)},0)):zD(t,i,r)}}function FJ(n,e,t,i,r){const s=()=>{let a;const o=c=>{c.done?t(c.value):a===void 0?a=!0:s()};do a=void 0,!r||!r.aborted?e(n,o,i):i(new Error("Aborted")),a===void 0&&(a=!1);while(a)};s()}function sG(n,e){let t;return FJ(n,zD,i=>t=i,i=>{throw i},e),t}function nG(n,e,t){return new Promise((i,r)=>{FJ(n,e,i,r,t)})}function vme(n,e){return(...t)=>sG(n(...t),e)}function eRe(n,e,t){return(...i)=>nG(n(...i),e,t)}class bl{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new bl(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new bl(this.x,this.y,this.width,this.height)}}class Rt extends Lr{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===Rt.PERSPECTIVE_CAMERA)this.fovMode===Rt.FOVMODE_VERTICAL_FIXED?(t=this.minZ*2*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=this.minZ*2*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,r=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??r)-(this.orthoBottom??-r)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,r=!0){super(e,i),this._position=P.Zero(),this._upVector=P.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=Rt.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new bl(0,0,1,1),this.layerMask=268435455,this.fovMode=Rt.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=Rt.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new Ae,this.onProjectionMatrixChangedObservable=new Ae,this.onAfterCheckInputsObservable=new Ae,this.onRestoreStateObservable=new Ae,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new ce,this._postProcesses=new Array,this._activeMeshes=new ba(256),this._globalPosition=P.Zero(),this._computedViewMatrix=ce.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=ce.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=we.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return this._stateStored?(this.fov=this._storedFov,!0):!1}restoreState(){return this._restoreStateValues()?(this.onRestoreStateObservable.notifyObservers(this),!0):!1}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(de.Error("You're trying to reuse a post process not defined as reusable."),0):(t==null||t<0?this._postProcesses.push(e):this._postProcesses[t]===null?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)}_getViewMatrix(){return ce.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var s,a,o;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),r=t.useReverseDepthBuffer;if(this.mode===Rt.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let c;i.useRightHandedSystem?c=ce.PerspectiveFovRHToRef:c=ce.PerspectiveFovLHToRef,c(this.fov,t.getAspectRatio(this),r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===Rt.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,r)}else{const c=t.getRenderWidth()/2,l=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?ce.ObliqueOffCenterRHToRef(this.orthoLeft??-c,this.orthoRight??c,this.orthoBottom??-l,this.orthoTop??l,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):ce.OrthoOffCenterRHToRef(this.orthoLeft??-c,this.orthoRight??c,this.orthoBottom??-l,this.orthoTop??l,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?ce.ObliqueOffCenterLHToRef(this.orthoLeft??-c,this.orthoRight??c,this.orthoBottom??-l,this.orthoTop??l,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):ce.OrthoOffCenterLHToRef(this.orthoLeft??-c,this.orthoRight??c,this.orthoBottom??-l,this.orthoTop??l,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=(s=this.oblique)==null?void 0:s.angle,this._cache.obliqueLength=(a=this.oblique)==null?void 0:a.length,this._cache.obliqueOffset=(o=this.oblique)==null?void 0:o.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){const t=this,i=this;return(t.radius||(i.target?P.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Tu.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Tu.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let i=!1;return this.rigCameras.forEach(r=>{r._updateFrustumPlanes(),i=i||e.isInFrustum(r._frustumPlanes)}),i}else return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw ci("Ray")}getForwardRayToRef(e,t=100,i,r){throw ci("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const r=this._rigCameras.pop();r&&r.dispose()}if(this._parentContainer){const r=this._parentContainer.cameras.indexOf(this);r>-1&&this._parentContainer.cameras.splice(r,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==Rt.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let r=this._postProcesses.length;for(;--r>=0;){const s=this._postProcesses[r];s&&s.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const i=this._rigCameras.pop();i&&i.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Ee.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==Rt.RIG_MODE_NONE){const i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);const r=this.createRigCamera(this.name+"_R",1);r&&(r._isRightCamera=!0),i&&r&&(this._rigCameras.push(i),this._rigCameras.push(r))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return ce.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=Ee.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eRt._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,r=Rt.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=Qe.Parse(r,e,t);if(e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=P.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(P.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(P.FromArray(e.target)),e.cameraRigMode){const a=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,a)}if(e.animations){for(let a=0;a{throw ci("UniversalCamera")};Rt.PERSPECTIVE_CAMERA=0;Rt.ORTHOGRAPHIC_CAMERA=1;Rt.FOVMODE_VERTICAL_FIXED=0;Rt.FOVMODE_HORIZONTAL_FIXED=1;Rt.RIG_MODE_NONE=0;Rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;Rt.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;Rt.RIG_MODE_STEREOSCOPIC_INTERLACED=14;Rt.RIG_MODE_VR=20;Rt.RIG_MODE_CUSTOM=22;Rt.ForceAttachControlToAlwaysPreventDefault=!1;B([Js("position")],Rt.prototype,"_position",void 0);B([Js("upVector")],Rt.prototype,"_upVector",void 0);B([K()],Rt.prototype,"orthoLeft",null);B([K()],Rt.prototype,"orthoRight",null);B([K()],Rt.prototype,"orthoBottom",null);B([K()],Rt.prototype,"orthoTop",null);B([K()],Rt.prototype,"fov",void 0);B([K()],Rt.prototype,"projectionPlaneTilt",void 0);B([K()],Rt.prototype,"minZ",void 0);B([K()],Rt.prototype,"maxZ",void 0);B([K()],Rt.prototype,"inertia",void 0);B([K()],Rt.prototype,"mode",null);B([K()],Rt.prototype,"layerMask",void 0);B([K()],Rt.prototype,"fovMode",void 0);B([K()],Rt.prototype,"cameraRigMode",void 0);B([K()],Rt.prototype,"interaxialDistance",void 0);B([K()],Rt.prototype,"isStereoscopicSideBySide",void 0);class Lz{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class yd{constructor(e,t,i){this.vectors=Va.BuildArray(8,P.Zero),this.center=P.Zero(),this.centerWorld=P.Zero(),this.extendSize=P.Zero(),this.extendSizeWorld=P.Zero(),this.directions=Va.BuildArray(3,P.Zero),this.vectorsWorld=Va.BuildArray(8,P.Zero),this.minimumWorld=P.Zero(),this.maximumWorld=P.Zero(),this.minimum=P.Zero(),this.maximum=P.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const r=e.x,s=e.y,a=e.z,o=t.x,c=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(r,s,a),this.maximum.copyFromFloats(o,c,l),h[0].copyFromFloats(r,s,a),h[1].copyFromFloats(o,c,l),h[2].copyFromFloats(o,s,a),h[3].copyFromFloats(r,c,a),h[4].copyFromFloats(r,s,l),h[5].copyFromFloats(o,c,a),h[6].copyFromFloats(r,c,l),h[7].copyFromFloats(o,s,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||ce.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=yd._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);const s=r*e,a=i.scaleInPlace(s*.5),o=this.center.subtractToRef(a,t[1]),c=this.center.addToRef(a,t[2]);return this.reConstruct(o,c,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,r=this.directions,s=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)s[o].copyFrom(a[o]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let o=0;o<8;++o){const c=s[o];P.TransformCoordinatesToRef(a[o],e,c),t.minimizeInPlace(c),i.maximizeInPlace(c)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}P.FromArrayToRef(e.m,0,r[0]),P.FromArrayToRef(e.m,4,r[1]),P.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return yd.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return yd.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,a=t.z,o=i.x,c=i.y,l=i.z,h=e.x,u=e.y,d=e.z,f=-ni;return!(o-hh-r||c-uu-s||l-dd-a)}intersectsSphere(e){return yd.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,r=this.maximumWorld,s=i.x,a=i.y,o=i.z,c=r.x,l=r.y,h=r.z,u=e.x,d=e.y,f=e.z,p=t.x,_=t.y,m=t.z;return!(cp||l_||hm)}dispose(){var e,t;(e=this._drawWrapperFront)==null||e.dispose(),(t=this._drawWrapperBack)==null||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){const s=yd._TmpVector3[0];return P.ClampToRef(i,e,t,s),P.DistanceSquared(i,s)<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const r=t[i];for(let s=0;s<8;++s)if(r.dotCoordinate(e[s])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0;const s=t[i];for(let a=0;a<8;++a)if(s.dotCoordinate(e[a])>=0){r=!1;break}if(r)return!1}return!0}}yd._TmpVector3=Va.BuildArray(3,P.Zero);class e1{constructor(e,t,i){this.center=P.Zero(),this.centerWorld=P.Zero(),this.minimum=P.Zero(),this.maximum=P.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const r=P.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=r*.5,this._update(i||ce.IdentityReadOnly)}scale(e){const t=this.radius*e,i=e1._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),a=this.center.addToRef(r,i[2]);return this.reConstruct(s,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{P.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=e1._TmpVector3[0];P.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=P.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const i=P.Dot(e.centerWorld,n),r=Math.abs(P.Dot(e.directions[0],n))*e.extendSize.x,s=Math.abs(P.Dot(e.directions[1],n))*e.extendSize.y,a=Math.abs(P.Dot(e.directions[2],n))*e.extendSize.z,o=r+s+a;t.min=i-o,t.max=i+o},Oh=(n,e,t)=>(ede(n,e,lY),ede(n,t,cY),!(lY.min>cY.max||cY.min>lY.max));class uc{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new yd(e,t,i),this.boundingSphere=new e1(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const i=uc._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=uc._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=P.Minimize(this.minimum,e),i=P.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=ie.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=ie.Vector3[0];return P.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),P.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return(t===2||t===3)&&this.boundingSphere.isCenterInFrustum(e)?!0:this.boundingSphere.isInFrustum(e)?t===1||t===3?!0:this.boundingBox.isInFrustum(e):!1}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,uc._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!(!this.boundingSphere.centerWorld||!this.boundingSphere.intersectsPoint(e)||!this.boundingBox.intersectsPoint(e))}intersects(e,t){if(!e1.Intersects(this.boundingSphere,e.boundingSphere)||!yd.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,r=e.boundingBox;return!(!Oh(i.directions[0],i,r)||!Oh(i.directions[1],i,r)||!Oh(i.directions[2],i,r)||!Oh(r.directions[0],i,r)||!Oh(r.directions[1],i,r)||!Oh(r.directions[2],i,r)||!Oh(P.Cross(i.directions[0],r.directions[0]),i,r)||!Oh(P.Cross(i.directions[0],r.directions[1]),i,r)||!Oh(P.Cross(i.directions[0],r.directions[2]),i,r)||!Oh(P.Cross(i.directions[1],r.directions[0]),i,r)||!Oh(P.Cross(i.directions[1],r.directions[1]),i,r)||!Oh(P.Cross(i.directions[1],r.directions[2]),i,r)||!Oh(P.Cross(i.directions[2],r.directions[0]),i,r)||!Oh(P.Cross(i.directions[2],r.directions[1]),i,r)||!Oh(P.Cross(i.directions[2],r.directions[2]),i,r))}}uc._TmpVector3=Va.BuildArray(2,P.Zero);class aG{static extractMinAndMaxIndexed(e,t,i,r,s,a){for(let o=i;o!Array.isArray(n)&&!Array.isArray(e))],aG,"extractMinAndMaxIndexed",null);B([e2.filter((...[n])=>!Array.isArray(n))],aG,"extractMinAndMax",null);function xme(n,e,t,i,r=null){const s=new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return aG.extractMinAndMaxIndexed(n,e,t,i,s,a),r&&(s.x-=s.x*r.x+r.y,s.y-=s.y*r.x+r.y,s.z-=s.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:s,maximum:a}}function W8(n,e,t,i=null,r){const s=new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return r||(r=3),aG.extractMinAndMax(n,e,t,r,s,a),i&&(s.x-=s.x*i.x+i.y,s.y-=s.y*i.x+i.y,s.z-=s.z*i.x+i.y,a.x+=a.x*i.x+i.y,a.y+=a.y*i.x+i.y,a.z+=a.z*i.x+i.y),{minimum:s,maximum:a}}class Xo{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(e=this._getDrawWrapper())==null?void 0:e.defines}set materialDefines(e){const t=this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0);t.defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Sn(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&((i=this._drawWrappers[e])==null||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:((e=this._getDrawWrapper())==null?void 0:e.effect)??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){const s=this._drawWrapper;s.setEffect(e,t,r),i!==void 0&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e);return}else for(const t of this._drawWrappers)t==null||t.dispose();this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,a,o,c=!0){return new Xo(e,t,i,r,s,a,o,c)}constructor(e,t,i,r,s,a,o,c=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=a,this._renderingMesh=o||a,l&&a.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=a.subMeshes.length-1,c&&(this.refreshBoundingInfo(),a.computeWorldMatrix(!0))}get IsGlobal(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()&&this.indexStart===0&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){const e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(t){if(this._isMultiMaterial(t)){const i=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==i&&(this._currentMaterial=i,this.resetDrawCache()),i}}else return e?this._mesh.getScene().defaultMaterial:null;return t}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(Z.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(this.indexStart===0&&this.indexCount===t.length){const r=this._renderingMesh.getBoundingInfo();i={minimum:r.minimum.clone(),maximum:r.maximum.clone()}}else i=xme(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new uc(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return t?t.isInFrustum(e,this._mesh.cullingStrategy):!1}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return t?t.isCompletelyInFrustum(e):!1}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let r=this.indexStart;rc&&(c=d)}return new Xo(e,o,c-o+1,t,i,r,s,a)}}class fD{}class et{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=vme(this._applyToCoroutine.bind(this)),this.uniqueId=et._UniqueIDGenerator,et._UniqueIDGenerator++}set(e,t){switch(e.length||de.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case Z.PositionKind:this.positions=e;break;case Z.NormalKind:this.normals=e;break;case Z.TangentKind:this.tangents=e;break;case Z.UVKind:this.uvs=e;break;case Z.UV2Kind:this.uvs2=e;break;case Z.UV3Kind:this.uvs3=e;break;case Z.UV4Kind:this.uvs4=e;break;case Z.UV5Kind:this.uvs5=e;break;case Z.UV6Kind:this.uvs6=e;break;case Z.ColorKind:this.colors=e;break;case Z.MatricesIndicesKind:this.matricesIndices=e;break;case Z.MatricesWeightsKind:this.matricesWeights=e;break;case Z.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case Z.MatricesWeightsExtraKind:this.matricesWeightsExtra=e;break}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(Z.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(Z.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(Z.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(Z.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(Z.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(Z.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(Z.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(Z.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(Z.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(Z.ColorKind,this.colors,t),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(Z.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(Z.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(Z.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(Z.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const r=e;r.subMeshes=[];for(const s of this.materialInfos)new Xo(s.materialIndex,s.verticesStart,s.verticesCount,s.indexStart,s.indexCount,r)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(Z.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(Z.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(Z.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(Z.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(Z.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(Z.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(Z.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(Z.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(Z.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(Z.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(Z.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(Z.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(Z.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(Z.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){const s=ie.Vector3[0],a=ie.Vector3[1];for(let o=i;o({vertexData:o})):[{vertexData:e}];return sG(this._mergeCoroutine(void 0,a,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,a=!1,o=!1){var f,p;this._validate();let c=t.map(_=>_.vertexData),l=this;if(o)for(const _ of c)_&&(_._validate(),!this.normals&&_.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&_.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&_.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&_.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&_.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&_.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&_.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&_.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&_.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&_.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&_.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&_.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&_.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const _ of c)if(_){if(o)this.normals&&!_.normals&&(_.normals=new Float32Array(_.positions.length)),this.tangents&&!_.tangents&&(_.tangents=new Float32Array(_.positions.length/3*4)),this.uvs&&!_.uvs&&(_.uvs=new Float32Array(_.positions.length/3*2)),this.uvs2&&!_.uvs2&&(_.uvs2=new Float32Array(_.positions.length/3*2)),this.uvs3&&!_.uvs3&&(_.uvs3=new Float32Array(_.positions.length/3*2)),this.uvs4&&!_.uvs4&&(_.uvs4=new Float32Array(_.positions.length/3*2)),this.uvs5&&!_.uvs5&&(_.uvs5=new Float32Array(_.positions.length/3*2)),this.uvs6&&!_.uvs6&&(_.uvs6=new Float32Array(_.positions.length/3*2)),this.colors&&!_.colors&&(_.colors=new Float32Array(_.positions.length/3*4),_.colors.fill(1)),this.matricesIndices&&!_.matricesIndices&&(_.matricesIndices=new Float32Array(_.positions.length/3*4)),this.matricesWeights&&!_.matricesWeights&&(_.matricesWeights=new Float32Array(_.positions.length/3*4)),this.matricesIndicesExtra&&!_.matricesIndicesExtra&&(_.matricesIndicesExtra=new Float32Array(_.positions.length/3*4)),this.matricesWeightsExtra&&!_.matricesWeightsExtra&&(_.matricesWeightsExtra=new Float32Array(_.positions.length/3*4));else if(_._validate(),!this.normals!=!_.normals||!this.tangents!=!_.tangents||!this.uvs!=!_.uvs||!this.uvs2!=!_.uvs2||!this.uvs3!=!_.uvs3||!this.uvs4!=!_.uvs4||!this.uvs5!=!_.uvs5||!this.uvs6!=!_.uvs6||!this.colors!=!_.colors||!this.matricesIndices!=!_.matricesIndices||!this.matricesWeights!=!_.matricesWeights||!this.matricesIndicesExtra!=!_.matricesIndicesExtra||!this.matricesWeightsExtra!=!_.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let _=0,m=0,g=0;const v=[];let x=null;const y=[];for(const b of this.splitBasedOnMaterialID())y.push({vertexData:b,transform:e});for(const b of t)if(b.vertexData)for(const T of b.vertexData.splitBasedOnMaterialID())y.push({vertexData:T,transform:b.transform});y.sort((b,T)=>{const S=b.vertexData.materialInfos?b.vertexData.materialInfos[0].materialIndex:0,N=T.vertexData.materialInfos?T.vertexData.materialInfos[0].materialIndex:0;return S>N?1:S===N?0:-1});for(const b of y){const T=b.vertexData;if(T.materialInfos?_=T.materialInfos[0].materialIndex:_=0,x&&x.materialIndex===_)x.indexCount+=T.indices.length,x.verticesCount+=T.positions.length/3;else{const S=new fD;S.materialIndex=_,S.indexStart=m,S.indexCount=T.indices.length,S.verticesStart=g,S.verticesCount=T.positions.length/3,v.push(S),x=S}m+=T.indices.length,g+=T.positions.length/3}const C=y.splice(0,1)[0];l=C.vertexData,e=C.transform,c=y.map(b=>b.vertexData),t=y,this.materialInfos=v}const h=c.reduce((_,m)=>{var g;return _+(((g=m.indices)==null?void 0:g.length)??0)},((f=l.indices)==null?void 0:f.length)??0);let d=s||c.some(_=>_.indices===l.indices)?(p=l.indices)==null?void 0:p.slice():l.indices;if(h>0){let _=(d==null?void 0:d.length)??0;if(d||(d=new Array(h)),d.length!==h){if(Array.isArray(d))d.length=h;else{const g=i||d instanceof Uint32Array?new Uint32Array(h):new Uint16Array(h);g.set(d),d=g}e&&e.determinant()<0&&et._FlipFaces(d,0,_)}let m=l.positions?l.positions.length/3:0;for(const{vertexData:g,transform:v}of t)if(g.indices){for(let x=0;x[_.vertexData.positions,_.transform])),r&&(yield),l.normals&&(this.normals=et._MergeElement(Z.NormalKind,l.normals,e,t.map(_=>[_.vertexData.normals,_.transform])),r&&(yield)),l.tangents&&(this.tangents=et._MergeElement(Z.TangentKind,l.tangents,e,t.map(_=>[_.vertexData.tangents,_.transform])),r&&(yield)),l.uvs&&(this.uvs=et._MergeElement(Z.UVKind,l.uvs,e,t.map(_=>[_.vertexData.uvs,_.transform])),r&&(yield)),l.uvs2&&(this.uvs2=et._MergeElement(Z.UV2Kind,l.uvs2,e,t.map(_=>[_.vertexData.uvs2,_.transform])),r&&(yield)),l.uvs3&&(this.uvs3=et._MergeElement(Z.UV3Kind,l.uvs3,e,t.map(_=>[_.vertexData.uvs3,_.transform])),r&&(yield)),l.uvs4&&(this.uvs4=et._MergeElement(Z.UV4Kind,l.uvs4,e,t.map(_=>[_.vertexData.uvs4,_.transform])),r&&(yield)),l.uvs5&&(this.uvs5=et._MergeElement(Z.UV5Kind,l.uvs5,e,t.map(_=>[_.vertexData.uvs5,_.transform])),r&&(yield)),l.uvs6&&(this.uvs6=et._MergeElement(Z.UV6Kind,l.uvs6,e,t.map(_=>[_.vertexData.uvs6,_.transform])),r&&(yield)),l.colors&&(this.colors=et._MergeElement(Z.ColorKind,l.colors,e,t.map(_=>[_.vertexData.colors,_.transform])),(l.hasVertexAlpha!==void 0||t.some(_=>_.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some(_=>_.vertexData.hasVertexAlpha)),r&&(yield)),l.matricesIndices&&(this.matricesIndices=et._MergeElement(Z.MatricesIndicesKind,l.matricesIndices,e,t.map(_=>[_.vertexData.matricesIndices,_.transform])),r&&(yield)),l.matricesWeights&&(this.matricesWeights=et._MergeElement(Z.MatricesWeightsKind,l.matricesWeights,e,t.map(_=>[_.vertexData.matricesWeights,_.transform])),r&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=et._MergeElement(Z.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map(_=>[_.vertexData.matricesIndicesExtra,_.transform])),r&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=et._MergeElement(Z.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map(_=>[_.vertexData.matricesWeightsExtra,_.transform]))),this}static _MergeElement(e,t,i,r){const s=r.filter(c=>c[0]!==null&&c[0]!==void 0);if(!t&&s.length==0)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));const a=s.reduce((c,l)=>c+l[0].length,t.length),o=e===Z.PositionKind?et._TransformVector3Coordinates:e===Z.NormalKind?et._TransformVector3Normals:e===Z.TangentKind?et._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const c=new Float32Array(a);c.set(t),i&&o(c,i,0,t.length);let l=t.length;for(const[h,u]of s)c.set(h,l),u&&o(c,u,l,h.length),l+=h.length;return c}else{const c=new Array(a);for(let h=0;h{const a=Z.DeduceStride(r);if(s.length%a!==0)throw new Error("The "+r+"s array count must be a multiple of "+a);return s.length/a},t=e(Z.PositionKind,this.positions),i=(r,s)=>{const a=e(r,s);if(a!==t)throw new Error("The "+r+"s element count ("+a+") does not match the positions count ("+t+")")};this.normals&&i(Z.NormalKind,this.normals),this.tangents&&i(Z.TangentKind,this.tangents),this.uvs&&i(Z.UVKind,this.uvs),this.uvs2&&i(Z.UV2Kind,this.uvs2),this.uvs3&&i(Z.UV3Kind,this.uvs3),this.uvs4&&i(Z.UV4Kind,this.uvs4),this.uvs5&&i(Z.UV5Kind,this.uvs5),this.uvs6&&i(Z.UV6Kind,this.uvs6),this.colors&&i(Z.ColorKind,this.colors),this.matricesIndices&&i(Z.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(Z.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(Z.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(Z.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return et.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return et._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return et._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const r=new et;return e.isVerticesDataPresent(Z.PositionKind)&&(r.positions=e.getVerticesData(Z.PositionKind,t,i)),e.isVerticesDataPresent(Z.NormalKind)&&(r.normals=e.getVerticesData(Z.NormalKind,t,i)),e.isVerticesDataPresent(Z.TangentKind)&&(r.tangents=e.getVerticesData(Z.TangentKind,t,i)),e.isVerticesDataPresent(Z.UVKind)&&(r.uvs=e.getVerticesData(Z.UVKind,t,i)),e.isVerticesDataPresent(Z.UV2Kind)&&(r.uvs2=e.getVerticesData(Z.UV2Kind,t,i)),e.isVerticesDataPresent(Z.UV3Kind)&&(r.uvs3=e.getVerticesData(Z.UV3Kind,t,i)),e.isVerticesDataPresent(Z.UV4Kind)&&(r.uvs4=e.getVerticesData(Z.UV4Kind,t,i)),e.isVerticesDataPresent(Z.UV5Kind)&&(r.uvs5=e.getVerticesData(Z.UV5Kind,t,i)),e.isVerticesDataPresent(Z.UV6Kind)&&(r.uvs6=e.getVerticesData(Z.UV6Kind,t,i)),e.isVerticesDataPresent(Z.ColorKind)&&(r.colors=e.getVerticesData(Z.ColorKind,t,i)),e.isVerticesDataPresent(Z.MatricesIndicesKind)&&(r.matricesIndices=e.getVerticesData(Z.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(Z.MatricesWeightsKind)&&(r.matricesWeights=e.getVerticesData(Z.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(Z.MatricesIndicesExtraKind)&&(r.matricesIndicesExtra=e.getVerticesData(Z.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(Z.MatricesWeightsExtraKind)&&(r.matricesWeightsExtra=e.getVerticesData(Z.MatricesWeightsExtraKind,t,i)),r.indices=e.getIndices(t,i),r}static CreateRibbon(e){throw ci("ribbonBuilder")}static CreateBox(e){throw ci("boxBuilder")}static CreateTiledBox(e){throw ci("tiledBoxBuilder")}static CreateTiledPlane(e){throw ci("tiledPlaneBuilder")}static CreateSphere(e){throw ci("sphereBuilder")}static CreateCylinder(e){throw ci("cylinderBuilder")}static CreateTorus(e){throw ci("torusBuilder")}static CreateLineSystem(e){throw ci("linesBuilder")}static CreateDashedLines(e){throw ci("linesBuilder")}static CreateGround(e){throw ci("groundBuilder")}static CreateTiledGround(e){throw ci("groundBuilder")}static CreateGroundFromHeightMap(e){throw ci("groundBuilder")}static CreatePlane(e){throw ci("planeBuilder")}static CreateDisc(e){throw ci("discBuilder")}static CreatePolygon(e,t,i,r,s,a,o){throw ci("polygonBuilder")}static CreateIcoSphere(e){throw ci("icoSphereBuilder")}static CreatePolyhedron(e){throw ci("polyhedronBuilder")}static CreateCapsule(e={orientation:P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw ci("capsuleBuilder")}static CreateTorusKnot(e){throw ci("torusKnotBuilder")}static ComputeNormals(e,t,i,r){let s=0,a=0,o=0,c=0,l=0,h=0,u=0,d=0,f=0,p=0,_=0,m=0,g=0,v=0,x=0,y=0,C=0,b=0,T=0,S=0,N=!1,D=!1,M=!1,I=!1,R=1,O=0,H=null;r&&(N=!!r.facetNormals,D=!!r.facetPositions,M=!!r.facetPartitioning,R=r.useRightHandedSystem===!0?-1:1,O=r.ratio||0,I=!!r.depthSort,H=r.distanceTo,I&&H===void 0&&(H=P.Zero()));let G=0,Q=0,$=0,V=0;for(M&&r&&r.bbSize&&(G=r.subDiv.X*O/r.bbSize.x,Q=r.subDiv.Y*O/r.bbSize.y,$=r.subDiv.Z*O/r.bbSize.z,V=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0),s=0;s!Array.isArray(n))],et,"_TransformVector3Coordinates",null);B([e2.filter((...[n])=>!Array.isArray(n))],et,"_TransformVector3Normals",null);B([e2.filter((...[n])=>!Array.isArray(n))],et,"_TransformVector4Normals",null);B([e2.filter((...[n])=>!Array.isArray(n))],et,"_FlipFaces",null);class ro{static get ForceFullSceneLoadingForIncremental(){return ro._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){ro._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return ro._ShowLoadingScreen}static set ShowLoadingScreen(e){ro._ShowLoadingScreen=e}static get loggingLevel(){return ro._LoggingLevel}static set loggingLevel(e){ro._LoggingLevel=e}static get CleanBoneMatrixWeights(){return ro._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){ro._CleanBoneMatrixWeights=e}}ro._ForceFullSceneLoadingForIncremental=!1;ro._ShowLoadingScreen=!0;ro._CleanBoneMatrixWeights=!1;ro._LoggingLevel=0;class br{}br.UseOpenGLOrientationForUV=!1;class Ua{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new Ua(Ua.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||bt.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===1||this.delayLoadState===0}get doNotSerialize(){for(let e=0;e{t._rebuild()})}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,r){i&&Array.isArray(t)&&(t=new Float32Array(t));const s=new Z(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:r,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const r=e.getKind();this._vertexBuffers[r]&&i&&this._vertexBuffers[r].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[r]=e;const s=this._meshes,a=s.length;if(r===Z.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const o=this._extend&&this._extend.minimum||new P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),c=this._extend&&this._extend.maximum||new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let l=0;l65535);for(const r of this._meshes)r._createGlobalSubMesh(!0),r.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),t!=null&&(this._totalVertices=t);for(const r of this._meshes)r._createGlobalSubMesh(!0),r.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._totalIndices!==void 0?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return!t&&(!e||this._meshes.length===1)?i:i.slice()}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){!e||!this._vertexArrayObjects||this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,r=i.indexOf(e);r!==-1&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,i.length===0&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&(e=this.getVerticesData(Z.PositionKind),!e))return;this._extend=W8(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)t===1&&this._vertexBuffers[i].create(),i===Z.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());t===1&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const r=this._meshes,s=r.length;for(let a=0;a0){for(let r=0;r0){for(let r=0;r0){for(let r=0;r-1&&this._parentContainer.geometries.splice(r,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new et;t.indices=[];const i=this.getIndices();if(i)for(let c=0;c0){const o=new Float32Array(e,a.positionsAttrDesc.offset,a.positionsAttrDesc.count);t.setVerticesData(Z.PositionKind,o,!1)}if(a.normalsAttrDesc&&a.normalsAttrDesc.count>0){const o=new Float32Array(e,a.normalsAttrDesc.offset,a.normalsAttrDesc.count);t.setVerticesData(Z.NormalKind,o,!1)}if(a.tangetsAttrDesc&&a.tangetsAttrDesc.count>0){const o=new Float32Array(e,a.tangetsAttrDesc.offset,a.tangetsAttrDesc.count);t.setVerticesData(Z.TangentKind,o,!1)}if(a.uvsAttrDesc&&a.uvsAttrDesc.count>0){const o=new Float32Array(e,a.uvsAttrDesc.offset,a.uvsAttrDesc.count);if(br.UseOpenGLOrientationForUV)for(let c=1;c0){const o=new Float32Array(e,a.uvs2AttrDesc.offset,a.uvs2AttrDesc.count);if(br.UseOpenGLOrientationForUV)for(let c=1;c0){const o=new Float32Array(e,a.uvs3AttrDesc.offset,a.uvs3AttrDesc.count);if(br.UseOpenGLOrientationForUV)for(let c=1;c0){const o=new Float32Array(e,a.uvs4AttrDesc.offset,a.uvs4AttrDesc.count);if(br.UseOpenGLOrientationForUV)for(let c=1;c0){const o=new Float32Array(e,a.uvs5AttrDesc.offset,a.uvs5AttrDesc.count);if(br.UseOpenGLOrientationForUV)for(let c=1;c0){const o=new Float32Array(e,a.uvs6AttrDesc.offset,a.uvs6AttrDesc.count);if(br.UseOpenGLOrientationForUV)for(let c=1;c0){const o=new Float32Array(e,a.colorsAttrDesc.offset,a.colorsAttrDesc.count);t.setVerticesData(Z.ColorKind,o,!1,a.colorsAttrDesc.stride)}if(a.matricesIndicesAttrDesc&&a.matricesIndicesAttrDesc.count>0){const o=new Int32Array(e,a.matricesIndicesAttrDesc.offset,a.matricesIndicesAttrDesc.count),c=[];for(let l=0;l>8),c.push((h&16711680)>>16),c.push(h>>24&255)}t.setVerticesData(Z.MatricesIndicesKind,c,!1)}if(a.matricesIndicesExtraAttrDesc&&a.matricesIndicesExtraAttrDesc.count>0){const o=new Int32Array(e,a.matricesIndicesExtraAttrDesc.offset,a.matricesIndicesExtraAttrDesc.count),c=[];for(let l=0;l>8),c.push((h&16711680)>>16),c.push(h>>24&255)}t.setVerticesData(Z.MatricesIndicesExtraKind,c,!1)}if(a.matricesWeightsAttrDesc&&a.matricesWeightsAttrDesc.count>0){const o=new Float32Array(e,a.matricesWeightsAttrDesc.offset,a.matricesWeightsAttrDesc.count);t.setVerticesData(Z.MatricesWeightsKind,o,!1)}if(a.indicesAttrDesc&&a.indicesAttrDesc.count>0){const o=new Int32Array(e,a.indicesAttrDesc.offset,a.indicesAttrDesc.count);t.setIndices(o,null)}if(a.subMeshesAttrDesc&&a.subMeshesAttrDesc.count>0){const o=new Int32Array(e,a.subMeshesAttrDesc.offset,a.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let c=0;c>8),a.push((c&16711680)>>16),a.push(c>>24&255)}t.setVerticesData(Z.MatricesIndicesKind,a,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(Z.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const a=[];for(let o=0;o>8),a.push((c&16711680)>>16),a.push(c>>24&255)}t.setVerticesData(Z.MatricesIndicesExtraKind,a,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(Ua._CleanMatricesWeights(e,t),t.setVerticesData(Z.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(Z.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let a=0;a-1){const u=t.getScene().getLastSkeletonById(e.skeletonId);if(!u)return;r=u.bones.length}else return;const s=t.getVerticesData(Z.MatricesIndicesKind),a=t.getVerticesData(Z.MatricesIndicesExtraKind),o=e.matricesWeights,c=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=o.length;for(let u=0;ul-1)&&(f=l-1),d>.001){const p=1/d;for(let _=0;_<4;_++)o[u+_]*=p;if(c)for(let _=0;_<4;_++)c[u+_]*=p}else f>=4?(c[u+f-4]=1-d,a[u+f-4]=r):(o[u+f]=1-d,s[u+f]=r)}t.setVerticesData(Z.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(Z.MatricesIndicesExtraKind,a)}static Parse(e,t,i){const r=new Ua(e.id,t,void 0,e.updatable);return r._loadedUniqueId=e.uniqueId,vr&&vr.AddTagsTo(r,e.tags),e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r._boundingInfo=new uc(P.FromArray(e.boundingBoxMinimum),P.FromArray(e.boundingBoxMaximum)),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(Z.UVKind),e.hasUVs2&&r._delayInfo.push(Z.UV2Kind),e.hasUVs3&&r._delayInfo.push(Z.UV3Kind),e.hasUVs4&&r._delayInfo.push(Z.UV4Kind),e.hasUVs5&&r._delayInfo.push(Z.UV5Kind),e.hasUVs6&&r._delayInfo.push(Z.UV6Kind),e.hasColors&&r._delayInfo.push(Z.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(Z.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(Z.MatricesWeightsKind),r._delayLoadingFunction=et.ImportVertexData):et.ImportVertexData(e,r),t.pushGeometry(r,!0),r}}class yme{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Ame(e)}sampleFrame(e=gr.Now){if(this._enabled){if(this._lastFrameTimeMs!=null){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return e===0?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class Ame{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}yt.prototype.setAlphaConstants=function(n,e,t,i){this._alphaState.setAlphaBlendConstants(n,e,t,i)};yt.prototype.setAlphaMode=function(n,e=!1){if(this._alphaMode===n){if(!e){const t=n===0;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(n){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break}e||(this.depthCullingState.depthMask=n===0),this._alphaMode=n};yt.prototype.getAlphaMode=function(){return this._alphaMode};yt.prototype.setAlphaEquation=function(n){if(this._alphaEquation!==n){switch(n){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774);break}this._alphaEquation=n}};yt.prototype.getAlphaEquation=function(){return this._alphaEquation};function Nz(n,e,t=!1,i){switch(n){case 3:{const s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e);return i&&s.set(new Int8Array(i)),s}case 0:{const s=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}case 4:{const s=e instanceof ArrayBuffer?new Int16Array(e):new Int16Array(t?e/2:e);return i&&s.set(new Int16Array(i)),s}case 5:case 8:case 9:case 10:case 2:{const s=e instanceof ArrayBuffer?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&s.set(new Uint16Array(i)),s}case 6:{const s=e instanceof ArrayBuffer?new Int32Array(e):new Int32Array(t?e/4:e);return i&&s.set(new Int32Array(i)),s}case 7:case 11:case 12:case 13:case 14:case 15:{const s=e instanceof ArrayBuffer?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&s.set(new Uint32Array(i)),s}case 1:{const s=e instanceof ArrayBuffer?new Float32Array(e):new Float32Array(t?e/4:e);return i&&s.set(new Float32Array(i)),s}}const r=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&r.set(new Uint8Array(i)),r}yt.prototype._readTexturePixelsSync=function(n,e,t,i=-1,r=0,s=null,a=!0,o=!1,c=0,l=0){var d,f;const h=this._gl;if(!h)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const p=h.createFramebuffer();if(!p)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=p}h.bindFramebuffer(h.FRAMEBUFFER,this._dummyFramebuffer),i>-1?h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_CUBE_MAP_POSITIVE_X+i,(d=n._hardwareTexture)==null?void 0:d.underlyingResource,r):h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,(f=n._hardwareTexture)==null?void 0:f.underlyingResource,r);let u=n.type!==void 0?this._getWebGLTextureType(n.type):h.UNSIGNED_BYTE;if(o)s||(s=Nz(n.type,4*e*t));else switch(u){case h.UNSIGNED_BYTE:s||(s=new Uint8Array(4*e*t)),u=h.UNSIGNED_BYTE;break;default:s||(s=new Float32Array(4*e*t)),u=h.FLOAT;break}return a&&this.flushFramebuffer(),h.readPixels(c,l,e,t,h.RGBA,u,s),h.bindFramebuffer(h.FRAMEBUFFER,this._currentFramebuffer),s};yt.prototype._readTexturePixels=function(n,e,t,i=-1,r=0,s=null,a=!0,o=!1,c=0,l=0){return Promise.resolve(this._readTexturePixelsSync(n,e,t,i,r,s,a,o,c,l))};yt.prototype.updateDynamicIndexBuffer=function(n,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(n);let i;n.is32Bits?i=e instanceof Uint32Array?e:new Uint32Array(e):i=e instanceof Uint16Array?e:new Uint16Array(e),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()};yt.prototype.updateDynamicVertexBuffer=function(n,e,t,i){this.bindArrayBuffer(n),t===void 0&&(t=0);const r=e.byteLength||e.length;i===void 0||i>=r&&t===0?e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e):e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(e).subarray(t,t+i)):(e instanceof ArrayBuffer?e=new Uint8Array(e,t,i):e=new Uint8Array(e.buffer,e.byteOffset+t,i),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)),this._resetVertexBufferBinding()};class De extends yt{static get NpmPackage(){return yt.NpmPackage}static get Version(){return yt.Version}static get Instances(){return bt.Instances}static get LastCreatedEngine(){return bt.LastCreatedEngine}static get LastCreatedScene(){return bt.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise((r,s)=>{const a=new Image;a.onload=()=>{a.decode().then(()=>{this.createImageBitmap(a,t).then(o=>{r(o)})})},a.onerror=()=>{s(`Error loading image ${a.src}`)},a.src=e})}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const s=this.createCanvas(t,i).getContext("2d");if(!s)throw new Error("Unable to get 2d context for resizeImageBitmap");return s.drawImage(e,0,0),s.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=i=>{this.disableContextMenu&&i.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=i=>{document.elementFromPoint(i.clientX,i.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(i)};const t=this.getHostWindow();t&&typeof t.addEventListener=="function"&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!De.audioEngine&&this._creationOptions.audioEngine&&De.AudioEngineFactory&&(De.audioEngine=De.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),Ny()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&De._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=De.OfflineProviderFactory!==void 0,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;(e=this._onPointerLockChange)==null||e.call(this)}getAspectRatio(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){const i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()}restoreStencilState(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)}setDirectViewport(e,t,i,r){const s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){const s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise((r,s)=>{this._loadFile(e,a=>{r(a)},void 0,t,i,(a,o)=>{s(o)})})}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,r){e!==void 0&&(t&&(this._boundUniforms[e]=t),!i||!i.depthStencilTexture?this._setTexture(e,null,void 0,void 0,r):this._setTexture(e,i,!1,!0,r))}setTextureFromPostProcess(e,t,i){let r=null;t&&(t._forcedOutputTexture?r=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(r=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,(r==null?void 0:r.texture)??null,i)}setTextureFromPostProcessOutput(e,t,i){var r;this._bindTexture(e,((r=t==null?void 0:t._outputTexture)==null?void 0:r.texture)??null,i)}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}_rebuildTextures(){for(const e of this.scenes)e._rebuildTextures();for(const e of this._virtualScenes)e._rebuildTextures();super._rebuildTextures()}_renderFrame(){for(let e=0;e1&&s){const o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(a,s),e.transformFeedback=o}return r.linkProgram(a),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),a}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach(t=>{t.postProcesses.forEach(i=>{i._outputTexture===e&&(i._outputTexture=null)}),t.cameras.forEach(i=>{i._postProcesses.forEach(r=>{r&&r._outputTexture===e&&(r._outputTexture=null)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++De._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(c){c._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],a,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,r,0,0,t.width,t.height,0),this.unBindFramebuffer(a),a.dispose(),s&&s()}))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3,r=0,s=0){const a=new j6(e,this._gl),o=new Ar(this,mi.Unknown,!0);return o._hardwareTexture=a,o.baseWidth=r,o.baseHeight=s,o.width=r,o.height=s,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,r=0){const s=this._gl,a=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),c=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,r,c,o,a,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){de.Error("WebGL 1 does not support texture comparison.");return}const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),t===0?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),t===0?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new z8(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const r=this._gl;return new Promise((s,a)=>{const o=()=>{const c=r.clientWaitSync(e,t,0);if(c==r.WAIT_FAILED){a();return}if(c==r.TIMEOUT_EXPIRED){setTimeout(o,i);return}s()};o()})}_readPixelsAsync(e,t,i,r,s,a,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const c=this._gl,l=c.createBuffer();c.bindBuffer(c.PIXEL_PACK_BUFFER,l),c.bufferData(c.PIXEL_PACK_BUFFER,o.byteLength,c.STREAM_READ),c.readPixels(e,t,i,r,s,a,0),c.bindBuffer(c.PIXEL_PACK_BUFFER,null);const h=c.fenceSync(c.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(c.flush(),this._clientWaitAsync(h,0,10).then(()=>(c.deleteSync(h),c.bindBuffer(c.PIXEL_PACK_BUFFER,l),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,o),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),c.deleteBuffer(l),o))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();bt.Instances.length===1&&De.audioEngine&&(De.audioEngine.dispose(),De.audioEngine=null);const e=this.getHostWindow();e&&typeof e.removeEventListener=="function"&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),Ny()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();const t=bt.Instances.indexOf(this);t>=0&&bt.Instances.splice(t,1),De.Instances.length||bt.OnEnginesDisposedObservable.notifyObservers(this),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){!this._renderingCanvas||!this._renderingCanvas.setAttribute||(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){if(!io())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!io())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=De.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then(()=>{e.focus()}).catch(()=>{}):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){const t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);let s=0,a=0;try{a=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:s,height:a,descent:a-s}}}De.ALPHA_DISABLE=0;De.ALPHA_ADD=1;De.ALPHA_COMBINE=2;De.ALPHA_SUBTRACT=3;De.ALPHA_MULTIPLY=4;De.ALPHA_MAXIMIZED=5;De.ALPHA_ONEONE=6;De.ALPHA_PREMULTIPLIED=7;De.ALPHA_PREMULTIPLIED_PORTERDUFF=8;De.ALPHA_INTERPOLATE=9;De.ALPHA_SCREENMODE=10;De.DELAYLOADSTATE_NONE=0;De.DELAYLOADSTATE_LOADED=1;De.DELAYLOADSTATE_LOADING=2;De.DELAYLOADSTATE_NOTLOADED=4;De.NEVER=512;De.ALWAYS=519;De.LESS=513;De.EQUAL=514;De.LEQUAL=515;De.GREATER=516;De.GEQUAL=518;De.NOTEQUAL=517;De.KEEP=7680;De.REPLACE=7681;De.INCR=7682;De.DECR=7683;De.INVERT=5386;De.INCR_WRAP=34055;De.DECR_WRAP=34056;De.TEXTURE_CLAMP_ADDRESSMODE=0;De.TEXTURE_WRAP_ADDRESSMODE=1;De.TEXTURE_MIRROR_ADDRESSMODE=2;De.TEXTUREFORMAT_ALPHA=0;De.TEXTUREFORMAT_LUMINANCE=1;De.TEXTUREFORMAT_LUMINANCE_ALPHA=2;De.TEXTUREFORMAT_RGB=4;De.TEXTUREFORMAT_RGBA=5;De.TEXTUREFORMAT_RED=6;De.TEXTUREFORMAT_R=6;De.TEXTUREFORMAT_RG=7;De.TEXTUREFORMAT_RED_INTEGER=8;De.TEXTUREFORMAT_R_INTEGER=8;De.TEXTUREFORMAT_RG_INTEGER=9;De.TEXTUREFORMAT_RGB_INTEGER=10;De.TEXTUREFORMAT_RGBA_INTEGER=11;De.TEXTURETYPE_UNSIGNED_BYTE=0;De.TEXTURETYPE_UNSIGNED_INT=0;De.TEXTURETYPE_FLOAT=1;De.TEXTURETYPE_HALF_FLOAT=2;De.TEXTURETYPE_BYTE=3;De.TEXTURETYPE_SHORT=4;De.TEXTURETYPE_UNSIGNED_SHORT=5;De.TEXTURETYPE_INT=6;De.TEXTURETYPE_UNSIGNED_INTEGER=7;De.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;De.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;De.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;De.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;De.TEXTURETYPE_UNSIGNED_INT_24_8=12;De.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;De.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;De.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;De.TEXTURE_NEAREST_SAMPLINGMODE=1;De.TEXTURE_BILINEAR_SAMPLINGMODE=2;De.TEXTURE_TRILINEAR_SAMPLINGMODE=3;De.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;De.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;De.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;De.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;De.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;De.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;De.TEXTURE_NEAREST_LINEAR=7;De.TEXTURE_NEAREST_NEAREST=1;De.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;De.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;De.TEXTURE_LINEAR_LINEAR=2;De.TEXTURE_LINEAR_NEAREST=12;De.TEXTURE_EXPLICIT_MODE=0;De.TEXTURE_SPHERICAL_MODE=1;De.TEXTURE_PLANAR_MODE=2;De.TEXTURE_CUBIC_MODE=3;De.TEXTURE_PROJECTION_MODE=4;De.TEXTURE_SKYBOX_MODE=5;De.TEXTURE_INVCUBIC_MODE=6;De.TEXTURE_EQUIRECTANGULAR_MODE=7;De.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;De.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;De.SCALEMODE_FLOOR=1;De.SCALEMODE_NEAREST=2;De.SCALEMODE_CEILING=3;De._RescalePostProcessFactory=null;De._RenderPassIdCounter=0;const tRe=ce.Compose(P.One(),we.FromEulerAngles(0,Math.PI,0),P.Zero());class Et extends Lr{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&Et.BILLBOARDMODE_USE_POSITION)!==0,this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==Et.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t),this._forward=new P(0,0,1),this._up=new P(0,1,0),this._right=new P(1,0,0),this._position=P.Zero(),this._rotation=P.Zero(),this._rotationQuaternion=null,this._scaling=P.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Et.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=ce.Zero(),this._usePivotMatrix=!1,this._absolutePosition=P.Zero(),this._absoluteScaling=P.Zero(),this._absoluteRotationQuaternion=we.Identity(),this._pivotMatrix=ce.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new Ae,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return P.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return P.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return P.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=ce.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Et.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=ce.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);r&&i&&i(this,r);for(const s of this.getChildTransformNodes(!0))s.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||we.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,r;if(e.x===void 0){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){const s=ie.Matrix[0];this.parent.getWorldMatrix().invertToRef(s),P.TransformCoordinatesFromFloatsToRef(t,i,r,s,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=P.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=ie.Matrix[0];return this._localMatrix.invertToRef(e),P.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=P.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=Ci.LOCAL){const a=Et._LookAtVectorCache,o=s===Ci.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,a),this.setDirection(a,t,i,r),s===Ci.WORLD&&this.parent)if(this.rotationQuaternion){const c=ie.Matrix[0];this.rotationQuaternion.toRotationMatrix(c);const l=ie.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(l),l.invert(),c.multiplyToRef(l,c),this.rotationQuaternion.fromRotationMatrix(c)}else{const c=ie.Quaternion[0];we.FromEulerVectorToRef(this.rotation,c);const l=ie.Matrix[0];c.toRotationMatrix(l);const h=ie.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),l.multiplyToRef(h,l),c.fromRotationMatrix(l),c.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=P.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return P.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){const s=-Math.atan2(e.z,e.x)+Math.PI/2,a=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,a);return this.rotationQuaternion?we.RotationYawPitchRollToRef(s+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=Ci.LOCAL){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==Ci.WORLD){const r=ie.Matrix[0];i.invertToRef(r),e=P.TransformCoordinates(e,r)}return this.setPivotMatrix(ce.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=P.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=P.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),P.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const r=ie.Quaternion[0],s=ie.Vector3[0],a=ie.Vector3[1],o=ie.Matrix[1];ce.IdentityToRef(o);const c=ie.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=Et._TmpRotation,we.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),ce.ComposeToRef(this.scaling,l,this.position,c),this.parent&&c.multiplyToRef(this.parent.computeWorldMatrix(!0),c),e&&(e.computeWorldMatrix(!0).invertToRef(o),c.multiplyToRef(o,c)),c.decompose(a,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(a),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(ce.Identity()),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling===e?!1:(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0));let r;if(!i||i===Ci.LOCAL)r=we.RotationAxisToRef(e,t,Et._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);else{if(this.parent){const s=this.parent.getWorldMatrix(),a=ie.Matrix[0];s.invertToRef(a),e=P.TransformNormal(e,a),s.determinant()<0&&(t*=-1)}r=we.RotationAxisToRef(e,t,Et._RotationAxisCache),r.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=we.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const r=ie.Vector3[0],s=ie.Vector3[1],a=ie.Vector3[2],o=ie.Quaternion[0],c=ie.Matrix[0],l=ie.Matrix[1],h=ie.Matrix[2],u=ie.Matrix[3];return e.subtractToRef(this.position,r),ce.TranslationToRef(r.x,r.y,r.z,c),ce.TranslationToRef(-r.x,-r.y,-r.z,l),ce.RotationAxisToRef(t,i,h),l.multiplyToRef(h,u),u.multiplyToRef(c,u),u.decompose(s,o,a),this.position.addInPlace(a),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const r=e.scale(t);if(!i||i===Ci.LOCAL){const s=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(s)}else this.setAbsolutePosition(this.getAbsolutePosition().add(r));return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=ie.Quaternion[1],we.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));const s=ie.Quaternion[0];return we.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Et.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const r=this._cache;r.pivotMatrixUpdated=!1,r.billboardMode=this.billboardMode,r.infiniteDistance=this.infiniteDistance,r.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const s=this._getEffectiveParent(),a=Et._TmpScaling;let o=this._position;if(this._infiniteDistance&&!this.parent&&t){const l=t.getWorldMatrix(),h=new P(l.m[12],l.m[13],l.m[14]);o=Et._TmpTranslation,o.copyFromFloats(this._position.x+h.x,this._position.y+h.y,this._position.z+h.z)}a.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let c;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,c=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(we.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(c=Et._TmpRotation,we.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,c)),this._usePivotMatrix){const l=ie.Matrix[1];ce.ScalingToRef(a.x,a.y,a.z,l);const h=ie.Matrix[0];c.toRotationMatrix(h),this._pivotMatrix.multiplyToRef(l,ie.Matrix[4]),ie.Matrix[4].multiplyToRef(h,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else ce.ComposeToRef(a,c,o,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),r.useBillboardPath){if(this._transformToBoneReferal){const d=this.parent;d.getSkeleton().prepare(),d.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),ie.Matrix[7])}else ie.Matrix[7].copyFrom(s.getWorldMatrix());const l=ie.Vector3[5],h=ie.Vector3[6],u=ie.Quaternion[0];ie.Matrix[7].decompose(h,u,l),ce.ScalingToRef(h.x,h.y,h.z,ie.Matrix[7]),ie.Matrix[7].setTranslation(l),Et.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,l),this._localMatrix.setTranslation(l)),this._localMatrix.multiplyToRef(ie.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const l=this.parent;l.getSkeleton().prepare(),this._localMatrix.multiplyToRef(l.getFinalMatrix(),ie.Matrix[6]),ie.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(r.useBillboardPath&&t&&this.billboardMode&&!r.useBillboardPosition){const l=ie.Vector3[0];if(this._worldMatrix.getTranslationToRef(l),ie.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&ie.Matrix[1].multiplyToRef(tRe,ie.Matrix[1]),ie.Matrix[1].setTranslationFromFloats(0,0,0),ie.Matrix[1].invertToRef(ie.Matrix[0]),(this.billboardMode&Et.BILLBOARDMODE_ALL)!==Et.BILLBOARDMODE_ALL){ie.Matrix[0].decompose(void 0,ie.Quaternion[0],void 0);const h=ie.Vector3[1];ie.Quaternion[0].toEulerAnglesToRef(h),(this.billboardMode&Et.BILLBOARDMODE_X)!==Et.BILLBOARDMODE_X&&(h.x=0),(this.billboardMode&Et.BILLBOARDMODE_Y)!==Et.BILLBOARDMODE_Y&&(h.y=0),(this.billboardMode&Et.BILLBOARDMODE_Z)!==Et.BILLBOARDMODE_Z&&(h.z=0),ce.RotationYawPitchRollToRef(h.y,h.x,h.z,ie.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ie.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ie.Vector3[0])}else if(r.useBillboardPath&&t&&r.useBillboardPosition){const l=ie.Vector3[0];this._worldMatrix.getTranslationToRef(l);const h=t.globalPosition;this._worldMatrix.invertToRef(ie.Matrix[1]);const u=ie.Vector3[1];P.TransformCoordinatesToRef(h,ie.Matrix[1],u),u.normalize();const d=-Math.atan2(u.z,u.x)+Math.PI/2,f=Math.sqrt(u.x*u.x+u.z*u.z),p=-Math.atan2(u.y,f);if(we.RotationYawPitchRollToRef(d,p,0,ie.Quaternion[0]),(this.billboardMode&Et.BILLBOARDMODE_ALL)!==Et.BILLBOARDMODE_ALL){const _=ie.Vector3[1];ie.Quaternion[0].toEulerAnglesToRef(_),(this.billboardMode&Et.BILLBOARDMODE_X)!==Et.BILLBOARDMODE_X&&(_.x=0),(this.billboardMode&Et.BILLBOARDMODE_Y)!==Et.BILLBOARDMODE_Y&&(_.y=0),(this.billboardMode&Et.BILLBOARDMODE_Z)!==Et.BILLBOARDMODE_Z&&(_.z=0),ce.RotationYawPitchRollToRef(_.y,_.x,_.z,ie.Matrix[0])}else ce.FromQuaternionToRef(ie.Quaternion[0],ie.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ie.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ie.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=ce.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;inew Et(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){const s=this.getDescendants(!0);for(let a=0;anew Et(e.name,t),e,t,i);if(e.localMatrix?r.setPreTransformMatrix(ce.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(ce.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let s=0;s(!t||t(r))&&r instanceof Et),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const i=this._parentContainer.transformNodes.indexOf(this);i>-1&&this._parentContainer.transformNodes.splice(i,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const i=this.getChildTransformNodes(!0);for(const r of i)r.parent=null,r.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const a=this.getHierarchyBoundingVectors(e,i),o=a.max.subtract(a.min),c=Math.max(o.x,o.y,o.z);if(c===0)return this;const l=1/c;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}Et.BILLBOARDMODE_NONE=0;Et.BILLBOARDMODE_X=1;Et.BILLBOARDMODE_Y=2;Et.BILLBOARDMODE_Z=4;Et.BILLBOARDMODE_ALL=7;Et.BILLBOARDMODE_USE_POSITION=128;Et.BillboardUseParentOrientation=!1;Et._TmpRotation=we.Zero();Et._TmpScaling=P.Zero();Et._TmpTranslation=P.Zero();Et._LookAtVectorCache=new P(0,0,0);Et._RotationAxisCache=new we;B([Js("position")],Et.prototype,"_position",void 0);B([Js("rotation")],Et.prototype,"_rotation",void 0);B([W_e("rotationQuaternion")],Et.prototype,"_rotationQuaternion",void 0);B([Js("scaling")],Et.prototype,"_scaling",void 0);B([K("billboardMode")],Et.prototype,"_billboardMode",void 0);B([K()],Et.prototype,"scalingDeterminant",void 0);B([K("infiniteDistance")],Et.prototype,"_infiniteDistance",void 0);B([K()],Et.prototype,"ignoreNonUniformScaling",void 0);B([K()],Et.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Cme{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new P(0,0,0),this._diffPositionForCollisions=new P(0,0,0),this._collisionResponse=!0}}class iRe{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=P.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class rRe{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new iRe,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new Cme,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class di extends Et{static get BILLBOARDMODE_NONE(){return Et.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Et.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Et.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Et.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Et.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Et.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return super._updateNonUniformScalingState(e)?(this._markSubMeshesAsMiscDirty(),!0):!1}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(t===1&&e!==1||t!==1&&e===1)&&this._markSubMeshesAsDirty(i=>{i.markAsMiscDirty(),i.markAsPrePassDirty()})}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return(t=this._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:t[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new rRe,this._waitingMaterialId=null,this.cullingStrategy=di.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new Ae,this.onCollisionPositionChangeObservable=new Ae,this.onMaterialChangedObservable=new Ae,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=Me.Red(),this.outlineWidth=.02,this.overlayColor=Me.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new P(.5,1,.5),this.ellipsoidOffset=new P(0,0,0),this.edgesWidth=1,this.edgesColor=new Ze(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new Ae,this._onCollisionPositionChange=(i,r,s=null)=>{r.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>De.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),s&&this.onCollideObservable.notifyObservers(s),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new Ft(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case $p.Aggressive:this.doNotSyncBoundingInfo=!0;case $p.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1;break}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+(this.getClassName()!=="InstancedMesh"?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==Et.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes){for(const t of this.subMeshes)t._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let r=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);i!==-1&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,r){return this}updateVerticesData(e,t,i,r){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new uc(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(Z.MatricesIndicesKind)&&this.isVerticesDataPresent(Z.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Et.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const r=new ce;(this.rotationQuaternion?this.rotationQuaternion:we.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(r);const a=P.Zero(),o=this.definedFacingForward?-1:1;return P.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,r,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const r=this.definedFacingForward?1:-1;return new P(e*r,t,i*r)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked?this:(this._refreshBoundingInfo(this._getPositionData(e,t),null),this)}_refreshBoundingInfo(e,t){if(e){const i=W8(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new uc(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i4,c=o?this.getVerticesData(Z.MatricesIndicesExtraKind):null,l=o?this.getVerticesData(Z.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this),u=ie.Vector3[0],d=ie.Matrix[0],f=ie.Matrix[1];let p=0;for(let _=0;_0&&(ce.FromFloat32ArrayToRefScaled(h,Math.floor(s[p+m]*16),g,f),d.addToSelf(f));if(o)for(m=0;m<4;m++)g=l[p+m],g>0&&(ce.FromFloat32ArrayToRefScaled(h,Math.floor(c[p+m]*16),g,f),d.addToSelf(f));r===Z.NormalKind?P.TransformNormalFromFloatsToRef(i[_],i[_+1],i[_+2],d,u):P.TransformCoordinatesFromFloatsToRef(i[_],i[_+1],i[_+2],d,u),u.toArray(i,_),r===Z.PositionKind&&this._positions&&this._positions[_/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,Z.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,Z.PositionKind)}_getPositionData(e,t){var r;let i=this.getVerticesData(Z.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.slice(),this._generatePointsArray(),this._positions){const s=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(s.length);for(let a=0;a1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(const a of this.getChildMeshes())if(a.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const i=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=i.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const s=e.verticesStart,a=e.verticesStart+e.verticesCount;for(let o=s;o1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=ie.Matrix[0],i=ie.Matrix[1];return ce.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,a=!1){const o=new Ro,c=this.getClassName(),l=c==="InstancedLinesMesh"||c==="LinesMesh"||c==="GreasedLineMesh"?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(h.boundingSphere,l)||!e.intersectsBox(h.boundingBox,l)))return o;if(r)return o.hit=!a,o.pickedMesh=a?null:this,o.distance=a?0:P.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let u=null;const d=this._scene.getIntersectingSubMeshCandidates(this,e),f=d.length;let p=!1;for(let _=0;_1&&!a&&!m.canIntersects(e))continue;const g=m.intersects(e,this._positions,this.getIndices(),t,i);if(g&&(t||!u||g.distanceo!==this&&o.actionManager===this.actionManager)||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let c=o.includedOnlyMeshes.indexOf(this);c!==-1&&o.includedOnlyMeshes.splice(c,1),c=o.excludedMeshes.indexOf(this),c!==-1&&o.excludedMeshes.splice(c,1);const l=o.getShadowGenerators();if(l){const h=l.values();for(let u=h.next();u.done!==!0;u=h.next()){const f=u.value.getShadowMap();f&&f.renderList&&(c=f.renderList.indexOf(this),c!==-1&&f.renderList.splice(c,1))}}}),(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes();const a=r.getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,a.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),a.wipeCaches(),r.removeMesh(this),this._parentContainer){const o=this._parentContainer.meshes.indexOf(this);o>-1&&this._parentContainer.meshes.splice(o,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){o=!0;break}o?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(o,c){return c.sqDistance-o.sqDistance},!e.facetDepthSortFrom){const o=this.getScene().activeCamera;e.facetDepthSortFrom=o?o.position:P.Zero()}e.depthSortedFacets=[];for(let o=0;oni?s.maximum.x-s.minimum.x:ni,e.bbSize.y=s.maximum.y-s.minimum.y>ni?s.maximum.y-s.minimum.y:ni,e.bbSize.z=s.maximum.z-s.minimum.z>ni?s.maximum.z-s.minimum.z:ni;let a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),P.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&et.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const o=e.depthSortedIndices.length/3|0;for(let c=0;cs.subDiv.max||o<0||o>s.subDiv.max||c<0||c>s.subDiv.max?null:s.facetPartitioning[a+s.subDiv.max*o+s.subDiv.max*s.subDiv.max*c]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,a=!0){const o=this.getWorldMatrix(),c=ie.Matrix[5];o.invertToRef(c);const l=ie.Vector3[8];P.TransformCoordinatesFromFloatsToRef(e,t,i,c,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,r,s,a);return r&&P.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),h}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,a=!0){let o=null,c=0,l=0,h=0,u=0,d=0,f=0,p=0,_=0;const m=this.getFacetLocalPositions(),g=this.getFacetLocalNormals(),v=this.getFacetsAtLocalCoordinates(e,t,i);if(!v)return null;let x=Number.MAX_VALUE,y=x,C,b,T;for(let S=0;S=0||s&&!a&&u<=0)&&(u=b.x*T.x+b.y*T.y+b.z*T.z,d=-(b.x*e+b.y*t+b.z*i-u)/(b.x*b.x+b.y*b.y+b.z*b.z),f=e+b.x*d,p=t+b.y*d,_=i+b.z*d,c=f-e,l=p-t,h=_-i,y=c*c+l*l+h*h,ye.emitter===this)}}di.OCCLUSION_TYPE_NONE=0;di.OCCLUSION_TYPE_OPTIMISTIC=1;di.OCCLUSION_TYPE_STRICT=2;di.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;di.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;di.CULLINGSTRATEGY_STANDARD=0;di.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;di.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;di.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;xe("BABYLON.AbstractMesh",di);class u2{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){Qe.Clone(()=>e,this)}serialize(){return Qe.Serialize(this)}parse(e,t,i){Qe.Parse(()=>this,e,t,i)}}B([K()],u2.prototype,"func",null);B([K()],u2.prototype,"funcRef",null);B([K()],u2.prototype,"funcMask",null);B([K()],u2.prototype,"opStencilFail",null);B([K()],u2.prototype,"opDepthFail",null);B([K()],u2.prototype,"opStencilDepthPass",null);B([K()],u2.prototype,"mask",null);B([K()],u2.prototype,"enabled",null);var Ko;(function(n){n[n.Created=1]="Created",n[n.Disposed=2]="Disposed",n[n.GetDefineNames=4]="GetDefineNames",n[n.PrepareUniformBuffer=8]="PrepareUniformBuffer",n[n.IsReadyForSubMesh=16]="IsReadyForSubMesh",n[n.PrepareDefines=32]="PrepareDefines",n[n.BindForSubMesh=64]="BindForSubMesh",n[n.PrepareEffect=128]="PrepareEffect",n[n.GetAnimatables=256]="GetAnimatables",n[n.GetActiveTextures=512]="GetActiveTextures",n[n.HasTexture=1024]="HasTexture",n[n.FillRenderTargetTextures=2048]="FillRenderTargetTextures",n[n.HasRenderTargetTextures=4096]="HasRenderTargetTextures",n[n.HardBindForSubMesh=8192]="HardBindForSubMesh"})(Ko||(Ko={}));function Sa(n){n.indexOf("vClipPlane")===-1&&n.push("vClipPlane"),n.indexOf("vClipPlane2")===-1&&n.push("vClipPlane2"),n.indexOf("vClipPlane3")===-1&&n.push("vClipPlane3"),n.indexOf("vClipPlane4")===-1&&n.push("vClipPlane4"),n.indexOf("vClipPlane5")===-1&&n.push("vClipPlane5"),n.indexOf("vClipPlane6")===-1&&n.push("vClipPlane6")}function d2(n,e,t){const i=!!(n.clipPlane??e.clipPlane),r=!!(n.clipPlane2??e.clipPlane2),s=!!(n.clipPlane3??e.clipPlane3),a=!!(n.clipPlane4??e.clipPlane4),o=!!(n.clipPlane5??e.clipPlane5),c=!!(n.clipPlane6??e.clipPlane6);i&&t.push("#define CLIPPLANE"),r&&t.push("#define CLIPPLANE2"),s&&t.push("#define CLIPPLANE3"),a&&t.push("#define CLIPPLANE4"),o&&t.push("#define CLIPPLANE5"),c&&t.push("#define CLIPPLANE6")}function bme(n,e,t){let i=!1;const r=!!(n.clipPlane??e.clipPlane),s=!!(n.clipPlane2??e.clipPlane2),a=!!(n.clipPlane3??e.clipPlane3),o=!!(n.clipPlane4??e.clipPlane4),c=!!(n.clipPlane5??e.clipPlane5),l=!!(n.clipPlane6??e.clipPlane6);return t.CLIPPLANE!==r&&(t.CLIPPLANE=r,i=!0),t.CLIPPLANE2!==s&&(t.CLIPPLANE2=s,i=!0),t.CLIPPLANE3!==a&&(t.CLIPPLANE3=a,i=!0),t.CLIPPLANE4!==o&&(t.CLIPPLANE4=o,i=!0),t.CLIPPLANE5!==c&&(t.CLIPPLANE5=c,i=!0),t.CLIPPLANE6!==l&&(t.CLIPPLANE6=l,i=!0),i}function fa(n,e,t){let i=e.clipPlane??t.clipPlane;fS(n,"vClipPlane",i),i=e.clipPlane2??t.clipPlane2,fS(n,"vClipPlane2",i),i=e.clipPlane3??t.clipPlane3,fS(n,"vClipPlane3",i),i=e.clipPlane4??t.clipPlane4,fS(n,"vClipPlane4",i),i=e.clipPlane5??t.clipPlane5,fS(n,"vClipPlane5",i),i=e.clipPlane6??t.clipPlane6,fS(n,"vClipPlane6",i)}function fS(n,e,t){t&&n.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}const tde=Me.Black(),ide={NUM_MORPH_INFLUENCERS:0};function Ha(n,e,t){if(!n||n.LOGARITHMICDEPTH||n.indexOf&&n.indexOf("LOGARITHMICDEPTH")>=0){const i=t.activeCamera;i.mode===1&&de.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}function Oo(n,e,t,i=!1){t&&n.fogEnabled&&(!e||e.applyFog)&&n.fogMode!==0&&(t.setFloat4("vFogInfos",n.fogMode,n.fogStart,n.fogEnd,n.fogDensity),i?(n.fogColor.toLinearSpaceToRef(tde,n.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",tde)):t.setColor3("vFogColor",n.fogColor))}function Y6(n,e,t){ide.NUM_MORPH_INFLUENCERS=t,VO(n,e,ide)}function VO(n,e,t){const i=t.NUM_MORPH_INFLUENCERS;if(i>0&&bt.LastCreatedEngine){const r=bt.LastCreatedEngine.getCaps().maxVertexAttribs,s=e.morphTargetManager;if(s!=null&&s.isUsingTextureForTargets)return;const a=s&&s.supportsNormals&&t.NORMAL,o=s&&s.supportsTangents&&t.TANGENT,c=s&&s.supportsUVs&&t.UV1;for(let l=0;lr&&de.Error("Cannot add more vertex attributes for mesh "+e.name)}}function s_(n,e=!1){n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"),e&&(n.push("previousWorld0"),n.push("previousWorld1"),n.push("previousWorld2"),n.push("previousWorld3"))}function d1(n,e){const t=n.morphTargetManager;!n||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function L5(n,e){e.bindToEffect(n,"Scene")}function ks(n,e,t){e._needUVs=!0,e[t]=!0,n.optimizeUVAllocation&&n.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=n.coordinatesIndex+1,e["MAINUV"+(n.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function ms(n,e,t){const i=n.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function zO(n,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&n.push("bakedVertexAnimationSettingsInstanced")}function sRe(n,e){return e.set(n),e}function Yl(n,e,t){if(!(!e||!n)&&(n.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(n.computeBonesUsingShaders=!1),n.useBones&&n.computeBonesUsingShaders&&n.skeleton)){const i=n.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureWidth")>-1){const r=i.getTransformMatrixTexture(n);e.setTexture("boneSampler",r),e.setFloat("boneTextureWidth",4*(i.bones.length+1))}else{const r=i.getTransformMatrices(n);r&&(e.setMatrices("mBones",r),t&&n.getScene().prePassRenderer&&n.getScene().prePassRenderer.getIndex(2)&&(t.previousBones[n.uniqueId]||(t.previousBones[n.uniqueId]=r.slice()),e.setMatrices("mPreviousBones",t.previousBones[n.uniqueId]),sRe(r,t.previousBones[n.uniqueId])))}}}function Eme(n,e,t){n.transferToEffect(e,t+"")}function HO(n,e,t,i,r,s=!0){n._bindLight(e,t,i,r,s)}function gc(n,e,t,i,r=4){const s=Math.min(e.lightSources.length,r);for(let a=0;a0&&(i.addCPUSkinningFallback(0,e),n.push("matricesIndices"),n.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(n.push("matricesIndicesExtra"),n.push("matricesWeightsExtra")))}function pa(n,e){(e.INSTANCES||e.THIN_INSTANCES)&&s_(n,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&n.push("instanceColor")}function uo(n,e,t=4,i=0){let r=0;for(let s=0;s0&&(r=i+s,e.addFallback(r,"LIGHT"+s)),n.SHADOWS||(n["SHADOW"+s]&&e.addFallback(i,"SHADOW"+s),n["SHADOWPCF"+s]&&e.addFallback(i,"SHADOWPCF"+s),n["SHADOWPCSS"+s]&&e.addFallback(i,"SHADOWPCSS"+s),n["SHADOWPOISSON"+s]&&e.addFallback(i,"SHADOWPOISSON"+s),n["SHADOWESM"+s]&&e.addFallback(i,"SHADOWESM"+s),n["SHADOWCLOSEESM"+s]&&e.addFallback(i,"SHADOWCLOSEESM"+s));return r++}function oG(n,e){return e.fogEnabled&&n.applyFog&&e.fogMode!==0}function Ql(n,e,t,i,r,s,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=t,a.POINTSIZE=i,a.FOG=r&&oG(n,e),a.NONUNIFORMSCALING=n.nonUniformScaling,a.ALPHATEST=s,a.DECAL_AFTER_DETAIL=o)}function vc(n,e,t,i,r=4,s=!1){if(!t._areLightsDirty)return t._needNormals;let a=0;const o={needNormals:t._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(n.lightsEnabled&&!s){for(const l of e.lightSources)if(GO(n,e,l,a,t,i,o),a++,a===r)break}t.SPECULARTERM=o.specularEnabled,t.SHADOWS=o.shadowEnabled;for(let l=a;l0&&(a.shadowEnabled=!0,o.prepareDefines(r,i))}}t.lightmapMode!=os.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+i]=!0,r["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==os.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+i]=!1,r["LIGHTMAPNOSPECULAR"+i]=!1)}function $l(n,e,t,i,r,s=null,a=!1){let o=uG(n,i);s!==!1&&(o=bme(t,n,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),i.THIN_INSTANCES!==a&&(i.THIN_INSTANCES=a,o=!0),o&&i.markAsUnprocessed()}function lG(n,e){if(n.useBones&&n.computeBonesUsingShaders&&n.skeleton){e.NUM_BONE_INFLUENCERS=n.numBoneInfluencers;const t=e.BONETEXTURE!==void 0;if(n.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=n.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;const i=n.getScene().prePassRenderer;if(i&&i.enabled){const r=i.excludedSkinnedMesh.indexOf(n)===-1;e.BONES_VELOCITY_ENABLED=r}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function cG(n,e){const t=n.morphTargetManager;t?(e.MORPHTARGETS_UV=t.supportsUVs&&e.UV1,e.MORPHTARGETS_TANGENT=t.supportsTangents&&e.TANGENT,e.MORPHTARGETS_NORMAL=t.supportsNormals&&e.NORMAL,e.NUM_MORPH_INFLUENCERS=t.numMaxInfluencers||t.numInfluencers,e.MORPHTARGETS=e.NUM_MORPH_INFLUENCERS>0,e.MORPHTARGETS_TEXTURE=t.isUsingTextureForTargets):(e.MORPHTARGETS_UV=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS=!1,e.NUM_MORPH_INFLUENCERS=0)}function UJ(n,e){const t=n.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function qn(n,e,t,i,r=!1,s=!0,a=!0){if(!e._areAttributesDirty&&e._needNormals===e._normals&&e._needUVs===e._uvs)return!1;e._normals=e._needNormals,e._uvs=e._needUVs,e.NORMAL=e._needNormals&&n.isVerticesDataPresent("normal"),e._needNormals&&n.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let o=1;o<=6;++o)e["UV"+o]=e._needUVs?n.isVerticesDataPresent(`uv${o===1?"":o}`):!1;if(t){const o=n.useVertexColors&&n.isVerticesDataPresent("color");e.VERTEXCOLOR=o,e.VERTEXALPHA=n.hasVertexAlpha&&o&&s}return n.isVerticesDataPresent("instanceColor")&&(n.hasInstances||n.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&lG(n,e),r&&cG(n,e),a&&UJ(n,e),!0}function N5(n,e){if(n.activeCamera){const t=e.MULTIVIEW;e.MULTIVIEW=n.activeCamera.outputRenderTarget!==null&&n.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function hG(n,e,t){const i=e.ORDER_INDEPENDENT_TRANSPARENCY,r=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=n.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!n.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||r!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function KO(n,e,t){const i=e.PREPASS;if(!e._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(n.prePassRenderer&&n.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=n.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=n.prePassRenderer.generateNormalsInWorldSpace;for(let s=0;s{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const r=t||bt.LastCreatedScene;r&&(this._scene=r,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Ee.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Sn(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=Ye.ClockWiseSideOrientation:this.sideOrientation=Ye.CounterClockWiseSideOrientation,this._uniformBuffer=new Ft(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Ye.OnEventObservable.notifyObservers(this,Ko.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const r=t.materialDefines;return r?(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh):!1}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Ye.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Ye.MATERIAL_OPAQUE||this._transparencyMode===Ye.MATERIAL_ALPHATEST}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1?!0:this._disableAlphaBlending?!1:e.hasVertexAlpha||this.needAlphaBlending()}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes){for(const r of i.subMeshes)if(r.getMaterial()===this)for(const s of r._drawWrappers)s&&this._materialContext===s.materialContext&&(s._wasPreviouslyReady=!1,s._wasPreviouslyUsingInstances=null,s._forceRebindOnNextCall=e)}e&&this.markAsDirty(Ye.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(t??this.sideOrientation)===Ye.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(Ko.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const r=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,L5(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const r=this._scene.getEngine();this._cachedDepthWriteState=r.getDepthWrite(),r.setDepthWrite(!1)}if(this.disableColorWrite){const r=this._scene.getEngine();this._cachedColorWriteState=r.getColorWrite(),r.setColorWrite(!1)}if(this.depthFunction!==0){const r=this._scene.getEngine();this._cachedDepthFunctionState=r.getDepthFunction()||0,r.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(Ko.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Ko.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Ko.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Ye._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const r of this.pluginManager._plugins){const s=e.pluginManager.getPlugin(r.name);s&&r.copyTo(s)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,r){const s={clipPlane:!1,useInstances:!1,...i},a=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const c=()=>{if(!this._scene||!this._scene.getEngine())return;const l=a.clipPlane;if(s.clipPlane&&(a.clipPlane=new yl(0,0,0,1)),this._storeEffectOnSubMeshes){let h=!0,u=null;if(e.subMeshes){const d=new Xo(0,0,0,0,0,e,void 0,!1,!1);d.materialDefines&&(d.materialDefines._renderId=-1),this.isReadyForSubMesh(e,d,s.useInstances)||(d.effect&&d.effect.getCompilationError()&&d.effect.allFallbacksProcessed()?u=d.effect.getCompilationError():(h=!1,setTimeout(c,16)))}h&&(this.allowShaderHotSwapping=o,u&&r&&r(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(c,16);s.clipPlane&&(a.clipPlane=l)};c()}forceCompilationAsync(e,t){return new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,s=>{r(s)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Ye._DirtyCallbackArray.length=0,e&Ye.TextureDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._TextureDirtyCallBack),e&Ye.LightDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._LightsDirtyCallBack),e&Ye.FresnelDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._FresnelDirtyCallBack),e&Ye.AttributesDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._AttributeDirtyCallBack),e&Ye.MiscDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._MiscDirtyCallBack),e&Ye.PrePassDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._PrePassDirtyCallBack),Ye._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Ye._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const i of t.subMeshes)i.getMaterial()===this&&i.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const i of t)if(i.subMeshes){for(const r of i.subMeshes)if(r.getMaterial(!1)===this)for(const s of r._drawWrappers)!s||!s.defines||!s.defines.markAllAsDirty||this._materialContext===s.materialContext&&e(s.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Ye._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Ye._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Ye._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Ye._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Ye._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Ye._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Ye._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Ye._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Ye._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Ye._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==$p.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){const r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(Ko.Disposed,this._eventInfo),this._parentContainer){const s=this._parentContainer.materials.indexOf(this);s>-1&&this._parentContainer.materials.splice(s,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(const s in this.meshMap){const a=this.meshMap[s];a&&(a.material=null,this.releaseVertexArrayObject(a,e))}else{const s=r.meshes;for(const a of s)a.material===this&&!a.sourceMesh&&(a.material=null,this.releaseVertexArrayObject(a,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=Qe.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(!e.customType)e.customType="BABYLON.StandardMaterial";else if(e.customType==="BABYLON.PBRMaterial"&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return de.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const s=Ee.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,r){var s;if(e.plugins)for(const a in e.plugins){const o=e.plugins[a];let c=(s=t.pluginManager)==null?void 0:s.getPlugin(o.name);if(!c){const l=Ee.Instantiate("BABYLON."+a);l&&(c=new l(t))}c==null||c.parse(o,i,r)}}}Ye.TriangleFillMode=0;Ye.WireFrameFillMode=1;Ye.PointFillMode=2;Ye.PointListDrawMode=3;Ye.LineListDrawMode=4;Ye.LineLoopDrawMode=5;Ye.LineStripDrawMode=6;Ye.TriangleStripDrawMode=7;Ye.TriangleFanDrawMode=8;Ye.ClockWiseSideOrientation=0;Ye.CounterClockWiseSideOrientation=1;Ye.TextureDirtyFlag=1;Ye.LightDirtyFlag=2;Ye.FresnelDirtyFlag=4;Ye.AttributesDirtyFlag=8;Ye.MiscDirtyFlag=16;Ye.PrePassDirtyFlag=32;Ye.AllDirtyFlag=63;Ye.MATERIAL_OPAQUE=0;Ye.MATERIAL_ALPHATEST=1;Ye.MATERIAL_ALPHABLEND=2;Ye.MATERIAL_ALPHATESTANDBLEND=3;Ye.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;Ye.MATERIAL_NORMALBLENDMETHOD_RNM=1;Ye.OnEventObservable=new Ae;Ye._AllDirtyCallBack=n=>n.markAllAsDirty();Ye._ImageProcessingDirtyCallBack=n=>n.markAsImageProcessingDirty();Ye._TextureDirtyCallBack=n=>n.markAsTexturesDirty();Ye._FresnelDirtyCallBack=n=>n.markAsFresnelDirty();Ye._MiscDirtyCallBack=n=>n.markAsMiscDirty();Ye._PrePassDirtyCallBack=n=>n.markAsPrePassDirty();Ye._LightsDirtyCallBack=n=>n.markAsLightDirty();Ye._AttributeDirtyCallBack=n=>n.markAsAttributesDirty();Ye._FresnelAndMiscDirtyCallBack=n=>{Ye._FresnelDirtyCallBack(n),Ye._MiscDirtyCallBack(n)};Ye._TextureAndMiscDirtyCallBack=n=>{Ye._TextureDirtyCallBack(n),Ye._MiscDirtyCallBack(n)};Ye._DirtyCallbackArray=[];Ye._RunDirtyCallBacks=n=>{for(const e of Ye._DirtyCallbackArray)e(n)};B([K()],Ye.prototype,"id",void 0);B([K()],Ye.prototype,"uniqueId",void 0);B([K()],Ye.prototype,"name",void 0);B([K()],Ye.prototype,"metadata",void 0);B([K()],Ye.prototype,"checkReadyOnEveryCall",void 0);B([K()],Ye.prototype,"checkReadyOnlyOnce",void 0);B([K()],Ye.prototype,"state",void 0);B([K("alpha")],Ye.prototype,"_alpha",void 0);B([K("backFaceCulling")],Ye.prototype,"_backFaceCulling",void 0);B([K("cullBackFaces")],Ye.prototype,"_cullBackFaces",void 0);B([K()],Ye.prototype,"sideOrientation",void 0);B([K("alphaMode")],Ye.prototype,"_alphaMode",void 0);B([K()],Ye.prototype,"_needDepthPrePass",void 0);B([K()],Ye.prototype,"disableDepthWrite",void 0);B([K()],Ye.prototype,"disableColorWrite",void 0);B([K()],Ye.prototype,"forceDepthWrite",void 0);B([K()],Ye.prototype,"depthFunction",void 0);B([K()],Ye.prototype,"separateCullingPass",void 0);B([K("fogEnabled")],Ye.prototype,"_fogEnabled",void 0);B([K()],Ye.prototype,"pointSize",void 0);B([K()],Ye.prototype,"zOffset",void 0);B([K()],Ye.prototype,"zOffsetUnits",void 0);B([K()],Ye.prototype,"pointsCloud",null);B([K()],Ye.prototype,"fillMode",null);B([K()],Ye.prototype,"useLogarithmicDepth",null);B([K()],Ye.prototype,"transparencyMode",null);class Fu extends Ye{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...r)=>{const s=t.apply(e,r);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(r,s)=>{const a=i.apply(e,[r,s]);return this._markAllSubMeshesAsTexturesDirty(),a}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new Fu(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,vr&&vr.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(r=>i.subMaterials.push(t.getLastMaterialById(r))),i}}xe("BABYLON.MultiMaterial",Fu);class Tme{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class kJ{}class nRe{constructor(){this.visibleInstances={},this.batchCache=new O$,this.batchCacheReplacementModeInFrozenMode=new O$,this.instancesBufferSize=32*16*4}}class O${constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class aRe{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class oRe{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class Se extends di{static _GetDefaultSideOrientation(e){return e||Se.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(Z.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(Z.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new Ae),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new Ae),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new Ae),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new Ae),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new Ae),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,r=null,s,a=!0){if(super(e,t),this._internalMeshDataInfo=new oRe,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new nRe,this._thinInstanceDataStorage=new aRe,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=Se.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(o,c,l)=>{o&&l&&(this._uniformBuffer?this.transferToEffect(c):l.bindOnlyWorldMatrix(c))},r){if(r._geometry&&r._geometry.applyToMesh(this),ol.DeepCopy(r,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=r,t.useClonedMeshMap&&(r._internalMeshDataInfo.meshMap||(r._internalMeshDataInfo.meshMap={}),r._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=r._originalBuilderSideOrientation,this._creationDataStorage=r._creationDataStorage,r._ranges){const o=r._ranges;for(const c in o)Object.prototype.hasOwnProperty.call(o,c)&&o[c]&&this.createAnimationRange(c,o[c].from,o[c].to)}if(r.metadata&&r.metadata.clone?this.metadata=r.metadata.clone():this.metadata=r.metadata,this._internalMetadata=r._internalMetadata,vr&&vr.HasTags(r)&&vr.AddTagsTo(this,vr.GetTags(r,!0)),this.setEnabled(r.isEnabled(!1)),this.parent=r.parent,this.setPivotMatrix(r.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+r.id,this.material=r.material,!s){const o=r.getDescendants(!0);for(let c=0;c{o.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new Ae(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const r=this.getTotalVertices()===0||t&&t.doNotInstantiate&&(t.doNotInstantiate===!0||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r);for(const s of this.getChildTransformNodes(!0))s.getClassName()==="InstancedMesh"&&r.getClassName()==="Mesh"&&s.sourceMesh===this?s.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):s.instantiateHierarchy(r,t,i);return r}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return de.Warn("You cannot use a mesh as LOD level twice"),this;const i=new Tme(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;io*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let c=0;c0||this.hasThinInstances);this.computeWorldMatrix();const a=this.material||r.defaultMaterial;if(a){if(a._storeEffectOnSubMeshes)for(const f of this.subMeshes){const p=f.getMaterial();if(p){if(p._storeEffectOnSubMeshes){if(!p.isReadyForSubMesh(this,f,s))return!1}else if(!p.isReady(this,s))return!1}}else if(!a.isReady(this,s))return!1}const o=i.currentRenderPassId;for(const f of this.lightSources){const p=f.getShadowGenerators();if(!p)continue;const _=p.values();for(let m=_.next();m.done!==!0;m=_.next()){const g=m.value;if(g&&(!((c=g.getShadowMap())!=null&&c.renderList)||(l=g.getShadowMap())!=null&&l.renderList&&((u=(h=g.getShadowMap())==null?void 0:h.renderList)==null?void 0:u.indexOf(this))!==-1)){const x=g.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let y=0;y0){const i=this.getIndices();if(!i)return null;const r=i.length;let s=!1;if(e)s=!0;else for(const a of this.subMeshes){if(a.indexStart+a.indexCount>r){s=!0;break}if(a.verticesStart+a.verticesCount>t){s=!0;break}}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new Xo(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,r=0;for(;i%3!==0;)i++;this.releaseSubMeshes();for(let s=0;s=t);s++)Xo.CreateFromIndices(0,r,s===e-1?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,r){if(this._geometry)this._geometry.setVerticesData(e,t,i,r);else{const s=new et;s.set(t,e);const a=this.getScene();new Ua(Ua.RandomId(),a,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);!i||i.isUpdatable()===t||this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=Ua.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(Z.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(Z.PositionKind,i,!1,!1),t){const r=this.getIndices(),s=this.getVerticesData(Z.NormalKind);if(!s)return this;et.ComputeNormals(i,r,s),this.updateVerticesData(Z.NormalKind,s,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(this._geometry.meshes.length===1)return this;const e=this._geometry,t=this._geometry.copy(Ua.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let r=this._geometry;r||(r=new Ua(Ua.RandomId(),this.getScene(),void 0,void 0,this)),r.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const r=new et;r.indices=e;const s=this.getScene();new Ua(Ua.RandomId(),s,r,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,r=!0){if(!this._geometry)return this;const s=this.getScene().getEngine();this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t);let a;if(this._unIndexed)a=null;else switch(this._getRenderingFillMode(i)){case Ye.PointFillMode:a=null;break;case Ye.WireFrameFillMode:a=e._getLinesIndexBuffer(this.getIndices(),s);break;default:case Ye.TriangleFillMode:a=this._geometry.getIndexBuffer();break}return!r||!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,a):this._geometry._bind(t,a,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const s=this.getScene().getEngine();return this._unIndexed||t==Ye.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ye.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),r=i._isInIntermediateRendering(),s=r?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=this._instanceDataStorage.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!s&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const o=this._instanceDataStorage.visibleInstances,c=i.getRenderId(),l=r?o.intermediateDefaultRenderId:o.defaultRenderId;a.visibleInstances[e]=o[c],!a.visibleInstances[e]&&l&&(a.visibleInstances[e]=o[l])}return a.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&a.visibleInstances[e]!==null&&a.visibleInstances[e]!==void 0,this._instanceDataStorage.previousBatch=a,a}_renderWithInstances(e,t,i,r,s){var v;const a=i.visibleInstances[e._id],o=a?a.length:0,c=this._instanceDataStorage,l=c.instancesBufferSize;let h=c.instancesBuffer,u=c.instancesPreviousBuffer;const f=(o+1)*16*4;for(;c.instancesBufferSizeC._distanceToCamera>b._distanceToCamera?-1:C._distanceToCamera1&&r.activeCamera===r.activeCameras[0]||s<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const o=this._getInstancesRenderList(e._id,!!i);if(o.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const c=r.getEngine();let l=0,h=null;this.ignoreCameraMaxZ&&r.activeCamera&&!r._isInIntermediateRendering()&&(l=r.activeCamera.maxZ,h=r.activeCamera,r.activeCamera.maxZ=0,r.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const u=e.getRenderingMesh(),d=o.hardwareInstancedRendering[e._id]||u.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,f=this._instanceDataStorage,p=e.getMaterial();if(!p)return h&&(h.maxZ=l,r.updateTransformMatrix(!0)),this;if(!f.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==p){if(p._storeEffectOnSubMeshes){if(!p.isReadyForSubMesh(this,e,d))return h&&(h.maxZ=l,r.updateTransformMatrix(!0)),this}else if(!p.isReady(this,d))return h&&(h.maxZ=l,r.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=p}else if(p._storeEffectOnSubMeshes&&!((S=e._drawWrapper)!=null&&S._wasPreviouslyReady)||!p._storeEffectOnSubMeshes&&!p._getDrawWrapper()._wasPreviouslyReady)return h&&(h.maxZ=l,r.updateTransformMatrix(!0)),this;t&&c.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let _;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?_=e._drawWrapper:_=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const m=(_==null?void 0:_.effect)??null;for(const N of r._beforeRenderingMeshStage)N.action(this,e,o,m);if(!_||!m)return h&&(h.maxZ=l,r.updateTransformMatrix(!0)),this;const g=i||this;let v;if(!f.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this.overrideMaterialSideOrientation!==null||this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)){const N=g._getWorldMatrixDeterminant();v=this.overrideMaterialSideOrientation,v==null&&(v=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),N<0&&(v=v===Ye.ClockWiseSideOrientation?Ye.CounterClockWiseSideOrientation:Ye.ClockWiseSideOrientation),f.sideOrientation=v}else v=f.sideOrientation;const x=this._internalMeshDataInfo._effectiveMaterial._preBind(_,v);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&c.setDepthWrite(!0);const y=this._internalMeshDataInfo._effectiveMaterial,C=y.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),d||this._bind(e,m,C,!1);const b=g.getWorldMatrix();y._storeEffectOnSubMeshes?y.bindForSubMesh(b,this,e):y.bind(b,this),!y.backFaceCulling&&y.separateCullingPass&&(c.setState(!0,y.zOffset,!1,!x,y.cullBackFaces,y.stencil,y.zOffsetUnits),this._processRendering(this,e,m,C,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),c.setState(!0,y.zOffset,!1,x,y.cullBackFaces,y.stencil,y.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,m,C,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const N of r._afterRenderingMeshStage)N.action(this,e,o,m);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),h&&(h.maxZ=l,r.updateTransformMatrix(!0)),r.performancePriority===$p.Aggressive&&!f.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(Z.MatricesWeightsKind)&&(this.isVerticesDataPresent(Z.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(Z.MatricesWeightsKind),t=e.length;for(let i=0;ig&&r++,C!==0&&x++,v+=C,g=C}if(l[x]++,x>a&&(a=x),v===0)s++;else{const y=1/v;let C=0;for(let b=0;bh&&o++}}const u=this.skeleton.bones.length,d=this.getVerticesData(Z.MatricesIndicesKind),f=this.getVerticesData(Z.MatricesIndicesExtraKind);let p=0;for(let m=0;m=u||v<0)&&p++}const _="Number of Weights = "+i/4+` Maximum influences = `+a+` Missing Weights = `+s+` Not Sorted = `+r+` Not Normalized = `+o+` WeightCounts = [`+l+`] Number of bones = `+u+` Bad Bone Indices = `+p;return{skinned:!0,valid:s===0&&o===0&&p===0,report:_}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===4&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;return Ee.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this),this.instances.forEach(r=>{r.refreshBoundingInfo(),r._syncSubMeshes()}),this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState===2||!super.isInFrustum(e)?!1:(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const r=this.getScene().multiMaterials;for(i=r.length-1;i>-1;i--)if(r[i].id===e)return this.material=r[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(Z.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(Z.PositionKind);const r=P.Zero();let s;for(s=0;s{const d=u.width,f=u.height,_=this.getEngine().createCanvas(d,f).getContext("2d");_.drawImage(u,0,0);const m=_.getImageData(0,0,d,f).data;this.applyDisplacementMapFromBuffer(m,d,f,t,i,s,a,o),r&&r(this)};return Ee.LoadImage(e,h,c||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,r,s,a,o,c=!1){if(!this.isVerticesDataPresent(Z.PositionKind)||!this.isVerticesDataPresent(Z.NormalKind)||!this.isVerticesDataPresent(Z.UVKind))return de.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(Z.PositionKind,!0,!0),h=this.getVerticesData(Z.NormalKind),u=this.getVerticesData(Z.UVKind);let d=P.Zero();const f=P.Zero(),p=Be.Zero();a=a||Be.Zero(),o=o||new Be(1,1);for(let _=0;_{const l=new Float32Array(i.length*c);let h=0;for(let u=0;u{const o=r.length-1-a,c=r[o];for(let l=0;l{for(let o=0;o-1&&(r.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),e.skeletonId!==void 0&&e.skeletonId!==null&&(r.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let s=0;s4,l=c?this.getVerticesData(Z.MatricesIndicesExtraKind):null,h=c?this.getVerticesData(Z.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),d=P.Zero(),f=new ce,p=new ce;let _=0,m;for(let g=0;g0&&(ce.FromFloat32ArrayToRefScaled(u,Math.floor(a[_+m]*16),v,p),f.addToSelf(p));if(c)for(m=0;m<4;m++)v=h[_+m],v>0&&(ce.FromFloat32ArrayToRefScaled(u,Math.floor(l[_+m]*16),v,p),f.addToSelf(p));P.TransformCoordinatesFromFloatsToRef(i._sourcePositions[g],i._sourcePositions[g+1],i._sourcePositions[g+2],f,d),d.toArray(r,g),t&&(P.TransformNormalFromFloatsToRef(i._sourceNormals[g],i._sourceNormals[g+1],i._sourceNormals[g+2],f,d),d.toArray(s,g)),f.reset()}return this.updateVerticesData(Z.PositionKind,r),t&&this.updateVerticesData(Z.NormalKind,s),this}static MinMax(e){let t=null,i=null;return e.forEach(function(r){const a=r.getBoundingInfo().boundingBox;!t||!i?(t=a.minimumWorld,i=a.maximumWorld):(t.minimizeInPlace(a.minimumWorld),i.maximizeInPlace(a.maximumWorld))}),!t||!i?{min:P.Zero(),max:P.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?Se.MinMax(e):e;return P.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,r,s,a){return sG(Se._MergeMeshesCoroutine(e,t,i,r,s,a,!1))}static MergeMeshesAsync(e,t=!0,i,r,s,a){return nG(Se._MergeMeshesCoroutine(e,t,i,r,s,a,!0),gme())}static*_MergeMeshesCoroutine(e,t=!0,i,r,s,a,o){if(e=e.filter(Boolean),e.length===0)return null;let c;if(!i){let T=0;for(c=0;c=65536)return de.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}a&&(s=!1);const l=new Array,h=new Array,u=new Array,d=e[0].overrideMaterialSideOrientation;for(c=0;c{const S=T.computeWorldMatrix(!0);return{vertexData:et.ExtractFromMesh(T,!1,!1),transform:S}},{vertexData:_,transform:m}=p(f);o&&(yield);const g=new Array(e.length-1);for(let T=1;T{throw ci("GroundMesh")};Se._GoldbergMeshParser=(n,e)=>{throw ci("GoldbergMesh")};Se._LinesMeshParser=(n,e)=>{throw ci("LinesMesh")};Se._GreasedLineMeshParser=(n,e)=>{throw ci("GreasedLineMesh")};Se._GreasedLineRibbonMeshParser=(n,e)=>{throw ci("GreasedLineRibbonMesh")};Se._TrailMeshParser=(n,e)=>{throw ci("TrailMesh")};xe("BABYLON.Mesh",Se);Se._instancedMeshFactory=(n,e)=>{const t=new Kf(n,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class Kf extends di{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const i of t.getAnimationRanges())i!=null&&this.createAnimationRange(i.name,i.from,i.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;((t=this._sourceMesh)==null?void 0:t.receiveShadows)!==e&&Ee.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;((t=this._sourceMesh)==null?void 0:t.material)!==e&&Ee.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;((t=this._sourceMesh)==null?void 0:t.visibility)!==e&&Ee.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;((t=this._sourceMesh)==null?void 0:t.skeleton)!==e&&Ee.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){!this._sourceMesh||e===this._sourceMesh.renderingGroupId||de.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||de.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==Et.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new ce);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,ie.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(ie.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(!t||t.length===0)this._currentLOD=this.sourceMesh;else{const i=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,i.boundingSphere)}return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&this.includedOnlyMeshes.indexOf(e)===-1||this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1||this.includeOnlyWithLayerMask!==0&&!(this.includeOnlyWithLayerMask&e.layerMask)||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0}dispose(e,t=!1){if(this._shadowGenerators){const i=this._shadowGenerators.values();for(let r=i.next();r.done!==!0;r=i.next())r.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const i=this._parentContainer.lights.indexOf(this);i>-1&&this._parentContainer.lights.splice(i,1),this._parentContainer=null}for(const i of this.getScene().meshes)i._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=Ui.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const r=Qe.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){const e=Qe.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach(t=>{e.excludedMeshesIds.push(t.id)})),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach(t=>{e.includedOnlyMeshesIds.push(t.id)})),Qe.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const r=Lr.Construct("Light_Type_"+e,t,i);return r||null}static Parse(e,t){const i=Ui.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const r=Qe.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(r.falloffType=e.falloffType),e.lightmapMode!==void 0&&(r.lightmapMode=e.lightmapMode),e.animations){for(let s=0;s{const s=t.apply(e,r);for(const a of r)a._resyncLightSource(this);return s};const i=e.splice;e.splice=(r,s)=>{const a=i.apply(e,[r,s]);for(const o of a)o._resyncLightSource(this);return a};for(const r of e)r._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...r)=>{const s=t.apply(e,r);return this._resyncMeshes(),s};const i=e.splice;e.splice=(r,s)=>{const a=i.apply(e,[r,s]);return this._resyncMeshes(),a},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)e.lightSources.indexOf(this)!==-1&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===Ui.INTENSITYMODE_AUTOMATIC&&(t===Ui.LIGHTTYPEID_DIRECTIONALLIGHT?i=Ui.INTENSITYMODE_ILLUMINANCE:i=Ui.INTENSITYMODE_LUMINOUSINTENSITY),t){case Ui.LIGHTTYPEID_POINTLIGHT:case Ui.LIGHTTYPEID_SPOTLIGHT:switch(i){case Ui.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Ui.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Ui.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case Ui.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Ui.INTENSITYMODE_ILLUMINANCE:e=1;break;case Ui.INTENSITYMODE_LUMINANCE:{let r=this.radius;r=Math.max(r,.001),e=2*Math.PI*(1-Math.cos(r));break}}break;case Ui.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Ui.FALLOFF_DEFAULT=os.FALLOFF_DEFAULT;Ui.FALLOFF_PHYSICAL=os.FALLOFF_PHYSICAL;Ui.FALLOFF_GLTF=os.FALLOFF_GLTF;Ui.FALLOFF_STANDARD=os.FALLOFF_STANDARD;Ui.LIGHTMAP_DEFAULT=os.LIGHTMAP_DEFAULT;Ui.LIGHTMAP_SPECULAR=os.LIGHTMAP_SPECULAR;Ui.LIGHTMAP_SHADOWSONLY=os.LIGHTMAP_SHADOWSONLY;Ui.INTENSITYMODE_AUTOMATIC=os.INTENSITYMODE_AUTOMATIC;Ui.INTENSITYMODE_LUMINOUSPOWER=os.INTENSITYMODE_LUMINOUSPOWER;Ui.INTENSITYMODE_LUMINOUSINTENSITY=os.INTENSITYMODE_LUMINOUSINTENSITY;Ui.INTENSITYMODE_ILLUMINANCE=os.INTENSITYMODE_ILLUMINANCE;Ui.INTENSITYMODE_LUMINANCE=os.INTENSITYMODE_LUMINANCE;Ui.LIGHTTYPEID_POINTLIGHT=os.LIGHTTYPEID_POINTLIGHT;Ui.LIGHTTYPEID_DIRECTIONALLIGHT=os.LIGHTTYPEID_DIRECTIONALLIGHT;Ui.LIGHTTYPEID_SPOTLIGHT=os.LIGHTTYPEID_SPOTLIGHT;Ui.LIGHTTYPEID_HEMISPHERICLIGHT=os.LIGHTTYPEID_HEMISPHERICLIGHT;B([or()],Ui.prototype,"diffuse",void 0);B([or()],Ui.prototype,"specular",void 0);B([K()],Ui.prototype,"falloffType",void 0);B([K()],Ui.prototype,"intensity",void 0);B([K()],Ui.prototype,"range",null);B([K()],Ui.prototype,"intensityMode",null);B([K()],Ui.prototype,"radius",null);B([K()],Ui.prototype,"_renderPriority",void 0);B([ze("_reorderLightsInScene")],Ui.prototype,"renderPriority",void 0);B([K("shadowEnabled")],Ui.prototype,"_shadowEnabled",void 0);B([K("excludeWithLayerMask")],Ui.prototype,"_excludeWithLayerMask",void 0);B([K("includeOnlyWithLayerMask")],Ui.prototype,"_includeOnlyWithLayerMask",void 0);B([K("lightmapMode")],Ui.prototype,"_lightmapMode",void 0);class Sme extends da{}class Mme{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach(e=>{e.dispose()}),this.rootNodes.length=0,this.skeletons.slice(0).forEach(e=>{e.dispose()}),this.skeletons.length=0,this.animationGroups.slice(0).forEach(e=>{e.dispose()}),this.animationGroups.length=0}}class jO extends da{constructor(e){super(),this._wasAddedToScene=!1,e=e||bt.LastCreatedScene,e&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add(()=>{this._wasAddedToScene||this.dispose()}),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{for(const t of this.geometries)t._rebuild();for(const t of this.meshes)t._rebuild();for(const t of this.particleSystems)t.rebuild();for(const t of this.textures)t._rebuild()}))}_topologicalSort(e){const t=new Map;for(const o of e)t.set(o.uniqueId,o);const i={dependsOn:new Map,dependedBy:new Map};for(const o of e){const c=o.uniqueId;i.dependsOn.set(c,new Set),i.dependedBy.set(c,new Set)}for(const o of e){const c=o.uniqueId,l=i.dependsOn.get(c);if(o instanceof Kf){const u=o.sourceMesh;t.has(u.uniqueId)&&(l.add(u.uniqueId),i.dependedBy.get(u.uniqueId).add(c))}const h=i.dependedBy.get(c);for(const u of o.getDescendants()){const d=u.uniqueId;t.has(d)&&(h.add(d),i.dependsOn.get(d).add(c))}}const r=[],s=[];for(const o of e){const c=o.uniqueId;i.dependsOn.get(c).size===0&&(s.push(o),t.delete(c))}const a=s;for(;a.length>0;){const o=a.shift();r.push(o);const c=i.dependedBy.get(o.uniqueId);for(const l of Array.from(c.values())){const h=i.dependsOn.get(l);h.delete(o.uniqueId),h.size===0&&t.get(l)&&(a.push(t.get(l)),t.delete(l))}}return t.size>0&&(de.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>de.Error(o.name))),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId))){e.push(i),t.add(i.uniqueId);for(const s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,r)}}_isNodeInContainer(e){return e instanceof di&&this.meshes.indexOf(e)!==-1||e instanceof Et&&this.transformNodes.indexOf(e)!==-1||e instanceof Ui&&this.lights.indexOf(e)!==-1||e instanceof Rt&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return de.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return de.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return de.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return de.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Ee.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const r={},s={},a=new Mme,o=[],c=[],l={doNotInstantiate:!0,...i},h=(_,m)=>{if(r[_.uniqueId]=m.uniqueId,s[m.uniqueId]=m,e&&(m.name=e(_.name)),m instanceof Se){const g=m;if(g.morphTargetManager){const v=_.morphTargetManager;g.morphTargetManager=v.clone();for(let x=0;x{if(h(_,m),_.parent){const g=r[_.parent.uniqueId],v=s[g];v?m.parent=v:m.parent=_.parent}if(m.position&&_.position&&m.position.copyFrom(_.position),m.rotationQuaternion&&_.rotationQuaternion&&m.rotationQuaternion.copyFrom(_.rotationQuaternion),m.rotation&&_.rotation&&m.rotation.copyFrom(_.rotation),m.scaling&&_.scaling&&m.scaling.copyFrom(_.scaling),m.material){const g=m;if(g.material)if(t){const v=_.material;if(c.indexOf(v)===-1){let x=v.clone(e?e(v.name):"Clone of "+v.name);if(c.push(v),r[v.uniqueId]=x.uniqueId,s[x.uniqueId]=x,v.getClassName()==="MultiMaterial"){const y=v;for(const C of y.subMaterials)C&&(x=C.clone(e?e(C.name):"Clone of "+C.name),c.push(C),r[C.uniqueId]=x.uniqueId,s[x.uniqueId]=x);y.subMaterials=y.subMaterials.map(C=>C&&s[r[C.uniqueId]])}}g.getClassName()!=="InstancedMesh"&&(g.material=s[r[v.uniqueId]])}else g.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(g.material)===-1&&this.scene.addMultiMaterial(g.material):this.scene.materials.indexOf(g.material)===-1&&this.scene.addMaterial(g.material)}m.parent===null&&a.rootNodes.push(m)};return f.forEach(_=>{if(_.getClassName()==="InstancedMesh"){const m=_,g=m.sourceMesh,v=r[g.uniqueId],y=(typeof v=="number"?s[v]:g).createInstance(m.name);p(m,y)}else{let m=!0;_.getClassName()==="TransformNode"||_.getClassName()==="Node"||_.skeleton||!_.getTotalVertices||_.getTotalVertices()===0?m=!1:l.doNotInstantiate&&(typeof l.doNotInstantiate=="function"?m=!l.doNotInstantiate(_):m=!l.doNotInstantiate);const g=m?_.createInstance(`instance of ${_.name}`):_.clone(`Clone of ${_.name}`,null,!0);if(!g)throw new Error(`Could not clone or instantiate node on Asset Container ${_.name}`);p(_,g)}}),this.skeletons.forEach(_=>{if(l.predicate&&!l.predicate(_))return;const m=_.clone(e?e(_.name):"Clone of "+_.name);for(const g of this.meshes)if(g.skeleton===_&&!g.isAnInstance){const v=s[r[g.uniqueId]];if(!v||v.isAnInstance||(v.skeleton=m,o.indexOf(m)!==-1))continue;o.push(m);for(const x of m.bones)x._linkedTransformNode&&(x._linkedTransformNode=s[r[x._linkedTransformNode.uniqueId]])}a.skeletons.push(m)}),this.animationGroups.forEach(_=>{if(l.predicate&&!l.predicate(_))return;const m=_.clone(e?e(_.name):"Clone of "+_.name,g=>s[r[g.uniqueId]]||g);a.animationGroups.push(m)}),a}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Ee.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach(i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))}),this.skeletons.forEach(i=>{e&&!e(i)||this.scene.addSkeleton(i)}),this.animations.forEach(i=>{e&&!e(i)||this.scene.addAnimation(i)}),this.animationGroups.forEach(i=>{e&&!e(i)||this.scene.addAnimationGroup(i)}),this.multiMaterials.forEach(i=>{e&&!e(i)||this.scene.addMultiMaterial(i)}),this.materials.forEach(i=>{e&&!e(i)||this.scene.addMaterial(i)}),this.morphTargetManagers.forEach(i=>{e&&!e(i)||this.scene.addMorphTargetManager(i)}),this.geometries.forEach(i=>{e&&!e(i)||this.scene.addGeometry(i)}),this.transformNodes.forEach(i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))}),this.actionManagers.forEach(i=>{e&&!e(i)||this.scene.addActionManager(i)}),this.textures.forEach(i=>{e&&!e(i)||this.scene.addTexture(i)}),this.reflectionProbes.forEach(i=>{e&&!e(i)||this.scene.addReflectionProbe(i)});for(const i of t)i.parent&&this.scene.getNodes().indexOf(i.parent)===-1&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Ee.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach(t=>{e&&!e(t)||this.scene.removeCamera(t)}),this.lights.forEach(t=>{e&&!e(t)||this.scene.removeLight(t)}),this.meshes.forEach(t=>{e&&!e(t)||this.scene.removeMesh(t,!0)}),this.skeletons.forEach(t=>{e&&!e(t)||this.scene.removeSkeleton(t)}),this.animations.forEach(t=>{e&&!e(t)||this.scene.removeAnimation(t)}),this.animationGroups.forEach(t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)}),this.multiMaterials.forEach(t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)}),this.materials.forEach(t=>{e&&!e(t)||this.scene.removeMaterial(t)}),this.morphTargetManagers.forEach(t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)}),this.geometries.forEach(t=>{e&&!e(t)||this.scene.removeGeometry(t)}),this.transformNodes.forEach(t=>{e&&!e(t)||this.scene.removeTransformNode(t)}),this.actionManagers.forEach(t=>{e&&!e(t)||this.scene.removeActionManager(t)}),this.textures.forEach(t=>{e&&!e(t)||this.scene.removeTexture(t)}),this.reflectionProbes.forEach(t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)})}dispose(){this.cameras.slice(0).forEach(e=>{e.dispose()}),this.cameras.length=0,this.lights.slice(0).forEach(e=>{e.dispose()}),this.lights.length=0,this.meshes.slice(0).forEach(e=>{e.dispose()}),this.meshes.length=0,this.skeletons.slice(0).forEach(e=>{e.dispose()}),this.skeletons.length=0,this.animationGroups.slice(0).forEach(e=>{e.dispose()}),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach(e=>{e.dispose()}),this.multiMaterials.length=0,this.materials.slice(0).forEach(e=>{e.dispose()}),this.materials.length=0,this.geometries.slice(0).forEach(e=>{e.dispose()}),this.geometries.length=0,this.transformNodes.slice(0).forEach(e=>{e.dispose()}),this.transformNodes.length=0,this.actionManagers.slice(0).forEach(e=>{e.dispose()}),this.actionManagers.length=0,this.textures.slice(0).forEach(e=>{e.dispose()}),this.textures.length=0,this.reflectionProbes.slice(0).forEach(e=>{e.dispose()}),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach(e=>{e.dispose()}),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(!(!e||!t))for(const r of e){let s=!0;if(i){for(const a of i)if(r===a){s=!1;break}}s&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new Sme);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||(t==="_environmentTexture"?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new Se("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=bt.LastCreatedScene,t,i=null){if(!e)return de.Error("No scene available to merge animations to"),[];const r=i||(o=>{let c=null;const l=o.animations.length?o.animations[0].targetProperty:"",h=o.name.split(".").join("").split("_primitive")[0];switch(l){case"position":case"rotationQuaternion":c=e.getTransformNodeByName(o.name)||e.getTransformNodeByName(h);break;case"influence":c=e.getMorphTargetByName(o.name)||e.getMorphTargetByName(h);break;default:c=e.getNodeByName(o.name)||e.getNodeByName(h)}return c});this.getNodes().forEach(o=>{const c=r(o);if(c!==null){for(const l of o.animations){const h=c.animations.filter(u=>u.targetProperty===l.targetProperty);for(const u of h){const d=c.animations.indexOf(u,0);d>-1&&c.animations.splice(d,1)}}c.animations=c.animations.concat(o.animations)}});const a=[];return this.animationGroups.slice().forEach(o=>{a.push(o.clone(o.name,r)),o.animatables.forEach(c=>{c.stop()})}),t.forEach(o=>{const c=r(o.target);c&&(e.beginAnimation(c,o.fromFrame,o.toFrame,o.loopAnimation,o.speedRatio,o.onAnimationEnd?o.onAnimationEnd:void 0,void 0,!0,void 0,o.onAnimationLoop?o.onAnimationLoop:void 0),e.stopAnimation(o.target))}),a}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.transformNodes.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.lights.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.cameras.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)})}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const r=t.pop();if(r instanceof Se?(r.geometry&&this.geometries.indexOf(r.geometry)===-1&&this.geometries.push(r.geometry),this.meshes.push(r)):r instanceof Et?this.transformNodes.push(r):r instanceof Ui?this.lights.push(r):r instanceof Rt&&this.cameras.push(r),r instanceof di){if(r.material&&this.materials.indexOf(r.material)===-1){this.materials.push(r.material);for(const s of r.material.getActiveTextures())this.textures.indexOf(s)===-1&&this.textures.push(s)}r.skeleton&&this.skeletons.indexOf(r.skeleton)===-1&&this.skeletons.push(r.skeleton),r.morphTargetManager&&this.morphTargetManagers.indexOf(r.morphTargetManager)===-1&&this.morphTargetManagers.push(r.morphTargetManager)}for(const s of r.getChildren())i.has(s)||t.push(s);i.add(r)}this.populateRootNodes()}}class lRe{constructor(e){if(this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},e=e||bt.LastCreatedScene,!!e){if(this._scene=e,!De.audioEngine){Ee.Warn("No audio engine initialized, failed to create an audio analyser");return}this._audioEngine=De.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))}}getFrequencyBinCount(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0}getByteFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs}getByteTimeDomainData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime}getFloatFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs}drawDebugCanvas(){if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=()=>{this.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){const e=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(let t=0;tnew Rme(n,e,t);class Rme{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new Ae,this.onAudioLockedObservable=new Ae,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!io())return;typeof window.AudioContext<"u"&&(this.canUseWebAudio=!0);const r=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{r&&r.canPlayType&&(r.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||r.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch{}try{r&&r.canPlayType&&r.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch{}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if(((e=this._audioContext)==null?void 0:e.state)==="running"){this._hideMuteButton(),this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this));return}this._tryToRun?(t=this._audioContext)==null||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return(e=this._audioContext)!=null&&e.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,this._audioContext.state==="running"&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,de.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then(()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)}).catch(()=>{this._tryToRun=!1,this.unlocked=!1}))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const t=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",()=>{this._triggerRunningState()},!0),this._muteButton.addEventListener("click",()=>{this.unlock()},!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class wf{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((e=De.audioEngine)!=null&&e.audioContext&&(this.isPlaying||this.isPaused)){const t=this.isPaused?0:De.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+t}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,s){var a;if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new Ae,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=P.Zero(),this._localDirection=new P(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=e,i=i||bt.LastCreatedScene,!!i)if(this._scene=i,wf._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(o,c,l,h,u)=>c0&&(l=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":c.push(t);case"Array":c.length===0&&(c=t);for(let h=0;h{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()}),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(u,d=>{this._soundLoaded(d)},void 0,!0,!0,d=>{d&&de.Error("XHR "+d.status+" error on: "+u+"."),de.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:o=!1;break}o?l||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):de.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch{de.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),De.audioEngine&&!De.audioEngine.WarnedWebAudioUnsupported&&(de.Error("Web Audio is not supported by your browser."),De.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(e=De.audioEngine)!=null&&e.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,this.soundTrackId===-1?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){var t;(t=De.audioEngine)!=null&&t.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;(t=De.audioEngine)!=null&&t.audioContext&&De.audioEngine.audioContext.decodeAudioData(e,i=>{this._audioBufferLoaded(i)},i=>{de.Error("Error while decoding audio data for: "+this.name+" / Error: "+i)})}setAudioBuffer(e){var t;(t=De.audioEngine)!=null&&t.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),this._offset!==void 0&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),this._length!==void 0&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(this._offset|0)+this._length))))}_createSpatialParameters(){var e;(e=De.audioEngine)!=null&&e.canUseWebAudio&&De.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??De.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,(e=this._soundPanner)==null||e.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){var e;(e=De.audioEngine)!=null&&e.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(t=De.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){if(t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const l=()=>{var h,u;if((h=De.audioEngine)!=null&&h.unlocked){const d=this._htmlAudioElement.play();d!==void 0&&d.catch(()=>{var f,p;(f=De.audioEngine)==null||f.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(p=De.audioEngine)==null?void 0:p.onAudioUnlockedObservable.addOnce(()=>{l()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(u=De.audioEngine)==null?void 0:u.onAudioUnlockedObservable.addOnce(()=>{l()}))};l()}}else{const l=()=>{var h,u,d;if((h=De.audioEngine)!=null&&h.audioContext){if(i=i||this._length,t!==void 0&&this._setOffset(t),this._soundSource){const f=this._soundSource;f.onended=()=>{f.disconnect()}}if(this._soundSource=(u=De.audioEngine)==null?void 0:u.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,t!==void 0&&(this._soundSource.loopStart=t),i!==void 0&&(this._soundSource.loopEnd=(t|0)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},c=e?((d=De.audioEngine)==null?void 0:d.audioContext.currentTime)+e:De.audioEngine.audioContext.currentTime;const f=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(c,f,this.loop?void 0:i)}}};((o=De.audioEngine)==null?void 0:o.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var h;((h=De.audioEngine)==null?void 0:h.audioContext.state)==="suspended"?(De.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=De.audioEngine.onAudioUnlockedObservable.addOnce(()=>{l()}))):l()},500):l()}this._startTime=c,this.isPlaying=!0,this.isPaused=!1}catch(c){de.Error("Error while trying to play audio: "+this.name+", "+c.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){var t;if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((t=De.audioEngine)!=null&&t.audioContext&&this._soundSource){const i=e?De.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(i)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(e=De.audioEngine)!=null&&e.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=De.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(i=De.audioEngine)!=null&&i.canUseWebAudio&&this._soundGain&&(t&&De.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(De.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,De.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,De.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=t=>this._onRegisterAfterWorldMatrixUpdate(t),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){var t;if(!e.getBoundingInfo)this.setPosition(e.absolutePosition);else{const r=e.getBoundingInfo();this.setPosition(r.boundingSphere.centerWorld)}(t=De.audioEngine)!=null&&t.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new wf(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,r){const s=e.name;let a;e.url?a=i+e.url:a=i+s;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let c;if(!r)c=new wf(s,a,t,()=>{t.removePendingData(c)},o),t.addPendingData(c);else{const l=()=>{r._isReadyToPlay?(c._audioBuffer=r.getAudioBuffer(),c._isReadyToPlay=!0,c.autoplay&&c.play(0,c._offset,c._length)):setTimeout(l,300)};c=new wf(s,new ArrayBuffer(0),t,null,o),l()}if(e.position){const l=P.FromArray(e.position);c.setPosition(l)}if(e.isDirectional&&(c.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const l=P.FromArray(e.localDirectionToMesh);c.setLocalDirectionToMesh(l)}if(e.connectedMeshId){const l=t.getMeshById(e.connectedMeshId);l&&c.attachToMesh(l)}return e.metadata&&(c.metadata=e.metadata),c}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&((e=De.audioEngine)==null||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}wf._SceneComponentInitialization=n=>{throw ci("AudioSceneComponent")};class Ime{constructor(e,t={}){this.id=-1,this._isInitialized=!1,e=e||bt.LastCreatedScene,e&&(this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){var e;(e=De.audioEngine)!=null&&e.canUseWebAudio&&De.audioEngine.audioContext&&(this._outputAudioNode=De.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(De.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(De.audioEngine&&De.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){var t;this._isInitialized||this._initializeSoundTrackAudioGraph(),(t=De.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),e.soundTrackId!==void 0&&(e.soundTrackId===-1?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);t!==-1&&this.soundCollection.splice(t,1)}setVolume(e){var t;(t=De.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if((e=De.audioEngine)!=null&&e.canUseWebAudio)for(let t=0;t{var a;let r=[],s;if(t.sounds=t.sounds||[],n.sounds!==void 0&&n.sounds!==null)for(let o=0,c=n.sounds.length;o{t.play(),t.autoplay=!0,this.scene.mainSoundTrack.addSound(t)})}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach(i=>{i.stop(),i.autoplay=!1,this.scene.mainSoundTrack.removeSound(i),t&&i.dispose()})}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){const a=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(a.x||0,a.y||0,a.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const a=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(a.x||0,a.y||0,a.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),P.TransformNormalToRef(vh._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),!isNaN(this._cameraDirectionTemp.x)&&!isNaN(this._cameraDirectionTemp.y)&&!isNaN(this._cameraDirectionTemp.z)&&(this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0)))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);let s;for(s=0;s{let e=n._getComponent(it.NAME_AUDIO);e||(e=new vh(n),n._addComponent(e))};class Pme{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let r=0;for(const a of i)r+=a;const s=r>0?1/r:0;for(let a=0;a{this._onended()})}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee,this)}serialize(){return Qe.Serialize(this)}parse(e,t,i){Qe.Parse(()=>this,e,t,i)}}B([$t(),ze("_markSubMeshesAsAttributesDirty")],Q6.prototype,"texture",void 0);B([K(),ze("_markSubMeshesAsAttributesDirty")],Q6.prototype,"isEnabled",void 0);B([K()],Q6.prototype,"animationParameters",void 0);B([K()],Q6.prototype,"time",void 0);class Im{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return this._texture?this._texture.isCube:!1}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return(e==null?void 0:e._shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=lc.Zero(),this._cachedBaseSize=lc.Zero(),this._initialSamplingMode=2,this._texture=Im._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return this.delayLoadState===4?(this.delayLoad(),!1):this._texture?this._texture.isReady:!1}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return!this.isReady()||!this._texture?(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize):this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class Er extends Im{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){if(this._texture)this._texture._gammaSpace===null&&(this._texture._gammaSpace=this._gammaSpace);else return this._gammaSpace;return this._texture._gammaSpace&&!this._texture._useSRGBBuffer}set gammaSpace(e){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this))}get isRGBD(){return this._texture!=null&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return this._texture?this._texture._linearSpecularLOD:!1}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=mh()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=Er.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new Ae,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Er._IsScene(e)?this._scene=e:this._engine=e:this._scene=bt.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}checkTransformsAreIdentical(e){return e!==null}getTextureMatrix(){return ce.IdentityReadOnly}getReflectionTextureMatrix(){return ce.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,a){const o=this._getEngine();if(!o)return null;const c=o._getUseSRGBBuffer(!!s,t),l=o.getLoadedTexturesCache();for(let h=0;h=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const t=this._parentContainer.textures.indexOf(this);t>-1&&this._parentContainer.textures.splice(t,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=Qe.Serialize(this);return Qe.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let r=0;r{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}}Er.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;B([K()],Er.prototype,"uniqueId",void 0);B([K()],Er.prototype,"name",void 0);B([K()],Er.prototype,"metadata",void 0);B([K("hasAlpha")],Er.prototype,"_hasAlpha",void 0);B([K("getAlphaFromRGB")],Er.prototype,"_getAlphaFromRGB",void 0);B([K()],Er.prototype,"level",void 0);B([K("coordinatesIndex")],Er.prototype,"_coordinatesIndex",void 0);B([K()],Er.prototype,"optimizeUVAllocation",void 0);B([K("coordinatesMode")],Er.prototype,"_coordinatesMode",void 0);B([K()],Er.prototype,"wrapU",null);B([K()],Er.prototype,"wrapV",null);B([K()],Er.prototype,"wrapR",void 0);B([K()],Er.prototype,"anisotropicFilteringLevel",void 0);B([K()],Er.prototype,"isCube",null);B([K()],Er.prototype,"is3D",null);B([K()],Er.prototype,"is2DArray",null);B([K()],Er.prototype,"gammaSpace",null);B([K()],Er.prototype,"invertZ",void 0);B([K()],Er.prototype,"lodLevelInAlpha",void 0);B([K()],Er.prototype,"lodGenerationOffset",null);B([K()],Er.prototype,"lodGenerationScale",null);B([K()],Er.prototype,"linearSpecularLOD",null);B([$t()],Er.prototype,"irradianceTexture",null);B([K()],Er.prototype,"isRenderTarget",void 0);function dG(n,e,t=!1){const i=e.width,r=e.height;if(n instanceof Float32Array){let l=n.byteLength/n.BYTES_PER_ELEMENT;const h=new Uint8Array(l);for(;--l>=0;){let u=n[l];u<0?u=0:u>1&&(u=1),h[l]=u*255}n=h}const s=document.createElement("canvas");s.width=i,s.height=r;const a=s.getContext("2d");if(!a)return null;const o=a.createImageData(i,r);if(o.data.set(n),a.putImageData(o,0,0),t){const l=document.createElement("canvas");l.width=i,l.height=r;const h=l.getContext("2d");return h?(h.translate(0,r),h.scale(1,-1),h.drawImage(s,0,0),l.toDataURL("image/png")):null}return s.toDataURL("image/png")}function VJ(n,e=0,t=0){const i=n.getInternalTexture();if(!i)return null;const r=n._readPixelsSync(e,t);return r?dG(r,n.getSize(),i.invertY):null}async function zJ(n,e=0,t=0){const i=n.getInternalTexture();if(!i)return null;const r=await n.readPixels(e,t);return r?dG(r,n.getSize(),i.invertY):null}const cRe={GenerateBase64StringFromPixelData:dG,GenerateBase64StringFromTexture:VJ,GenerateBase64StringFromTextureAsync:zJ};class ve extends Er{static _CreateVideoTexture(e,t,i,r=!1,s=!1,a=ve.TRILINEAR_SAMPLINGMODE,o={},c,l=5){throw ci("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,r,s=ve.TRILINEAR_SAMPLINGMODE,a=null,o=null,c=null,l=!1,h,u,d,f,p){super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new Ae,this._isBlocking=!0,this.name=e||"",this.url=e;let _,m=!1,g=null,v=!0;typeof i=="object"&&i!==null?(_=i.noMipmap??!1,r=i.invertY??!br.UseOpenGLOrientationForUV,s=i.samplingMode??ve.TRILINEAR_SAMPLINGMODE,a=i.onLoad??null,o=i.onError??null,c=i.buffer??null,l=i.deleteBuffer??!1,h=i.format,u=i.mimeType,d=i.loaderOptions,f=i.creationFlags,m=i.useSRGBBuffer??!1,g=i.internalTexture??null,v=i.gammaSpace??v):_=!!i,this._gammaSpace=v,this._noMipmap=_,this._invertY=r===void 0?!br.UseOpenGLOrientationForUV:r,this._initialSamplingMode=s,this._buffer=c,this._deleteBuffer=l,this._mimeType=u,this._loaderOptions=d,this._creationFlags=f,this._useSRGBBuffer=m,this._forcedExtension=p,h&&(this._format=h);const x=this.getScene(),y=this._getEngine();if(!y)return;y.onBeforeTextureInitObservable.notifyObservers(this);const C=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),this._texture._cachedWrapU!==null&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),this._texture._cachedWrapV!==null&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),this._texture._cachedWrapR!==null&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),a&&a(),!this.isBlocking&&x&&x.resetCachedMaterial()},b=(T,S)=>{this._loadingError=!0,this._errorObject={message:T,exception:S},o&&o(T,S),ve.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!g){this._delayedOnLoad=C,this._delayedOnError=b;return}if(this._texture=g??this._getFromCache(this.url,_,s,this._invertY,m,this.isCube),this._texture)if(this._texture.isReady)H8.SetImmediate(()=>C());else{const T=this._texture.onLoadedObservable.add(C);this._texture.onErrorObservable.add(S=>{var N;b(S.message,S.exception),(N=this._texture)==null||N.onLoadedObservable.remove(T)})}else if(!x||!x.useDelayedTextureLoading){try{this._texture=y.createTexture(this.url,_,this._invertY,x,s,C,b,this._buffer,void 0,this._format,this._forcedExtension,u,d,f,m)}catch(T){throw b("error loading",T),T}l&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=C,this._delayedOnError=b}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,s=>s.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(this.delayLoadState!==4)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?H8.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,P.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}checkTransformsAreIdentical(e){return e!==null&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,(!this._cachedTextureMatrix||!this._rowGenerationMatrix)&&(this._cachedTextureMatrix=ce.Zero(),this._rowGenerationMatrix=new ce,this._t0=P.Zero(),this._t1=P.Zero(),this._t2=P.Zero()),ce.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(ce.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,ie.Matrix[0]),ce.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,ie.Matrix[1]),ce.ScalingToRef(this._cachedUScale,this._cachedVScale,0,ie.Matrix[2]),ce.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,ie.Matrix[3]),ie.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ie.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ie.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ie.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),ce.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();return t?(this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedTextureMatrix):this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode)if(this.coordinatesMode===ve.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=ce.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=ce.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case ve.PLANAR_MODE:{ce.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break}case ve.PROJECTION_MODE:{ce.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const i=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=i.updateFlag,i.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:ce.IdentityToRef(this._cachedReflectionTextureMatrix);break}return t&&e.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return Qe.Clone(()=>new ve(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var i;const e=this.name;ve.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(ve._SerializeInternalTextureUniqueId);return t?((ve.SerializeBuffers||ve.ForceSerializeBuffers)&&(typeof this._buffer=="string"&&this._buffer.substr(0,5)==="data:"?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+BO(this._buffer):(ve.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?VJ(this):zJ(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,ve._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=((i=this._texture)==null?void 0:i.uniqueId)??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const l=dD.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&l.updateSamplingMode&&l._samplingMode&&l._samplingMode!==e.samplingMode&&l.updateSamplingMode(e.samplingMode),l}if(e.isCube&&!e.isRenderTarget)return ve._CubeTextureParser(e,t,i);const r=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!r)return null;let s;if(r){const c=t.getEngine().getLoadedTexturesCache();for(const l of c)if(l.uniqueId===e.internalTextureUniqueId){s=l;break}}const a=c=>{var l;if(c&&c._texture&&(c._texture._cachedWrapU=null,c._texture._cachedWrapV=null,c._texture._cachedWrapR=null),e.samplingMode){const h=e.samplingMode;c&&c.samplingMode!==h&&c.updateSamplingMode(h)}if(c&&e.animations)for(let h=0;h{let c=!0;if(e.noMipmap&&(c=!1),e.mirrorPlane){const l=ve._CreateMirror(e.name,e.renderTargetSize,t,c);return l._waitingRenderList=e.renderList,l.mirrorPlane=yl.FromArray(e.mirrorPlane),a(l),l}else if(e.isRenderTarget){let l=null;if(e.isCube){if(t.reflectionProbes)for(let h=0;h{a(l)},e._creationFlags??0,e._useSRGBBuffer??!1),l.name=e.name;else{let h;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?h=e.name:h=i+e.name,e.url&&(e.url.startsWith("data:")||ve.UseSerializedUrlIfAny)&&(h=e.url);const u={noMipmap:!c,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{a(l)},internalTexture:s};l=new ve(h,t,u)}return l}},e,t)}static CreateFromBase64String(e,t,i,r,s,a=ve.TRILINEAR_SAMPLINGMODE,o=null,c=null,l=5,h){return new ve("data:"+t,i,r,s,a,o,c,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,r=!1,s,a=!0,o=ve.TRILINEAR_SAMPLINGMODE,c=null,l=null,h=5,u){return e.substr(0,5)!=="data:"&&(e="data:"+e),new ve(e,i,s,a,o,c,l,t,r,h,void 0,void 0,u)}}ve.SerializeBuffers=!0;ve.ForceSerializeBuffers=!1;ve.OnTextureLoadErrorObservable=new Ae;ve._SerializeInternalTextureUniqueId=!1;ve._CubeTextureParser=(n,e,t)=>{throw ci("CubeTexture")};ve._CreateMirror=(n,e,t,i)=>{throw ci("MirrorTexture")};ve._CreateRenderTargetTexture=(n,e,t,i,r)=>{throw ci("RenderTargetTexture")};ve.NEAREST_SAMPLINGMODE=1;ve.NEAREST_NEAREST_MIPLINEAR=8;ve.BILINEAR_SAMPLINGMODE=2;ve.LINEAR_LINEAR_MIPNEAREST=11;ve.TRILINEAR_SAMPLINGMODE=3;ve.LINEAR_LINEAR_MIPLINEAR=3;ve.NEAREST_NEAREST_MIPNEAREST=4;ve.NEAREST_LINEAR_MIPNEAREST=5;ve.NEAREST_LINEAR_MIPLINEAR=6;ve.NEAREST_LINEAR=7;ve.NEAREST_NEAREST=1;ve.LINEAR_NEAREST_MIPNEAREST=9;ve.LINEAR_NEAREST_MIPLINEAR=10;ve.LINEAR_LINEAR=2;ve.LINEAR_NEAREST=12;ve.EXPLICIT_MODE=0;ve.SPHERICAL_MODE=1;ve.PLANAR_MODE=2;ve.CUBIC_MODE=3;ve.PROJECTION_MODE=4;ve.SKYBOX_MODE=5;ve.INVCUBIC_MODE=6;ve.EQUIRECTANGULAR_MODE=7;ve.FIXED_EQUIRECTANGULAR_MODE=8;ve.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;ve.CLAMP_ADDRESSMODE=0;ve.WRAP_ADDRESSMODE=1;ve.MIRROR_ADDRESSMODE=2;ve.UseSerializedUrlIfAny=!1;B([K()],ve.prototype,"url",void 0);B([K()],ve.prototype,"uOffset",void 0);B([K()],ve.prototype,"vOffset",void 0);B([K()],ve.prototype,"uScale",void 0);B([K()],ve.prototype,"vScale",void 0);B([K()],ve.prototype,"uAng",void 0);B([K()],ve.prototype,"vAng",void 0);B([K()],ve.prototype,"wAng",void 0);B([K()],ve.prototype,"uRotationCenter",void 0);B([K()],ve.prototype,"vRotationCenter",void 0);B([K()],ve.prototype,"wRotationCenter",void 0);B([K()],ve.prototype,"homogeneousRotationInUVTransform",void 0);B([K()],ve.prototype,"isBlocking",null);xe("BABYLON.Texture",ve);Qe._TextureParser=ve.Parse;yt.prototype.updateRawTexture=function(n,e,t,i,r=null,s=0,a=!1){if(!n)return;const o=this._getRGBABufferInternalSizedFormat(s,t,a),c=this._getInternalFormat(t),l=this._getWebGLTextureType(s);this._bindTextureDirectly(this._gl.TEXTURE_2D,n,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(n._bufferView=e,n.format=t,n.type=s,n.invertY=i,n._compression=r),n.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],n.width,n.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,n.width,n.height,0,c,l,e),n.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),n.isReady=!0};yt.prototype.createRawTexture=function(n,e,t,i,r,s,a,o=null,c=0,l=0,h=!1){const u=new Ar(this,mi.Raw);u.baseWidth=e,u.baseHeight=t,u.width=e,u.height=t,u.format=i,u.generateMipMaps=r,u.samplingMode=a,u.invertY=s,u._compression=o,u.type=c,u._useSRGBBuffer=this._getUseSRGBBuffer(h,!r),this._doNotHandleContextLost||(u._bufferView=n),this.updateRawTexture(u,n,i,s,o,c,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(a,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u};yt.prototype.createRawCubeTexture=function(n,e,t,i,r,s,a,o=null){const c=this._gl,l=new Ar(this,mi.CubeRaw);l.isCube=!0,l.format=t,l.type=i,this._doNotHandleContextLost||(l._bufferViewArray=n);const h=this._getWebGLTextureType(i);let u=this._getInternalFormat(t);u===c.RGB&&(u=c.RGBA),h===c.FLOAT&&!this._caps.textureFloatLinearFiltering?(r=!1,a=1,de.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):h===this._gl.HALF_FLOAT_OES&&!this._caps.textureHalfFloatLinearFiltering?(r=!1,a=1,de.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):h===c.FLOAT&&!this._caps.textureFloatRender?(r=!1,de.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):h===c.HALF_FLOAT&&!this._caps.colorBufferFloat&&(r=!1,de.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));const d=e,f=d;if(l.width=d,l.height=f,l.invertY=s,l._compression=o,!this.needPOTTextures||FD(l.width)&&FD(l.height)||(r=!1),n)this.updateRawCubeTexture(l,n,t,i,s,o);else{const m=this._getRGBABufferInternalSizedFormat(i),g=0;this._bindTextureDirectly(c.TEXTURE_CUBE_MAP,l,!0);for(let v=0;v<6;v++)o?c.compressedTexImage2D(c.TEXTURE_CUBE_MAP_POSITIVE_X+v,g,this.getCaps().s3tc[o],l.width,l.height,0,void 0):c.texImage2D(c.TEXTURE_CUBE_MAP_POSITIVE_X+v,g,m,l.width,l.height,0,u,h,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,l,!0),n&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const _=this._getSamplingParameters(a,r);return c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MAG_FILTER,_.mag),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MIN_FILTER,_.min),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this._bindTextureDirectly(c.TEXTURE_CUBE_MAP,null),l.generateMipMaps=r,l.samplingMode=a,l.isReady=!0,l};yt.prototype.updateRawCubeTexture=function(n,e,t,i,r,s=null,a=0){n._bufferViewArray=e,n.format=t,n.type=i,n.invertY=r,n._compression=s;const o=this._gl,c=this._getWebGLTextureType(i);let l=this._getInternalFormat(t);const h=this._getRGBABufferInternalSizedFormat(i);let u=!1;l===o.RGB&&(l=o.RGBA,u=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,n,!0),this._unpackFlipY(r===void 0?!0:!!r),n.width%4!==0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let f=0;f<6;f++){let p=e[f];s?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+f,a,this.getCaps().s3tc[s],n.width,n.height,0,p):(u&&(p=wme(p,n.width,n.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+f,a,h,n.width,n.height,0,l,c,p))}(!this.needPOTTextures||FD(n.width)&&FD(n.height))&&n.generateMipMaps&&a===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),n.isReady=!0};yt.prototype.createRawCubeTextureFromUrl=function(n,e,t,i,r,s,a,o,c=null,l=null,h=3,u=!1){const d=this._gl,f=this.createRawCubeTexture(null,t,i,r,!s,u,h,null);e==null||e.addPendingData(f),f.url=n,f.isReady=!1,this._internalTexturesCache.push(f);const p=(m,g)=>{e==null||e.removePendingData(f),l&&m&&l(m.status+" "+m.statusText,g)},_=m=>{const g=f.width,v=a(m);if(v){if(o){const x=this._getWebGLTextureType(r);let y=this._getInternalFormat(i);const C=this._getRGBABufferInternalSizedFormat(r);let b=!1;y===d.RGB&&(y=d.RGBA,b=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const T=o(v);for(let S=0;S>S;for(let D=0;D<6;D++){let M=T[S][D];b&&(M=wme(M,N,N,r)),d.texImage2D(D,S,C,N,N,0,y,x,M)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,v,i,r,u);f.isReady=!0,e==null||e.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),c&&c()}};return this._loadFile(n,m=>{_(m)},void 0,e==null?void 0:e.offlineProvider,!0,p),f};function wme(n,e,t,i){let r,s=1;i===1?r=new Float32Array(e*t*4):i===2?(r=new Uint16Array(e*t*4),s=15360):i===7?r=new Uint32Array(e*t*4):r=new Uint8Array(e*t*4);for(let a=0;a0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return(!this._transformMatrices||this._isDirty)&&this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let i=!0;for(const r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0){for(const t of this.bones)if(t._linkedTransformNode){const i=t._linkedTransformNode;t.position=i.position,i.rotationQuaternion?t.rotationQuaternion=i.rotationQuaternion:t.rotation=i.rotation,t.scaling=i.scaling}}if(this.needInitialSkinMatrix)for(const t of this._meshesWithPoseMatrix){const i=t.getPoseMatrix();let r=this._isDirty;if((!t._bonesTransformMatrices||t._bonesTransformMatrices.length!==16*(this.bones.length+1))&&(t._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),r=!0),!!r){if(this._synchronizedWithMesh!==t){this._synchronizedWithMesh=t;for(const s of this.bones)s.getParent()||(s.getBindMatrix().multiplyToRef(i,ie.Matrix[1]),s._updateAbsoluteBindMatrices(ie.Matrix[1]));if(this.isUsingTextureForMatrices){const s=(this.bones.length+1)*4;(!t._transformMatrixTexture||t._transformMatrixTexture.getSize().width!==s)&&(t._transformMatrixTexture&&t._transformMatrixTexture.dispose(),t._transformMatrixTexture=$s.CreateRGBATexture(t._bonesTransformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(t._bonesTransformMatrices,i),this.isUsingTextureForMatrices&&t._transformMatrixTexture&&t._transformMatrixTexture.update(t._bonesTransformMatrices)}}else{if(!this._isDirty)return;(!this._transformMatrices||this._transformMatrices.length!==16*(this.bones.length+1))&&(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=$s.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach(i=>{i.enableBlending=!0,i.blendingSpeed=e})})}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){var t;const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(a.animation=r.animations[0].serialize()),e.ranges=[];for(const o in this._ranges){const c=this._ranges[o];if(!c)continue;const l={};l.name=o,l.from=c.from,l.to=c.to,e.ranges.push(l)}}return e}static Parse(e,t){const i=new a1(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=P.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix;let r;for(r=0;r-1&&(o=i.bones[s.parentBoneIndex]);const c=s.rest?ce.FromArray(s.rest):null,l=new _s(s.name,i,o,ce.FromArray(s.matrix),c,null,a);s.id!==void 0&&s.id!==null&&(l.id=s.id),s.length&&(l.length=s.length),s.metadata&&(l.metadata=s.metadata),s.animation&&l.animations.push(ke.Parse(s.animation)),s.linkedTransformNodeId!==void 0&&s.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,l._waitingTransformNodeId=s.linkedTransformNodeId)}if(e.ranges)for(r=0;r0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}}class hRe{constructor(e,t){this._scene=e,t instanceof a1?(this._skeleton=t,this._mesh=null):(this._mesh=t,this._skeleton=t.skeleton)}async bakeVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=e.reduce((o,c)=>o+c.to-c.from+1,0);if(isNaN(i))throw new Error("Invalid animation ranges.");let r=0;const s=(t+1)*4*4*i,a=new Float32Array(s);this._scene.stopAnimation(this._skeleton),this._skeleton.returnToRest();for(const o of e)for(let c=o.from;c<=o.to;c++)await this._executeAnimationFrame(a,c,r++);return a}async _executeAnimationFrame(e,t,i){return new Promise((r,s)=>{this._scene.beginAnimation(this._skeleton,t,t,!1,1,()=>{const a=this._skeleton.getTransformMatrices(this._mesh);e.set(a,i*a.length),r()})})}textureFromBakedVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=$s.CreateRGBATexture(e,(t+1)*4,e.length/((t+1)*4*4),this._scene,!1,!1,ve.NEAREST_NEAREST,1);return i.name="VAT"+this._skeleton.name,i}serializeBakedVertexDataToObject(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=(t+1)*4,r=e.length/((t+1)*4*4);return{vertexData:BO(e),width:i,height:r}}loadBakedVertexDataFromObject(e){return new Float32Array(FO(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}class Lme{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===ft.POINTERDOWN){this._isPointerDown=!0;return}i.type===ft.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=gr.Now;let r=0;this._lastFrameTime!=null&&(r=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();const s=i-this._lastInteractionTime-this._idleRotationWaitTime,a=Math.max(Math.min(s/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*a,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(r/1e3))})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??gr.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(i&&(i.computeWorldMatrix(!0),i.getBoundingInfo)){const r=i.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=r*.05,this.upperRadiusTransitionRange=r*.05}}):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))})}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return this._attachedCamera?this._attachedCamera.radius===e&&!this._radiusIsAnimating:!1}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(V3.EasingFunction.setEasingMode(V3.EasingMode),this._radiusBounceTransition=ke.CreateAnimation("radius",ke.ANIMATIONTYPE_FLOAT,60,V3.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=ke.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,()=>this._clearAnimationLocks());t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}V3.EasingFunction=new pme(.3);V3.EasingMode=Un.EASINGMODE_EASEOUT;class fh{constructor(){this.onTargetFramingAnimationEndObservable=new Ae,this._mode=fh.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();fh.EasingFunction.setEasingMode(fh.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===ft.POINTERDOWN){this._isPointerDown=!0;return}i.type===ft.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&i.getBoundingInfo&&this.zoomOnMesh(i,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const r=new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let a=0;a{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),h&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===fh.IgnoreBoundsSizeMode&&(r=ri.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=gr.Now-this._lastInteractionTime,t=Math.PI*.5-this._defaultElevation,i=Math.PI*.5;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=ke.CreateAnimation("beta",ke.ANIMATIONTYPE_FLOAT,60,fh.EasingFunction));const r=ke.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});r&&this._animatables.push(r)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=gr.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return this._attachedCamera?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1}}fh.EasingFunction=new _me;fh.EasingMode=Un.EASINGMODE_EASEINOUT;fh.IgnoreBoundsSizeMode=0;fh.FitFrustumSidesMode=1;class pS{constructor(e,t=new P,i=0,r=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=r}}class uRe{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new pS(P.Up()),new pS(P.Down()),new pS(P.Left()),new pS(P.Right()),new pS(P.Forward()),new pS(P.Forward().scaleInPlace(-1))],this._tmpMatrix=new ce,this._tmpVector=new P,this._zeroVector=P.Zero(),this._lookAtTmpMatrix=new ce}init(){}_closestFace(e){return this._faceVectors.forEach(t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=we.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),P.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=P.GetAngleBetweenVectors(t.rotatedDirection,e,P.Cross(t.rotatedDirection,e))}),this._faceVectors.reduce((t,i)=>t.ignore?i:i.ignore||t.diff{if(!this._scene.activeCamera)return;let t=this._scene.activeCamera.position;this._scene.activeCamera.devicePosition&&(t=this._scene.activeCamera.devicePosition);const i=this._closestFace(t.subtract(e.position));this._scene.activeCamera.leftCamera?this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix):this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix),P.TransformCoordinatesToRef(P.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach(s=>{i.direction.x&&s.direction.x&&(s.ignore=!0),i.direction.y&&s.direction.y&&(s.ignore=!0),i.direction.z&&s.direction.z&&(s.ignore=!0)});const r=this._closestFace(this._tmpVector);this._faceVectors.forEach(s=>{s.ignore=!1}),this._ui.position.copyFrom(e.position),i.direction.x&&(i.rotatedDirection.scaleToRef(e.scaling.x/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.y&&(i.rotatedDirection.scaleToRef(e.scaling.y/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.z&&(i.rotatedDirection.scaleToRef(e.scaling.z/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),this._ui.rotationQuaternion||(this._ui.rotationQuaternion=we.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,r.rotatedDirection,this._ui.rotationQuaternion),r.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),r.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),r.direction.z&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.z/2,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)})}detach(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)}}class dRe{get delay(){return this.fadeInDelay}set delay(e){this.fadeInDelay=e,this.fadeOutDelay=e}constructor(){this.fadeInDelay=0,this.fadeOutDelay=0,this.fadeInTime=300,this.fadeOutTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._delay=0,this._time=300,this._update=()=>{if(this._ownerNode){if(this._hoverValue+=this._hovered?this._millisecondsPerFrame:-this._millisecondsPerFrame,this._setAllVisibility(this._ownerNode,(this._hoverValue-this._delay)/this._time),this._ownerNode.visibility>1){if(this._setAllVisibility(this._ownerNode,1),this._hoverValue>this._time){this._hoverValue=this._time,this._detachObserver();return}}else if(this._ownerNode.visibility<0&&(this._setAllVisibility(this._ownerNode,0),this._hoverValue<0)){this._hoverValue=0,this._detachObserver();return}this._attachObserver()}}}get name(){return"FadeInOut"}init(){}attach(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)}detach(){this._ownerNode=null}fadeIn(e=!0){this._delay=e?this.fadeInDelay:this.fadeOutDelay,this._time=e?this.fadeInTime:this.fadeOutTime,this._detachObserver(),!(this._ownerNode&&(e&&this._ownerNode.visibility>=1||!e&&this._ownerNode.visibility<=0))&&(this._hovered=e,this._hovered||(this._delay*=-1),this._ownerNode.visibility>=1?this._hoverValue=this._time:this._ownerNode.visibility<=0&&(this._hoverValue=0),this._update())}fadeOut(){this.fadeIn(!1)}_setAllVisibility(e,t){e.visibility=t,e.getChildMeshes().forEach(i=>{this._setAllVisibility(i,t)})}_attachObserver(){var e;this._onBeforeRenderObserver||(this._onBeforeRenderObserver=(e=this._ownerNode)==null?void 0:e.getScene().onBeforeRenderObservable.add(this._update))}_detachObserver(){var e;this._onBeforeRenderObserver&&((e=this._ownerNode)==null||e.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)}}class Fi{constructor(e,t,i=Number.MAX_VALUE,r=ni){this.origin=e,this.direction=t,this.length=i,this.epsilon=r}clone(){return new Fi(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const r=Fi._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),s=Fi._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let a=0,o=Number.MAX_VALUE,c,l,h,u;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xs.x)return!1}else if(c=1/this.direction.x,l=(r.x-this.origin.x)*c,h=(s.x-this.origin.x)*c,h===-1/0&&(h=1/0),l>h&&(u=l,l=h,h=u),a=Math.max(l,a),o=Math.min(h,o),a>o)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.ys.y)return!1}else if(c=1/this.direction.y,l=(r.y-this.origin.y)*c,h=(s.y-this.origin.y)*c,h===-1/0&&(h=1/0),l>h&&(u=l,l=h,h=u),a=Math.max(l,a),o=Math.min(h,o),a>o)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zs.z)return!1}else if(c=1/this.direction.z,l=(r.z-this.origin.z)*c,h=(s.z-this.origin.z)*c,h===-1/0&&(h=1/0),l>h&&(u=l,l=h,h=u),a=Math.max(l,a),o=Math.min(h,o),a>o)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,a=i*i+r*r+s*s,o=e.radius+t,c=o*o;if(a<=c)return!0;const l=i*this.direction.x+r*this.direction.y+s*this.direction.z;return l<0?!1:a-l*l<=c}intersectsTriangle(e,t,i){const r=Fi._TmpVector3[0],s=Fi._TmpVector3[1],a=Fi._TmpVector3[2],o=Fi._TmpVector3[3],c=Fi._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),P.CrossToRef(this.direction,s,a);const l=P.Dot(r,a);if(l===0)return null;const h=1/l;this.origin.subtractToRef(e,o);const u=P.Dot(o,a)*h;if(u<-this.epsilon||u>1+this.epsilon)return null;P.CrossToRef(o,r,c);const d=P.Dot(this.direction,c)*h;if(d<-this.epsilon||u+d>1+this.epsilon)return null;const f=P.Dot(s,c)*h;return f>this.length?null:new Lz(1-u-d,u,f)}intersectsPlane(e){let t;const i=P.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{const r=P.Dot(e.normal,this.origin);return t=(-e.d-r)/i,t<0?t<-999999997475243e-21?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const i=(this.origin.y-t)/this.direction.y;return i>0?null:new P(this.origin.x+this.direction.x*-i,t,this.origin.z+this.direction.z*-i)}case"x":{const i=(this.origin.x-t)/this.direction.x;return i>0?null:new P(t,this.origin.y+this.direction.y*-i,this.origin.z+this.direction.z*-i)}case"z":{const i=(this.origin.z-t)/this.direction.z;return i>0?null:new P(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,a=!1){const o=ie.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?Fi.TransformToRef(this,o,this._tmpRay):this._tmpRay=Fi.Transform(this,o),e.intersects(this._tmpRay,t,i,r,s,a)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;rt.distance?1:0}intersectionSegment(e,t,i){const r=this.origin,s=ie.Vector3[0],a=ie.Vector3[1],o=ie.Vector3[2],c=ie.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(Fi._Rayl,o),r.addToRef(o,a),e.subtractToRef(r,c);const l=P.Dot(s,s),h=P.Dot(s,o),u=P.Dot(o,o),d=P.Dot(s,c),f=P.Dot(o,c),p=l*u-h*h;let _,m=p,g,v=p;pm&&(_=m,g=f+h,v=u)),g<0?(g=0,-d<0?_=0:-d>l?_=m:(_=-d,m=l)):g>v&&(g=v,-d+h<0?_=0:-d+h>l?_=m:(_=-d+h,m=l));const x=Math.abs(_)0&&y<=this.length&&T.lengthSquared()=n.distance?null:l};pt.prototype._internalPick=function(n,e,t,i,r){let s=null;const a=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let c=0;c1&&this.cameraToUseForPointers!==this.activeCamera),s=this.cameraToUseForPointers||this.activeCamera;for(let a=0;a(this._tempPickingRay||(this._tempPickingRay=Fi.Zero()),this.createPickingRayToRef(n,e,a,this._tempPickingRay,r||null),this._tempPickingRay),t,i,!0);return s&&(s.ray=this.createPickingRay(n,e,ce.Identity(),r||null)),s};Object.defineProperty(pt.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1});pt.prototype.pick=function(n,e,t,i,r,s,a=!1){const o=this._internalPick((c,l)=>(this._tempPickingRay||(this._tempPickingRay=Fi.Zero()),this.createPickingRayToRef(n,e,c,this._tempPickingRay,r||null,!1,l),this._tempPickingRay),t,i,!1,s);return o&&(o.ray=this.createPickingRay(n,e,ce.Identity(),r||null)),o};pt.prototype.pickWithRay=function(n,e,t,i){const r=this._internalPick(s=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=ce.Identity()),s.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Fi.Zero()),Fi.TransformToRef(n,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t,!1,i);return r&&(r.ray=n),r};pt.prototype.multiPick=function(n,e,t,i,r){return this._internalMultiPick(s=>this.createPickingRay(n,e,s,i||null),t,r)};pt.prototype.multiPickWithRay=function(n,e,t){return this._internalMultiPick(i=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=ce.Identity()),i.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Fi.Zero()),Fi.TransformToRef(n,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t)};Rt.prototype.getForwardRay=function(n=100,e,t){return this.getForwardRayToRef(new Fi(P.Zero(),P.Zero(),n),n,e,t)};Rt.prototype.getForwardRayToRef=function(n,e=100,t,i){t||(t=this.getWorldMatrix()),n.length=e,i?n.origin.copyFrom(i):n.origin.copyFrom(this.position);const r=ie.Vector3[2];r.set(0,0,this._scene.useRightHandedSystem?-1:1);const s=ie.Vector3[3];return P.TransformNormalToRef(r,t,s),P.NormalizeToRef(s,n.direction),n};class Vr{static _RemoveAndStorePivotPoint(e){e&&Vr._PivotCached===0&&(e.getPivotPointToRef(Vr._OldPivotPoint),Vr._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,Vr._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(ce.IdentityReadOnly),Vr._OldPivotPoint.subtractToRef(e.getPivotPoint(),Vr._PivotTranslation),Vr._PivotTmpVector.copyFromFloats(1,1,1),Vr._PivotTmpVector.subtractInPlace(e.scaling),Vr._PivotTmpVector.multiplyInPlace(Vr._PivotTranslation),e.position.addInPlace(Vr._PivotTmpVector))),Vr._PivotCached++}static _RestorePivotPoint(e){e&&!Vr._OldPivotPoint.equalsToFloats(0,0,0)&&Vr._PivotCached===1&&(e.setPivotPoint(Vr._OldPivotPoint),e._postMultiplyPivotMatrix=Vr._PivotPostMultiplyPivotMatrix,Vr._PivotTmpVector.copyFromFloats(1,1,1),Vr._PivotTmpVector.subtractInPlace(e.scaling),Vr._PivotTmpVector.multiplyInPlace(Vr._PivotTranslation),e.position.subtractInPlace(Vr._PivotTmpVector)),this._PivotCached--}}Vr._PivotCached=0;Vr._OldPivotPoint=new P;Vr._PivotTranslation=new P;Vr._PivotTmpVector=new P;Vr._PivotPostMultiplyPivotMatrix=!1;function fG(n){const e=[],t=[],i=[],r=[],s=n.width||n.size||1,a=n.height||n.size||1,o=n.sideOrientation===0?0:n.sideOrientation||et.DEFAULTSIDE,c=s/2,l=a/2;t.push(-c,-l,0),i.push(0,0,-1),r.push(0,br.UseOpenGLOrientationForUV?1:0),t.push(c,-l,0),i.push(0,0,-1),r.push(1,br.UseOpenGLOrientationForUV?1:0),t.push(c,l,0),i.push(0,0,-1),r.push(1,br.UseOpenGLOrientationForUV?0:1),t.push(-c,l,0),i.push(0,0,-1),r.push(0,br.UseOpenGLOrientationForUV?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),et._ComputeSides(o,t,e,i,r,n.frontUVs,n.backUVs);const h=new et;return h.indices=e,h.positions=t,h.normals=i,h.uvs=r,h}function n_(n,e={},t=null){const i=new Se(n,t);return e.sideOrientation=Se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,fG(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}const fRe={CreatePlane:n_};et.CreatePlane=fG;Se.CreatePlane=(n,e,t,i,r)=>n_(n,{size:e,width:e,height:e,sideOrientation:r,updatable:i},t);class Ao{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new Ae,this.onDragStartObservable=new Ae,this.onDragEndObservable=new Ae,this.onEnabledObservable=new Ae,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=i=>!0,this._tmpVector=new P(0,0,0),this._alternatePickedPoint=new P(0,0,0),this._worldDragAxis=new P(0,0,0),this._targetPosition=new P(0,0,0),this._attachedToElement=!1,this._startDragRay=new Fi(new P,new P),this._lastPointerRay={},this._dragDelta=new P,this._pointA=new P(0,0,0),this._pointC=new P(0,0,0),this._localAxis=new P(0,0,0),this._lookAt=new P(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,Ao._PlaneScene||(this._debugMode?Ao._PlaneScene=this._scene:(Ao._PlaneScene=new pt(this._scene.getEngine(),{virtual:!0}),Ao._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{Ao._PlaneScene.dispose(),Ao._PlaneScene=null}))),this._dragPlane=n_("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:Se.DOUBLESIDE},Ao._PlaneScene),this.lastDragPosition=new P(0,0,0);const i=t||(r=>this.attachedNode==r||r.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(r=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(r.type==ft.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&r.pickInfo&&r.pickInfo.hit&&r.pickInfo.pickedMesh&&r.pickInfo.pickedPoint&&r.pickInfo.ray&&i(r.pickInfo.pickedMesh)&&this._activeDragButton===-1&&this.dragButtons.indexOf(r.event.button)!==-1&&(this._activeDragButton=r.event.button,this._activePointerInfo=r,this._startDrag(r.event.pointerId,r.pickInfo.ray,r.pickInfo.pickedPoint));else if(r.type==ft.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==r.event.pointerId&&(this._activeDragButton===r.event.button||this._activeDragButton===-1)&&this.releaseDrag();else if(r.type==ft.POINTERMOVE){const s=r.event.pointerId;if(this.currentDraggingPointerId===Ao._AnyMouseId&&s!==Ao._AnyMouseId){const a=r.event;(a.pointerType==="mouse"||!this._scene.getEngine().hostInformation.isMobile&&a instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[s]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=s)}this._lastPointerRay[s]||(this._lastPointerRay[s]=new Fi(new P,new P)),r.pickInfo&&r.pickInfo.ray&&(this._lastPointerRay[s].origin.copyFrom(r.pickInfo.ray.origin),this._lastPointerRay[s].direction.copyFrom(r.pickInfo.ray.direction),this.currentDraggingPointerId==s&&this.dragging&&this._moveDrag(r.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let r=!1;Vr._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),r=!0),Vr._RestorePivotPoint(this.attachedNode),r&&this.attachedNode.computeWorldMatrix()}})}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if(this._scene.activeCamera.getClassName()==="ArcRotateCamera"){const e=this._scene.activeCamera;e.attachControl(e.inputs?e.inputs.noPreventDefault:!0,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(this._scene.activeCamera.inputs?this._scene.activeCamera.inputs.noPreventDefault:!0);this._attachedToElement=!1}}startDrag(e=Ao._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===Ao._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;Vr._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),Vr._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){Vr._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=P.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),Vr._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(P.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle)if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*P.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const c=P.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-c,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}else return null;const i=this._dragPlane.forward,r=this._dragPlane.position,s=e.direction.dot(i);if(Math.abs(s).999?Math.abs(P.Dot(P.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(P.Right()):this._lookAt.copyFrom(P.UpReadOnly):(P.CrossToRef(this._localAxis,this._pointC,this._lookAt),P.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?P.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}Ao._AnyMouseId=-2;class pRe{constructor(){this._startDistance=0,this._initialScale=new P(0,0,0),this._targetScale=new P(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new Ao({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new Ao({}),this._dragBehaviorB.moveAttached=!1}get name(){return"MultiPointerScale"}init(){}_getCurrentDistance(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()}attach(e){this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add(()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorA.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))}),this._dragBehaviorB.onDragStartObservable.add(()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorB.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))}),[this._dragBehaviorA,this._dragBehaviorB].forEach(t=>{t.onDragObservable.add(()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const i=this._getCurrentDistance()/this._startDistance;this._initialScale.scaleToRef(i,this._targetScale)}})}),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add(()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const t=this._targetScale.subtract(e.scaling).scaleInPlace(.1);t.length()>.01&&e.scaling.addInPlace(t)}})}detach(){this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach(e=>{e.onDragStartObservable.clear(),e.onDragObservable.clear(),this._ownerNode.removeBehavior(e)})}}class E0{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new P,this._tmpQuaternion=new we,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new Ae,this.onDragObservable=new Ae,this.onDragEndObservable=new Ae,this.allowMultiPointer=!0}get currentDraggingPointerId(){return this.currentDraggingPointerIds[0]!==void 0?this.currentDraggingPointerIds[0]:-1}set currentDraggingPointerId(e){this.currentDraggingPointerIds[0]=e}get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}get name(){return"BaseSixDofDrag"}get isMoving(){return this._moving}init(){}get _pointerCamera(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera}_createVirtualMeshInfo(){const e=new di("",E0._virtualScene);e.rotationQuaternion=new we;const t=new di("",E0._virtualScene);t.rotationQuaternion=new we;const i=new di("",E0._virtualScene);return i.rotationQuaternion=new we,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new P,startingPivotOrientation:new we,startingPosition:new P,startingOrientation:new we,lastOriginPosition:new P,lastDragPosition:new P}}_resetVirtualMeshesPosition(){for(let e=0;ef&&(f=Math.min(p-u,0)),h.scaleInPlace(f),h.addToRef(s.pivotMesh.absolutePosition,this._tmpVector),s.pivotMesh.setAbsolutePosition(this._tmpVector),h.addToRef(s.dragMesh.absolutePosition,this._tmpVector),s.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),E0._virtualScene||(E0._virtualScene=new pt(this._scene.getEngine(),{virtual:!0}),E0._virtualScene.detachControl());const t=i=>this._ownerNode===i||i.isDescendantOf(this._ownerNode)&&(!this.draggableMeshes||this.draggableMeshes.indexOf(i)!==-1);this._pointerObserver=this._scene.onPointerObservable.add(i=>{const r=i.event.pointerId;this._virtualMeshesInfo[r]||(this._virtualMeshesInfo[r]=this._createVirtualMeshInfo());const s=this._virtualMeshesInfo[r],a=i.event.pointerType==="xr-near";if(i.type==ft.POINTERDOWN){if(!s.dragging&&i.pickInfo&&i.pickInfo.hit&&i.pickInfo.pickedMesh&&i.pickInfo.pickedPoint&&i.pickInfo.ray&&(!a||i.pickInfo.aimTransform)&&t(i.pickInfo.pickedMesh)){if(!this.allowMultiPointer&&this.currentDraggingPointerIds.length>0)return;this._pointerCamera&&this._pointerCamera.cameraRigMode===Rt.RIG_MODE_NONE&&!this._pointerCamera._isLeftCamera&&!this._pointerCamera._isRightCamera&&i.pickInfo.ray.origin.copyFrom(this._pointerCamera.globalPosition),this._ownerNode.computeWorldMatrix(!0);const o=this._virtualMeshesInfo[r];a?(this._dragging=i.pickInfo.originMesh?this._dragType.NEAR_DRAG:this._dragType.DRAG_WITH_CONTROLLER,o.originMesh.position.copyFrom(i.pickInfo.aimTransform.position),this._dragging===this._dragType.NEAR_DRAG&&i.pickInfo.gripTransform?o.originMesh.rotationQuaternion.copyFrom(i.pickInfo.gripTransform.rotationQuaternion):o.originMesh.rotationQuaternion.copyFrom(i.pickInfo.aimTransform.rotationQuaternion)):(this._dragging=this._dragType.DRAG,o.originMesh.position.copyFrom(i.pickInfo.ray.origin)),o.lastOriginPosition.copyFrom(o.originMesh.position),o.dragMesh.position.copyFrom(i.pickInfo.pickedPoint),o.lastDragPosition.copyFrom(i.pickInfo.pickedPoint),o.pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),o.pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),o.startingPosition.copyFrom(o.dragMesh.position),o.startingPivotPosition.copyFrom(o.pivotMesh.position),o.startingOrientation.copyFrom(o.dragMesh.rotationQuaternion),o.startingPivotOrientation.copyFrom(o.pivotMesh.rotationQuaternion),a?(o.originMesh.addChild(o.dragMesh),o.originMesh.addChild(o.pivotMesh)):o.originMesh.lookAt(o.dragMesh.position),o.dragging=!0,this.currentDraggingPointerIds.indexOf(r)===-1&&this.currentDraggingPointerIds.push(r),this.detachCameraControls&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.inputs&&this._pointerCamera.inputs.attachedToElement?(this._pointerCamera.detachControl(),this._attachedToElement=!0):(!this.allowMultiPointer||this.currentDraggingPointerIds.length===0)&&(this._attachedToElement=!1)),this._targetDragStart(o.pivotMesh.position,o.pivotMesh.rotationQuaternion,r),this.onDragStartObservable.notifyObservers({position:o.pivotMesh.position})}}else if(i.type==ft.POINTERUP||i.type==ft.POINTERDOUBLETAP){const o=this.currentDraggingPointerIds.indexOf(r);s.dragging=!1,o!==-1&&(this.currentDraggingPointerIds.splice(o,1),this.currentDraggingPointerIds.length===0&&(this._moving=!1,this._dragging=this._dragType.NONE,this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1)),s.originMesh.removeChild(s.dragMesh),s.originMesh.removeChild(s.pivotMesh),this._targetDragEnd(r),this.onDragEndObservable.notifyObservers({}))}else if(i.type==ft.POINTERMOVE&&this.currentDraggingPointerIds.indexOf(r)!==-1&&s.dragging&&i.pickInfo&&(i.pickInfo.ray||i.pickInfo.aimTransform)){let c=this.zDragFactor;(this.currentDraggingPointerIds.length>1||i.pickInfo.originMesh)&&(c=0),this._ownerNode.computeWorldMatrix(!0),a?this._pointerUpdateXR(i.pickInfo.aimTransform,i.pickInfo.gripTransform,r,c):this._pointerUpdate2D(i.pickInfo.ray,r,c),this._tmpQuaternion.copyFrom(s.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,s.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),s.pivotMesh.absolutePosition.subtractToRef(s.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:s.pivotMesh.position,pickInfo:i.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,r),s.lastDragPosition.copyFrom(s.dragMesh.absolutePosition),this._moving=!0}})}_applyZOffset(e,t,i){e.position.z-=e.position.z<1?t*i:t*i*e.position.z,e.position.z<0&&(e.position.z=0)}_targetDragStart(e,t,i){}_targetDrag(e,t,i){}_targetDragEnd(e){}_reattachCameraControls(){if(this._pointerCamera)if(this._pointerCamera.getClassName()==="ArcRotateCamera"){const e=this._pointerCamera;e.attachControl(e.inputs?e.inputs.noPreventDefault:!0,e._useCtrlForPanning,e._panningMouseButton)}else this._pointerCamera.attachControl(this._pointerCamera.inputs?this._pointerCamera.inputs.noPreventDefault:!0)}detach(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver));for(const e in this._virtualMeshesInfo)this._virtualMeshesInfo[e].originMesh.dispose(),this._virtualMeshesInfo[e].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()}}class Nme extends E0{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new P(0,0,0),this._targetOrientation=new we,this._targetScaling=new P(1,1,1),this._startingPosition=new P(0,0,0),this._startingOrientation=new we,this._startingScaling=new P(1,1,1),this.onPositionChangedObservable=new Ae,this.dragDeltaRatio=.2,this.rotateDraggedObject=!0,this.rotateAroundYOnly=!1,this.rotateWithMotionController=!0,this.disableMovement=!1,this.faceCameraOnDragStart=!1}get name(){return"SixDofDrag"}attach(e){super.attach(e),e.isNearGrabbable=!0,this._virtualTransformNode=new Et("virtual_sixDof",E0._virtualScene),this._virtualTransformNode.rotationQuaternion=we.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add(()=>{if(this.currentDraggingPointerIds.length===1&&this._moving&&!this.disableMovement){const t=ie.Vector3[0];t.copyFrom(this._targetPosition).subtractInPlace(e.absolutePosition).scaleInPlace(this.dragDeltaRatio);const i=ie.Vector3[1];if(i.copyFrom(t),e.parent){const r=ie.Matrix[0];e.parent.absoluteRotationQuaternion.toRotationMatrix(r),r.invert(),P.TransformNormalToRef(t,r,i)}if(e.position.addInPlace(i),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),!e.parent||e.parent.scaling&&!e.parent.scaling.isNonUniformWithinEpsilon(.001)){const r=ie.Quaternion[0];if(r.copyFrom(this._targetOrientation),e.parent){const s=ie.Quaternion[0];s.copyFrom(e.parent.absoluteRotationQuaternion),s.invertInPlace(),s.multiplyToRef(this._targetOrientation,r)}we.SlerpToRef(e.rotationQuaternion,r,this.dragDeltaRatio,e.rotationQuaternion)}}})}_getPositionOffsetAround(e,t,i){const r=ie.Matrix[0],s=ie.Matrix[1],a=ie.Matrix[2],o=ie.Matrix[3],c=ie.Matrix[4];return ce.TranslationToRef(e.x,e.y,e.z,r),ce.TranslationToRef(-e.x,-e.y,-e.z,s),ce.FromQuaternionToRef(i,a),ce.ScalingToRef(t,t,t,o),s.multiplyToRef(a,c),c.multiplyToRef(o,c),c.multiplyToRef(r,c),c.getTranslation()}_onePointerPositionUpdated(e,t){ie.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?we.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,ie.Quaternion[0]):ie.Quaternion[0].copyFrom(t),ie.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&t.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)}_twoPointersPositionUpdated(){const e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,t=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,i=ie.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const r=ie.Vector3[1];t.subtractToRef(e,r);const s=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,a=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,o=ie.Vector3[2];s.addToRef(a,o),o.scaleInPlace(.5);const c=ie.Vector3[3];a.subtractToRef(s,c);const l=c.length()/r.length(),h=o.subtract(i),u=we.FromEulerAngles(0,P.GetAngleBetweenVectorsOnPlane(r.normalize(),c.normalize(),P.UpReadOnly),0),d=this._ownerNode.parent;this._ownerNode.setParent(null);const f=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),l,u);this._virtualTransformNode.rotationQuaternion.multiplyToRef(u,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(l,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(h.addInPlace(f),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(d)}_targetDragStart(){const e=this.currentDraggingPointerIds.length;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=we.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));const t=this._ownerNode.getAbsolutePivotPoint();if(e===1){if(this._targetPosition.copyFrom(this._ownerNode.absolutePosition),this._targetOrientation.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.absoluteScaling),this.faceCameraOnDragStart&&this._scene.activeCamera){const i=ie.Vector3[0];this._scene.activeCamera.position.subtractToRef(t,i),i.normalize();const r=ie.Quaternion[0];this._scene.useRightHandedSystem?we.FromLookDirectionRHToRef(i,new P(0,1,0),r):we.FromLookDirectionLHToRef(i,new P(0,1,0),r),r.normalize(),we.RotationYawPitchRollToRef(r.toEulerAngles().y,0,0,ie.Quaternion[0]),this._targetOrientation.copyFrom(ie.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else e===2&&(this._virtualTransformNode.setPivotPoint(new P(0,0,0),Ci.LOCAL),this._virtualTransformNode.position.copyFrom(this._ownerNode.absolutePosition),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.absoluteScaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._virtualTransformNode.setPivotPoint(t,Ci.WORLD),this._resetVirtualMeshesPosition())}_targetDrag(e,t){this.currentDraggingPointerIds.length===1?this._onePointerPositionUpdated(e,t):this.currentDraggingPointerIds.length===2&&this._twoPointersPositionUpdated()}_targetDragEnd(){if(this.currentDraggingPointerIds.length===1){this._resetVirtualMeshesPosition();const e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}}detach(){super.detach(),this._ownerNode&&(this._ownerNode.isNearGrabbable=!1,this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver)),this._virtualTransformNode&&this._virtualTransformNode.dispose()}}class _Re{constructor(){this._attachPointLocalOffset=new P,this._workingPosition=new P,this._workingQuaternion=new we,this._lastTick=-1,this._hit=!1,this.hitNormalOffset=.05,this.meshes=[],this.interpolatePose=!0,this.lerpTime=250,this.keepOrientationVertical=!0,this.enabled=!0,this.maxStickingDistance=.8}get name(){return"SurfaceMagnetism"}init(){}attach(e,t){this._attachedMesh=e,this._scene=t||e.getScene(),this._attachedMesh.rotationQuaternion||(this._attachedMesh.rotationQuaternion=we.RotationYawPitchRoll(this._attachedMesh.rotation.y,this._attachedMesh.rotation.x,this._attachedMesh.rotation.z)),this.updateAttachPoint(),this._workingPosition.copyFrom(this._attachedMesh.position),this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion),this._addObservables()}detach(){this._attachedMesh=null,this._removeObservables()}_getTargetPose(e){if(!this._attachedMesh)return null;if(e&&e.hit){const t=e.getNormal(!0,!0),i=e.pickedPoint;if(!t||!i)return null;t.normalize();const r=ie.Vector3[0];return r.copyFrom(t),r.scaleInPlace(this.hitNormalOffset),r.addInPlace(i),this._attachedMesh.parent&&(ie.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),P.TransformNormalToRef(r,ie.Matrix[0],r)),{position:r,quaternion:we.RotationYawPitchRoll(-Math.atan2(t.x,-t.z),this.keepOrientationVertical?0:Math.atan2(t.y,Math.sqrt(t.z*t.z+t.x*t.x)),0)}}return null}updateAttachPoint(){this._getAttachPointOffsetToRef(this._attachPointLocalOffset)}findAndUpdateTarget(e){if(this._hit=!1,!e.ray)return!1;const t=e.ray.intersectsMeshes(this.meshes)[0];if(this._attachedMesh&&t&&t.hit&&t.pickedMesh){const i=this._getTargetPose(t);i&&P.Distance(this._attachedMesh.position,i.position){this.enabled&&e.type==ft.POINTERMOVE&&e.pickInfo&&this.findAndUpdateTarget(e.pickInfo)}),this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add(()=>{const e=Date.now();this._updateTransformToGoal(e-this._lastTick),this._lastTick=e})}_removeObservables(){this._scene.onPointerObservable.remove(this._pointerObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRender),this._pointerObserver=null,this._onBeforeRender=null}}class mRe{constructor(){this._tmpQuaternion=new we,this._tmpVectors=[new P,new P,new P,new P,new P,new P,new P],this._tmpMatrix=new ce,this._tmpInvertView=new ce,this._tmpForward=new P,this._tmpNodeForward=new P,this._tmpPosition=new P,this._workingPosition=new P,this._workingQuaternion=new we,this._lastTick=-1,this._recenterNextUpdate=!0,this.interpolatePose=!0,this.lerpTime=500,this.ignoreCameraPitchAndRoll=!1,this.pitchOffset=15,this.maxViewVerticalDegrees=30,this.maxViewHorizontalDegrees=30,this.orientToCameraDeadzoneDegrees=60,this.ignoreDistanceClamp=!1,this.ignoreAngleClamp=!1,this.verticalMaxDistance=0,this.defaultDistance=.8,this.maximumDistance=2,this.minimumDistance=.3,this.useFixedVerticalOffset=!1,this.fixedVerticalOffset=0,this._enabled=!0}get followedCamera(){return this._followedCamera||this._scene.activeCamera}set followedCamera(e){this._followedCamera=e}get name(){return"Follow"}init(){}attach(e,t){this._scene=e.getScene(),this.attachedNode=e,t&&(this.followedCamera=t),this._addObservables()}detach(){this.attachedNode=null,this._removeObservables()}recenter(){this._recenterNextUpdate=!0}_angleBetweenVectorAndPlane(e,t){return this._tmpVectors[0].copyFrom(e),e=this._tmpVectors[0],this._tmpVectors[1].copyFrom(t),t=this._tmpVectors[1],e.normalize(),t.normalize(),Math.PI/2-Math.acos(P.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,r=this.maximumDistance;const s=this.defaultDistance,a=this._tmpVectors[0];a.copyFrom(e);let o=a.length();if(a.normalizeFromLength(o),this.ignoreCameraPitchAndRoll){i=this._length2D(a)*i,r=this._length2D(a)*r;const l=this._length2D(e);a.scaleInPlace(o/l),o=l}let c=o;return t?c=s:c=_t.Clamp(o,i,r),e.copyFrom(a).scaleInPlace(c),o!==c}_applyVerticalClamp(e){this.verticalMaxDistance!==0&&(e.y=_t.Clamp(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){we.RotationYawPitchRollToRef(Math.atan2(e.x,e.z),Math.atan2(e.y,Math.sqrt(e.z*e.z+e.x*e.x)),0,t)}_applyPitchOffset(e){const t=this._tmpVectors[0],i=this._tmpVectors[1];t.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),i.copyFromFloats(1,0,0),P.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),P.TransformNormalToRef(i,e,i),we.RotationAxisToRef(i,this.pitchOffset*Math.PI/180,this._tmpQuaternion),t.rotateByQuaternionToRef(this._tmpQuaternion,t),this._toOrientationQuatToRef(t,this._tmpQuaternion),this._tmpQuaternion.toRotationMatrix(this._tmpMatrix),e.copyFrom(this._tmpMatrix)}_angularClamp(e,t){const i=this._tmpVectors[5];i.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1);const r=this._tmpVectors[6];r.copyFromFloats(1,0,0),P.TransformNormalToRef(i,e,i),P.TransformNormalToRef(r,e,r);const s=P.UpReadOnly;if(t.length()d&&(we.RotationAxisToRef(r,-u+d,c),t.rotateByQuaternionToRef(c,t),o=!0)}const l=this._angleBetweenVectorAndPlane(t,r)*(this._scene.useRightHandedSystem?-1:1),h=this.maxViewHorizontalDegrees*Math.PI/180*.5;return l<-h?(we.RotationAxisToRef(s,-l-h,c),t.rotateByQuaternionToRef(c,t),o=!0):l>h&&(we.RotationAxisToRef(s,-l+h,c),t.rotateByQuaternionToRef(c,t),o=!0),o}_orientationClamp(e,t){var o;const i=this._tmpVectors[0];i.copyFrom(e).scaleInPlace(-1).normalize();const r=this._tmpVectors[1],s=this._tmpVectors[2];r.copyFromFloats(0,1,0),P.CrossToRef(i,r,s);const a=s.length();athis.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),r=this._workingPosition,s=this._workingQuaternion,a=this.attachedNode.getPivotPoint(),o=this._tmpInvertView;o.copyFrom(e.getViewMatrix()),o.invert(),P.TransformCoordinatesToRef(a,i,r);const c=this._tmpPosition;c.copyFromFloats(0,0,0),P.TransformCoordinatesToRef(c,i,c),c.scaleInPlace(-1).subtractInPlace(a),r.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(o);let l=!1;const h=this._tmpForward;h.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),P.TransformNormalToRef(h,o,h);const u=this._tmpNodeForward;if(u.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),P.TransformNormalToRef(u,i,u),this._recenterNextUpdate)r.copyFrom(h).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const f=r.length();r.copyFrom(h).scaleInPlace(f)}else l=this._angularClamp(o,r);let d=!1;this.ignoreDistanceClamp||(d=this._distanceClamp(r,l),this._applyVerticalClamp(r)),this.useFixedVerticalOffset&&(r.y=c.y-e.globalPosition.y+this.fixedVerticalOffset),(l||d||this._passedOrientationDeadzone(r,u)||this._recenterNextUpdate)&&this._orientationClamp(r,s),this._workingPosition.subtractInPlace(a),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}}_updateTransformToGoal(e){if(!this.attachedNode||!this.followedCamera||!this._enabled)return;this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=we.Identity());const t=this.attachedNode.parent;if(this.attachedNode.setParent(null),!this.interpolatePose){this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition),this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);return}const i=new P;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),P.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const r=new we;r.copyFrom(this.attachedNode.rotationQuaternion),we.SmoothToRef(r,this._workingQuaternion,e,this.lerpTime,this.attachedNode.rotationQuaternion),this.attachedNode.setParent(t)}_addObservables(){this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add(()=>{if(!this.followedCamera)return;const e=Date.now();this._updateLeashing(this.followedCamera),this._updateTransformToGoal(e-this._lastTick),this._lastTick=e})}_removeObservables(){this._onBeforeRender&&this._scene.onBeforeRenderObservable.remove(this._onBeforeRender)}}class pr{}pr.ANCHOR_SYSTEM="xr-anchor-system";pr.BACKGROUND_REMOVER="xr-background-remover";pr.HIT_TEST="xr-hit-test";pr.MESH_DETECTION="xr-mesh-detection";pr.PHYSICS_CONTROLLERS="xr-physics-controller";pr.PLANE_DETECTION="xr-plane-detection";pr.POINTER_SELECTION="xr-controller-pointer-selection";pr.TELEPORTATION="xr-controller-teleportation";pr.FEATURE_POINTS="xr-feature-points";pr.HAND_TRACKING="xr-hand-tracking";pr.IMAGE_TRACKING="xr-image-tracking";pr.NEAR_INTERACTION="xr-near-interaction";pr.DOM_OVERLAY="xr-dom-overlay";pr.MOVEMENT="xr-controller-movement";pr.LIGHT_ESTIMATION="xr-light-estimation";pr.EYE_TRACKING="xr-eye-tracking";pr.WALKING_LOCOMOTION="xr-walking-locomotion";pr.LAYERS="xr-layers";pr.DEPTH_SENSING="xr-depth-sensing";pr.SPACE_WARP="xr-space-warp";pr.RAW_CAMERA_ACCESS="xr-raw-camera-access";class vn{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(()=>{this.getEnabledFeatures().forEach(t=>{const i=this._features[t];i.enabled&&!i.featureImplementation.attached&&!i.featureImplementation.disableAutoAttach&&this.attachFeature(t)})}),this._xrSessionManager.onXRSessionEnded.add(()=>{this.getEnabledFeatures().forEach(t=>{const i=this._features[t];i.enabled&&i.featureImplementation.attached&&this.detachFeature(t)})})}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){const s=this._AvailableFeatures[e][t];if(!s)throw new Error("feature not found");return s(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||Ee.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||Ee.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t=typeof e=="string"?e:e.Name,i=this._features[t];return i&&i.enabled?(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0):!1}dispose(){this.getEnabledFeatures().forEach(e=>{this.disableFeature(e)})}enableFeature(e,t="latest",i={},r=!0,s=!0){const a=typeof e=="string"?e:e.Name;let o=0;if(typeof t=="string"){if(!t)throw new Error(`Error in provided version - ${a} (${t})`);if(t==="stable"?o=vn.GetStableVersionOfFeature(a):t==="latest"?o=vn.GetLatestVersionOfFeature(a):o=+t,o===-1||isNaN(o))throw new Error(`feature not found - ${a} (${t})`)}else o=t;const c=vn._ConflictingFeatures[a];if(c!==void 0&&this.getEnabledFeatures().indexOf(c)!==-1)throw new Error(`Feature ${a} cannot be enabled while ${c} is enabled.`);const l=this._features[a],h=vn.ConstructFeature(a,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${a}`);l&&this.disableFeature(a);const u=h();if(u.dependsOn&&!u.dependsOn.every(f=>!!this._features[f]))throw new Error(`Dependant features missing. Make sure the following features are enabled - ${u.dependsOn.join(", ")}`);if(u.isCompatible())return this._features[a]={featureImplementation:u,enabled:!0,version:o,required:s},r?this._xrSessionManager.session&&!this._features[a].featureImplementation.attached&&this.attachFeature(a):this._features[a].featureImplementation.disableAutoAttach=!0,this._features[a].featureImplementation;if(s)throw new Error("required feature not compatible");return Ee.Warn(`Feature ${a} not compatible with the current environment/browser and was not enabled.`),u}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const r=this._features[i],s=r.featureImplementation.xrNativeFeatureName;if(s&&(r.required?(e.requiredFeatures=e.requiredFeatures||[],e.requiredFeatures.indexOf(s)===-1&&e.requiredFeatures.push(s)):(e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.indexOf(s)===-1&&e.optionalFeatures.push(s))),r.featureImplementation.getXRSessionInitExtension){const a=await r.featureImplementation.getXRSessionInitExtension();e={...e,...a}}}return e}}vn._AvailableFeatures={};vn._ConflictingFeatures={[pr.TELEPORTATION]:pr.MOVEMENT,[pr.MOVEMENT]:pr.TELEPORTATION};class Lo{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){var t;!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&((t=this._xrSessionManager.enabledFeatures)==null?void 0:t.indexOf(e))===-1&&de.Warn(`The feature ${e} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`),this._xrNativeFeatureName=e}constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this._xrNativeFeatureName="",this.onFeatureAttachObservable=new Ae,this.onFeatureDetachObservable=new Ae}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;if(!this._xrSessionManager.enabledFeatures)de.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");else if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName)===-1)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,t=>this._onXRFrame(t)),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach(e=>{e.observable.remove(e.observer)}),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t,i){this._removeOnDetach.push({observable:e,observer:e.add(t,void 0,i)})}}class as{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}as.DistanceJoint=0;as.HingeJoint=1;as.BallAndSocketJoint=2;as.WheelJoint=3;as.SliderJoint=4;as.PrismaticJoint=5;as.UniversalJoint=6;as.Hinge2Joint=as.WheelJoint;as.PointToPointJoint=8;as.SpringJoint=9;as.LockJoint=10;class gRe extends as{constructor(e){super(as.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class HJ extends as{constructor(e,t){super(e,t)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class vRe extends HJ{constructor(e){super(as.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class xRe extends HJ{constructor(e){super(as.Hinge2Joint,e)}setMotor(e,t,i=0){this._physicsPlugin.setMotor(this,e||0,t,i)}setLimit(e,t,i=0){this._physicsPlugin.setLimit(this,e,t,i)}}Se._PhysicsImpostorParser=function(n,e,t){return new Zt(e,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},n)};class Zt{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){if(this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=P.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new we,this._tmpQuat2=new we,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new we),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach(s=>{s(this)}))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach(s=>{s(this)}),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,Zt._TmpVecs[0]),this.object.translate(Zt._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=s=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent||!this._physicsEngine)return;const a=this._physicsEngine.getImpostorWithPhysicsBody(s.body);a&&(this.onCollideEvent&&this.onCollideEvent(this,a),this._onPhysicsCollideCallbacks.filter(o=>o.otherImpostors.indexOf(a)!==-1).forEach(o=>{o.callback(this,a,s.point,s.distance,s.impulse,s.normal)}))},!this.object){de.Error("No object was provided. A physics object is obligatory");return}this.object.parent&&i.mass!==0&&de.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=we.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new we),this._options.mass=i.mass===void 0?0:i.mass,this._options.friction=i.friction===void 0?.2:i.friction,this._options.restitution=i.restitution===void 0?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=i.pressure===void 0?200:i.pressure,this._options.stiffness=i.stiffness===void 0?1:i.stiffness,this._options.velocityIterations=i.velocityIterations===void 0?20:i.velocityIterations,this._options.positionIterations=i.positionIterations===void 0?20:i.positionIterations,this._options.fixedPoints=i.fixedPoints===void 0?0:i.fixedPoints,this._options.margin=i.margin===void 0?0:i.margin,this._options.damping=i.damping===void 0?0:i.damping,this._options.path=i.path===void 0?null:i.path,this._options.shape=i.shape===void 0?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&de.Warn("You must affect impostors to children before affecting impostor to parent.")):de.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),!this._isDisposed&&(!this.parent||this._options.ignoreParent)&&this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof di?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=Zt.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const s=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}else return Zt.DEFAULT_OBJECT_SIZE}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):P.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):P.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):de.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):de.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let r=-1;this._onPhysicsCollideCallbacks.some((a,o)=>{if(a.callback===t&&a.otherImpostors.length===i.length){const c=a.otherImpostors.every(l=>i.indexOf(l)>-1);return c&&(r=o),c}return!1})?this._onPhysicsCollideCallbacks.splice(r,1):de.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):we.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const r=new as(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,s){if(!this._physicsEngine)return this;const a=this._physicsEngine.getPhysicsPlugin();return a.appendAnchor?(this._physicsEngine&&a.appendAnchor(this,e,t,i,r,s),this):this}addHook(e,t,i,r){if(!this._physicsEngine)return this;const s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor?(this._physicsEngine&&s.appendHook(this,e,t,i,r),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new Zt(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach(e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new we),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,r,s){const a=Zt._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(s){const c=Zt._TmpQuat;o.rotationQuaternion.multiplyToRef(s,c),e.setRotationQuaternion(c,Ci.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,Ci.WORLD,t);a.x=0,a.y=0,a.z=0,i&&(a.x=i.x,a.y=i.y,a.z=i.z,e.getDirectionToRef(a,t,a),r==null&&(r=i.length()),a.x*=r,a.y*=r,a.z*=r),e.getParent()?(a.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(a,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=a.x,t.position.y-=a.y,t.position.z-=a.z)}syncImpostorWithBone(e,t,i,r,s,a){const o=this.object;if(o.rotationQuaternion)if(s){const h=Zt._TmpQuat;e.getRotationQuaternionToRef(Ci.WORLD,t,h),h.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(Ci.WORLD,t,o.rotationQuaternion);const c=Zt._TmpVecs[0],l=Zt._TmpVecs[1];a||(a=Zt._TmpVecs[2],a.x=0,a.y=1,a.z=0),e.getDirectionToRef(a,t,l),e.getAbsolutePositionToRef(t,c),r==null&&i&&(r=i.length()),r!=null&&(c.x+=l.x*r,c.y+=l.y*r,c.z+=l.z*r),o.setAbsolutePosition(c)}}Zt.DEFAULT_OBJECT_SIZE=new P(1,1,1);Zt.IDENTITY_QUATERNION=we.Identity();Zt._TmpVecs=Va.BuildArray(3,P.Zero);Zt._TmpQuat=we.Identity();Zt.NoImpostor=0;Zt.SphereImpostor=1;Zt.BoxImpostor=2;Zt.PlaneImpostor=3;Zt.MeshImpostor=4;Zt.CapsuleImpostor=6;Zt.CylinderImpostor=7;Zt.ParticleImpostor=8;Zt.HeightmapImpostor=9;Zt.ConvexHullImpostor=10;Zt.CustomImpostor=100;Zt.RopeImpostor=101;Zt.ClothImpostor=102;Zt.SoftbodyImpostor=103;var T0;(function(n){n[n.Clean=0]="Clean",n[n.Stop=1]="Stop",n[n.Sync=2]="Sync",n[n.NoSync=3]="NoSync"})(T0||(T0={}));class ai{static get ForceFullSceneLoadingForIncremental(){return ro.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){ro.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return ro.ShowLoadingScreen}static set ShowLoadingScreen(e){ro.ShowLoadingScreen=e}static get loggingLevel(){return ro.loggingLevel}static set loggingLevel(e){ro.loggingLevel=e}static get CleanBoneMatrixWeights(){return ro.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){ro.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return ai._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=ai._RegisteredPlugins[e];return t||(de.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),ai.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in ai._RegisteredPlugins){const i=ai._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return ai._RegisteredPlugins[t]}return ai.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");t!==-1&&(e=e.substring(0,t));const i=e.lastIndexOf("."),r=e.substring(i,e.length).toLowerCase();return ai._GetPluginForExtension(r)}static _GetDirectLoad(e){return e.substr(0,5)==="data:"?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+(e.rawData?"binary data":e.url);return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,r,s,a,o,c){const l=ai._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=o?ai._GetPluginForExtension(o):l?ai._GetPluginForDirectLoad(e.url):ai._GetPluginForFilename(e.url);if(e.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let u;if(h.plugin.createPlugin!==void 0?u=h.plugin.createPlugin():u=h.plugin,!u)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(ai.OnPluginActivatedObservable.notifyObservers(u),l&&(u.canDirectLoad&&u.canDirectLoad(e.url)||!UO(e.url))){if(u.directLoad){const y=u.directLoad(t,l);y.then?y.then(C=>{i(u,C)}).catch(C=>{s("Error in directLoad of _loadData: "+C,C)}):i(u,y)}else i(u,l);return u}const d=h.isBinary,f=(y,C)=>{if(t.isDisposed){s("Scene has been disposed");return}i(u,y,C)};let p=null,_=!1;const m=u.onDisposeObservable;m&&m.add(()=>{_=!0,p&&(p.abort(),p=null),a()});const g=()=>{if(_)return;const y=(C,b)=>{s(C==null?void 0:C.statusText,b)};if(!u.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=u.loadFile?u.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,f,r,d,y,c):t._loadFile(e.file||e.url,f,r,!0,d,y)},v=t.getEngine();let x=v.enableOfflineSupport;if(x){let y=!1;for(const C of t.disableOfflineSupportExceptionRules)if(C.test(e.url)){y=!0;break}x=!y}return x&&De.OfflineProviderFactory?t.offlineProvider=De.OfflineProviderFactory(e.url,g,v.disableManifestCheck):g(),u}static _GetFileInfo(e,t){let i,r,s=null,a=null;if(!t)i=e,r=Ee.GetFilename(e),e=Ee.GetFolderPath(e);else if(t.name){const o=t;i=`file:${o.name}`,r=o.name,s=o}else if(ArrayBuffer.isView(t))i="",r=mh(),a=t;else if(typeof t=="string"&&t.startsWith("data:"))i=t,r="";else{const o=t;if(o.substr(0,1)==="/")return Ee.Error("Wrong sceneFilename parameter"),null;i=e+o,r=o}return{url:i,rootUrl:e,name:r,file:s,rawData:a}}static GetPluginForExtension(e){return ai._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!ai._RegisteredPlugins[e]}static RegisterPlugin(e){if(typeof e.extensions=="string"){const t=e.extensions;ai._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach(i=>{ai._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",r=bt.LastCreatedScene,s=null,a=null,o=null,c=null,l=""){if(!r)return de.Error("No scene available to import mesh to"),null;const h=ai._GetFileInfo(t,i);if(!h)return null;const u={};r.addPendingData(u);const d=()=>{r.removePendingData(u)},f=(m,g)=>{const v=ai._FormatErrorMessage(h,m,g);o?o(r,v,new kf(v,z0.SceneLoaderError,g)):de.Error(v),d()},p=a?m=>{try{a(m)}catch(g){f("Error in onProgress callback: "+g,g)}}:void 0,_=(m,g,v,x,y,C,b,T)=>{if(r.importedMeshesFiles.push(h.url),s)try{s(m,g,v,x,y,C,b,T)}catch(S){f("Error in onSuccess callback: "+S,S)}r.removePendingData(u)};return ai._LoadData(h,r,(m,g,v)=>{if(m.rewriteRootURL&&(h.rootUrl=m.rewriteRootURL(h.rootUrl,v)),m.importMesh){const x=m,y=[],C=[],b=[];if(!x.importMesh(e,r,g,h.rootUrl,y,C,b,f))return;r.loadingPluginName=m.name,_(y,C,b,[],[],[],[],[])}else m.importMeshAsync(e,r,g,h.rootUrl,p,h.name).then(y=>{r.loadingPluginName=m.name,_(y.meshes,y.particleSystems,y.skeletons,y.animationGroups,y.transformNodes,y.geometries,y.lights,y.spriteManagers)}).catch(y=>{f(y.message,y)})},p,f,d,c,l)}static ImportMeshAsync(e,t,i="",r=bt.LastCreatedScene,s=null,a=null,o=""){return new Promise((c,l)=>{ai.ImportMesh(e,t,i,r,(h,u,d,f,p,_,m,g)=>{c({meshes:h,particleSystems:u,skeletons:d,animationGroups:f,transformNodes:p,geometries:_,lights:m,spriteManagers:g})},s,(h,u,d)=>{l(d||new Error(u))},a,o)})}static Load(e,t="",i=bt.LastCreatedEngine,r=null,s=null,a=null,o=null,c=""){return i?ai.Append(e,t,new pt(i),r,s,a,o,c):(Ee.Error("No engine available"),null)}static LoadAsync(e,t="",i=bt.LastCreatedEngine,r=null,s=null,a=""){return new Promise((o,c)=>{ai.Load(e,t,i,l=>{o(l)},r,(l,h,u)=>{c(u||new Error(h))},s,a)})}static Append(e,t="",i=bt.LastCreatedScene,r=null,s=null,a=null,o=null,c=""){if(!i)return de.Error("No scene available to append to"),null;const l=ai._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const u=()=>{i.removePendingData(h)};ai.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));const d=(_,m)=>{const g=ai._FormatErrorMessage(l,_,m);a?a(i,g,new kf(g,z0.SceneLoaderError,m)):de.Error(g),u()},f=s?_=>{try{s(_)}catch(m){d("Error in onProgress callback",m)}}:void 0,p=()=>{if(r)try{r(i)}catch(_){d("Error in onSuccess callback",_)}i.removePendingData(h)};return ai._LoadData(l,i,(_,m)=>{if(_.load){if(!_.load(i,m,l.rootUrl,d))return;i.loadingPluginName=_.name,p()}else _.loadAsync(i,m,l.rootUrl,f,l.name).then(()=>{i.loadingPluginName=_.name,p()}).catch(v=>{d(v.message,v)})},f,d,u,o,c)}static AppendAsync(e,t="",i=bt.LastCreatedScene,r=null,s=null,a=""){return new Promise((o,c)=>{ai.Append(e,t,i,l=>{o(l)},r,(l,h,u)=>{c(u||new Error(h))},s,a)})}static LoadAssetContainer(e,t="",i=bt.LastCreatedScene,r=null,s=null,a=null,o=null,c=""){if(!i)return de.Error("No scene available to load asset container to"),null;const l=ai._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const u=()=>{i.removePendingData(h)},d=(_,m)=>{const g=ai._FormatErrorMessage(l,_,m);a?a(i,g,new kf(g,z0.SceneLoaderError,m)):de.Error(g),u()},f=s?_=>{try{s(_)}catch(m){d("Error in onProgress callback",m)}}:void 0,p=_=>{if(r)try{r(_)}catch(m){d("Error in onSuccess callback",m)}i.removePendingData(h)};return ai._LoadData(l,i,(_,m)=>{if(_.loadAssetContainer){const v=_.loadAssetContainer(i,m,l.rootUrl,d);if(!v)return;v.populateRootNodes(),i.loadingPluginName=_.name,p(v)}else _.loadAssetContainerAsync?_.loadAssetContainerAsync(i,m,l.rootUrl,f,l.name).then(v=>{v.populateRootNodes(),i.loadingPluginName=_.name,p(v)}).catch(v=>{d(v.message,v)}):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},f,d,u,o,c)}static LoadAssetContainerAsync(e,t="",i=bt.LastCreatedScene,r=null,s=null){return new Promise((a,o)=>{ai.LoadAssetContainer(e,t,i,c=>{a(c)},r,(c,l,h)=>{o(h||new Error(l))},s)})}static ImportAnimations(e,t="",i=bt.LastCreatedScene,r=!0,s=T0.Clean,a=null,o=null,c=null,l=null,h=null){if(!i){de.Error("No scene available to load animations to");return}if(r){for(const p of i.animatables)p.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(p=>{p.dispose()}),i.getNodes().forEach(p=>{p.animations&&(p.animations=[])})}else switch(s){case T0.Clean:i.animationGroups.slice().forEach(f=>{f.dispose()});break;case T0.Stop:i.animationGroups.forEach(f=>{f.stop()});break;case T0.Sync:i.animationGroups.forEach(f=>{f.reset(),f.restart()});break;case T0.NoSync:break;default:de.Error("Unknown animation group loading mode value '"+s+"'");return}const u=i.animatables.length,d=f=>{f.mergeAnimationsTo(i,i.animatables.slice(u),a),f.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)};this.LoadAssetContainer(e,t,i,d,c,l,h)}static ImportAnimationsAsync(e,t="",i=bt.LastCreatedScene,r=!0,s=T0.Clean,a=null,o=null,c=null,l=null,h=null){return new Promise((u,d)=>{ai.ImportAnimations(e,t,i,r,s,a,f=>{u(f)},c,(f,p,_)=>{d(_||new Error(p))},h)})}}ai.NO_LOGGING=0;ai.MINIMAL_LOGGING=1;ai.SUMMARY_LOGGING=2;ai.DETAILED_LOGGING=3;ai.OnPluginActivatedObservable=new Ae;ai._RegisteredPlugins={};ai._ShowingLoadingScreen=!1;class Rn extends Ye{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new ce,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return e?!this._storeEffectOnSubMeshes||!e.subMeshes||e.subMeshes.length===0?!0:this.isReadyForSubMesh(e,e.subMeshes[0],t):!1}_isReadyForSubMesh(e){const t=e.materialDefines;return!!(!this.checkReadyOnEveryCall&&e.effect&&t&&t._renderId===this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,r=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,r)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}var se;(function(n){n[n.Float=1]="Float",n[n.Int=2]="Int",n[n.Vector2=4]="Vector2",n[n.Vector3=8]="Vector3",n[n.Vector4=16]="Vector4",n[n.Color3=32]="Color3",n[n.Color4=64]="Color4",n[n.Matrix=128]="Matrix",n[n.Object=256]="Object",n[n.AutoDetect=1024]="AutoDetect",n[n.BasedOnInput=2048]="BasedOnInput",n[n.All=4095]="All"})(se||(se={}));var Ce;(function(n){n[n.Vertex=1]="Vertex",n[n.Fragment=2]="Fragment",n[n.Neutral=4]="Neutral",n[n.VertexAndFragment=3]="VertexAndFragment"})(Ce||(Ce={}));class rde{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){const t=e.sharedData.emitComments,i=this.target===Ce.Fragment;this.compilationString=` ${t?`//Entry point `:""}void main(void) { ${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` ${t?`//Constants `:""}${this._constantDeclaration} ${this.compilationString}`);let r="";for(const s in this.functions)r+=this.functions[s]+` `;this.compilationString=` ${r} ${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString} ${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString} ${this._injectAtEnd}`),this.compilationString=`${this.compilationString} }`,this.sharedData.varyingDeclaration&&(this.compilationString=` ${t?`//Varyings `:""}${this.sharedData.varyingDeclaration} ${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=` ${t?`//Samplers `:""}${this._samplerDeclaration} ${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=` ${t?`//Uniforms `:""}${this._uniformDeclaration} ${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=` ${t?`//Attributes `:""}${this._attributeDeclaration} ${this.compilationString}`),this.compilationString=`precision highp float; `+this.compilationString,this.compilationString=`#if defined(WEBGL2) || defines(WEBGPU) precision highp sampler2DArray; #endif `+this.compilationString,i&&(this.compilationString=`#if defined(PREPASS)\r #extension GL_EXT_draw_buffers : require\r layout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r highp vec4 gl_FragColor;\r #endif\r `+this.compilationString);for(const s in this.extensions){const a=this.extensions[s];this.compilationString=` ${a} ${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),this.sharedData.variableNames[e]===void 0?(this.sharedData.variableNames[e]=0,e==="output"||e==="texture"?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return this.sharedData.defineNames[e]===void 0?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2D ${e}; `,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e}; `,this.samplers.push(e))}_getGLType(e){switch(e){case se.Float:return"float";case se.Int:return"int";case se.Vector2:return"vec2";case se.Color3:case se.Vector3:return"vec3";case se.Color4:case se.Vector4:return"vec4";case se.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i} ${t} #endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+` `+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] `;let r=bi.IncludesShadersStore[e]+` `;if(this.sharedData.emitComments&&(r=t+` `+r),!i)return r;if(i.replaceStrings)for(let s=0;s${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] `:this.functions[s]=`#include<${e}>${i!=null&&i.substitutionVars?"("+(i==null?void 0:i.substitutionVars)+")":""} `,this.sharedData.emitComments&&(this.functions[s]=t+` `+this.functions[s]);return}if(this.functions[s]=bi.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+` `+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,` `)),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,` `)),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,` `)),i.replaceStrings)for(let a=0;athis._setDefaultValue(e))}_setDefaultValue(e){var r,s,a,o;const t=((s=(r=this._externalProperties)==null?void 0:r[e])==null?void 0:s.type)??typeof this[e],i=(o=(a=this._externalProperties)==null?void 0:a[e])==null?void 0:o.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1;break}}toString(){let e="";for(let t=0;te.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===Ce.Vertex||(e.ownerBlock.target===Ce.Neutral||e.ownerBlock.target===Ce.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===Ce.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===Ce.Vertex||e.target===Ce.Vertex||(e.ownerBlock.target===Ce.Neutral||e.ownerBlock.target===Ce.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===Ce.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===Ce.Fragment||(e.ownerBlock.target===Ce.Neutral||e.ownerBlock.target===Ce.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=new Array,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=se.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new Ae,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=Ce.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===Au.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===Ce.Fragment){if(i.target===Ce.Vertex)return Au.TargetIncompatible;for(const a of i.outputs)if(a.ownerBlock.target!=Ce.Neutral&&a.isConnectedInVertexShader)return Au.TargetIncompatible}if(this.type!==e.type&&e.innerType!==se.AutoDetect)return Jy.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1||e._acceptedConnectionPointType&&Jy.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?Au.Compatible:Au.TypeIncompatible;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return Au.TypeIncompatible;let r=i,s=t;return this.direction===Zs.Input&&(r=t,s=i),r.isAnAncestorOf(s)?Au.HierarchyIssue:Au.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return t===-1?this:(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this)}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}}class zt{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){this._target&e||(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter(i=>i.name===e);return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter(i=>i.name===e);return t.length?t[0]:null}constructor(e,t=Ce.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===Ce.Neutral,this._isFinalMerger=i,this._isInput=this.getClassName()==="InputBlock",this._isTeleportOut=this.getClassName()==="NodeMaterialTeleportOutBlock",this._isTeleportIn=this.getClassName()==="NodeMaterialTeleportInBlock",this._name=e,this.uniqueId=kO.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===Ce.Neutral}initialize(e){}bind(e,t,i,r){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return t.indexOf(".")===-1&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some(e=>e.isConnectedInFragmentShader)}registerInput(e,t,i=!1,r,s){return s=s??new Jy(e,this,Zs.Input),s.type=t,s.isOptional=i,r&&(s.target=r),this._inputs.push(s),this}registerOutput(e,t,i,r){return r=r??new Jy(e,this,Zs.Output),r.type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===se.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===Ce.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return t===-1||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints){for(const i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(this._outputs.length===0)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){const s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),r=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,s){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput)||this.target===Ce.Vertex?!1:!!((this.target===Ce.VertexAndFragment||this.target===Ce.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);const s=t._vertexState!=null,a=e._buildTarget===Ce.Vertex&&e.target!==Ce.VertexAndFragment;if(s&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==Ce.VertexAndFragment&&a)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const o=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+o.associatedVariableName,t._getGLType(o.type))&&(t._vertexState.compilationString+=`${"v_"+o.associatedVariableName} = ${o.associatedVariableName}; `),i.associatedVariableName="v_"+o.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const i of this._outputs)i.associatedVariableName||(i.associatedVariableName=e._getFreeVariableName(i.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==Ce.Neutral&&(!(i.target&this.target)||!(i.target&e.target)))continue;const r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&de.Log(`${e.target===Ce.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case Ce.Vertex:e.sharedData.checks.emitVertex=!0;break;case Ce.Fragment:e.sharedData.checks.emitFragment=!0;break}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=` //${this.name} `),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(i.target&e.target)for(const r of i.endpoints){const s=r.ownerBlock;s&&s.target&e.target&&t.indexOf(s)!==-1&&this._processBuild(s,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector}; ${e}.visibleOnFrame = ${this.visibleOnFrame}; ${e}.target = ${this.target}; `}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,e.indexOf(this._codeVariableName)!==-1){let s=0;do s++,this._codeVariableName=i+s;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let r=` // ${this.getClassName()} `;this.comments&&(r+=`// ${this.comments} `),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); `,r+=this._dumpPropertiesCode();for(const s of this.inputs){if(!s.isConnected)continue;const o=s.connectedPoint.ownerBlock;t.indexOf(o)===-1&&(r+=o._dumpCode(e,t))}for(const s of this.outputs)if(s.hasEndpoints)for(const a of s.endpoints){const o=a.ownerBlock;o&&t.indexOf(o)===-1&&(r+=o._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(e.indexOf(this)!==-1)return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); `}return t}clone(e,t=""){const i=this.serialize(),r=gn(i.customType);if(r){const s=new r;return s._deserialize(i,e,t),s}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((r,s)=>{r.displayName&&(this.inputs[s].displayName=r.displayName),r.isExposedOnFrame&&(this.inputs[s].isExposedOnFrame=r.isExposedOnFrame,this.inputs[s].exposedPortPosition=r.exposedPortPosition)}),i&&i.forEach((r,s)=>{r.displayName&&(this.outputs[s].displayName=r.displayName),r.isExposedOnFrame&&(this.outputs[s].isExposedOnFrame=r.isExposedOnFrame,this.outputs[s].exposedPortPosition=r.exposedPortPosition)})}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class Bz extends zt{constructor(e){super(e,Ce.Neutral),this.complementW=1,this.complementZ=0,this.target=Ce.Vertex,this.registerInput("vector",se.AutoDetect),this.registerInput("transform",se.Matrix),this.registerOutput("output",se.Vector4),this.registerOutput("xyz",se.Vector3),this._inputs[0].onConnectionObservable.add(t=>{if(t.ownerBlock.isInput){const i=t.ownerBlock;(i.name==="normal"||i.name==="tangent")&&(this.complementW=0)}})}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform;if(t.connectedPoint){if(this.complementW===0){const r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),e.sharedData.blocksWithDefines.push(this);const s=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${s} = mat3(${i.associatedVariableName}); `,e.compilationString+=`#ifdef NONUNIFORMSCALING `,e.compilationString+=`${s} = transposeMat3(inverseMat3(${s})); `,e.compilationString+=`#endif `,t.connectedPoint.type){case se.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); `;break;case se.Vector3:case se.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); `;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); `;break}}else{const r=i.associatedVariableName;switch(t.connectedPoint.type){case se.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); `;break;case se.Vector3:case se.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); `;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * ${t.associatedVariableName}; `;break}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; `)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=e.complementZ!==void 0?e.complementZ:0,this.complementW=e.complementW!==void 0?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ}; `;return e+=`${this._codeVariableName}.complementW = ${this.complementW}; `,e}}xe("BABYLON.TransformBlock",Bz);class pD extends zt{constructor(e){super(e,Ce.Vertex,!0),this.registerInput("vector",se.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const i of e)if(i.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName}; `,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w; `,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant; `),this}}xe("BABYLON.VertexOutputBlock",pD);var Gt;(function(n){n[n.Boolean=0]="Boolean",n[n.Float=1]="Float",n[n.Int=2]="Int",n[n.Vector2=3]="Vector2",n[n.List=4]="List"})(Gt||(Gt={}));function Xt(n,e=Gt.Boolean,t="PROPERTIES",i){return(r,s)=>{let a=r._propStore;a||(a=[],r._propStore=a),a.push({propertyName:s,displayName:n,type:e,groupName:t,options:i??{}})}}class Pm extends zt{constructor(e){super(e,Ce.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",se.Color4,!0),this.registerInput("rgb",se.AutoDetect,!0),this.registerInput("a",se.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(se.Color3|se.Vector3|se.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&Ha(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,r=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||r.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)r.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${r.associatedVariableName}); `:e.compilationString+=`gl_FragColor = ${t.associatedVariableName}; `;else if(i.connectedPoint){let a="1.0";r.connectedPoint&&(a=r.associatedVariableName),i.connectedPoint.type===se.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${a}); `:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${a}); `}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName} `,e.compilationString+=`gl_FragColor = toLinearSpace(gl_FragColor); `,e.compilationString+=`#endif `,e.compilationString+=`#ifdef ${this._gammaDefineName} `,e.compilationString+=`gl_FragColor = toGammaSpace(gl_FragColor); `,e.compilationString+=`#endif `,(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5; `),e.compilationString+=`#if defined(PREPASS)\r `,e.compilationString+=`gl_FragData[0] = gl_FragColor;\r `,e.compilationString+=`#endif\r `,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; `,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; `,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth}; `,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=e.useLogarithmicDepth??!1}}B([Xt("Convert to gamma space",Gt.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Pm.prototype,"convertToGammaSpace",void 0);B([Xt("Convert to linear space",Gt.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Pm.prototype,"convertToLinearSpace",void 0);B([Xt("Use logarithmic depth",Gt.Boolean,"PROPERTIES")],Pm.prototype,"useLogarithmicDepth",void 0);xe("BABYLON.FragmentOutputBlock",Pm);var ml;(function(n){n[n.Uniform=0]="Uniform",n[n.Attribute=1]="Attribute",n[n.Varying=2]="Varying",n[n.Undefined=3]="Undefined"})(ml||(ml={}));var Zi;(function(n){n[n.World=1]="World",n[n.View=2]="View",n[n.Projection=3]="Projection",n[n.ViewProjection=4]="ViewProjection",n[n.WorldView=5]="WorldView",n[n.WorldViewProjection=6]="WorldViewProjection",n[n.CameraPosition=7]="CameraPosition",n[n.FogColor=8]="FogColor",n[n.DeltaTime=9]="DeltaTime",n[n.CameraParameters=10]="CameraParameters",n[n.MaterialAlpha=11]="MaterialAlpha"})(Zi||(Zi={}));class GJ{constructor(e=P.Zero(),t=P.Up()){this.position=e,this.normal=t}clone(){return new GJ(this.position.clone(),this.normal.clone())}}class KJ{constructor(e=P.Zero(),t=P.Up(),i=Be.Zero()){this.position=e,this.normal=t,this.uv=i}clone(){return new KJ(this.position.clone(),this.normal.clone(),this.uv.clone())}}var Tm;(function(n){n[n.None=0]="None",n[n.Time=1]="Time",n[n.RealTime=2]="RealTime"})(Tm||(Tm={}));const ARe={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},hY={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},sde={particle_texturemask:!0};class Gi extends zt{get type(){if(this._type===se.AutoDetect){if(this.isUniform&&this.value!=null){if(!isNaN(this.value))return this._type=se.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=se.Vector2,this._type;case"Vector3":return this._type=se.Vector3,this._type;case"Vector4":return this._type=se.Vector4,this._type;case"Color3":return this._type=se.Color3,this._type;case"Color4":return this._type=se.Color4,this._type;case"Matrix":return this._type=se.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=se.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=se.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=se.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=se.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Zi.World:case Zi.WorldView:case Zi.WorldViewProjection:case Zi.View:case Zi.ViewProjection:case Zi.Projection:return this._type=se.Matrix,this._type;case Zi.CameraPosition:return this._type=se.Vector3,this._type;case Zi.FogColor:return this._type=se.Color3,this._type;case Zi.DeltaTime:case Zi.MaterialAlpha:return this._type=se.Float,this._type;case Zi.CameraParameters:return this._type=se.Vector4,this._type}}return this._type}constructor(e,t=Ce.Vertex,i=se.AutoDetect){super(e,t,!1),this._mode=ml.Undefined,this._animationType=Tm.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new Ae,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return this.isAttribute?!0:super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=ml.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===se.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=ml.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=ml.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===ml.Undefined}get isUniform(){return this._mode===ml.Uniform}set isUniform(e){this._mode=e?ml.Uniform:ml.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===ml.Attribute}set isAttribute(e){this._mode=e?ml.Attribute:ml.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===ml.Varying}set isVarying(e){this._mode=e?ml.Varying:ml.Undefined,this.associatedVariableName=""}get isSystemValue(){return this._systemValue!=null}get systemValue(){return this._systemValue}set systemValue(e){this._mode=ml.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Tm.Time:{this.type===se.Float&&(this.value+=e.getAnimationRatio()*.01);break}case Tm.RealTime:{this.type===se.Float&&(this.value=(gr.Now-e.getEngine().startTime)/1e3);break}}}_emitDefine(e){return e[0]==="!"?`#ifndef ${e.substring(1)} `:`#ifdef ${e} `}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case se.Float:this.value=0;break;case se.Vector2:this.value=Be.Zero();break;case se.Vector3:this.value=P.Zero();break;case se.Vector4:this.value=Ct.Zero();break;case se.Color3:this.value=Me.White();break;case se.Color4:this.value=new Ze(1,1,1,1);break;case se.Matrix:this.value=ce.Identity();break}}_emitConstant(e){switch(this.type){case se.Float:return`${e._emitFloat(this.value)}`;case se.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case se.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case se.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case se.Color3:return wr.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&wr.Color3[0].toGammaSpaceToRef(wr.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&wr.Color3[0].toLinearSpaceToRef(wr.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${wr.Color3[0].r}, ${wr.Color3[0].g}, ${wr.Color3[0].b})`;case se.Color4:return wr.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&wr.Color4[0].toGammaSpaceToRef(wr.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&wr.Color4[0].toLinearSpaceToRef(wr.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${wr.Color4[0].r}, ${wr.Color4[0].g}, ${wr.Color4[0].b}, ${wr.Color4[0].a})`}return""}get _noContextSwitch(){return hY[this.name]}_emit(e,t){if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(e.constants.indexOf(this.associatedVariableName)!==-1)return;e.constants.push(this.associatedVariableName),e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)}; `;return}if(e.uniforms.indexOf(this.associatedVariableName)!==-1)return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName}; `,t&&(e._uniformDeclaration+=`#endif `);const i=e.sharedData.hints;if(this._systemValue!==null&&this._systemValue!==void 0)switch(this._systemValue){case Zi.WorldView:i.needWorldViewMatrix=!0;break;case Zi.WorldViewProjection:i.needWorldViewProjectionMatrix=!0;break}else this._animationType!==Tm.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=ARe[this.name]??this.name,this.target===Ce.Vertex&&e._vertexState){hY[this.name]?sde[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t);return}if(e.attributes.indexOf(this.associatedVariableName)!==-1)return;e.attributes.push(this.associatedVariableName),hY[this.name]?sde[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName}; `,t&&(e._attributeDeclaration+=`#endif `))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;const s=this.associatedVariableName;switch(this._systemValue){case Zi.World:e.setMatrix(s,t);break;case Zi.WorldView:e.setMatrix(s,i);break;case Zi.WorldViewProjection:e.setMatrix(s,r);break}}_transmit(e,t,i){if(this.isAttribute)return;const r=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case Zi.World:case Zi.WorldView:case Zi.WorldViewProjection:return;case Zi.View:e.setMatrix(r,t.getViewMatrix());break;case Zi.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case Zi.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case Zi.CameraPosition:t.bindEyePosition(e,r,!0);break;case Zi.FogColor:e.setColor3(r,t.fogColor);break;case Zi.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case Zi.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Zi.MaterialAlpha:e.setFloat(r,i.alpha);break}return}const s=this._valueCallback?this._valueCallback():this._storedValue;if(s!==null)switch(this.type){case se.Float:e.setFloat(r,s);break;case se.Int:e.setInt(r,s);break;case se.Color3:wr.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&wr.Color3[0].toGammaSpaceToRef(wr.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&wr.Color3[0].toLinearSpaceToRef(wr.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,wr.Color3[0]);break;case se.Color4:wr.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&wr.Color4[0].toGammaSpaceToRef(wr.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&wr.Color4[0].toLinearSpaceToRef(wr.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,wr.Color4[0]);break;case se.Vector2:e.setVector2(r,s);break;case se.Vector3:e.setVector3(r,s);break;case se.Vector4:e.setVector4(r,s);break;case se.Matrix:e.setMatrix(r,s);break}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}"); `;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${Zi[this._systemValue]}); `;if(this.isUniform){const t=[];let i="";switch(this.type){case se.Float:i=`${this.value}`;break;case se.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case se.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case se.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case se.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case se.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case se.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`;break}return t.push(`${e}.value = ${i}`),this.type===se.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Tm[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(`; `)}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this._storedValue!=null&&this._mode===ml.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.name==="tangent"&&e.mode===ml.Attribute&&e.type===se.Vector3&&(this._type=se.Vector4),!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const r=gn(e.valueType);r&&(this._storedValue=r.FromArray(e.value))}}}xe("BABYLON.InputBlock",Gi);class WJ extends zt{constructor(e){super(e,Ce.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",se.AutoDetect,!1,Ce.VertexAndFragment),this.registerOutput("rgba",se.Color4,Ce.Neutral),this.registerOutput("rgb",se.Color3,Ce.Neutral),this.registerOutput("r",se.Float,Ce.Neutral),this.registerOutput("g",se.Float,Ce.Neutral),this.registerOutput("b",se.Float,Ce.Neutral),this.registerOutput("a",se.Float,Ce.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(se.Vector2|se.Vector3|se.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?Ce.VertexAndFragment:Ce.Fragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; `,!!this._outputs.some(i=>i.isConnectedInVertexShader)){this._writeTextureRead(e,!0);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===Ce.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); `;return}if(this.uv.ownerBlock.target===Ce.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); `;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); `}_writeOutput(e,t,i,r=!1){if(r){if(e.target===Ce.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; `;return}if(this.uv.ownerBlock.target===Ce.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; `;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; `,e.compilationString+=`#ifdef ${this._linearDefineName} `,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); `,e.compilationString+=`#endif `,e.compilationString+=`#ifdef ${this._gammaDefineName} `,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); `,e.compilationString+=`#endif `}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==Ce.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!this._outputs.some(i=>i.isConnectedInFragmentShader))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ve.Parse(e.texture,t,i))}}xe("BABYLON.CurrentScreenBlock",WJ);class jJ extends zt{constructor(e){super(e,Ce.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",se.AutoDetect,!1,Ce.VertexAndFragment),this.registerOutput("rgba",se.Color4,Ce.Neutral),this.registerOutput("rgb",se.Color3,Ce.Neutral),this.registerOutput("r",se.Float,Ce.Neutral),this.registerOutput("g",se.Float,Ce.Neutral),this.registerOutput("b",se.Float,Ce.Neutral),this.registerOutput("a",se.Float,Ce.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(se.Vector2|se.Vector3|se.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="particle_uv"&&t(r));i||(i=new Gi("uv"),i.setAsAttribute("particle_uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; `,e.compilationString+=`#ifdef ${this._linearDefineName} `,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); `,e.compilationString+=`#endif `,e.compilationString+=`#ifdef ${this._gammaDefineName} `,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); `,e.compilationString+=`#endif `}_buildBlock(e){if(super._buildBlock(e),e.target===Ce.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName}); `;for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ve.Parse(e.texture,t,i))}}xe("BABYLON.ParticleTextureBlock",jJ);class XJ extends zt{constructor(e){super(e,Ce.Fragment),this._isUnique=!0,this.registerInput("color",se.Color4,!1,Ce.Fragment),this.registerOutput("rampColor",se.Color4,Ce.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==Ce.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=` #ifdef RAMPGRADIENT vec4 baseColor = ${this.color.associatedVariableName}; float alpha = ${this.color.associatedVariableName}.a; float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.)); baseColor.rgb *= rampColor.rgb; // Remapped alpha float finalAlpha = baseColor.a; baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0); ${this._declareOutput(this.rampColor,e)} = baseColor; #else ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName}; #endif `,this}}xe("BABYLON.ParticleRampGradientBlock",XJ);class YJ extends zt{constructor(e){super(e,Ce.Fragment),this._isUnique=!0,this.registerInput("color",se.Color4,!1,Ce.Fragment),this.registerInput("alphaTexture",se.Float,!1,Ce.Fragment),this.registerInput("alphaColor",se.Float,!1,Ce.Fragment),this.registerOutput("blendColor",se.Color4,Ce.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==Ce.Vertex)return e.compilationString+=` #ifdef BLENDMULTIPLYMODE ${this._declareOutput(this.blendColor,e)}; float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha); ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a; #else ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName}; #endif `,this}}xe("BABYLON.ParticleBlendMultiplyBlock",YJ);class Hn{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let r=0;r0&&(s.computeBonesUsingShaders=!1);continue}if(!(!s.computeBonesUsingShaders||s.numBoneInfluencers===0)){if(s.material.getEffect()===t)s.computeBonesUsingShaders=!1;else if(s.subMeshes){for(const a of s.subMeshes)if(a.effect===t){s.computeBonesUsingShaders=!1;break}}}}}else{const i=this._defines[this._currentRank];if(i)for(let r=0;r0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get texture(){var e;return((e=this._textures)==null?void 0:e[0])??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r,s){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),t!==void 0&&t>=0&&(this._layerIndices[e]=t),i!==void 0&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){var o;return(o=this._depthStencilTexture)==null||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=a,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:a},this),this._depthStencilTexture}_shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var t,i,r,s,a;let e=null;if(this._isMulti){const o=this.textures;if(o&&o.length>0){let c=!1,l=o.length,h=-1;const u=o[o.length-1]._source;(u===mi.Depth||u===mi.DepthStencil)&&(c=!0,h=o[o.length-1].format,l--);const d=[],f=[],p=[],_=[],m=[],g=[],v=[],x={};for(let b=0;b1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e;if(this._textures)for(let t=0;t<((e=this._textures)==null?void 0:e.length);++t)this._textures[t].dispose();this._textures=null}dispose(e=!1){var t;e||((t=this._depthStencilTexture)==null||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class ERe extends XO{constructor(e,t,i,r,s){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){if(this._depthStencilBuffer){const o=this._engine._currentFramebuffer,c=this._context;this._engine._bindUnboundFramebuffer(this._framebuffer),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_STENCIL_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.STENCIL_ATTACHMENT,c.RENDERBUFFER,null),this._engine._bindUnboundFramebuffer(o),c.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,r,s,a)}_shareDepth(e){super._shareDepth(e);const t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;const s=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;this._engine._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,s,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var o,c;if(!e._hardwareTexture)return;const s=this._framebuffer,a=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(s),this._engine.webGLVersion>1){const l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??((o=this.layerIndices)==null?void 0:o[t])??0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=i??((c=this.faceIndices)==null?void 0:c[t])??0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{const l=this._context,h=l["COLOR_ATTACHMENT"+t+"_WEBGL"],u=i!==void 0?l.TEXTURE_CUBE_MAP_POSITIVE_X+i:l.TEXTURE_2D;l.framebufferTexture2D(l.FRAMEBUFFER,h,u,e._hardwareTexture.underlyingResource,r)}this._engine._bindUnboundFramebuffer(a)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var r;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=((r=this._attachments)==null?void 0:r.length)??this.textures.length;for(let s=0;s1&&(s.format===15?h=t.DEPTH_COMPONENT16:s.format===16?h=t.DEPTH_COMPONENT24:s.format===17||s.format===13?h=t.DEPTH24_STENCIL8:s.format===14?h=t.DEPTH_COMPONENT32F:s.format===18&&(h=t.DEPTH32F_STENCIL8)),s.is2DArray?t.texImage3D(r,0,h,s.width,s.height,i,0,l,c,null):t.texImage2D(r,0,h,s.width,s.height,0,l,c,null),this._bindTextureDirectly(r,null),this._internalTexturesCache.push(s),s};yt.prototype.updateRenderTargetTextureSampleCount=function(n,e){if(this.webGLVersion<2||!n||!n.texture)return 1;if(n.samples===e)return e;const t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),n._depthStencilBuffer&&(t.deleteRenderbuffer(n._depthStencilBuffer),n._depthStencilBuffer=null),n._MSAAFramebuffer&&(t.deleteFramebuffer(n._MSAAFramebuffer),n._MSAAFramebuffer=null);const i=n.texture._hardwareTexture;if(i.releaseMSAARenderBuffers(),e>1&&typeof t.renderbufferStorageMultisample=="function"){const r=t.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");n._MSAAFramebuffer=r,this._bindUnboundFramebuffer(n._MSAAFramebuffer);const s=this._createRenderBuffer(n.texture.width,n.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(n.texture.type,n.texture.format,n.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!s)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(s)}else this._bindUnboundFramebuffer(n._framebuffer);return n.texture.samples=e,n._samples=e,n._depthStencilBuffer=this._setupFramebufferDepthAttachments(n._generateStencilBuffer,n._generateDepthBuffer,n.texture.width,n.texture.height,e),this._bindUnboundFramebuffer(null),e};class Pt{static RegisterShaderCodeProcessing(e,t){if(!t){delete Pt._CustomShaderCodeProcessing[e??""];return}Pt._CustomShaderCodeProcessing[e??""]=t}static _GetShaderCodeProcessing(e){return Pt._CustomShaderCodeProcessing[e]??Pt._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach(t=>{t.setSamples(this._samples)})}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,r,s,a,o=1,c,l,h=null,u=0,d="postprocess",f,p=!1,_=5,m=Vs.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new ba(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new Be(1,1),this._texelSize=Be.Zero(),this.onActivateObservable=new Ae,this.onSizeChangedObservable=new Ae,this.onApplyObservable=new Ae,this.onBeforeRenderObservable=new Ae,this.onAfterRenderObservable=new Ae,this.name=e;let g=1,v=null;if(i&&!Array.isArray(i)){const x=i;i=x.uniforms??null,r=x.samplers??null,g=x.size??1,a=x.camera??null,o=x.samplingMode??1,c=x.engine,l=x.reusable,h=x.defines??null,u=x.textureType??0,d=x.vertexUrl??"postprocess",f=x.indexParameters,p=x.blockCompilation??!1,_=x.textureFormat??5,m=x.shaderLanguage??Vs.GLSL,v=x.uniformBuffers??null}else s&&(typeof s=="number"?g=s:g={width:s.width,height:s.height});a!=null?(this._camera=a,this._scene=a.getScene(),a.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):c&&(this._engine=c,this._engine.postProcesses.push(this)),this._options=g,this.renderTargetSamplingMode=o||1,this._reusable=l||!1,this._textureType=u,this._textureFormat=_,this._shaderLanguage=m,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=v||[],this._indexParameters=f,this._drawWrapper=new Sn(this._engine),p||this.updateEffect(h)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new ba(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,a,o,c){const l=Pt._GetShaderCodeProcessing(this.name);if(l!=null&&l.defineCustomBindings){const h=(t==null?void 0:t.slice())??[];h.push(...this._parameters);const u=(i==null?void 0:i.slice())??[];u.push(...this._samplers),e=l.defineCustomBindings(this.name,e,h,u),t=h,i=u}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o??this._vertexUrl,fragment:c??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:s??null,onError:a??null,indexParameters:r||this._indexParameters,processCodeAfterIncludes:l!=null&&l.processCodeAfterIncludes?(h,u)=>l.processCodeAfterIncludes(this.name,h,u):null,processFinalCode:l!=null&&l.processFinalCode?(h,u)=>l.processFinalCode(this.name,h,u):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let r=0;r0&&this._textures.reset(),this.width=e,this.height=t;let a=null;if(i){for(let l=0;l{_.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(_,this.samples)}),this._flushTextureCache(),this._renderId++}return d||(d=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,c/h),this._engine.bindFramebuffer(d,0,o,c,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(d,0,void 0,void 0,this.forceFullscreenViewport)),(p=(f=this._engine)._debugInsertMarker)==null||p.call(f,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:r.clearColor,r._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),d}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){var e;return((e=this._drawWrapper.effect)==null?void 0:e.isReady())??!1}apply(){var t,i,r;if(!((t=this._drawWrapper.effect)!=null&&t.isReady()))return null;this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a);let e;return this._shareOutputWithPostProcess?e=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?e=this._forcedOutputTexture:e=this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e==null?void 0:e.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),(r=(i=Pt._GetShaderCodeProcessing(this.name))==null?void 0:i.bindCustomBindings)==null||r.call(i,this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return this._prePassEffectConfiguration?(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0):!1}dispose(e){e=e||this._camera,this._disposeTextures();let t;if(this._scene&&(t=this._scene.postProcesses.indexOf(this),t!==-1&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const i=this._parentContainer.postProcesses.indexOf(this);i>-1&&this._parentContainer.postProcesses.splice(i,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),t!==-1&&this._engine.postProcesses.splice(t,1),!!e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),t===0&&e._postProcesses.length>0){const i=this._camera._getFirstPostProcess();i&&i.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=Qe.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=Pt.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const r=gn(e.customType);if(!r||!r._Parse)return null;const s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return Qe.Parse(()=>new Pt(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,r)}}Pt._CustomShaderCodeProcessing={};B([K()],Pt.prototype,"uniqueId",void 0);B([K()],Pt.prototype,"name",void 0);B([K()],Pt.prototype,"width",void 0);B([K()],Pt.prototype,"height",void 0);B([K()],Pt.prototype,"renderTargetSamplingMode",void 0);B([P5()],Pt.prototype,"clearColor",void 0);B([K()],Pt.prototype,"autoClear",void 0);B([K()],Pt.prototype,"forceAutoClearInAlphaMode",void 0);B([K()],Pt.prototype,"alphaMode",void 0);B([K()],Pt.prototype,"alphaConstants",void 0);B([K()],Pt.prototype,"enablePixelPerfectMode",void 0);B([K()],Pt.prototype,"forceFullscreenViewport",void 0);B([K()],Pt.prototype,"scaleMode",void 0);B([K()],Pt.prototype,"alwaysForcePOT",void 0);B([K("samples")],Pt.prototype,"_samples",void 0);B([K()],Pt.prototype,"adaptScaleToCurrentViewport",void 0);xe("BABYLON.PostProcess",Pt);class _D extends zt{constructor(e){super(e,Ce.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",se.Vector4,!0),this.registerInput("xyz ",se.Vector3,!0),this.registerInput("xy ",se.Vector2,!0),this.registerInput("zw ",se.Vector2,!0),this.registerInput("x",se.Float,!0),this.registerInput("y",se.Float,!0),this.registerInput("z",se.Float,!0),this.registerInput("w",se.Float,!0),this.registerOutput("xyzw",se.Vector4),this.registerOutput("xyz",se.Vector3),this.registerOutput("xy",se.Vector2),this.registerOutput("zw",se.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return e==="xyzw "?"xyzwIn":e==="xyz "?"xyzIn":e==="xy "?"xyIn":e==="zw "?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,r=this.z,s=this.w,a=this.xyIn,o=this.zwIn,c=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],u=this._outputs[1],d=this._outputs[2],f=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)}; `),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; `),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; `)):c.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${c.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; `),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${c.associatedVariableName}${this._buildSwizzle(3)}; `),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${c.associatedVariableName}${this._buildSwizzle(2)}; `)):a.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)}; `:e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; `),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; `),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)}; `),f.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(f,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; `:e.compilationString+=this._declareOutput(f,e)+` = vec2(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)}; `)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)}; `:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; `),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; `),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)}; `),f.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(f,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; `:e.compilationString+=this._declareOutput(f,e)+` = vec2(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)}; `)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.xSwizzle=e.xSwizzle??"x",this.ySwizzle=e.ySwizzle??"y",this.zSwizzle=e.zSwizzle??"z",this.wSwizzle=e.wSwizzle??"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}"; `,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}"; `,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}"; `,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}"; `,e}}xe("BABYLON.VectorMergerBlock",_D);class YO extends zt{constructor(e){super(e,Ce.Neutral),this.sourceRange=new Be(-1,1),this.targetRange=new Be(0,1),this.registerInput("input",se.AutoDetect),this.registerInput("sourceMin",se.Float,!0),this.registerInput("sourceMax",se.Float,!0),this.registerInput("targetMin",se.Float,!0),this.registerInput("targetMax",se.Float,!0),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),a=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${a} - ${s}) / (${r} - ${i}); `,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y}); `;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y}); `,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=Be.FromArray(e.sourceRange),this.targetRange=Be.FromArray(e.targetRange)}}B([Xt("From",Gt.Vector2)],YO.prototype,"sourceRange",void 0);B([Xt("To",Gt.Vector2)],YO.prototype,"targetRange",void 0);xe("BABYLON.RemapBlock",YO);class Fz extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("left",se.AutoDetect),this.registerInput("right",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1,!0),this._inputs[0].acceptedConnectionPointTypes.push(se.Float),this._inputs[1].acceptedConnectionPointTypes.push(se.Float)}getClassName(){return"MultiplyBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName}; `,this}}xe("BABYLON.MultiplyBlock",Fz);var wc;(function(n){n[n.Material=0]="Material",n[n.PostProcess=1]="PostProcess",n[n.Particle=2]="Particle",n[n.ProceduralTexture=3]="ProceduralTexture"})(wc||(wc={}));class TRe extends Kr{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class yo{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:P.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:P.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:P.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:P.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let r=0;for(const s of t){if(s.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=P.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.applyFog=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new P(10,10,10),this.onAnimationEnd=null,this.blendMode=yo.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new Be(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new P(0,0,0),this._useLogarithmicDepth=!1,this.gravity=P.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new Ze(1,1,1,1),this.color2=new Ze(1,1,1,1),this.colorDead=new Ze(0,0,0,1),this.textureMask=new Ze(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new TRe,this.id=e,this.name=e}createPointEmitter(e,t){throw new Error("Method not implemented.")}createHemisphericEmitter(e=1,t=1){throw new Error("Method not implemented.")}createSphereEmitter(e=1,t=1){throw new Error("Method not implemented.")}createDirectedSphereEmitter(e=1,t=new P(0,1,0),i=new P(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,r=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new P(0,1,0),s=new P(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,r){throw new Error("Method not implemented.")}}yo.BLENDMODE_ONEONE=0;yo.BLENDMODE_STANDARD=1;yo.BLENDMODE_ADD=2;yo.BLENDMODE_MULTIPLY=3;yo.BLENDMODE_MULTIPLYADD=4;class QJ extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("rgba",se.Color4,!0),this.registerInput("rgb ",se.Color3,!0),this.registerOutput("rgb",se.Color3),this.registerOutput("r",se.Float),this.registerOutput("g",se.Float),this.registerOutput("b",se.Float),this.registerOutput("a",se.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return e==="rgb "?"rgbIn":e}_outputRename(e){return e==="rgb"?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],a=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb; `),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.r; `),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g; `),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.b; `),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.a; `),this}}xe("BABYLON.ColorSplitterBlock",QJ);yt.prototype.createRenderTargetCubeTexture=function(n,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,n),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type===1&&!this._caps.textureFloatLinearFiltering||i.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(i.samplingMode=1);const r=this._gl,s=new Ar(this,mi.RenderTarget);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,s,!0);const a=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,de.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,a.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let c=0;c<6;c++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+c,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),n,n,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const o=r.createFramebuffer();return this._bindUnboundFramebuffer(o),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,n,n),i.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=o,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,s.width=n,s.height=n,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=i.generateMipMaps,s.samplingMode=i.samplingMode,s.type=i.type,s.format=i.format,this._internalTexturesCache.push(s),t.setTextures(s),t};const uY={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class QO{constructor(e,t=uY){this._fullscreenViewport=new bl(0,0,1,1);const i=t.positions??uY.positions,r=t.indices??uY.indices;this.engine=e,this._vertexBuffers={[Z.PositionKind]:new Z(e,i,Z.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(r),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(r);for(const s in this._vertexBuffers)this._vertexBuffers[s]._rebuild()})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return e.renderTarget!==void 0}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=t===null?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[Z.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[Z.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class H0{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.onApplyObservable=new Ae;let t;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)}));const r=e.defines?e.defines.join(` `):"";this._drawWrapper=new Sn(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,r,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new bi(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,r,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()}))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const Bme="passPixelShader",Fme=`varying vec2 vUV;uniform sampler2D textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);}`;Re.ShadersStore[Bme]=Fme;const nde={name:Bme,shader:Fme};class sl{static _CreateDumpRenderer(){if(!sl._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new yt(e,!1,i)}catch{e=document.createElement("canvas"),t=new yt(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;const r=new QO(t),s=new H0({engine:t,name:nde.name,fragmentShader:nde.shader,samplerNames:["textureSampler"]});sl._DumpToolsEngine={canvas:e,engine:t,renderer:r,wrapper:s}}return sl._DumpToolsEngine}static async DumpFramebuffer(e,t,i,r,s="image/png",a,o){const c=await i.readPixels(0,0,e,t),l=new Uint8Array(c.buffer);sl.DumpData(e,t,l,r,s,a,!0,void 0,o)}static DumpDataAsync(e,t,i,r="image/png",s,a=!1,o=!1,c){return new Promise(l=>{sl.DumpData(e,t,i,h=>l(h),r,s,a,o,c)})}static DumpData(e,t,i,r,s="image/png",a,o=!1,c=!1,l){const h=sl._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){const d=new Uint8Array(i.length);let f=i.length;for(;f--;){const p=i[f];d[f]=Math.round(_t.Clamp(p)*255)}i=d}const u=h.engine.createRawTexture(i,e,t,5,!1,!o,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",u),h.renderer.draw(),c?Ee.ToBlob(h.canvas,d=>{const f=new FileReader;f.onload=p=>{const _=p.target.result;r&&r(_)},f.readAsArrayBuffer(d)},s,l):Ee.EncodeScreenshotCanvasData(h.canvas,r,s,a,l),u.dispose()}static Dispose(){sl._DumpToolsEngine&&(sl._DumpToolsEngine.wrapper.dispose(),sl._DumpToolsEngine.renderer.dispose(),sl._DumpToolsEngine.engine.dispose()),sl._DumpToolsEngine=null}}const SRe=()=>{Ee.DumpData=sl.DumpData,Ee.DumpDataAsync=sl.DumpDataAsync,Ee.DumpFramebuffer=sl.DumpFramebuffer};SRe();class es extends ve{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=I_e(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;Array.isArray(e)?i=e:i=[e];for(let r=0;r{var S;const T=this._renderList?this._renderList.length:0;(b===0&&T>0||T===0)&&((S=this.getScene())==null||S.meshes.forEach(N=>{N._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new Ae,this.onAfterUnbindObservable=new Ae,this.onBeforeRenderObservable=new Ae,this.onAfterRenderObservable=new Ae,this.onClearObservable=new Ae,this.onResizeObservable=new Ae,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=P.Zero(),i=this.getScene(),!i)return;const y=this.getScene().getEngine();this._gammaSpace=x,this._coordinatesMode=ve.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=y.onResizeObservable.add(()=>{}),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=s,this._renderingManager=new rl(i),this._renderingManager._useSceneAutoClearSetup=!0,!u&&(this._renderTargetOptions={generateMipMaps:r,type:a,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:p,creationFlags:_,noColorAttachment:m,useSRGBBuffer:g,colorAttachment:v,label:this.name},this.samplingMode===ve.NEAREST_SAMPLINGMODE&&(this.wrapU=ve.CLAMP_ADDRESSMODE,this.wrapV=ve.CLAMP_ADDRESSMODE),f||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=ve.INVCUBIC_MODE,this._textureMatrix=ce.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,p!==void 0&&(this.samples=p)))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14){var a;(a=this._renderTarget)==null||a.createDepthStencilTexture(e,t,i,r,s)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;return e||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var r;const t=this.isCube;(r=this._renderTarget)==null||r.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),t?this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const r=this.getScene();if(!r)return i;const s=r.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let h=0;h{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):(!r||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0,s=null){var l,h,u;const a=this.getScene();if(!a)return;const o=a.getEngine();if((l=o._debugPushGroup)==null||l.call(o,`render to face #${e} layer #${r}`,1),this._prepareFrame(a,e,r,t),this.is2DArray?(o.currentRenderPassId=this._renderPassIds[r],this.onBeforeRenderObservable.notifyObservers(r)):(o.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),o.snapshotRendering&&o.snapshotRenderingMode===1)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||a.clearColor,!0,!0,!0);else{let d=null;const f=this.renderList?this.renderList:a.getActiveMeshes().data,p=this.renderList?this.renderList.length:a.getActiveMeshes().length;this.getCustomRenderList&&(d=this.getCustomRenderList(this.is2DArray?r:e,f,p)),d?this._prepareRenderingManager(d,d.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(f,p,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),d=f);for(const m of a._beforeRenderTargetClearStage)m.action(this,e,r);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||a.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||a.updateTransformMatrix(!0);for(const m of a._beforeRenderTargetDrawStage)m.action(this,e,r);this._renderingManager.render(this.customRenderFunction,d,this.renderParticles,this.renderSprites);for(const m of a._afterRenderTargetDrawStage)m.action(this,e,r);const _=((h=this._texture)==null?void 0:h.generateMipMaps)??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&a.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const m of a._afterRenderTargetPostProcessStage)m.action(this,e,r);this._texture&&(this._texture.generateMipMaps=_),this._doNotChangeAspectRatio||a.updateTransformMatrix(!0),i&&sl.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&e===5&&o.generateMipMapsForCubemap(this._texture),(u=o._debugPopGroup)==null||u.call(o,1)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new es(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(const r of e.cameras)t=r.customRenderTargets.indexOf(this),t>=0&&r.customRenderTargets.splice(t,1);(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===es.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=es.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}es.REFRESHRATE_RENDER_ONCE=0;es.REFRESHRATE_RENDER_ONEVERYFRAME=1;es.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;ve._CreateRenderTargetTexture=(n,e,t,i,r)=>new es(n,e,t,i);class Ume{constructor(e){this.name=it.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(it.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Ee.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}const MRe="proceduralVertexShader",RRe=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[MRe]=RRe;class Yf extends ve{constructor(e,t,i,r,s=null,a=!0,o=!1,c=0){super(null,r,!a),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new Ae,this.onBeforeGenerationObservable=new Ae,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,s!==null&&!(s instanceof ve)?(this._options=s,this._fallbackTexture=s.fallbackTexture??null):(this._options={},this._fallbackTexture=s),r=this.getScene()||bt.LastCreatedScene;let l=r._getComponent(it.NAME_PROCEDURALTEXTURE);l||(l=new Ume(r),r._addComponent(l)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=c,this._generateMipMaps=a,this._drawWrapper=new Sn(this._fullEngine),this.setFragment(i);const h=this._createRtWrapper(o,t,a,c);this._texture=h.texture;const u=[];u.push(1,1),u.push(-1,1),u.push(-1,-1),u.push(1,-1),this._vertexBuffers[Z.PositionKind]=new Z(this._fullEngine,u,Z.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r,...this._options}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r,...this._options}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId?this._contentData:(this._contentData?this._contentData.then(e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId}):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId),this._contentData)}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[Z.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===es.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=es.REFRESHRATE_RENDER_ONCE)}reset(){var e;(e=this._drawWrapper.effect)==null||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady()){e(this);return}const t=this.getEffect();t&&t.executeWhenCompiled(()=>{e(this)})}isReady(){const e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;const i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:typeof this._fragment=="string"?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[Z.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var r;(r=this._rtWrapper)==null||r.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0})),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return!this.isEnabled||!this.isReady()||!this._texture?(this._texture&&(this._texture.isReady=!1),!1):this._fallbackTextureUsed?!1:this._currentRefreshId===-1?(this._currentRefreshId=1,this._frameId++,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){this._uniforms.indexOf(e)===-1&&this._uniforms.push(e)}setTexture(e,t){return this._samplers.indexOf(e)===-1&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var s,a;const t=this.getScene();if(!t)return;const i=this._fullEngine;if(i.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),i.setState(!1),!this.nodeMaterialSource){for(const o in this._textures)this._drawWrapper.effect.setTexture(o,this._textures[o]);for(const o in this._ints)this._drawWrapper.effect.setInt(o,this._ints[o]);for(const o in this._floats)this._drawWrapper.effect.setFloat(o,this._floats[o]);for(const o in this._floatsArrays)this._drawWrapper.effect.setArray(o,this._floatsArrays[o]);for(const o in this._colors3)this._drawWrapper.effect.setColor3(o,this._colors3[o]);for(const o in this._colors4){const c=this._colors4[o];this._drawWrapper.effect.setFloat4(o,c.r,c.g,c.b,c.a)}for(const o in this._vectors2)this._drawWrapper.effect.setVector2(o,this._vectors2[o]);for(const o in this._vectors3)this._drawWrapper.effect.setVector3(o,this._vectors3[o]);for(const o in this._matrices)this._drawWrapper.effect.setMatrix(o,this._matrices[o])}if(!this._texture||!this._rtWrapper)return;(s=i._debugPushGroup)==null||s.call(i,`procedural texture generation for ${this.name}`,1);const r=i.currentViewport;if(this.isCube)for(let o=0;o<6;o++)i.bindFramebuffer(this._rtWrapper,o,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",o),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(Ye.TriangleFillMode,0,6);else i.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(Ye.TriangleFillMode,0,6);i.unBindFramebuffer(this._rtWrapper,this.isCube),r&&i.setViewport(r),this.isCube&&i.generateMipMapsForCubemap(this._texture),(a=i._debugPopGroup)==null||a.call(i,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new Yf(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){const e=this.getScene();if(!e)return;const t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[Z.PositionKind];i&&(i.dispose(),this._vertexBuffers[Z.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}B([K()],Yf.prototype,"isEnabled",void 0);B([K()],Yf.prototype,"autoClear",void 0);B([K()],Yf.prototype,"_generateMipMaps",void 0);B([K()],Yf.prototype,"_size",void 0);B([K()],Yf.prototype,"refreshRate",null);xe("BABYLON.ProceduralTexture",Yf);var qa;(function(n){n[n.Cos=0]="Cos",n[n.Sin=1]="Sin",n[n.Abs=2]="Abs",n[n.Exp=3]="Exp",n[n.Exp2=4]="Exp2",n[n.Round=5]="Round",n[n.Floor=6]="Floor",n[n.Ceiling=7]="Ceiling",n[n.Sqrt=8]="Sqrt",n[n.Log=9]="Log",n[n.Tan=10]="Tan",n[n.ArcTan=11]="ArcTan",n[n.ArcCos=12]="ArcCos",n[n.ArcSin=13]="ArcSin",n[n.Fract=14]="Fract",n[n.Sign=15]="Sign",n[n.Radians=16]="Radians",n[n.Degrees=17]="Degrees"})(qa||(qa={}));class $J extends zt{constructor(e){super(e,Ce.Neutral),this.operation=qa.Cos,this.registerInput("input",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case qa.Cos:{i="cos";break}case qa.Sin:{i="sin";break}case qa.Abs:{i="abs";break}case qa.Exp:{i="exp";break}case qa.Exp2:{i="exp2";break}case qa.Round:{i="round";break}case qa.Floor:{i="floor";break}case qa.Ceiling:{i="ceil";break}case qa.Sqrt:{i="sqrt";break}case qa.Log:{i="log";break}case qa.Tan:{i="tan";break}case qa.ArcTan:{i="atan";break}case qa.ArcCos:{i="acos";break}case qa.ArcSin:{i="asin";break}case qa.Fract:{i="fract";break}case qa.Sign:{i="sign";break}case qa.Radians:{i="radians";break}case qa.Degrees:{i="degrees";break}}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName}); `,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${qa[this.operation]}; `}}xe("BABYLON.TrigonometryBlock",$J);const dY={effect:null,subMesh:null};class $w extends Kr{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){this[e]===void 0&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class Ss extends Rn{static _BlockIsTextureBlock(e){return e.getClassName()==="TextureBlock"||e.getClassName()==="ReflectionTextureBaseBlock"||e.getClassName()==="ReflectionTextureBlock"||e.getClassName()==="ReflectionBlock"||e.getClassName()==="RefractionBlock"||e.getClassName()==="CurrentScreenBlock"||e.getClassName()==="ParticleTextureBlock"||e.getClassName()==="ImageSourceBlock"||e.getClassName()==="TriPlanarBlock"||e.getClassName()==="BiPlanarBlock"||e.getClassName()==="PrePassTextureBlock"}_getGlobalNodeMaterialEditor(){if(typeof NODEEDITOR<"u")return NODEEDITOR;if(typeof BABYLON<"u"&&typeof BABYLON.NodeEditor<"u")return BABYLON}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||bt.LastCreatedScene),this._buildId=Ss._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new ce,this._cachedWorldViewProjectionMatrix=new ce,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new Ae,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=wc.Material,this.forceAlphaBlending=!1,this._options={emitComments:!1,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e)if(!t)t=i;else return Ee.Warn("More than one block was found with the name `"+e+"`"),t;return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(t!==-1)return this._optimizers.splice(t,1),this}addOutputNode(e){if(e.target===null)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&Ce.Vertex&&this._addVertexOutputNode(e),e.target&Ce.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return e.target===null?this:(e.target&Ce.Vertex&&this._removeVertexOutputNode(e),e.target&Ce.Fragment&&this._removeFragmentOutputNode(e),this)}_addVertexOutputNode(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=Ce.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(t!==-1)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(this._fragmentOutputNodes.indexOf(e)===-1)return e.target=Ce.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(t!==-1)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return this.ignoreAlpha?!1:this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){(e.target===Ce.VertexAndFragment||t.target===Ce.Fragment&&e.target===Ce.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,r)}_initializeBlock(e,t,i,r=!0){if(e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1){if(e.isUnique){const s=e.getClassName();for(const a of this.attachedBlocks)if(a.getClassName()===s)throw`Cannot have multiple blocks of type ${s} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const s of e.inputs){s.associatedVariableName="";const a=s.connectedPoint;if(a){const o=a.ownerBlock;o!==e&&this._processInitializeOnLink(o,t,i,r)}}if(e.isTeleportOut){const s=e;s.entryPoint&&this._processInitializeOnLink(s.entryPoint,t,i,r)}for(const s of e.outputs)s.associatedVariableName=""}_resetDualBlocks(e,t){e.target===Ce.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const r=i.connectedPoint;if(r){const s=r.ownerBlock;s!==e&&this._resetDualBlocks(s,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){!this._vertexCompilationState&&!i&&(i=!0),this._buildWasSuccessful=!1;const r=this.getScene().getEngine(),s=this._mode===wc.Particle;if(this._vertexOutputNodes.length===0&&!s)throw"You must define at least one vertexOutputNode";if(this._fragmentOutputNodes.length===0)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new rde,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=Ce.Vertex,this._fragmentCompilationState=new rde,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=Ce.Fragment,this._sharedData=new yRe,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=s;const a=[],o=[];for(const h of this._vertexOutputNodes)a.push(h),this._initializeBlock(h,this._vertexCompilationState,o,i);for(const h of this._fragmentOutputNodes)o.push(h),this._initializeBlock(h,this._fragmentCompilationState,a,i);this.optimize();for(const h of a)h.build(this._vertexCompilationState,a);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const h of o)this._resetDualBlocks(h,this._buildId-1);for(const h of o)h.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=Ss._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(de.Log("Vertex shader:"),de.Log(this._vertexCompilationState.compilationString),de.Log("Fragment shader:"),de.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const c=this.getScene().meshes;for(const h of c)if(h.subMeshes)for(const u of h.subMeshes){if(u.getMaterial()!==this||!u.materialDefines)continue;const d=u.materialDefines;d.markAllAsDirty(),d.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,r=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(Z.NormalKind),t.TANGENT=e.isVerticesDataPresent(Z.TangentKind);const a=e.useVertexColors&&e.isVerticesDataPresent(Z.ColorKind);t.VERTEXCOLOR_NME=a;let o=!1;for(let l=1;l<=6;++l){const h=t["UV"+l];t["UV"+l]=e.isVerticesDataPresent(`uv${l===1?"":l}`),o=o||t["UV"+l]!==h}const c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;KO(this.getScene(),t,!c),(i!==t.NORMAL||r!==t.TANGENT||s!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate(i=>i.getClassName()==="PrePassOutputBlock"),t=[4];return!e||this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter(i=>i.getClassName()==="PrePassTextureBlock"),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const r of t)i.texturesRequired.includes(r)||i.texturesRequired.push(r);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,r,s,a=0,o=5){return this.mode!==wc.PostProcess?(de.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,s,a,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,s,a,o=0,c=5){let l=this.name+this._buildId;const h=new $w,u=new di(l+"PostProcess",this.getScene());let d=this._buildId;return this._processDefines(u,h),bi.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new Pt(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,s,a,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,c),e.nodeMaterialSource=this,e.onApplyObservable.add(f=>{d!==this._buildId&&(delete bi.ShadersStore[l+"VertexShader"],delete bi.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),d=this._buildId),this._processDefines(u,h)&&(bi.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),H8.SetImmediate(()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l))),this._checkInternals(f)}),e}createProceduralTexture(e,t){if(this.mode!==wc.ProceduralTexture)return de.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const r=new Yf(i,e,null,t),s=new di(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};const a=new $w,o=this._processDefines(s,a);bi.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let c=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[Z.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),o==null?void 0:o.fallbacks,void 0);r.nodeMaterialSource=this,r._setEffect(c);let l=this._buildId;return r.onBeforeGenerationObservable.add(()=>{l!==this._buildId&&(delete bi.ShadersStore[i+"VertexShader"],delete bi.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,a.markAllAsDirty(),l=this._buildId);const h=this._processDefines(s,a);h&&(bi.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),H8.SetImmediate(()=>{c=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[Z.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),h==null?void 0:h.fallbacks,void 0),r._setEffect(c)})),this._checkInternals(c)}),r}_createEffectForParticles(e,t,i,r,s,a,o,c=""){let l=this.name+this._buildId+"_"+t;a||(a=new $w),o||(o=this.getScene().getMeshByName(this.name+"Particle"),o||(o=new di(this.name+"Particle",this.getScene()),o.reservedDataStore={hidden:!0}));let h=this._buildId;const u=[];let d=c;if(!s){const f=this._processDefines(o,a);bi.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(u,t),d=u.join(` `),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString()+` `+d,f==null?void 0:f.fallbacks,i,r,e),e.setCustomEffect(s,t)}s.onBindObservable.add(f=>{h!==this._buildId&&(delete bi.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,a.markAllAsDirty(),h=this._buildId),u.length=0,e.fillDefines(u,t);const p=u.join(` `);p!==d&&(a.markAllAsDirty(),d=p);const _=this._processDefines(o,a);if(_){bi.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),f=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString()+` `+d,_==null?void 0:_.fallbacks,i,r,e),e.setCustomEffect(f,t),this._createEffectForParticles(e,t,i,r,f,a,o,c);return}this._checkInternals(f)})}_checkInternals(e){if(this._sharedData.animatedInputs){const t=this.getScene(),i=t.getFrameId();if(this._animationFrame!==i){for(const r of this._sharedData.animatedInputs)r.animate(t);this._animationFrame=i}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){if(this.mode!==wc.Particle){de.Log("Incompatible material mode");return}this._createEffectForParticles(e,yo.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,yo.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==wc.Material){de.Log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,r){let s=null;const a=this.getScene();if(uG(a,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(o=>{o.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(o=>{o.prepareDefines(e,this,t,i,r)}),t.isDirty){const o=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach(d=>{d.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)});const c=[];this._sharedData.dynamicUniformBlocks.forEach(d=>{d.updateUniformsAndSamples(this._vertexCompilationState,this,t,c)});const l=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(d=>{l.indexOf(d)===-1&&l.push(d)});const h=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(d=>{h.indexOf(d)===-1&&h.push(d)});const u=new Hn;this._sharedData.blocksWithFallbacks.forEach(d=>{d.provideFallbacks(e,u)}),s={lightDisposed:o,uniformBuffers:c,mergedUniforms:l,mergedSamplers:h,fallbacks:u}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const r=this.getScene();if(this._sharedData.animatedInputs){const l=r.getFrameId();if(this._animationFrame!==l){for(const h of this._sharedData.animatedInputs)h.animate(r);this._animationFrame=l}}const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new $w);const a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(this._prepareDefinesForAttributes(e,a),this._sharedData.blockingBlocks.some(l=>!l.isReady(e,this,a,i)))return!1;const c=this._processDefines(e,a,i,t);if(c){const l=t.effect,h=a.toString();let u=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:c.mergedUniforms,uniformBuffersNames:c.uniformBuffers,samplers:c.mergedSamplers,defines:h,fallbacks:c.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:a.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:a.NUM_MORPH_INFLUENCERS}},o);if(u)if(this._onEffectCreatedObservable&&(dY.effect=u,dY.subMesh=t,this._onEffectCreatedObservable.notifyObservers(dY)),this.allowShaderHotSwapping&&l&&!u.isReady()){if(u=l,a.markAsUnprocessed(),c.lightDisposed)return a._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(u,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader ${this._vertexCompilationState.compilationString} // Fragment shader ${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const r of this._sharedData.inputBlocks)r._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);const a=this._mustRebind(r,s,i,t.visibility),o=this._sharedData;if(a){for(const c of o.bindableBlocks)c.bind(s,this,t,i);for(const c of o.forcedBindableBlocks)c.bind(s,this,t,i);for(const c of o.inputBlocks)c._transmit(s,r,this)}else if(!this.isFrozen)for(const c of o.forcedBindableBlocks)c.bind(s,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter(t=>t.texture).map(t=>t.texture)),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)Ss._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const r of this.getTextureBlocks().filter(s=>s.texture).map(s=>s.texture))r.dispose();for(const r of this.attachedBlocks)r.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t={nodeMaterial:this,...e};this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise(t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),typeof this.BJSNODEMATERIALEDITOR>"u"){const i=e&&e.editorURL?e.editorURL:Ss.EditorURL;Ee.LoadBabylonScript(i,()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e==null?void 0:e.nodeEditorConfig),t()})}else this._createNodeEditor(e==null?void 0:e.nodeEditorConfig),t()})}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new Gi("Position");e.setAsAttribute("position");const t=new Gi("World");t.setAsSystemValue(Zi.World);const i=new Bz("WorldPos");e.connectTo(i),t.connectTo(i);const r=new Gi("ViewProjection");r.setAsSystemValue(Zi.ViewProjection);const s=new Bz("WorldPos * ViewProjectionTransform");i.connectTo(s),r.connectTo(s);const a=new pD("VertexOutput");s.connectTo(a);const o=new Gi("color");o.value=new Ze(.8,.8,.8,1);const c=new Pm("FragmentOutput");o.connectTo(c),this.addOutputNode(a),this.addOutputNode(c),this._mode=wc.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Gi("Position");e.setAsAttribute("position2d");const t=new Gi("Constant1");t.isConstant=!0,t.value=1;const i=new _D("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const r=new pD("VertexOutput");i.connectTo(r);const s=new Gi("Scale");s.visibleInInspector=!0,s.value=new Be(1,1);const a=new YO("uv0");e.connectTo(a);const o=new Fz("UV scale");a.connectTo(o),s.connectTo(o);const c=new WJ("CurrentScreen");o.connectTo(c),c.texture=new ve("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const l=new Pm("FragmentOutput");c.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=wc.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Gi("Position");e.setAsAttribute("position2d");const t=new Gi("Constant1");t.isConstant=!0,t.value=1;const i=new _D("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const r=new pD("VertexOutput");i.connectTo(r);const s=new Gi("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=Tm.Time,s.isConstant=!1;const a=new Gi("Color3");a.value=new Me(1,1,1),a.isConstant=!1;const o=new Pm("FragmentOutput"),c=new _D("VectorMerger");c.visibleInInspector=!1;const l=new $J("Cos");l.operation=qa.Cos,e.connectTo(c),s.output.connectTo(l.input),l.output.connectTo(c.z),c.xyzOut.connectTo(o.rgb),this.addOutputNode(r),this.addOutputNode(o),this._mode=wc.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Gi("uv");e.setAsAttribute("particle_uv");const t=new jJ("ParticleTexture");e.connectTo(t);const i=new Gi("Color");i.setAsAttribute("particle_color");const r=new Fz("Texture * Color");t.connectTo(r),i.connectTo(r);const s=new XJ("ParticleRampGradient");r.connectTo(s);const a=new QJ("ColorSplitter");i.connectTo(a);const o=new YJ("ParticleBlendMultiply");s.connectTo(o),t.connectTo(o,{output:"a"}),a.connectTo(o,{output:"a"});const c=new Pm("FragmentOutput");o.connectTo(c),this.addOutputNode(c),this._mode=wc.Particle}async loadAsync(e,t=""){return Ss.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(t.indexOf(e)===-1){t.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const s=r.ownerBlock;s!==e&&this._gatherBlocks(s,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const a of this._vertexOutputNodes)this._gatherBlocks(a,t);const r=[];for(const a of this._fragmentOutputNodes)this._gatherBlocks(a,r);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); `;s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${wc[this.mode]}; `;for(const a of t)a.isInput&&e.indexOf(a)===-1&&(s+=a._dumpCode(i,e));for(const a of r)a.isInput&&e.indexOf(a)===-1&&(s+=a._dumpCode(i,e));e=[],s+=` // Connections `;for(const a of this._vertexOutputNodes)s+=a._dumpCodeForOutputConnections(e);for(const a of this._fragmentOutputNodes)s+=a._dumpCodeForOutputConnections(e);s+=` // Output nodes `;for(const a of this._vertexOutputNodes)s+=`nodeMaterial.addOutputNode(${a._codeVariableName}); `;for(const a of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${a._codeVariableName}); `;return s+=`nodeMaterial.build(); `,s}serialize(e){const t=e?{}:Qe.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const r of this._vertexOutputNodes)this._gatherBlocks(r,i),t.outputNodes.push(r.uniqueId);for(const r of this._fragmentOutputNodes)this._gatherBlocks(r,i),t.outputNodes.indexOf(r.uniqueId)===-1&&t.outputNodes.push(r.uniqueId)}t.blocks=[];for(const r of i)t.blocks.push(r.serialize());if(!e)for(const r of this.attachedBlocks)i.indexOf(r)===-1&&t.blocks.push(r.serialize());return t}_restoreConnections(e,t,i){for(const r of e.outputs)for(const s of t.blocks){const a=i[s.id];if(a){for(const o of s.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===r.name){const c=a.getInputByName(o.inputName);if(!c||c.isConnected)continue;r.connectTo(c,!0),this._restoreConnections(a,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){i||this.clear();const r={};for(const s of e.blocks){const a=gn(s.customType);if(a){const o=new a;o._deserialize(s,this.getScene(),t),r[s.id]=o,this.attachedBlocks.push(o)}}for(const s of this.attachedBlocks)if(s.isTeleportOut){const a=s,o=a._tempEntryPointUniqueId;o&&r[o].attachToEndpoint(a)}for(let s=0;snew Ss(e,this.getScene(),this.options),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach(t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((r,s)=>{i.onLoadedObservable.addOnce(()=>{r()}),i.onErrorObservable.addOnce(a=>{s(a)})}))}),Promise.all(e)}static Parse(e,t,i=""){const r=Qe.Parse(()=>new Ss(e.name,t),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,r="",s=!1,a){const o=a??new Ss(e,i),c=await i._loadFileAsync(t),l=JSON.parse(c);return o.parseSerializedObject(l,r),s||o.build(),o}static ParseFromSnippetAsync(e,t=bt.LastCreatedScene,i="",r,s=!1,a=!1){return e==="_BLANK"?Promise.resolve(Ss.CreateDefault("blank",t)):new Promise((o,c)=>{const l=new on;l.addEventListener("readystatechange",()=>{if(l.readyState==4)if(l.status==200){const h=JSON.parse(JSON.parse(l.responseText).jsonPayload),u=JSON.parse(h.nodeMaterial);r||(r=Qe.Parse(()=>new Ss(e,t),u,t,i),r.uniqueId=t.getUniqueId()),r.parseSerializedObject(u),r.snippetId=e;try{s||r.build()}catch(d){c(d)}a?r.whenTexturesReadyAsync().then(()=>{o(r)}).catch(d=>{c(d)}):o(r)}else c("Unable to load the snippet "+e)}),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()})}static CreateDefault(e,t){const i=new Ss(e,t);return i.setToDefault(),i.build(),i}}Ss._BuildIdGenerator=0;Ss.EditorURL=`${Ee._DefaultCdnUrl}/v${De.Version}/nodeEditor/babylon.nodeEditor.js`;Ss.SnippetUrl="https://snippet.babylonjs.com";Ss.IgnoreTexturesAtLoadTime=!1;B([K()],Ss.prototype,"ignoreAlpha",void 0);B([K()],Ss.prototype,"maxSimultaneousLights",void 0);B([K("mode")],Ss.prototype,"_mode",void 0);B([K("comment")],Ss.prototype,"comment",void 0);B([K()],Ss.prototype,"forceAlphaBlending",void 0);xe("BABYLON.NodeMaterial",Ss);function pG(n){const e=n.sideOrientation||et.DEFAULTSIDE,t=n.radius||1,i=n.flat===void 0?!0:n.flat,r=(n.subdivisions||4)|0,s=n.radiusX||t,a=n.radiusY||t,o=n.radiusZ||t,c=(1+Math.sqrt(5))/2,l=[-1,c,-0,1,c,0,-1,-c,0,1,-c,0,0,-1,-c,0,1,-c,0,-1,c,0,1,c,c,0,1,c,0,-1,-c,0,1,-c,0,-1],h=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],f=138/1024,p=239/1024,_=60/1024,m=26/1024,g=-40/1024,v=20/1024,x=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],y=[],C=[],b=[],T=[];let S=0;const N=new Array(3),D=new Array(3);let M;for(M=0;M<3;M++)N[M]=P.Zero(),D[M]=Be.Zero();for(let R=0;R<20;R++){for(M=0;M<3;M++){const H=h[3*R+M];N[M].copyFromFloats(l[3*u[H]],l[3*u[H]+1],l[3*u[H]+2]),N[M].normalize(),D[M].copyFromFloats(d[2*H]*f+_+x[R]*g,d[2*H+1]*p+m+x[R]*v)}const O=(H,G,Q,$)=>{const V=P.Lerp(N[0],N[2],G/r),j=P.Lerp(N[1],N[2],G/r),k=r===G?N[2]:P.Lerp(V,j,H/(r-G));k.normalize();let z;if(i){const he=P.Lerp(N[0],N[2],$/r),le=P.Lerp(N[1],N[2],$/r);z=P.Lerp(he,le,Q/(r-$))}else z=new P(k.x,k.y,k.z);z.x/=s,z.y/=a,z.z/=o,z.normalize();const Y=Be.Lerp(D[0],D[2],G/r),J=Be.Lerp(D[1],D[2],G/r),re=r===G?D[2]:Be.Lerp(Y,J,H/(r-G));C.push(k.x*s,k.y*a,k.z*o),b.push(z.x,z.y,z.z),T.push(re.x,br.UseOpenGLOrientationForUV?1-re.y:re.y),y.push(S),S++};for(let H=0;H$O(n,e,t);var _m;(function(n){n.WRIST="wrist",n.THUMB="thumb",n.INDEX="index",n.MIDDLE="middle",n.RING="ring",n.LITTLE="little"})(_m||(_m={}));var li;(function(n){n.WRIST="wrist",n.THUMB_METACARPAL="thumb-metacarpal",n.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",n.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",n.THUMB_TIP="thumb-tip",n.INDEX_FINGER_METACARPAL="index-finger-metacarpal",n.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",n.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",n.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",n.INDEX_FINGER_TIP="index-finger-tip",n.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",n.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",n.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",n.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",n.MIDDLE_FINGER_TIP="middle-finger-tip",n.RING_FINGER_METACARPAL="ring-finger-metacarpal",n.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",n.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",n.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",n.RING_FINGER_TIP="ring-finger-tip",n.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",n.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",n.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",n.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",n.PINKY_FINGER_TIP="pinky-finger-tip"})(li||(li={}));const Lp=[li.WRIST,li.THUMB_METACARPAL,li.THUMB_PHALANX_PROXIMAL,li.THUMB_PHALANX_DISTAL,li.THUMB_TIP,li.INDEX_FINGER_METACARPAL,li.INDEX_FINGER_PHALANX_PROXIMAL,li.INDEX_FINGER_PHALANX_INTERMEDIATE,li.INDEX_FINGER_PHALANX_DISTAL,li.INDEX_FINGER_TIP,li.MIDDLE_FINGER_METACARPAL,li.MIDDLE_FINGER_PHALANX_PROXIMAL,li.MIDDLE_FINGER_PHALANX_INTERMEDIATE,li.MIDDLE_FINGER_PHALANX_DISTAL,li.MIDDLE_FINGER_TIP,li.RING_FINGER_METACARPAL,li.RING_FINGER_PHALANX_PROXIMAL,li.RING_FINGER_PHALANX_INTERMEDIATE,li.RING_FINGER_PHALANX_DISTAL,li.RING_FINGER_TIP,li.PINKY_FINGER_METACARPAL,li.PINKY_FINGER_PHALANX_PROXIMAL,li.PINKY_FINGER_PHALANX_INTERMEDIATE,li.PINKY_FINGER_PHALANX_DISTAL,li.PINKY_FINGER_TIP],PRe={[_m.WRIST]:[li.WRIST],[_m.THUMB]:[li.THUMB_METACARPAL,li.THUMB_PHALANX_PROXIMAL,li.THUMB_PHALANX_DISTAL,li.THUMB_TIP],[_m.INDEX]:[li.INDEX_FINGER_METACARPAL,li.INDEX_FINGER_PHALANX_PROXIMAL,li.INDEX_FINGER_PHALANX_INTERMEDIATE,li.INDEX_FINGER_PHALANX_DISTAL,li.INDEX_FINGER_TIP],[_m.MIDDLE]:[li.MIDDLE_FINGER_METACARPAL,li.MIDDLE_FINGER_PHALANX_PROXIMAL,li.MIDDLE_FINGER_PHALANX_INTERMEDIATE,li.MIDDLE_FINGER_PHALANX_DISTAL,li.MIDDLE_FINGER_TIP],[_m.RING]:[li.RING_FINGER_METACARPAL,li.RING_FINGER_PHALANX_PROXIMAL,li.RING_FINGER_PHALANX_INTERMEDIATE,li.RING_FINGER_PHALANX_DISTAL,li.RING_FINGER_TIP],[_m.LITTLE]:[li.PINKY_FINGER_METACARPAL,li.PINKY_FINGER_PHALANX_PROXIMAL,li.PINKY_FINGER_PHALANX_INTERMEDIATE,li.PINKY_FINGER_PHALANX_DISTAL,li.PINKY_FINGER_TIP]};class kme{get handMesh(){return this._handMesh}getHandPartMeshes(e){return PRe[e].map(t=>this._jointMeshes[Lp.indexOf(t)])}getJointMesh(e){return this._jointMeshes[Lp.indexOf(e)]}constructor(e,t,i,r,s=!1,a=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=s,this._jointsInvisible=a,this._jointScaleFactor=o,this._jointTransforms=new Array(Lp.length),this._jointTransformMatrices=new Float32Array(Lp.length*16),this._tempJointMatrix=new ce,this._jointRadii=new Float32Array(Lp.length),this._scene=t[0].getScene();for(let c=0;c{c._doNotLoadControllerMesh=!0})}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach(r=>{r.alwaysSelectAsActiveMesh=!0}),this._handMesh.skeleton){const r=this._handMesh.skeleton;Lp.forEach((s,a)=>{const o=r.getBoneIndexByName(t?t[s]:s);o!==-1&&r.bones[o].linkTransformNode(this._jointTransforms[a])})}}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const r=i,s=Lp.map(o=>r[o]||i.get(o));let a=!1;if(e.fillPoses&&e.fillJointRadii)a=e.fillPoses(s,t,this._jointTransformMatrices)&&e.fillJointRadii(s,this._jointRadii);else if(e.getJointPose){a=!0;for(let o=0;o{const l=this._jointTransforms[c];ce.FromArrayToRef(this._jointTransformMatrices,c*16,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,l.rotationQuaternion,l.position);const h=this._jointRadii[c]*this._jointScaleFactor,u=this._jointMeshes[c];u.isVisible=!this._handMesh&&!this._jointsInvisible,u.position.copyFrom(l.position),u.rotationQuaternion.copyFrom(l.rotationQuaternion),u.scaling.setAll(h),this._scene.useRightHandedSystem||(u.position.z*=-1,u.rotationQuaternion.z*=-1,u.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(l.position.z*=-1,l.rotationQuaternion.z*=-1,l.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){var t;this._handMesh&&(e?((t=this._handMesh.skeleton)==null||t.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1)}}class ss extends Lo{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map(i=>{var a,o,c,l,h;const r=[],s=((a=e.jointMeshes)==null?void 0:a.sourceMesh)||$O("jointParent",ss._ICOSPHERE_PARAMS);s.isVisible=!!((o=e.jointMeshes)!=null&&o.keepOriginalVisible);for(let u=0;u{var d,f,p,_,m,g;const s={};(f=(d=ss._RightHandGLB)==null?void 0:d.meshes[1])!=null&&f.isDisposed()&&(ss._RightHandGLB=null),(_=(p=ss._LeftHandGLB)==null?void 0:p.meshes[1])!=null&&_.isDisposed()&&(ss._LeftHandGLB=null);const a=!!(ss._RightHandGLB&&ss._LeftHandGLB),o=await Promise.all([ss._RightHandGLB||ai.ImportMeshAsync("",ss.DEFAULT_HAND_MODEL_BASE_URL,ss.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),ss._LeftHandGLB||ai.ImportMeshAsync("",ss.DEFAULT_HAND_MODEL_BASE_URL,ss.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);ss._RightHandGLB=o[0],ss._LeftHandGLB=o[1];const c=await Ss.ParseFromFileAsync("handShader",ss.DEFAULT_HAND_MODEL_SHADER_URL,e);c.needDepthPrePass=!0,c.transparencyMode=Ye.MATERIAL_ALPHABLEND,c.alphaMode=2,c.build(!1);const l={base:Me.FromInts(116,63,203),fresnel:Me.FromInts(149,102,229),fingerColor:Me.FromInts(177,130,255),tipFresnel:Me.FromInts(220,200,255),...(m=i==null?void 0:i.handMeshes)==null?void 0:m.customColors},h={base:c.getBlockByName("baseColor"),fresnel:c.getBlockByName("fresnelColor"),fingerColor:c.getBlockByName("fingerColor"),tipFresnel:c.getBlockByName("tipFresnelColor")};h.base.value=l.base,h.fresnel.value=l.fresnel,h.fingerColor.value=l.fingerColor,h.tipFresnel.value=l.tipFresnel;const u=(g=t._getBaseLayerWrapper())==null?void 0:g.isMultiview;["left","right"].forEach(v=>{const x=v=="left"?ss._LeftHandGLB:ss._RightHandGLB;if(!x)throw new Error("Could not load hand model");const y=x.meshes[1];y._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,u||(y.material=c.clone(`${v}HandShaderClone`,!0)),y.isVisible=!1,s[v]=y,!a&&!e.useRightHandedSystem&&x.meshes[1].rotate($n.Y,Math.PI)}),c.dispose(),r({left:s.left,right:s.right})})}static _GenerateDefaultHandMeshRigMapping(e){const t=e=="right"?"R":"L";return{[li.WRIST]:`wrist_${t}`,[li.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[li.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[li.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[li.THUMB_TIP]:`thumb_tip_${t}`,[li.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[li.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[li.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[li.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[li.INDEX_FINGER_TIP]:`index_tip_${t}`,[li.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[li.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[li.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[li.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[li.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[li.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[li.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[li.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[li.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[li.RING_FINGER_TIP]:`ring_tip_${t}`,[li.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[li.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[li.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[li.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[li.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return typeof XRHand<"u"}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return e=="none"?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this._worldScaleObserver=null,this.onHandAddedObservable=new Ae,this.onHandRemovedObservable=new Ae,this._attachHand=s=>{var c,l,h;if(!s.inputSource.hand||s.inputSource.handedness=="none"||!this._handResources.jointMeshes)return;const a=s.inputSource.handedness,o=new kme(s,this._handResources.jointMeshes[a],this._handResources.handMeshes&&this._handResources.handMeshes[a],this._handResources.rigMappings&&this._handResources.rigMappings[a],(c=this.options.handMeshes)==null?void 0:c.meshesUseLeftHandedCoordinates,(l=this.options.jointMeshes)==null?void 0:l.invisible,(h=this.options.jointMeshes)==null?void 0:h.scaleFactor);this._attachedHands[s.uniqueId]=o,this._trackingHands[a]=o,this.onHandAddedObservable.notifyObservers(o)},this._detachHand=s=>{this._detachHandById(s.uniqueId)},this.xrNativeFeatureName="hand-tracking";const r=t.jointMeshes;if(r&&(typeof r.disableDefaultHandMesh<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=r.disableDefaultHandMesh),typeof r.handMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=r.handMeshes),typeof r.leftHandedSystemMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=r.leftHandedSystemMeshes),typeof r.rigMapping<"u")){t.handMeshes=t.handMeshes||{};const s={},a={};[[r.rigMapping.left,s],[r.rigMapping.right,a]].forEach(o=>{const c=o[0],l=o[1];c.forEach((h,u)=>{l[Lp[u]]=h})}),t.handMeshes.customRigMappings={left:s,right:a}}}attach(){var e,t,i,r;return super.attach()?(this._handResources={jointMeshes:ss._GenerateTrackedJointMeshes(this.options),handMeshes:((e=this.options.handMeshes)==null?void 0:e.customMeshes)||null,rigMappings:((t=this.options.handMeshes)==null?void 0:t.customRigMappings)||null},!((i=this.options.handMeshes)!=null&&i.customMeshes)&&!((r=this.options.handMeshes)!=null&&r.disableDefaultMeshes)&&(ss._GenerateDefaultHandMeshesAsync(bt.LastCreatedScene,this._xrSessionManager,this.options).then(s=>{var a,o;this._handResources.handMeshes=s,this._handResources.rigMappings={left:ss._GenerateDefaultHandMeshRigMapping("left"),right:ss._GenerateDefaultHandMeshRigMapping("right")},(a=this._trackingHands.left)==null||a.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),(o=this._trackingHands.right)==null||o.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right,this._xrSessionManager),this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor)}),this._worldScaleObserver=this._xrSessionManager.onWorldScaleFactorChangedObservable.add(s=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(s.newScaleFactor/s.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(s.newScaleFactor/s.previousScaleFactor))})),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0):!1}_onXRFrame(e){var t,i;(t=this._trackingHands.left)==null||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),(i=this._trackingHands.right)==null||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){var r;const i=this.getHandByControllerId(e);if(i){const s=i.xrController.inputSource.handedness=="left"?"left":"right";((r=this._trackingHands[s])==null?void 0:r.xrController.uniqueId)===e&&(this._trackingHands[s]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){var e;return super.detach()?(Object.keys(this._attachedHands).forEach(t=>{var i;return this._detachHandById(t,(i=this.options.handMeshes)==null?void 0:i.disposeOnSessionEnd)}),(e=this.options.handMeshes)!=null&&e.disposeOnSessionEnd&&this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose())),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0):!1}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!((e=this.options.handMeshes)!=null&&e.customMeshes)&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),ss._RightHandGLB=null,ss._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose()))}}ss.Name=pr.HAND_TRACKING;ss.Version=1;ss.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/";ss.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb";ss.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb";ss.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json";ss._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2};ss._RightHandGLB=null;ss._LeftHandGLB=null;vn.AddWebXRFeature(ss.Name,(n,e)=>()=>new ss(n,e),ss.Version,!1);var A3;(function(n){n[n.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",n[n.RADIAL_SIDE=1]="RADIAL_SIDE",n[n.ULNAR_SIDE=2]="ULNAR_SIDE",n[n.BELOW_WRIST=3]="BELOW_WRIST"})(A3||(A3={}));var mm;(function(n){n[n.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",n[n.HAND_ROTATION=1]="HAND_ROTATION"})(mm||(mm={}));var C3;(function(n){n[n.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",n[n.PALM_UP=1]="PALM_UP",n[n.GAZE_FOCUS=2]="GAZE_FOCUS",n[n.PALM_AND_GAZE=3]="PALM_AND_GAZE"})(C3||(C3={}));class wRe{constructor(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=C3.PALM_AND_GAZE,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=A3.ULNAR_SIDE,this.zoneOrientationMode=mm.HAND_ROTATION,this.nodeOrientationMode=mm.HAND_ROTATION,this.handedness="none",this.lerpTime=100,this._zoneAxis[A3.ABOVE_FINGER_TIPS]=new P(0,1,0),this._zoneAxis[A3.RADIAL_SIDE]=new P(-1,0,0),this._zoneAxis[A3.ULNAR_SIDE]=new P(1,0,0),this._zoneAxis[A3.BELOW_WRIST]=new P(0,-1,0)}get name(){return"HandConstraint"}enable(){this._node.setEnabled(!0)}disable(){this._node.setEnabled(!1)}_getHandPose(){if(!this._handTracking)return null;let e;if(this.handedness==="none"?e=this._handTracking.getHandByHandedness("left")||this._handTracking.getHandByHandedness("right"):e=this._handTracking.getHandByHandedness(this.handedness),e){const t=e.getJointMesh(li.PINKY_FINGER_METACARPAL),i=e.getJointMesh(li.MIDDLE_FINGER_METACARPAL),r=e.getJointMesh(li.WRIST);if(r&&i&&t){const s={position:i.absolutePosition,quaternion:new we,id:e.xrController.uniqueId},a=ie.Vector3[0],o=ie.Vector3[1],c=ie.Vector3[2];return a.copyFrom(i.absolutePosition).subtractInPlace(r.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),P.CrossToRef(a,o,o),P.CrossToRef(o,a,c),we.FromLookDirectionLHToRef(o,a,s.quaternion),s}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=we.RotationYawPitchRoll(this._node.rotation.y,this._node.rotation.x,this._node.rotation.z));let t=Date.now();this._sceneRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{const i=this._getHandPose();if(this._node.reservedDataStore=this._node.reservedDataStore||{},this._node.reservedDataStore.nearInteraction=this._node.reservedDataStore.nearInteraction||{},this._node.reservedDataStore.nearInteraction.excludedControllerId=null,i){const r=ie.Vector3[0],s=this._scene.activeCamera;r.copyFrom(this._zoneAxis[this.targetZone]);const a=ie.Quaternion[0];if(s&&(this.zoneOrientationMode===mm.LOOK_AT_CAMERA||this.nodeOrientationMode===mm.LOOK_AT_CAMERA)){const h=ie.Vector3[1];h.copyFrom(s.position).subtractInPlace(i.position).normalize(),this._scene.useRightHandedSystem?we.FromLookDirectionRHToRef(h,P.UpReadOnly,a):we.FromLookDirectionLHToRef(h,P.UpReadOnly,a)}this.zoneOrientationMode===mm.HAND_ROTATION?i.quaternion.toRotationMatrix(ie.Matrix[0]):a.toRotationMatrix(ie.Matrix[0]),P.TransformNormalToRef(r,ie.Matrix[0],r),r.scaleInPlace(this.targetOffset);const o=ie.Vector3[2],c=ie.Quaternion[1];o.copyFrom(i.position).addInPlace(r),this.nodeOrientationMode===mm.HAND_ROTATION?c.copyFrom(i.quaternion):c.copyFrom(a);const l=Date.now()-t;P.SmoothToRef(this._node.position,o,l,this.lerpTime,this._node.position),we.SmoothToRef(this._node.rotationQuaternion,c,l,this.lerpTime,this._node.rotationQuaternion),this._node.reservedDataStore.nearInteraction.excludedControllerId=i.id}this._setVisibility(i),t=Date.now()})}_setVisibility(e){let t=!0,i=!0;const r=this._scene.activeCamera;if(r){const s=r.getForwardRay();if(this.handConstraintVisibility===C3.GAZE_FOCUS||this.handConstraintVisibility===C3.PALM_AND_GAZE){i=!1;let a;this._eyeTracking&&(a=this._eyeTracking.getEyeGaze()),a=a||s;const o=ie.Vector3[0];e?e.position.subtractToRef(a.origin,o):this._node.getAbsolutePosition().subtractToRef(a.origin,o);const c=P.Dot(o,a.direction),l=c*c;c>0&&o.lengthSquared()-lthis.palmUpStrictness*2-1&&(t=!0)}}this._node.setEnabled(t&&i)}detach(){this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver)}linkToXRExperience(e){const t=e.featuresManager?e.featuresManager:e;if(!t)Ee.Error("XR features manager must be available or provided directly for the Hand Menu to work");else{try{this._eyeTracking=t.getEnabledFeature(pr.EYE_TRACKING)}catch{}try{this._handTracking=t.getEnabledFeature(pr.HAND_TRACKING)}catch{Ee.Error("Hand tracking must be enabled for the Hand Menu to work")}}}}class Cu{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=P.Zero(),this.poleTargetPosition=P.Zero(),this.poleTargetLocalOffset=P.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=we.Identity(),this._bone1Mat=ce.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=P.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const r=t.getParent();if(!r){this._notEnoughInformation=!0,de.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=r,this._bone2.children.length===0&&!this._bone2.length){this._notEnoughInformation=!0,de.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");return}this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();const s=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.z&&(this._adjustRoll=Math.PI*.5,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const a=this._bone1.getScale(),o=this._bone2.getScale();this._bone1Length=this._bone1.length*a.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*o.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const a=this._bone2.children[0].getAbsolutePosition(e),o=this._bone2.getAbsolutePosition(e),c=this._bone1.getAbsolutePosition(e);this._bone2Length=P.Distance(a,o),this._bone1Length=P.Distance(o,c)}else{e.computeWorldMatrix(!0);const a=this._bone2.getScale();this._bone2Length=this._bone2.length*a.y*this.mesh.scaling.y;const o=this._bone2.getAbsolutePosition(e),c=this._bone1.getAbsolutePosition(e);this._bone1Length=P.Distance(o,c)}this._bone1.getRotationMatrixToRef(Ci.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||e==null)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=Cu._TmpMats[0],r=Cu._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&P.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const s=Cu._TmpVecs[0],a=Cu._TmpVecs[1],o=Cu._TmpVecs[2],c=Cu._TmpVecs[3],l=Cu._TmpVecs[4],h=Cu._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,l),l.x==0&&l.y==0&&l.z==0?l.y=1:l.normalize(),e.subtractToRef(s,c),c.normalize(),P.CrossToRef(c,l,a),a.normalize(),P.CrossToRef(c,a,o),o.normalize(),ce.FromXYZAxesToRef(o,c,a,i);const u=this._bone1Length,d=this._bone2Length;let f=P.Distance(s,e);this._maxReach>0&&(f=Math.min(this._maxReach,f));let p=(d*d+f*f-u*u)/(2*d*f),_=(f*f+u*u-d*d)/(2*f*u);p>1&&(p=1),_>1&&(_=1),p<-1&&(p=-1),_<-1&&(_=-1);const m=Math.acos(p),g=Math.acos(_);let v=-m-g;if(this._rightHandedSystem)ce.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),ce.RotationAxisToRef(this._bendAxis,g,r),r.multiplyToRef(i,i);else{const x=Cu._TmpVecs[5];x.copyFrom(this._bendAxis),x.x*=-1,ce.RotationAxisToRef(x,-g,r),r.multiplyToRef(i,i)}this.poleAngle&&(ce.RotationAxisToRef(c,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||we.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),we.FromRotationMatrixToRef(i,h),we.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),v=this._bone2Ang*(1-this.slerpAmount)+v*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,Ci.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,Ci.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,v,Ci.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=v}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new we),e.getRotationQuaternionToRef(Ci.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}Cu._TmpVecs=[P.Zero(),P.Zero(),P.Zero(),P.Zero(),P.Zero(),P.Zero()];Cu._TmpQuat=we.Identity();Cu._TmpMats=[ce.Identity(),ce.Identity()];class gl{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),this._maxYaw!=null&&(this._midYawConstraint=this._getAngleDiff(this._minYaw,this._maxYaw)*.5+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),this._minYaw!=null&&(this._midYawConstraint=this._getAngleDiff(this._minYaw,this._maxYaw)*.5+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=P.Up(),this.upAxisSpace=Ci.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=we.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=P.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),r.maxYaw!=null?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,r.minYaw!=null?this.minYaw=r.minYaw:this.minYaw=-Math.PI,r.maxPitch!=null?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,r.minPitch!=null?this.minPitch=r.minPitch:this.minPitch=-Math.PI,r.slerpAmount!=null&&(this.slerpAmount=r.slerpAmount),r.upAxis!=null&&(this.upAxis=r.upAxis),r.upAxisSpace!=null&&(this.upAxisSpace=r.upAxisSpace),r.yawAxis!=null||r.pitchAxis!=null){let s=$n.Y,a=$n.X;r.yawAxis!=null&&(s=r.yawAxis.clone(),s.normalize()),r.pitchAxis!=null&&(a=r.pitchAxis.clone(),a.normalize());const o=P.Cross(a,s);this._transformYawPitch=ce.Identity(),ce.FromXYZAxesToRef(a,s,o,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}r.useAbsoluteValueForYaw!==void 0&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}!t.getParent()&&this.upAxisSpace==Ci.BONE&&(this.upAxisSpace=Ci.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped){this._firstFrameSkipped=!0;return}const e=this.bone,t=gl._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const r=gl._TmpMats[0],s=gl._TmpMats[1],a=this.mesh,o=e.getParent(),c=gl._TmpVecs[1];c.copyFrom(this.upAxis),this.upAxisSpace==Ci.BONE&&o?(this._transformYawPitch&&P.TransformCoordinatesToRef(c,this._transformYawPitchInv,c),o.getDirectionToRef(c,this.mesh,c)):this.upAxisSpace==Ci.LOCAL&&(a.getDirectionToRef(c,c),(a.scaling.x!=1||a.scaling.y!=1||a.scaling.z!=1)&&c.normalize());let l=!1,h=!1;if((this._maxYaw!=Math.PI||this._minYaw!=-Math.PI)&&(l=!0),(this._maxPitch!=Math.PI||this._minPitch!=-Math.PI)&&(h=!0),l||h){const _=gl._TmpMats[2],m=gl._TmpMats[3];if(this.upAxisSpace==Ci.BONE&&c.y==1&&o)o.getRotationMatrixToRef(Ci.WORLD,this.mesh,_);else if(this.upAxisSpace==Ci.LOCAL&&c.y==1&&!o)_.copyFrom(a.getWorldMatrix());else{let v=gl._TmpVecs[2];v.copyFrom(this._fowardAxis),this._transformYawPitch&&P.TransformCoordinatesToRef(v,this._transformYawPitchInv,v),o?o.getDirectionToRef(v,this.mesh,v):a.getDirectionToRef(v,v);const x=P.Cross(c,v);x.normalize(),v=P.Cross(x,c),ce.FromXYZAxesToRef(x,c,v,_)}_.invertToRef(m);let g=null;if(h){const v=gl._TmpVecs[3];i.subtractToRef(t,v),P.TransformCoordinatesToRef(v,m,v),g=Math.sqrt(v.x*v.x+v.z*v.z);const x=Math.atan2(v.y,g);let y=x;x>this._maxPitch?(v.y=this._maxPitchTan*g,y=this._maxPitch):xthis._maxYaw||yMath.PI?this._isAngleBetween(x,this._maxYaw,this._midYawConstraint)?(v.z=this._maxYawCos*g,v.x=this._maxYawSin*g,C=this._maxYaw):this._isAngleBetween(x,this._midYawConstraint,this._minYaw)&&(v.z=this._minYawCos*g,v.x=this._minYawSin*g,C=this._minYaw):y>this._maxYaw?(v.z=this._maxYawCos*g,v.x=this._maxYawSin*g,x<0&&this.useAbsoluteValueForYaw&&(v.x*=-1),C=this._maxYaw):yMath.PI){const b=gl._TmpVecs[8];b.copyFrom($n.Z),this._transformYawPitch&&P.TransformCoordinatesToRef(b,this._transformYawPitchInv,b);const T=gl._TmpMats[4];this._boneQuat.toRotationMatrix(T),this.mesh.getWorldMatrix().multiplyToRef(T,T),P.TransformCoordinatesToRef(b,T,b),P.TransformCoordinatesToRef(b,m,b);const S=Math.atan2(b.x,b.z),N=this._getAngleBetween(S,x),D=this._getAngleBetween(S,this._midYawConstraint);if(N>D){g==null&&(g=Math.sqrt(v.x*v.x+v.z*v.z));const M=this._getAngleBetween(S,this._maxYaw);this._getAngleBetween(S,this._minYaw)Math.PI?i-=Math.PI*2:i<-Math.PI&&(i+=Math.PI*2),i}_getAngleBetween(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t;let i=0;return eMath.PI&&(i=Math.PI*2-i),i}_isAngleBetween(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,i=i<0?i+2*Math.PI:i,tt&&ei&&e{const n=new Uint8Array(4),e=new Uint32Array(n.buffer);return!!((e[0]=1)&n[0])})();Object.defineProperty(Z.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0});Object.defineProperty(Z.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0});Object.defineProperty(Z.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0});Z.prototype._rebuild=function(){var n,e;(n=this._buffer)==null||n._rebuild(),(e=this._alignedBuffer)==null||e._rebuild()};Z.prototype.dispose=function(){var n;this._ownsBuffer&&this._buffer.dispose(),(n=this._alignedBuffer)==null||n.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0};Z.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer};Z.prototype._alignBuffer=function(){var u;const n=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4===0&&this.byteOffset%4===0||!n)return;const e=Z.GetTypeByteLength(this.type),t=this.byteStride+3&-4,i=t/e,r=this._maxVerticesCount,a=r*t/e;let o;if(Array.isArray(n)){const d=new Float32Array(n);o=new DataView(d.buffer,d.byteOffset,d.byteLength)}else n instanceof ArrayBuffer?o=new DataView(n,0,n.byteLength):o=new DataView(n.buffer,n.byteOffset,n.byteLength);let c;this.type===Z.BYTE?c=new Int8Array(a):this.type===Z.UNSIGNED_BYTE?c=new Uint8Array(a):this.type===Z.SHORT?c=new Int16Array(a):this.type===Z.UNSIGNED_SHORT?c=new Uint16Array(a):this.type===Z.INT?c=new Int32Array(a):this.type===Z.UNSIGNED_INT?c=new Uint32Array(a):c=new Float32Array(a);const l=this.getSize();let h=this.byteOffset;for(let d=0;d{if(t.type!==ft.POINTERWHEEL)return;const i=t.event,r=i.deltaMode===X6.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ft.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}B([K()],ZO.prototype,"wheelPrecisionX",void 0);B([K()],ZO.prototype,"wheelPrecisionY",void 0);B([K()],ZO.prototype,"wheelPrecisionZ",void 0);class _G{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Ee.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let r=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=o=>{var u,d;const c=o.event,l=c.pointerType==="touch";if(o.type!==ft.POINTERMOVE&&this.buttons.indexOf(c.button)===-1)return;const h=c.target;if(this._altKey=c.altKey,this._ctrlKey=c.ctrlKey,this._metaKey=c.metaKey,this._shiftKey=c.shiftKey,this._buttonsPressed=c.buttons,t.isPointerLock){const f=c.movementX,p=c.movementY;this.onTouch(null,f,p),this._pointA=null,this._pointB=null}else{if(o.type!==ft.POINTERDOWN&&l&&((u=this._pointA)==null?void 0:u.pointerId)!==c.pointerId&&((d=this._pointB)==null?void 0:d.pointerId)!==c.pointerId)return;if(o.type===ft.POINTERDOWN&&(this._currentActiveButton===-1||l)){try{h==null||h.setPointerCapture(c.pointerId)}catch{}if(this._pointA===null)this._pointA={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType};else if(this._pointB===null)this._pointB={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType};else return;this._currentActiveButton===-1&&!l&&(this._currentActiveButton=c.button),this.onButtonDown(c),e||(c.preventDefault(),i&&i.focus())}else if(o.type===ft.POINTERDOUBLETAP)this.onDoubleTap(c.pointerType);else if(o.type===ft.POINTERUP&&(this._currentActiveButton===c.button||l)){try{h==null||h.releasePointerCapture(c.pointerId)}catch{}l||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==c.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==c.pointerId?this._pointB=null:this._pointA=this._pointB=null,(r!==0||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentActiveButton=-1,this.onButtonUp(c),e||c.preventDefault()}else if(o.type===ft.POINTERMOVE){if(e||c.preventDefault(),this._pointA&&this._pointB===null){const f=c.clientX-this._pointA.x,p=c.clientY-this._pointA.y;this.onTouch(this._pointA,f,p),this._pointA.x=c.clientX,this._pointA.y=c.clientY}else if(this._pointA&&this._pointB){const f=this._pointA.pointerId===c.pointerId?this._pointA:this._pointB;f.x=c.clientX,f.y=c.clientY;const p=this._pointA.x-this._pointB.x,_=this._pointA.y-this._pointB.y,m=p*p+_*_,g={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:c.pointerId,type:o.type};this.onMultiTouch(this._pointA,this._pointB,r,m,s,g),s=g,r=m}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ft.POINTERDOWN|ft.POINTERUP|ft.POINTERMOVE|ft.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=o=>this.onContextMenu(o),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const a=this.camera.getScene().getEngine().getHostWindow();a&&Ee.RegisterTopRootEvents(a,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Ee.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,r,s,a){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}B([K()],_G.prototype,"buttons",void 0);var Rl={};class qO{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();if(this.attached[t]){de.Warn("camera input of type "+t+" already exists on camera");return}this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault)}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=Rt.ForceAttachControlToAlwaysPreventDefault?!1:e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const i in this.attached){const r=this.attached[i],s=Qe.Serialize(r);t[r.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const i in t){const r=Rl[i];if(r){const s=t[i],a=Qe.Parse(()=>new r,s,null);this.add(a)}}}else for(const i in this.attached){const r=Rl[this.attached[i].getClassName()];if(r){const s=Qe.Parse(()=>new r,e,null);this.remove(this.attached[i]),this.add(s)}}}}class DRe{constructor(e,t){this.x=e,this.y=t}}class Io{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,s=1,a=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=Io.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=s,this._rightStickAxisX=a,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){this._onleftstickchanged&&(this._leftStick.x!==e.x||this._leftStick.y!==e.y)&&this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){this._onrightstickchanged&&(this._rightStick.x!==e.x||this._rightStick.y!==e.y)&&this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}Io.GAMEPAD=0;Io.GENERIC=1;Io.XBOX=2;Io.POSE_ENABLED=3;Io.DUALSHOCK=4;class zme extends Io{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new Ae,this.onButtonUpObservable=new Ae,this.type=Io.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{t.type!==Io.POSE_ENABLED&&(!this.gamepad||t.type===Io.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Io.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(t.x!=0){const r=t.x/this.gamepadRotationSensibility;r!=0&&Math.abs(r)>.005&&(e.inertialAlphaOffset+=r)}if(t.y!=0){const r=t.y/this.gamepadRotationSensibility*this._yAxisScale;r!=0&&Math.abs(r)>.005&&(e.inertialBetaOffset+=r)}}const i=this.gamepad.leftStick;if(i&&i.y!=0){const r=i.y/this.gamepadMoveSensibility;r!=0&&Math.abs(r)>.005&&(this.camera.inertialRadiusOffset-=r)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}B([K()],JO.prototype,"gamepadRotationSensibility",void 0);B([K()],JO.prototype,"gamepadMoveSensibility",void 0);Rl.ArcRotateCameraGamepadInput=JO;class Qf{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=Ee.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(!i.metaKey){if(t.type===Z0.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1){const r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?i=r/(1+this.wheelDeltaPercentage):i=r*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Ee.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==ft.POINTERWHEEL)return;const i=t.event;let r=0;const s=i.deltaMode===X6.DOM_DELTA_LINE?ORe:1,a=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(a,this,i);else if(this.wheelDeltaPercentage){if(r=this._computeDeltaFromMouseWheelLegacyEvent(a,this.camera.radius),r>0){let o=this.camera.radius,c=this.camera.inertialRadiusOffset+r;for(let l=0;l<20&&Math.abs(c)>.001;l++)o-=c,c*=this.camera.inertia;o=_t.Clamp(o,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(a,o)}}else r=a/(this.wheelPrecision*40);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ft.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=yl.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,ce.Identity(),e,!1);(e.targetScreenOffset.x!==0||e.targetScreenOffset.y!==0)&&(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=P.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let r=0;return this._hitPlane&&(r=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(r))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const c=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/ic&&(e=(t.radius-c)*i-t.inertialRadiusOffset)}const s=e/i/t.radius,a=this._getPosition(),o=ie.Vector3[6];a.subtractToRef(t.target,o),o.scaleInPlace(s),o.scaleInPlace(i),this._inertialPanning.addInPlace(o),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,a)):this.multiTouchPanning?this._computeMultiTouchPanning(s,a):this.pinchZoom&&this._computePinchZoom(i,r))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}yh.MinimumRadiusForPinch=.001;B([K()],yh.prototype,"buttons",void 0);B([K()],yh.prototype,"angularSensibilityX",void 0);B([K()],yh.prototype,"angularSensibilityY",void 0);B([K()],yh.prototype,"pinchPrecision",void 0);B([K()],yh.prototype,"pinchDeltaPercentage",void 0);B([K()],yh.prototype,"useNaturalPinchZoom",void 0);B([K()],yh.prototype,"pinchZoom",void 0);B([K()],yh.prototype,"panningSensibility",void 0);B([K()],yh.prototype,"multiTouchPanning",void 0);B([K()],yh.prototype,"multiTouchPanAndZoom",void 0);Rl.ArcRotateCameraPointersInput=yh;class mG extends qO{constructor(e){super(e)}addMouseWheel(){return this.add(new B5),this}addPointers(){return this.add(new yh),this}addKeyboard(){return this.add(new Qf),this}}mG.prototype.addVRDeviceOrientation=function(){return this.add(new ZJ),this};class ZJ{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=Ee.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&(typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(i=>{i==="granted"?t.addEventListener("deviceorientation",this._deviceOrientationHandler):Ee.Warn("Permission not granted.")}).catch(i=>{Ee.Error(i)}):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){e.alpha!==null&&(this._alpha=(+e.alpha|0)*this.alphaCorrection),e.gamma!==null&&(this._gamma=(+e.gamma|0)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}Rl.ArcRotateCameraVRDeviceOrientationInput=ZJ;class f2{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=Ee.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(t.type===Z0.KEYDOWN)(this.keysForward.indexOf(i.keyCode)!==-1||this.keysBackward.indexOf(i.keyCode)!==-1||this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),e||i.preventDefault());else if(this.keysForward.indexOf(i.keyCode)!==-1||this.keysBackward.indexOf(i.keyCode)!==-1||this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1){const r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),e||i.preventDefault()}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{this._pointerInput(t)},ft.POINTERDOWN|ft.POINTERUP|ft.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add(()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)})}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,r=this.camera.getEngine();if(!this.touchEnabled&&t.pointerType==="touch"||e.type!==ft.POINTERMOVE&&this.buttons.indexOf(t.button)===-1)return;const s=t.target;if(e.type===ft.POINTERDOWN){try{s==null||s.setPointerCapture(t.pointerId)}catch{}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),r.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===ft.POINTERUP){try{s==null||s.releasePointerCapture(t.pointerId)}catch{}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===ft.POINTERMOVE){if(!this._previousPosition){r.isPointerLock&&this._onMouseMove(e.event);return}const a=t.clientX-this._previousPosition.x,o=t.clientY-this._previousPosition.y;this._rotateCamera(a,o),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const r=e.movementX,s=e.movementY;this._rotateCamera(r,s),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,r=i._calculateHandednessMultiplier();e*=r;const s=e/this.angularSensibility,a=t/this.angularSensibility,o=we.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let c;if(this.buttonsPitch.some(l=>l===this.activeButton)&&(c=we.RotationAxis($n.X,a),o.multiplyInPlace(c)),this.buttonsYaw.some(l=>l===this.activeButton)){c=we.RotationAxis($n.Y,s),o.multiplyInPlace(c);const l=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ll===this.activeButton)&&(c=we.RotationAxis($n.Z,-s),i._trackRoll-=s,o.multiplyInPlace(c)),o.toEulerAnglesToRef(i.rotation)}}B([K()],e9.prototype,"buttons",void 0);B([K()],e9.prototype,"angularSensibility",void 0);Rl.FlyCameraMouseInput=e9;class ll{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=Ee.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(!i.metaKey){if(t.type===Z0.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(this.keysHeightOffsetIncr.indexOf(i.keyCode)!==-1||this.keysHeightOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetIncr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRadiusIncr.indexOf(i.keyCode)!==-1||this.keysRadiusDecr.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysHeightOffsetIncr.indexOf(i.keyCode)!==-1||this.keysHeightOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetIncr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRadiusIncr.indexOf(i.keyCode)!==-1||this.keysRadiusDecr.indexOf(i.keyCode)!==-1){const r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach(e=>{this.keysHeightOffsetIncr.indexOf(e)!==-1&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:this.keysHeightOffsetDecr.indexOf(e)!==-1&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:this.keysRotationOffsetIncr.indexOf(e)!==-1&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):this.keysRotationOffsetDecr.indexOf(e)!==-1&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):this.keysRadiusIncr.indexOf(e)!==-1&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:this.keysRadiusDecr.indexOf(e)!==-1&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)})}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}B([K()],ll.prototype,"keysHeightOffsetIncr",void 0);B([K()],ll.prototype,"keysHeightOffsetDecr",void 0);B([K()],ll.prototype,"keysHeightOffsetModifierAlt",void 0);B([K()],ll.prototype,"keysHeightOffsetModifierCtrl",void 0);B([K()],ll.prototype,"keysHeightOffsetModifierShift",void 0);B([K()],ll.prototype,"keysRotationOffsetIncr",void 0);B([K()],ll.prototype,"keysRotationOffsetDecr",void 0);B([K()],ll.prototype,"keysRotationOffsetModifierAlt",void 0);B([K()],ll.prototype,"keysRotationOffsetModifierCtrl",void 0);B([K()],ll.prototype,"keysRotationOffsetModifierShift",void 0);B([K()],ll.prototype,"keysRadiusIncr",void 0);B([K()],ll.prototype,"keysRadiusDecr",void 0);B([K()],ll.prototype,"keysRadiusModifierAlt",void 0);B([K()],ll.prototype,"keysRadiusModifierCtrl",void 0);B([K()],ll.prototype,"keysRadiusModifierShift",void 0);B([K()],ll.prototype,"heightSensibility",void 0);B([K()],ll.prototype,"rotationSensibility",void 0);B([K()],ll.prototype,"radiusSensibility",void 0);Rl.FollowCameraKeyboardMoveInput=ll;class c4{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Ee.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==ft.POINTERWHEEL)return;const i=t.event;let r=0;const s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&de.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?r=s*.01*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=s*.01*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=s*.01*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=s*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ft.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}B([K()],c4.prototype,"axisControlRadius",void 0);B([K()],c4.prototype,"axisControlHeight",void 0);B([K()],c4.prototype,"axisControlRotation",void 0);B([K()],c4.prototype,"wheelPrecision",void 0);B([K()],c4.prototype,"wheelDeltaPercentage",void 0);Rl.FollowCameraMouseWheelInput=c4;class Ah extends _G{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,s,a){if(i===0&&s===null||r===0&&a===null)return;let o=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!==0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&de.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&de.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&de.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}B([K()],Ah.prototype,"angularSensibilityX",void 0);B([K()],Ah.prototype,"angularSensibilityY",void 0);B([K()],Ah.prototype,"pinchPrecision",void 0);B([K()],Ah.prototype,"pinchDeltaPercentage",void 0);B([K()],Ah.prototype,"axisXControlRadius",void 0);B([K()],Ah.prototype,"axisXControlHeight",void 0);B([K()],Ah.prototype,"axisXControlRotation",void 0);B([K()],Ah.prototype,"axisYControlRadius",void 0);B([K()],Ah.prototype,"axisYControlHeight",void 0);B([K()],Ah.prototype,"axisYControlRotation",void 0);B([K()],Ah.prototype,"axisPinchControlRadius",void 0);B([K()],Ah.prototype,"axisPinchControlHeight",void 0);B([K()],Ah.prototype,"axisPinchControlRotation",void 0);Rl.FollowCameraPointersInput=Ah;class ku{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=Ee.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(!i.metaKey){if(t.type===Z0.KEYDOWN)(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),e||i.preventDefault());else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1){const r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),e||i.preventDefault()}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{const s=r.event,a=s.pointerType==="touch";if(!this.touchEnabled&&a||r.type!==ft.POINTERMOVE&&this.buttons.indexOf(s.button)===-1)return;const o=s.target;if(r.type===ft.POINTERDOWN){if(a&&this._activePointerId!==-1||!a&&this._currentActiveButton!==-1)return;this._activePointerId=s.pointerId;try{o==null||o.setPointerCapture(s.pointerId)}catch{}this._currentActiveButton===-1&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===ft.POINTERUP){if(a&&this._activePointerId!==s.pointerId||!a&&this._currentActiveButton!==s.button)return;try{o==null||o.releasePointerCapture(s.pointerId)}catch{}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===ft.POINTERMOVE&&(this._activePointerId===s.pointerId||!a)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){const c=this.camera._calculateHandednessMultiplier(),l=(s.clientX-this._previousPosition.x)*c,h=s.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=l/this.angularSensibility,this.camera.cameraRotation.x+=h/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:l,offsetY:h}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=r=>{if(!t.isPointerLock)return;const s=this.camera._calculateHandednessMultiplier(),a=r.movementX*s;this.camera.cameraRotation.y+=a/this.angularSensibility;const o=r.movementY;this.camera.cameraRotation.x+=o/this.angularSensibility,this._previousPosition=null,e||r.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ft.POINTERDOWN|ft.POINTERUP|ft.POINTERMOVE),i&&(this._contextMenuBind=r=>this.onContextMenu(r),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}B([K()],t9.prototype,"buttons",void 0);B([K()],t9.prototype,"angularSensibility",void 0);Rl.FreeCameraMouseInput=t9;var Ws;(function(n){n[n.MoveRelative=0]="MoveRelative",n[n.RotateRelative=1]="RotateRelative",n[n.MoveScene=2]="MoveScene"})(Ws||(Ws={}));class $f extends ZO{constructor(){super(...arguments),this._moveRelative=P.Zero(),this._rotateRelative=P.Zero(),this._moveScene=P.Zero(),this._wheelXAction=Ws.MoveRelative,this._wheelXActionCoordinate=y3.X,this._wheelYAction=Ws.MoveRelative,this._wheelYActionCoordinate=y3.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==Ws.MoveRelative||(this._wheelXAction=Ws.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Ws.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==Ws.MoveRelative||(this._wheelYAction=Ws.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Ws.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==Ws.MoveRelative||(this._wheelZAction=Ws.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Ws.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==Ws.RotateRelative||(this._wheelXAction=Ws.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Ws.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==Ws.RotateRelative||(this._wheelYAction=Ws.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Ws.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==Ws.RotateRelative||(this._wheelZAction=Ws.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Ws.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==Ws.MoveScene||(this._wheelXAction=Ws.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Ws.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==Ws.MoveScene||(this._wheelYAction=Ws.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Ws.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==Ws.MoveScene||(this._wheelZAction=Ws.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Ws.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(this._wheelDeltaX===0&&this._wheelDeltaY===0&&this._wheelDeltaZ==0)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=ce.Zero();this.camera.getViewMatrix().invertToRef(e);const t=P.Zero();P.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(e===0||t===null||i===null)return;let r=null;switch(t){case Ws.MoveRelative:r=this._moveRelative;break;case Ws.RotateRelative:r=this._rotateRelative;break;case Ws.MoveScene:r=this._moveScene;break}switch(i){case y3.X:r.set(e,0,0);break;case y3.Y:r.set(0,e,0);break;case y3.Z:r.set(0,0,e);break}}}B([K()],$f.prototype,"wheelXMoveRelative",null);B([K()],$f.prototype,"wheelYMoveRelative",null);B([K()],$f.prototype,"wheelZMoveRelative",null);B([K()],$f.prototype,"wheelXRotateRelative",null);B([K()],$f.prototype,"wheelYRotateRelative",null);B([K()],$f.prototype,"wheelZRotateRelative",null);B([K()],$f.prototype,"wheelXMoveScene",null);B([K()],$f.prototype,"wheelYMoveScene",null);B([K()],$f.prototype,"wheelZMoveScene",null);Rl.FreeCameraMouseWheelInput=$f;class i9{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=Ee.IsSafari()}attachControl(e){e=Ee.BackCompatCameraNoPreventDefault(arguments);let t=null;if(this._pointerInput===void 0&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const r=i.event,s=r.pointerType==="mouse"||this._isSafari&&typeof r.pointerType>"u";if(!(!this.allowMouse&&s)){if(i.type===ft.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),this._pointerPressed.length!==1)return;t={x:r.clientX,y:r.clientY}}else if(i.type===ft.POINTERUP){e||r.preventDefault();const a=this._pointerPressed.indexOf(r.pointerId);if(a===-1||(this._pointerPressed.splice(a,1),a!=0))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===ft.POINTERMOVE){if(e||r.preventDefault(),!t||this._pointerPressed.indexOf(r.pointerId)!=0)return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ft.POINTERDOWN|ft.POINTERUP|ft.POINTERMOVE),this._onLostFocus){const r=this.camera.getEngine().getInputElement();r&&r.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(this._offsetX===null||this._offsetY===null||this._offsetX===0&&this._offsetY===0)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&this._pointerPressed.length===1||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const r=e._computeLocalCameraSpeed(),s=new P(0,0,this.touchMoveSensibility!==0?r*this._offsetY/this.touchMoveSensibility:0);ce.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(P.TransformCoordinates(s,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}B([K()],i9.prototype,"touchAngularSensibility",void 0);B([K()],i9.prototype,"touchMoveSensibility",void 0);Rl.FreeCameraTouchInput=i9;class r9 extends qO{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new ku),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new t9(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new $f,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new i9),this}clear(){super.clear(),this._mouseInput=null}}r9.prototype.addDeviceOrientation=function(n){return this._deviceOrientationInput||(this._deviceOrientationInput=new qJ,n&&(this._deviceOrientationInput.smoothFactor=n),this.add(this._deviceOrientationInput)),this};class qJ{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let r=!1;const s=()=>{window.removeEventListener("deviceorientation",s),r=!0,t()};e&&setTimeout(()=>{r||(window.removeEventListener("deviceorientation",s),i("WaitForOrientationChangeAsync timed out"))},e),typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(a=>{a=="granted"?window.addEventListener("deviceorientation",s):Ee.Warn("Permission not granted.")}).catch(a=>{Ee.Error(a)}):window.addEventListener("deviceorientation",s)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new we,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new Ae,this._orientationChanged=()=>{this._screenOrientationAngle=window.orientation!==void 0?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Ee.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=e.alpha!==null?Ee.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=e.beta!==null?Ee.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=e.gamma!==null?Ee.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=e.alpha!==null?e.alpha:0,this._beta=e.beta!==null?e.beta:0,this._gamma=e.gamma!==null?e.gamma:0),e.alpha!==null&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new we(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,this._camera!=null&&!this._camera.rotationQuaternion&&(this._camera.rotationQuaternion=new we),this._camera&&this._camera.onDisposeObservable.add(()=>{this._onDeviceOrientationChangedObservable.clear()})}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(i=>{i==="granted"?t():Ee.Warn("Permission not granted.")}).catch(i=>{Ee.Error(i)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(we.RotationYawPitchRollToRef(Ee.ToRadians(this._alpha),Ee.ToRadians(this._beta),-Ee.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Rl.FreeCameraDeviceOrientationInput=qJ;class s9{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=ce.Identity(),this._deltaTransform=P.Zero(),this._vector3=P.Zero(),this._vector2=Be.Zero()}get invertYAxis(){return this._yAxisScale!==1}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(t=>{t.type!==Io.POSE_ENABLED&&(!this.gamepad||t.type===Io.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Io.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;this.gamepadMoveSensibility!==0&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&this.gamepadAngularSensibility!==0?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):ce.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const r=e._computeLocalCameraSpeed()*50;this._vector3.copyFromFloats(t.x*r,0,-t.y*r),P.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}B([K()],s9.prototype,"gamepadAngularSensibility",void 0);B([K()],s9.prototype,"gamepadMoveSensibility",void 0);Rl.FreeCameraGamepadInput=s9;var go;(function(n){n[n.X=0]="X",n[n.Y=1]="Y",n[n.Z=2]="Z"})(go||(go={}));class Qt{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i={...Qt._GetDefaultOptions(),...t};if(e?this._leftJoystick=!0:this._leftJoystick=!1,Qt._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=go.X,this._axisTargetedByUpAndDown=go.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Dz,this.deltaPosition=P.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{Qt._VJCanvasWidth=window.innerWidth,Qt._VJCanvasHeight=window.innerHeight,Qt.Canvas&&(Qt.Canvas.width=Qt._VJCanvasWidth,Qt.Canvas.height=Qt._VJCanvasHeight),Qt._HalfWidth=Qt._VJCanvasWidth/2},!Qt.Canvas){window.addEventListener("resize",this._onResize,!1),Qt.Canvas=document.createElement("canvas"),Qt._VJCanvasWidth=window.innerWidth,Qt._VJCanvasHeight=window.innerHeight,Qt.Canvas.width=window.innerWidth,Qt.Canvas.height=window.innerHeight,Qt.Canvas.style.width="100%",Qt.Canvas.style.height="100%",Qt.Canvas.style.position="absolute",Qt.Canvas.style.backgroundColor="transparent",Qt.Canvas.style.top="0px",Qt.Canvas.style.left="0px",Qt.Canvas.style.zIndex="5",Qt.Canvas.style.touchAction="none",Qt.Canvas.setAttribute("touch-action","none");const r=Qt.Canvas.getContext("2d");if(!r)throw new Error("Unable to create canvas for virtual joystick");Qt._VJCanvasContext=r,Qt._VJCanvasContext.strokeStyle="#ffffff",Qt._VJCanvasContext.lineWidth=2,document.body.appendChild(Qt.Canvas)}Qt._HalfWidth=Qt.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&Qt._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new Be(0,0),this._joystickPreviousPointerPos=new Be(0,0),this._joystickPointerStartPos=new Be(0,0),this._deltaJoystickVector=new Be(0,0),this._onPointerDownHandlerRef=r=>{this._onPointerDown(r)},this._onPointerMoveHandlerRef=r=>{this._onPointerMove(r)},this._onPointerUpHandlerRef=r=>{this._onPointerUp(r)},Qt.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),Qt.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),Qt.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),Qt.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),Qt.Canvas.addEventListener("contextmenu",r=>{r.preventDefault()},!1),requestAnimationFrame(()=>{this._drawVirtualJoystick()})}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),this._leftJoystick===!0?t=e.clientXQt._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):Qt._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const a=new Be(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),o=a.length();o>this.containerSize&&a.scaleInPlace(this.containerSize/o),this._joystickPointerPos.x=this._joystickPointerStartPos.x+a.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+a.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?Qt._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,this.containerSize*2,this.containerSize*2):(Qt._VJCanvasContext.beginPath(),Qt._VJCanvasContext.strokeStyle=this._joystickColor,Qt._VJCanvasContext.lineWidth=2,Qt._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,Math.PI*2,!0),Qt._VJCanvasContext.stroke(),Qt._VJCanvasContext.closePath(),Qt._VJCanvasContext.beginPath(),Qt._VJCanvasContext.lineWidth=6,Qt._VJCanvasContext.strokeStyle=this._joystickColor,Qt._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,Math.PI*2,!0),Qt._VJCanvasContext.stroke(),Qt._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?Qt._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,this.puckSize*2,this.puckSize*2):(Qt._VJCanvasContext.beginPath(),Qt._VJCanvasContext.strokeStyle=this._joystickColor,Qt._VJCanvasContext.lineWidth=2,Qt._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,Math.PI*2,!0),Qt._VJCanvasContext.stroke(),Qt._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(Qt._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),Qt._VJCanvasContext.beginPath(),Qt._VJCanvasContext.fillStyle="white",Qt._VJCanvasContext.beginPath(),Qt._VJCanvasContext.strokeStyle="red",Qt._VJCanvasContext.lineWidth=6,Qt._VJCanvasContext.arc(t.x,t.y,40,0,Math.PI*2,!0),Qt._VJCanvasContext.stroke(),Qt._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){Qt.Canvas&&(Qt.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),Qt.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),Qt.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),Qt.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(Qt.Canvas),Qt.Canvas=null),this._released=!0}}Qt._GlobalJoystickIndex=0;Qt._AlwaysVisibleSticks=0;r9.prototype.addVirtualJoystick=function(){return this.add(new JJ),this};class JJ{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=e._computeLocalCameraSpeed()*50,i=ce.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=P.TransformCoordinates(new P(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new Qt(!0),this._leftjoystick.setAxisForUpDown(go.Z),this._leftjoystick.setAxisForLeftRight(go.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new Qt(!1),this._rightjoystick.setAxisForUpDown(go.X),this._rightjoystick.setAxisForLeftRight(go.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}Rl.FreeCameraVirtualJoystickInput=JJ;Lr.AddNodeConstructor("TargetCamera",(n,e)=>()=>new Ln(n,P.Zero(),e));class Ln extends Rt{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=P.Zero(),this._tmpTargetVector=P.Zero(),this.cameraDirection=new P(0,0,0),this.cameraRotation=new Be(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new we,this.rotation=new P(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=P.Zero(),this._initialFocalDistance=1,this._viewMatrix=ce.Zero(),this._camMatrix=ce.Zero(),this._cameraTransformMatrix=ce.Zero(),this._cameraRotationMatrix=ce.Zero(),this._referencePoint=new P(0,0,1),this._transformedReferencePoint=P.Zero(),this._deferredPositionUpdate=new P,this._deferredRotationQuaternionUpdate=new we,this._deferredRotationUpdate=new P,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=P.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return super._restoreStateValues()?(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0):!1}_initCache(){super._initCache(),this._cache.lockedTarget=new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new we(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(e.getFps()*100))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=ni),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),ce.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&we.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent){this.parent.getWorldMatrix().invertToRef(ie.Matrix[0]),P.TransformNormalToRef(this.cameraDirection,ie.Matrix[0],ie.Vector3[0]),this._deferredPositionUpdate.addInPlace(ie.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,this.noRotationConstraint||(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(we.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))),t&&(Math.abs(this.cameraDirection.x){this._newPosition.copyFrom(a),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>De.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&o&&this.onCollide(o))},this.inputs=new r9(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ee.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new P(0,0,0),this.cameraRotation=new Be(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):t=this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=P.Zero(),this._transformedDirection=P.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}B([Js()],El.prototype,"ellipsoid",void 0);B([Js()],El.prototype,"ellipsoidOffset",void 0);B([K()],El.prototype,"checkCollisions",void 0);B([K()],El.prototype,"applyGravity",void 0);Lr.AddNodeConstructor("TouchCamera",(n,e)=>()=>new eee(n,P.Zero(),e));class eee extends El{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}Lr.AddNodeConstructor("ArcRotateCamera",(n,e)=>()=>new Rr(n,0,0,1,P.Zero(),e));class Rr extends Ln{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new ce,this._upToYMatrix=new ce,this._upVector=P.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){ce.RotationAlignToRef(P.UpReadOnly,this._upVector,this._yToUpMatrix),ce.RotationAlignToRef(this._upVector,P.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return e?e.useNaturalPinchZoom:!1}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return e?e.zoomToMouseLocation:!1}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return this._bouncingBehavior!=null}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new V3,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return this._framingBehavior!=null}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new fh,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return this._autoRotationBehavior!=null}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Lme,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,a,o=!0){super(e,P.Zero(),a,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=P.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=Be.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new ce,this.panningAxis=new P(1,1,0),this._transformedDirection=new P,this.mapPanning=!1,this.onMeshTargetChangedObservable=new Ae,this.checkCollisions=!1,this.collisionRadius=new P(.5,.5,.5),this._previousPosition=P.Zero(),this._collisionVelocity=P.Zero(),this._newPosition=P.Zero(),this._computationVector=P.Zero(),this._onCollisionPositionChange=(c,l,h=null)=>{h?(this.setPosition(l),this.onCollide&&this.onCollide(h)):this._previousPosition.copyFrom(this._position);const u=Math.cos(this.alpha),d=Math.sin(this.alpha),f=Math.cos(this.beta);let p=Math.sin(this.beta);p===0&&(p=1e-4);const _=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*u*p,this.radius*f,this.radius*d*p),_.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let m=this.upVector;this.allowUpsideDown&&this.beta<0&&(m=m.clone(),m=m.negate()),this._computeViewMatrix(this._position,_,m),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=P.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new mG(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=Be.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const t=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?t.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(t)}const e=this._getLockedTargetPosition();return e||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return super._restoreStateValues()?(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0):!1}_isSynchronizedViewMatrix(){return super._isSynchronizedViewMatrix()?this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset):!1}attachControl(e,t,i=!0,r=2){const s=arguments;t=Ee.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,typeof s[0]=="boolean"&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this.inertialAlphaOffset!==0||this.inertialBetaOffset!==0||this.inertialRadiusOffset!==0){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&P.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);const e=this.alpha;this._computationVector.x===0&&this._computationVector.z===0?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=t*2*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,r=!1){if(r=this.overrideCloneAlphaBetaRadius??r,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const s=e,a=this._getTargetPosition();if(a&&!i&&a.equals(s))return;this._targetHost=null,this._target=s,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let r=Math.sin(this.beta);r===0&&(r=1e-4),this.radius===0&&(this.radius=1e-4);const s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&P.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const a=this.getScene().collisionCoordinator;this._collider||(this._collider=a.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,a.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let a=this.upVector;this.allowUpsideDown&&r<0&&(a=a.negate()),this._computeViewMatrix(this._position,s,a),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Se.MinMax(e);let r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(e.min===void 0){const s=e||this.getScene().meshes;i=Se.MinMax(s),r=P.Distance(i.min,i.max)}else{const s=e;i=s,r=s.distance}this._target=Se.Center(i),t||(this.maxZ=r*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case Rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Rt.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Rt.RIG_MODE_STEREOSCOPIC_INTERLACED:case Rt.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const r=new Rr(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case Rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Rt.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Rt.RIG_MODE_STEREOSCOPIC_INTERLACED:case Rt.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle;break}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const r=P.Distance(e,t),a=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),c=o*a,h=r*.5*i,u=h*Math.sqrt(1+1/(c*c)),d=h*Math.sqrt(1+1/(o*o));return Math.max(u,d)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}B([K()],Rr.prototype,"alpha",void 0);B([K()],Rr.prototype,"beta",void 0);B([K()],Rr.prototype,"radius",void 0);B([K()],Rr.prototype,"overrideCloneAlphaBetaRadius",void 0);B([Js("target")],Rr.prototype,"_target",void 0);B([I5("targetHost")],Rr.prototype,"_targetHost",void 0);B([K()],Rr.prototype,"inertialAlphaOffset",void 0);B([K()],Rr.prototype,"inertialBetaOffset",void 0);B([K()],Rr.prototype,"inertialRadiusOffset",void 0);B([K()],Rr.prototype,"lowerAlphaLimit",void 0);B([K()],Rr.prototype,"upperAlphaLimit",void 0);B([K()],Rr.prototype,"lowerBetaLimit",void 0);B([K()],Rr.prototype,"upperBetaLimit",void 0);B([K()],Rr.prototype,"lowerRadiusLimit",void 0);B([K()],Rr.prototype,"upperRadiusLimit",void 0);B([K()],Rr.prototype,"inertialPanningX",void 0);B([K()],Rr.prototype,"inertialPanningY",void 0);B([K()],Rr.prototype,"pinchToPanMaxDistance",void 0);B([K()],Rr.prototype,"panningDistanceLimit",void 0);B([Js()],Rr.prototype,"panningOriginTarget",void 0);B([K()],Rr.prototype,"panningInertia",void 0);B([K()],Rr.prototype,"zoomToMouseLocation",null);B([K()],Rr.prototype,"zoomOnFactor",void 0);B([LO()],Rr.prototype,"targetScreenOffset",void 0);B([K()],Rr.prototype,"allowUpsideDown",void 0);B([K()],Rr.prototype,"useInputToRestoreState",void 0);Lr.AddNodeConstructor("DeviceOrientationCamera",(n,e)=>()=>new gG(n,P.Zero(),e));class gG extends El{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new we,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new we,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add(r=>{this._dragFactor!=0&&(this._initialQuaternion||(this._initialQuaternion=new we),we.FromEulerAnglesToRef(0,r.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))}))})}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=$n.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new we),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class Hme extends qO{constructor(e){super(e)}addKeyboard(){return this.add(new f2),this}addMouse(){return this.add(new e9),this}}class n9 extends Ln{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new P(1,1,1),this.ellipsoidOffset=new P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=P.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=P.Zero(),this._diffPosition=P.Zero(),this._newPosition=P.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(s,a,o=null)=>{(l=>{this._newPosition.copyFrom(l),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>De.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&o&&this.onCollide(o))})(a)},this.inputs=new Hme(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ee.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new P(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):t=this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=P.Zero(),this._transformedDirection=P.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=this.rotation.z,r=t-i,s=.001;Math.abs(r)>=s&&(this.rotation.z+=r/e,Math.abs(t-this.rotation.z)<=s&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}B([Js()],n9.prototype,"ellipsoid",void 0);B([Js()],n9.prototype,"ellipsoidOffset",void 0);B([K()],n9.prototype,"checkCollisions",void 0);B([K()],n9.prototype,"applyGravity",void 0);class Gme extends qO{constructor(e){super(e)}addKeyboard(){return this.add(new ll),this}addMouseWheel(){return this.add(new c4),this}addPointers(){return this.add(new Ah),this}addVRDeviceOrientation(){return de.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Lr.AddNodeConstructor("FollowCamera",(n,e)=>()=>new Fc(n,P.Zero(),e));Lr.AddNodeConstructor("ArcFollowCamera",(n,e)=>()=>new Kme(n,0,0,1,null,e));class Fc extends Ln{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new Gme(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=ie.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),r=Ee.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),a=s.x+Math.sin(r)*this.radius,o=s.z+Math.cos(r)*this.radius,c=a-this.position.x,l=s.y+this.heightOffset-this.position.y,h=o-this.position.z;let u=c*this.cameraAcceleration*2,d=l*this.cameraAcceleration,f=h*this.cameraAcceleration*2;(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),(f>this.maxCameraSpeed||f<-this.maxCameraSpeed)&&(f=f<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new P(this.position.x+u,this.position.y+d,this.position.z+f),this.setTarget(s)}attachControl(e,t){t=Ee.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),this.lowerHeightOffsetLimit!==null&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),this.lowerRotationOffsetLimit!==null&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}B([K()],Fc.prototype,"radius",void 0);B([K()],Fc.prototype,"lowerRadiusLimit",void 0);B([K()],Fc.prototype,"upperRadiusLimit",void 0);B([K()],Fc.prototype,"rotationOffset",void 0);B([K()],Fc.prototype,"lowerRotationOffsetLimit",void 0);B([K()],Fc.prototype,"upperRotationOffsetLimit",void 0);B([K()],Fc.prototype,"heightOffset",void 0);B([K()],Fc.prototype,"lowerHeightOffsetLimit",void 0);B([K()],Fc.prototype,"upperHeightOffsetLimit",void 0);B([K()],Fc.prototype,"cameraAcceleration",void 0);B([K()],Fc.prototype,"maxCameraSpeed",void 0);B([I5("lockedTargetId")],Fc.prototype,"lockedTarget",void 0);class Kme extends Ln{constructor(e,t,i,r,s,a){super(e,P.Zero(),a),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=P.Zero(),this.setMeshTarget(s)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}var Fh;(function(n){n[n.A=0]="A",n[n.B=1]="B",n[n.X=2]="X",n[n.Y=3]="Y",n[n.LB=4]="LB",n[n.RB=5]="RB",n[n.Back=8]="Back",n[n.Start=9]="Start",n[n.LeftStick=10]="LeftStick",n[n.RightStick=11]="RightStick"})(Fh||(Fh={}));var yy;(function(n){n[n.Up=12]="Up",n[n.Down=13]="Down",n[n.Left=14]="Left",n[n.Right=15]="Right"})(yy||(yy={}));class Wme extends Io{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new Ae,this.onButtonUpObservable=new Ae,this.onPadDownObservable=new Ae,this.onPadUpObservable=new Ae,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=Io.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(e===1&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),e===0&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,Fh.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,Fh.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,Fh.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,Fh.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Fh.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Fh.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Fh.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Fh.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Fh.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Fh.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,yy.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,yy.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,yy.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,yy.Right)}update(){super.update(),this._isXboxOnePad?(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value):(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value)}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}var fd;(function(n){n[n.Cross=0]="Cross",n[n.Circle=1]="Circle",n[n.Square=2]="Square",n[n.Triangle=3]="Triangle",n[n.L1=4]="L1",n[n.R1=5]="R1",n[n.Share=8]="Share",n[n.Options=9]="Options",n[n.LeftStick=10]="LeftStick",n[n.RightStick=11]="RightStick"})(fd||(fd={}));var Ay;(function(n){n[n.Up=12]="Up",n[n.Down=13]="Down",n[n.Left=14]="Left",n[n.Right=15]="Right"})(Ay||(Ay={}));class jme extends Io{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new Ae,this.onButtonUpObservable=new Ae,this.onPadDownObservable=new Ae,this.onPadUpObservable=new Ae,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=Io.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(e===1&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),e===0&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,fd.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,fd.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,fd.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,fd.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,fd.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,fd.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,fd.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,fd.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,fd.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,fd.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Ay.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Ay.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Ay.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Ay.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class Xme{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new Ae,io()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new Ae(t=>{for(const i in this._babylonGamepads){const r=this._babylonGamepads[i];r&&r._isConnected&&this.onGamepadConnectedObservable.notifyObserver(t,r)}}),this._onGamepadConnectedEvent=t=>{const i=t.gamepad;if(i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected)return;let r;this._babylonGamepads[i.index]?(r=this._babylonGamepads[i.index],r.browserGamepad=i,r._isConnected=!0):r=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(r),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=t=>{const i=t.gamepad;for(const r in this._babylonGamepads)if(this._babylonGamepads[r].index===i.index){const s=this._babylonGamepads[r];s._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(s),s.dispose&&s.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const t=this._scene?this._scene.getEngine().getHostWindow():window;t&&(t.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),t.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=Io.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach(e=>{e.dispose()}),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){this._oneGamepadConnected||(this._oneGamepadConnected=!0);let t;const i=e.id.search("054c")!==-1&&e.id.search("0ce6")===-1,r=e.id.search("Xbox One")!==-1;return r||e.id.search("Xbox 360")!==-1||e.id.search("xinput")!==-1||e.id.search("045e")!==-1&&e.id.search("Surface Dock")===-1?t=new Wme(e.id,e.index,e,r):i?t=new jme(e.id,e.index,e):t=new zme(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const e in this._babylonGamepads){const t=this._babylonGamepads[e];if(!(!t||!t.isConnected))try{t.update()}catch{this._loggedErrors.indexOf(t.index)===-1&&(Ee.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&De.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new h4(n,P.Zero(),e));class h4 extends eee{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}Rt._CreateDefaultParsedCamera=(n,e)=>new h4(n,P.Zero(),e);Lr.AddNodeConstructor("GamepadCamera",(n,e)=>()=>new vG(n,P.Zero(),e));class vG extends h4{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}const LRe="passCubePixelShader",NRe=`varying vec2 vUV;uniform samplerCube textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 uv=vUV*2.0-1.0; #ifdef POSITIVEX gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); #endif #ifdef NEGATIVEX gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); #endif #ifdef POSITIVEY gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); #endif #ifdef NEGATIVEY gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); #endif #ifdef POSITIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); #endif #ifdef NEGATIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); #endif }`;Re.ShadersStore[LRe]=NRe;class Zf extends Pt{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,a,o=0,c=!1){super(e,"pass",null,null,t,i,r,s,a,void 0,o,void 0,null,c)}static _Parse(e,t,i,r){return Qe.Parse(()=>new Zf(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}}xe("BABYLON.PassPostProcess",Zf);class tee extends Pt{get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ");break}}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,r,s,a,o=0,c=!1){super(e,"passCube",null,null,t,i,r,s,a,"#define POSITIVEX",o,void 0,null,c),this._face=0}static _Parse(e,t,i,r){return Qe.Parse(()=>new tee(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}}De._RescalePostProcessFactory=n=>new Zf("rescale",1,null,2,n,!1,0);const BRe="anaglyphPixelShader",FRe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`;Re.ShadersStore[BRe]=FRe;class iee extends Pt{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,s,a){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,s,a),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(o=>{o.setTextureFromPostProcess("leftSampler",this._passedProcess)})}}xe("BABYLON.AnaglyphPostProcess",iee);function a9(n){n._rigCameras[0]._rigPostProcess=new Zf(n.name+"_passthru",1,n._rigCameras[0]),n._rigCameras[1]._rigPostProcess=new iee(n.name+"_anaglyph",1,n._rigCameras)}Lr.AddNodeConstructor("AnaglyphArcRotateCamera",(n,e,t)=>()=>new Qme(n,0,0,1,P.Zero(),t.interaxial_distance,e));class Qme extends Rr{constructor(e,t,i,r,s,a,o){super(e,t,i,r,s,o),this._setRigMode=()=>a9(this),this.interaxialDistance=a,this.setCameraRigMode(Rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:a})}getClassName(){return"AnaglyphArcRotateCamera"}}Lr.AddNodeConstructor("AnaglyphFreeCamera",(n,e,t)=>()=>new $me(n,P.Zero(),t.interaxial_distance,e));class $me extends El{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>a9(this),this.interaxialDistance=i,this.setCameraRigMode(Rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Lr.AddNodeConstructor("AnaglyphGamepadCamera",(n,e,t)=>()=>new Zme(n,P.Zero(),t.interaxial_distance,e));class Zme extends vG{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>a9(this),this.interaxialDistance=i,this.setCameraRigMode(Rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Lr.AddNodeConstructor("AnaglyphUniversalCamera",(n,e,t)=>()=>new qme(n,P.Zero(),t.interaxial_distance,e));class qme extends h4{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>a9(this),this.interaxialDistance=i,this.setCameraRigMode(Rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}const URe="stereoscopicInterlacePixelShader",kRe=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; #ifdef IS_STEREOSCOPIC_HORIZ useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); #else #ifdef IS_STEREOSCOPIC_INTERLACED float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); #else useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); #endif #endif if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} `;Re.ShadersStore[URe]=kRe;class Jme extends Pt{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,s,a,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,a,o,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new Be(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new Be(1/this.width,1/this.height)}),this.onApplyObservable.add(c=>{c.setTextureFromPostProcess("camASampler",this._passedProcess),c.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}}class VRe extends Pt{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,r,s,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,s,a,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new Be(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new Be(1/this.width,1/this.height)}),this.onApplyObservable.add(o=>{o.setTextureFromPostProcess("camASampler",this._passedProcess),o.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}}function o9(n){const e=n.cameraRigMode===Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||n.cameraRigMode===Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,t=n.cameraRigMode===Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;n.cameraRigMode===Rt.RIG_MODE_STEREOSCOPIC_INTERLACED?(n._rigCameras[0]._rigPostProcess=new Zf(n.name+"_passthru",1,n._rigCameras[0]),n._rigCameras[1]._rigPostProcess=new Jme(n.name+"_stereoInterlace",n._rigCameras,!1,!0)):(n._rigCameras[t?1:0].viewport=new bl(0,0,e?.5:1,e?1:.5),n._rigCameras[t?0:1].viewport=new bl(e?.5:0,e?0:.5,e?.5:1,e?1:.5))}Lr.AddNodeConstructor("StereoscopicArcRotateCamera",(n,e,t)=>()=>new e2e(n,0,0,1,P.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class e2e extends Rr{constructor(e,t,i,r,s,a,o,c){super(e,t,i,r,s,c),this._setRigMode=()=>o9(this),this.interaxialDistance=a,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:a})}getClassName(){return"StereoscopicArcRotateCamera"}}Lr.AddNodeConstructor("StereoscopicFreeCamera",(n,e,t)=>()=>new t2e(n,P.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class t2e extends El{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>o9(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Lr.AddNodeConstructor("StereoscopicGamepadCamera",(n,e,t)=>()=>new i2e(n,P.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class i2e extends vG{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>o9(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Lr.AddNodeConstructor("StereoscopicFreeCamera",(n,e,t)=>()=>new r2e(n,P.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class r2e extends h4{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>o9(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}class zRe extends h4{set distanceBetweenEyes(e){this._distanceBetweenEyes=e}get distanceBetweenEyes(){return this._distanceBetweenEyes}set distanceToProjectionPlane(e){this._distanceToProjectionPlane=e}get distanceToProjectionPlane(){return this._distanceToProjectionPlane}constructor(e,t,i,r=1,s=.065){super(e,t,i),this._distanceBetweenEyes=s,this._distanceToProjectionPlane=r,this.setCameraRigMode(Rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=s}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new Ln(e,P.Zero(),this.getScene()),i=new Et("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(ce.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e()=>new s2e(n,P.Zero(),e));class s2e extends El{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class $6{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return ce.Translation(t,0,0)}get rightHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return ce.Translation(-t,0,0)}get leftPreViewMatrix(){return ce.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return ce.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new $6;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}const HRe="vrDistortionCorrectionPixelShader",GRe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;Re.ShadersStore[HRe]=GRe;class L$ extends Pt{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,ve.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new Be(2,2/this.aspectRatio),this._scaleFactor=new Be(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new Be(this._isRightEye?.5-this._lensCenterOffset*.5:.5+this._lensCenterOffset*.5,.5)}),this.onApplyObservable.add(s=>{s.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),s.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),s.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),s.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])})}}const KRe="vrMultiviewToSingleviewPixelShader",WRe=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;Re.ShadersStore[KRe]=WRe;class N$ extends es{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}De.prototype.createMultiviewRenderTargetTexture=function(n,e,t,i){const r=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const s=this._createHardwareRenderTargetWrapper(!1,!1,{width:n,height:e});s._framebuffer=r.createFramebuffer();const a=new Ar(this,mi.Unknown,!0);return a.width=n,a.height=e,a.isMultiview=!0,t||(t=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,t),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.RGBA8,n,e,2)),s._colorTextureArray=t,i||(i=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,i),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.DEPTH24_STENCIL8,n,e,2)),s._depthStencilTextureArray=i,a.isReady=!0,s.setTextures(a),s._depthStencilTexture=a,s};De.prototype.bindMultiviewFramebuffer=function(n){const e=n,t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"};De.prototype.bindSpaceWarpFramebuffer=function(n){const e=n,t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_ATTACHMENT,e._depthStencilTextureArray,0,0,2);else throw new Error("Invalid Space Warp framebuffer")};Rt.prototype._useMultiviewToSingleView=!1;Rt.prototype._multiviewTexture=null;Rt.prototype._resizeOrCreateMultiviewTexture=function(n,e){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=n||this._multiviewTexture.getRenderHeight()!=e)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new N$(this.getScene(),{width:n,height:e})):this._multiviewTexture=new N$(this.getScene(),{width:n,height:e})};function n2e(n,e){const t=new Ft(n,void 0,!0,e);return t.addUniform("viewProjection",16),t.addUniform("viewProjectionR",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}const jRe=pt.prototype.createSceneUniformBuffer;pt.prototype._transformMatrixR=ce.Zero();pt.prototype._multiviewSceneUbo=null;pt.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=n2e(this.getEngine(),"scene_multiview")};pt.prototype.createSceneUniformBuffer=function(n){return this._multiviewSceneUbo?n2e(this.getEngine(),n):jRe.bind(this)(n)};pt.prototype._updateMultiviewUbo=function(n,e){n&&e&&n.multiplyToRef(e,this._transformMatrixR),n&&e&&(n.multiplyToRef(e,ie.Matrix[0]),Tu.GetRightPlaneToRef(ie.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))};pt.prototype._renderMultiviewToSingleView=function(n){n._resizeOrCreateMultiviewTexture(n._rigPostProcess&&n._rigPostProcess&&n._rigPostProcess.width>0?n._rigPostProcess.width:this.getEngine().getRenderWidth(!0),n._rigPostProcess&&n._rigPostProcess&&n._rigPostProcess.height>0?n._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),n.outputRenderTarget=n._multiviewTexture,this._renderForCamera(n),n.outputRenderTarget=null;for(let e=0;e{}),this.onApplyObservable.add(s=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?s.setInt("imageIndex",0):s.setInt("imageIndex",1),s.setTexture("multiviewSampler",r._multiviewTexture)})}}function xG(n,e){const t=e.vrCameraMetrics||$6.GetDefault();n._rigCameras[0]._cameraRigParams.vrMetrics=t,n._rigCameras[0].viewport=new bl(0,0,.5,1),n._rigCameras[0]._cameraRigParams.vrWorkMatrix=new ce,n._rigCameras[0]._cameraRigParams.vrHMatrix=t.leftHMatrix,n._rigCameras[0]._cameraRigParams.vrPreViewMatrix=t.leftPreViewMatrix,n._rigCameras[0].getProjectionMatrix=n._rigCameras[0]._getVRProjectionMatrix,n._rigCameras[1]._cameraRigParams.vrMetrics=t,n._rigCameras[1].viewport=new bl(.5,0,.5,1),n._rigCameras[1]._cameraRigParams.vrWorkMatrix=new ce,n._rigCameras[1]._cameraRigParams.vrHMatrix=t.rightHMatrix,n._rigCameras[1]._cameraRigParams.vrPreViewMatrix=t.rightPreViewMatrix,n._rigCameras[1].getProjectionMatrix=n._rigCameras[1]._getVRProjectionMatrix,t.multiviewEnabled&&(n.getScene().getEngine().getCaps().multiview?(n._useMultiviewToSingleView=!0,n._rigPostProcess=new a2e("VRMultiviewToSingleview",n,t.postProcessScaleFactor)):(de.Warn("Multiview is not supported, falling back to standard rendering"),t.multiviewEnabled=!1)),t.compensateDistortion&&(n._rigCameras[0]._rigPostProcess=new L$("VR_Distort_Compensation_Left",n._rigCameras[0],!1,t),n._rigCameras[1]._rigPostProcess=new L$("VR_Distort_Compensation_Right",n._rigCameras[1],!0,t))}Lr.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(n,e)=>()=>new o2e(n,0,0,1,P.Zero(),e));class o2e extends Rr{constructor(e,t,i,r,s,a,o=!0,c=$6.GetDefault()){super(e,t,i,r,s,a),this._setRigMode=l=>xG(this,l),c.compensateDistortion=o,this.setCameraRigMode(Rt.RIG_MODE_VR,{vrCameraMetrics:c}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Lr.AddNodeConstructor("VRDeviceOrientationFreeCamera",(n,e)=>()=>new yG(n,P.Zero(),e));class yG extends gG{constructor(e,t,i,r=!0,s=$6.GetDefault()){super(e,t,i),this._setRigMode=a=>xG(this,a),s.compensateDistortion=r,this.setCameraRigMode(Rt.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Lr.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(n,e)=>()=>new l2e(n,P.Zero(),e));class l2e extends yG{constructor(e,t,i,r=!0,s=$6.GetDefault()){super(e,t,i,r,s),this._setRigMode=a=>xG(this,a),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class Uz{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&t.prePassRenderer.getIndex(2)!==-1){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const a=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=a.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==a.frameId&&(this._lastUpdateFrameId=a.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}}class $e{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,De.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,De.MarkAllMaterialsAsDirty(1))}}$e._DiffuseTextureEnabled=!0;$e._DetailTextureEnabled=!0;$e._DecalMapEnabled=!0;$e._AmbientTextureEnabled=!0;$e._OpacityTextureEnabled=!0;$e._ReflectionTextureEnabled=!0;$e._EmissiveTextureEnabled=!0;$e._SpecularTextureEnabled=!0;$e._BumpTextureEnabled=!0;$e._LightmapTextureEnabled=!0;$e._RefractionTextureEnabled=!0;$e._ColorGradingTextureEnabled=!0;$e._FresnelEnabled=!0;$e._ClearCoatTextureEnabled=!0;$e._ClearCoatBumpTextureEnabled=!0;$e._ClearCoatTintTextureEnabled=!0;$e._SheenTextureEnabled=!0;$e._AnisotropicTextureEnabled=!0;$e._ThicknessTextureEnabled=!0;$e._RefractionIntensityTextureEnabled=!0;$e._TranslucencyIntensityTextureEnabled=!0;$e._IridescenceTextureEnabled=!0;const XRe="decalFragmentDeclaration",YRe=`#ifdef DECAL uniform vec4 vDecalInfos; #endif `;Re.IncludesShadersStore[XRe]=YRe;const QRe="defaultFragmentDeclaration",$Re=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; #ifdef SPECULARTERM uniform vec4 vSpecularColor; #endif uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; #ifdef DIFFUSE uniform vec2 vDiffuseInfos; #endif #ifdef AMBIENT uniform vec2 vAmbientInfos; #endif #ifdef OPACITY uniform vec2 vOpacityInfos; #endif #ifdef EMISSIVE uniform vec2 vEmissiveInfos; #endif #ifdef LIGHTMAP uniform vec2 vLightmapInfos; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; #endif #ifdef ALPHATEST uniform float alphaCutOff; #endif #if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) uniform mat4 view; #endif #ifdef REFRACTION uniform vec4 vRefractionInfos; #ifndef REFRACTIONMAP_3D uniform mat4 refractionMatrix; #endif #ifdef REFRACTIONFRESNEL uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; #endif #if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; #endif #endif #if defined(SPECULAR) && defined(SPECULARTERM) uniform vec2 vSpecularInfos; #endif #ifdef DIFFUSEFRESNEL uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; #endif #ifdef OPACITYFRESNEL uniform vec4 opacityParts; #endif #ifdef EMISSIVEFRESNEL uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; #endif #ifdef REFLECTION uniform vec2 vReflectionInfos; #if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) uniform mat4 reflectionMatrix; #endif #ifndef REFLECTIONMAP_SKYBOX #if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; #endif #endif #ifdef REFLECTIONFRESNEL uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; #endif #endif #ifdef DETAIL uniform vec4 vDetailInfos; #endif #include #define ADDITIONAL_FRAGMENT_DECLARATION `;Re.IncludesShadersStore[QRe]=$Re;const ZRe="sceneUboDeclaration",qRe=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; #ifdef MULTIVIEW mat4 viewProjectionR; #endif mat4 view;mat4 projection;vec4 vEyePosition;}; `;Re.IncludesShadersStore[ZRe]=qRe;const JRe="meshUboDeclaration",eIe=`#ifdef WEBGL2 uniform mat4 world;uniform float visibility; #else layout(std140,column_major) uniform;uniform Mesh {mat4 world;float visibility;}; #endif #define WORLD_UBO `;Re.IncludesShadersStore[JRe]=eIe;const tIe="defaultUboDeclaration",iIe=`layout(std140,column_major) uniform;uniform Material {vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; #define ADDITIONAL_UBO_DECLARATION }; #include #include `;Re.IncludesShadersStore[tIe]=iIe;const rIe="prePassDeclaration",sIe=`#ifdef PREPASS #extension GL_EXT_draw_buffers : require layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; #ifdef PREPASS_DEPTH varying highp vec3 vViewPos; #endif #ifdef PREPASS_VELOCITY varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; #endif #endif `;Re.IncludesShadersStore[rIe]=sIe;const nIe="oitDeclaration",aIe=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY #extension GL_EXT_draw_buffers : require layout(location=0) out vec2 depth; layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; #define MAX_DEPTH 99999.0 highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; #endif `;Re.IncludesShadersStore[nIe]=aIe;const oIe="mainUVVaryingDeclaration",lIe=`#ifdef MAINUV{X} varying vec2 vMainUV{X}; #endif `;Re.IncludesShadersStore[oIe]=lIe;const cIe="helperFunctions",hIe=`const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; #define saturate(x) clamp(x,0.0,1.0) #define absEps(x) abs(x)+Epsilon #define maxEps(x) max(x,Epsilon) #define saturateEps(x) clamp(x,Epsilon,1.0) mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( vec3(i0.x,i1.x,i2.x), vec3(i0.y,i1.y,i2.y), vec3(i0.z,i1.z,i2.z) );return outMatrix;} mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} #if USE_EXACT_SRGB_CONVERSIONS vec3 toLinearSpaceExact(vec3 color) {vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); #else return vec3( color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); #endif } vec3 toGammaSpaceExact(vec3 color) {vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); #else return vec3( color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); #endif } #endif float toLinearSpace(float color) { #if USE_EXACT_SRGB_CONVERSIONS float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; #else return pow(color,LinearEncodePowerApprox); #endif } vec3 toLinearSpace(vec3 color) { #if USE_EXACT_SRGB_CONVERSIONS return toLinearSpaceExact(color); #else return pow(color,vec3(LinearEncodePowerApprox)); #endif } vec4 toLinearSpace(vec4 color) { #if USE_EXACT_SRGB_CONVERSIONS return vec4(toLinearSpaceExact(color.rgb),color.a); #else return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); #endif } float toGammaSpace(float color) { #if USE_EXACT_SRGB_CONVERSIONS float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; #else return pow(color,GammaEncodePowerApprox); #endif } vec3 toGammaSpace(vec3 color) { #if USE_EXACT_SRGB_CONVERSIONS return toGammaSpaceExact(color); #else return pow(color,vec3(GammaEncodePowerApprox)); #endif } vec4 toGammaSpace(vec4 color) { #if USE_EXACT_SRGB_CONVERSIONS return vec4(toGammaSpaceExact(color.rgb),color.a); #else return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); #endif } float square(float value) {return value*value;} vec3 square(vec3 value) {return value*value;} float pow5(float value) {float sq=value*value;return sq*sq*value;} float getLuminance(vec3 color) {return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); } vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} `;Re.IncludesShadersStore[cIe]=hIe;const uIe="lightFragmentDeclaration",dIe=`#ifdef LIGHT{X} uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; #ifdef SPECULARTERM uniform vec4 vLightSpecular{X}; #else vec4 vLightSpecular{X}=vec4(0.); #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DArrayShadow shadowSampler{X}; #else uniform highp sampler2DArray shadowSampler{X}; #endif #ifdef SHADOWCSMDEBUG{X} const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] ( vec3 ( 1.5,0.0,0.0 ), vec3 ( 0.0,1.5,0.0 ), vec3 ( 0.0,0.0,5.5 ), vec3 ( 1.5,0.0,5.5 ), vec3 ( 1.5,1.5,0.0 ), vec3 ( 1.0,1.0,1.0 ), vec3 ( 0.0,1.0,5.5 ), vec3 ( 0.5,3.5,0.75 ) );vec3 shadowDebug{X}; #endif #ifdef SHADOWCSMUSESHADOWMAXZ{X} int index{X}=-1; #else int index{X}=SHADOWCSMNUM_CASCADES{X}-1; #endif float diff{X}=0.; #elif defined(SHADOWCUBE{X}) uniform samplerCube shadowSampler{X}; #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DShadow shadowSampler{X}; #else uniform sampler2D shadowSampler{X}; #endif uniform mat4 lightMatrix{X}; #endif uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; #endif #ifdef SPOTLIGHT{X} uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; #elif defined(POINTLIGHT{X}) uniform vec4 vLightFalloff{X}; #elif defined(HEMILIGHT{X}) uniform vec3 vLightGround{X}; #endif #ifdef PROJECTEDLIGHTTEXTURE{X} uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; #endif #endif `;Re.IncludesShadersStore[uIe]=dIe;const fIe="lightUboDeclaration",pIe=`#ifdef LIGHT{X} uniform Light{X} {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; #ifdef SPOTLIGHT{X} vec4 vLightDirection;vec4 vLightFalloff; #elif defined(POINTLIGHT{X}) vec4 vLightFalloff; #elif defined(HEMILIGHT{X}) vec3 vLightGround; #endif vec4 shadowsInfo;vec2 depthValues;} light{X}; #ifdef PROJECTEDLIGHTTEXTURE{X} uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DArrayShadow shadowSampler{X}; #else uniform highp sampler2DArray shadowSampler{X}; #endif #ifdef SHADOWCSMDEBUG{X} const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] ( vec3 ( 1.5,0.0,0.0 ), vec3 ( 0.0,1.5,0.0 ), vec3 ( 0.0,0.0,5.5 ), vec3 ( 1.5,0.0,5.5 ), vec3 ( 1.5,1.5,0.0 ), vec3 ( 1.0,1.0,1.0 ), vec3 ( 0.0,1.0,5.5 ), vec3 ( 0.5,3.5,0.75 ) );vec3 shadowDebug{X}; #endif #ifdef SHADOWCSMUSESHADOWMAXZ{X} int index{X}=-1; #else int index{X}=SHADOWCSMNUM_CASCADES{X}-1; #endif float diff{X}=0.; #elif defined(SHADOWCUBE{X}) uniform samplerCube shadowSampler{X}; #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DShadow shadowSampler{X}; #else uniform sampler2D shadowSampler{X}; #endif uniform mat4 lightMatrix{X}; #endif #endif #endif `;Re.IncludesShadersStore[fIe]=pIe;const _Ie="lightsFragmentFunctions",mIe=`struct lightingInfo {vec3 diffuse; #ifdef SPECULARTERM vec3 specular; #endif #ifdef NDOTL float ndl; #endif };lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) {vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} else {lightVectorW=normalize(-lightData.xyz);} float ndl=max(0.,dot(vNormal,lightVectorW)); #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=ndl*diffuseColor*attenuation; #ifdef SPECULARTERM vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; #endif return result;} lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) {cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW)); #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=ndl*diffuseColor*attenuation; #ifdef SPECULARTERM vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; #endif return result;} result.diffuse=vec3(0.); #ifdef SPECULARTERM result.specular=vec3(0.); #endif #ifdef NDOTL result.ndl=0.; #endif return result;} lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=mix(groundColor,diffuseColor,ndl); #ifdef SPECULARTERM vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; #endif return result;} #define inline vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;Re.IncludesShadersStore[_Ie]=mIe;const gIe="shadowsFragmentFunctions",vIe=`#ifdef SHADOWS #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else #define TEXTUREFUNC(s,c,b) texture2D(s,c,b) #endif #ifndef SHADOWFLOAT float unpack(vec4 color) {const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} #endif float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) {float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} #define inline float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) {vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; #ifndef SHADOWFLOAT float shadow=unpack(textureCube(shadowSampler,directionToLight)); #else float shadow=textureCube(shadowSampler,directionToLight).x; #endif return depth>shadow ? darkness : 1.0;} #define inline float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) {vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); #ifndef SHADOWFLOAT if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} #endif #define inline float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); #else float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; #endif return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} #define inline float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); #ifndef SHADOWFLOAT if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); #else float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; #endif float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} #define inline float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); #else float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; #endif float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} #ifdef IS_NDC_HALF_ZRANGE #define ZINCLIP clipSpace.z #else #define ZINCLIP uvDepth.z #endif #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define GREATEST_LESS_THAN_ONE 0.99999994 /* disable_uniformity_analysis */ #define inline float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} #define inline float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} #define inline float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} #define inline float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} #define inline float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} #define inline float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} const vec3 PoissonSamplers32[64]=vec3[64]( vec3(0.06407013,0.05409927,0.), vec3(0.7366577,0.5789394,0.), vec3(-0.6270542,-0.5320278,0.), vec3(-0.4096107,0.8411095,0.), vec3(0.6849564,-0.4990818,0.), vec3(-0.874181,-0.04579735,0.), vec3(0.9989998,0.0009880066,0.), vec3(-0.004920578,-0.9151649,0.), vec3(0.1805763,0.9747483,0.), vec3(-0.2138451,0.2635818,0.), vec3(0.109845,0.3884785,0.), vec3(0.06876755,-0.3581074,0.), vec3(0.374073,-0.7661266,0.), vec3(0.3079132,-0.1216763,0.), vec3(-0.3794335,-0.8271583,0.), vec3(-0.203878,-0.07715034,0.), vec3(0.5912697,0.1469799,0.), vec3(-0.88069,0.3031784,0.), vec3(0.5040108,0.8283722,0.), vec3(-0.5844124,0.5494877,0.), vec3(0.6017799,-0.1726654,0.), vec3(-0.5554981,0.1559997,0.), vec3(-0.3016369,-0.3900928,0.), vec3(-0.5550632,-0.1723762,0.), vec3(0.925029,0.2995041,0.), vec3(-0.2473137,0.5538505,0.), vec3(0.9183037,-0.2862392,0.), vec3(0.2469421,0.6718712,0.), vec3(0.3916397,-0.4328209,0.), vec3(-0.03576927,-0.6220032,0.), vec3(-0.04661255,0.7995201,0.), vec3(0.4402924,0.3640312,0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.) );const vec3 PoissonSamplers64[64]=vec3[64]( vec3(-0.613392,0.617481,0.), vec3(0.170019,-0.040254,0.), vec3(-0.299417,0.791925,0.), vec3(0.645680,0.493210,0.), vec3(-0.651784,0.717887,0.), vec3(0.421003,0.027070,0.), vec3(-0.817194,-0.271096,0.), vec3(-0.705374,-0.668203,0.), vec3(0.977050,-0.108615,0.), vec3(0.063326,0.142369,0.), vec3(0.203528,0.214331,0.), vec3(-0.667531,0.326090,0.), vec3(-0.098422,-0.295755,0.), vec3(-0.885922,0.215369,0.), vec3(0.566637,0.605213,0.), vec3(0.039766,-0.396100,0.), vec3(0.751946,0.453352,0.), vec3(0.078707,-0.715323,0.), vec3(-0.075838,-0.529344,0.), vec3(0.724479,-0.580798,0.), vec3(0.222999,-0.215125,0.), vec3(-0.467574,-0.405438,0.), vec3(-0.248268,-0.814753,0.), vec3(0.354411,-0.887570,0.), vec3(0.175817,0.382366,0.), vec3(0.487472,-0.063082,0.), vec3(-0.084078,0.898312,0.), vec3(0.488876,-0.783441,0.), vec3(0.470016,0.217933,0.), vec3(-0.696890,-0.549791,0.), vec3(-0.149693,0.605762,0.), vec3(0.034211,0.979980,0.), vec3(0.503098,-0.308878,0.), vec3(-0.016205,-0.872921,0.), vec3(0.385784,-0.393902,0.), vec3(-0.146886,-0.859249,0.), vec3(0.643361,0.164098,0.), vec3(0.634388,-0.049471,0.), vec3(-0.688894,0.007843,0.), vec3(0.464034,-0.188818,0.), vec3(-0.440840,0.137486,0.), vec3(0.364483,0.511704,0.), vec3(0.034028,0.325968,0.), vec3(0.099094,-0.308023,0.), vec3(0.693960,-0.366253,0.), vec3(0.678884,-0.204688,0.), vec3(0.001801,0.780328,0.), vec3(0.145177,-0.898984,0.), vec3(0.062655,-0.611866,0.), vec3(0.315226,-0.604297,0.), vec3(-0.780145,0.486251,0.), vec3(-0.371868,0.882138,0.), vec3(0.200476,0.494430,0.), vec3(-0.494552,-0.711051,0.), vec3(0.612476,0.705252,0.), vec3(-0.578845,-0.768792,0.), vec3(-0.772454,-0.090976,0.), vec3(0.504440,0.372295,0.), vec3(0.155736,0.065157,0.), vec3(0.391522,0.849605,0.), vec3(-0.620106,-0.328104,0.), vec3(0.789239,-0.419965,0.), vec3(-0.545396,0.538133,0.), vec3(-0.178564,-0.596057,0.) ); #define inline float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) #endif #if defined(DETAIL) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) #endif #if defined(BUMP) && defined(PARALLAX) const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; icurrRayHeight) {float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} else {currRayHeight-=stepSize;vLastOffset=vCurrOffset; #ifdef PARALLAX_RHS vCurrOffset-=stepSize*vMaxOffset; #else vCurrOffset+=stepSize*vMaxOffset; #endif lastSampledHeight=currSampledHeight;}} return vCurrOffset;} vec2 parallaxOffset(vec3 viewDir,float heightScale) {float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height; #ifdef PARALLAX_RHS return texCoordOffset; #else return -texCoordOffset; #endif } #endif `;Re.IncludesShadersStore[wIe]=DIe;const OIe="clipPlaneFragmentDeclaration",LIe=`#ifdef CLIPPLANE varying float fClipDistance; #endif #ifdef CLIPPLANE2 varying float fClipDistance2; #endif #ifdef CLIPPLANE3 varying float fClipDistance3; #endif #ifdef CLIPPLANE4 varying float fClipDistance4; #endif #ifdef CLIPPLANE5 varying float fClipDistance5; #endif #ifdef CLIPPLANE6 varying float fClipDistance6; #endif `;Re.IncludesShadersStore[OIe]=LIe;const NIe="logDepthDeclaration",BIe=`#ifdef LOGARITHMICDEPTH uniform float logarithmicDepthConstant;varying float vFragmentDepth; #endif `;Re.IncludesShadersStore[NIe]=BIe;const FIe="fogFragmentDeclaration",UIe=`#ifdef FOG #define FOGMODE_NONE 0. #define FOGMODE_EXP 1. #define FOGMODE_EXP2 2. #define FOGMODE_LINEAR 3. #define E 2.71828 uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() {float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) {fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} else if (FOGMODE_EXP==vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDensity);} else if (FOGMODE_EXP2==vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} return clamp(fogCoeff,0.0,1.0);} #endif `;Re.IncludesShadersStore[FIe]=UIe;const kIe="clipPlaneFragment",VIe=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) if (false) {} #endif #ifdef CLIPPLANE else if (fClipDistance>0.0) {discard;} #endif #ifdef CLIPPLANE2 else if (fClipDistance2>0.0) {discard;} #endif #ifdef CLIPPLANE3 else if (fClipDistance3>0.0) {discard;} #endif #ifdef CLIPPLANE4 else if (fClipDistance4>0.0) {discard;} #endif #ifdef CLIPPLANE5 else if (fClipDistance5>0.0) {discard;} #endif #ifdef CLIPPLANE6 else if (fClipDistance6>0.0) {discard;} #endif `;Re.IncludesShadersStore[kIe]=VIe;const zIe="bumpFragment",HIe=`vec2 uvOffset=vec2(0.0,0.0); #if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) #ifdef NORMALXYSCALE float normalScale=1.0; #elif defined(BUMP) float normalScale=vBumpInfos.y; #else float normalScale=1.0; #endif #if defined(TANGENT) && defined(NORMAL) mat3 TBN=vTBN; #elif defined(BUMP) vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); #else vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); #endif #elif defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) mat3 TBN=vTBN; #else vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); #endif #endif #ifdef PARALLAX mat3 invTBN=transposeMat3(TBN); #ifdef PARALLAXOCCLUSION uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); #else uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); #endif #endif #ifdef DETAIL vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); #endif #ifdef BUMP #ifdef OBJECTSPACE_NORMALMAP #define CUSTOM_FRAGMENT_BUMP_FRAGMENT normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); #elif !defined(DETAIL) normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); #else vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; #if DETAIL_NORMALBLENDMETHOD==0 detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); #elif DETAIL_NORMALBLENDMETHOD==1 detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; #endif normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); #endif #elif defined(DETAIL) detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); #endif `;Re.IncludesShadersStore[zIe]=HIe;const GIe="decalFragment",KIe=`#ifdef DECAL #ifdef GAMMADECAL decalColor.rgb=toLinearSpace(decalColor.rgb); #endif #ifdef DECAL_SMOOTHALPHA decalColor.a*=decalColor.a; #endif surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); #endif `;Re.IncludesShadersStore[GIe]=KIe;const WIe="depthPrePass",jIe=`#ifdef DEPTHPREPASS gl_FragColor=vec4(0.,0.,0.,1.0);return; #endif `;Re.IncludesShadersStore[WIe]=jIe;const XIe="lightFragment",YIe=`#ifdef LIGHT{X} #if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) #else #ifdef PBR #ifdef SPOTLIGHT{X} preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); #elif defined(POINTLIGHT{X}) preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); #elif defined(HEMILIGHT{X}) preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); #elif defined(DIRLIGHT{X}) preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); #endif preInfo.NdotV=NdotV; #ifdef SPOTLIGHT{X} #ifdef LIGHT_FALLOFF_GLTF{X} preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); #elif defined(LIGHT_FALLOFF_PHYSICAL{X}) preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); #elif defined(LIGHT_FALLOFF_STANDARD{X}) preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); #else preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); #endif #elif defined(POINTLIGHT{X}) #ifdef LIGHT_FALLOFF_GLTF{X} preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); #elif defined(LIGHT_FALLOFF_PHYSICAL{X}) preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); #elif defined(LIGHT_FALLOFF_STANDARD{X}) preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); #else preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); #endif #else preInfo.attenuation=1.0; #endif #ifdef HEMILIGHT{X} preInfo.roughness=roughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif #ifdef IRIDESCENCE preInfo.iridescenceIntensity=iridescenceIntensity; #endif #ifdef HEMILIGHT{X} info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); #elif defined(SS_TRANSLUCENCY) info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); #else info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); #endif #ifdef SPECULARTERM #ifdef ANISOTROPIC info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); #else info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); #endif #endif #ifdef SHEEN #ifdef SHEEN_LINKWITHALBEDO preInfo.roughness=sheenOut.sheenIntensity; #else #ifdef HEMILIGHT{X} preInfo.roughness=sheenOut.sheenRoughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif #endif info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); #endif #ifdef CLEARCOAT #ifdef HEMILIGHT{X} preInfo.roughness=clearcoatOut.clearCoatRoughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); #ifdef CLEARCOAT_TINT absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; #ifdef SPECULARTERM info.specular*=absorption; #endif #endif info.diffuse*=info.clearCoat.w; #ifdef SPECULARTERM info.specular*=info.clearCoat.w; #endif #ifdef SHEEN info.sheen*=info.clearCoat.w; #endif #endif #else #ifdef SPOTLIGHT{X} info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); #elif defined(HEMILIGHT{X}) info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); #elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); #endif #endif #ifdef PROJECTEDLIGHTTEXTURE{X} info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X}); #endif #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} for (int i=0; i=0.) {index{X}=i;break;}} #ifdef SHADOWCSMUSESHADOWMAXZ{X} if (index{X}>=0) #endif { #if defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #else shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #endif #else shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #ifdef SHADOWCSMDEBUG{X} shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; #endif #ifndef SHADOWCSMNOBLEND{X} float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) {index{X}+=1;float nextShadow=0.; #if defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #elif defined(SHADOWMEDIUMQUALITY{X}) nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #else nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #endif #else nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif shadow=mix(nextShadow,shadow,diffRatio); #ifdef SHADOWCSMDEBUG{X} shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); #endif } #endif } #elif defined(SHADOWCLOSEESM{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); #else shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWESM{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); #else shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPOISSON{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); #else shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #else #if defined(SHADOWCUBE{X}) shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues); #else shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #endif #ifdef SHADOWONLY #ifndef SHADOWINUSE #define SHADOWINUSE #endif globalShadow+=shadow;shadowLightCount+=1.0; #endif #else shadow=1.; #endif aggShadow+=shadow;numLights+=1.0; #ifndef SHADOWONLY #ifdef CUSTOMUSERLIGHTING diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); #ifdef SPECULARTERM specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); #endif #elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) diffuseBase+=lightmapColor.rgb*shadow; #ifdef SPECULARTERM #ifndef LIGHTMAPNOSPECULAR{X} specularBase+=info.specular*shadow*lightmapColor.rgb; #endif #endif #ifdef CLEARCOAT #ifndef LIGHTMAPNOSPECULAR{X} clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; #endif #endif #ifdef SHEEN #ifndef LIGHTMAPNOSPECULAR{X} sheenBase+=info.sheen.rgb*shadow; #endif #endif #else #ifdef SHADOWCSMDEBUG{X} diffuseBase+=info.diffuse*shadowDebug{X}; #else diffuseBase+=info.diffuse*shadow; #endif #ifdef SPECULARTERM specularBase+=info.specular*shadow; #endif #ifdef CLEARCOAT clearCoatBase+=info.clearCoat.rgb*shadow; #endif #ifdef SHEEN sheenBase+=info.sheen.rgb*shadow; #endif #endif #endif #endif `;Re.IncludesShadersStore[XIe]=YIe;const QIe="logDepthFragment",$Ie=`#ifdef LOGARITHMICDEPTH gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; #endif `;Re.IncludesShadersStore[QIe]=$Ie;const ZIe="fogFragment",qIe=`#ifdef FOG float fog=CalcFogFactor(); #ifdef PBR fog=toLinearSpace(fog); #endif color.rgb=mix(vFogColor,color.rgb,fog); #endif `;Re.IncludesShadersStore[ZIe]=qIe;const JIe="oitFragment",ePe=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY float fragDepth=gl_FragCoord.z; #ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; #endif ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); #ifdef USE_REVERSE_DEPTHBUFFER float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; #else float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; #endif float alphaMultiplier=1.0-lastFrontColor.a; #ifdef USE_REVERSE_DEPTHBUFFER if (fragDepth>nearestDepth || fragDepthfurthestDepth) { #endif return;} #ifdef USE_REVERSE_DEPTHBUFFER if (fragDepthfurthestDepth) { #else if (fragDepth>nearestDepth && fragDepth #if defined(BUMP) || !defined(NORMAL) #extension GL_OES_standard_derivatives : enable #endif #include[SCENE_MRT_COUNT] #include #define CUSTOM_FRAGMENT_BEGIN #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif varying vec3 vPositionW; #ifdef NORMAL varying vec3 vNormalW; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif #include[1..7] #include #include<__decl__lightFragment>[0..maxSimultaneousLights] #include #include #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) #ifdef REFRACTION #ifdef REFRACTIONMAP_3D uniform samplerCube refractionCubeSampler; #else uniform sampler2D refraction2DSampler; #endif #endif #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) #endif #include #ifdef REFLECTION #ifdef REFLECTIONMAP_3D uniform samplerCube reflectionCubeSampler; #else uniform sampler2D reflection2DSampler; #endif #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #endif #include #endif #include #include #include #include #include #include #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; #ifdef NORMAL vec3 normalW=normalize(vNormalW); #else vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); #endif #include #ifdef TWOSIDEDLIGHTING normalW=gl_FrontFacing ? normalW : -normalW; #endif #ifdef DIFFUSE baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); #if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) #endif #include #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) baseColor.rgb*=vColor.rgb; #endif #ifdef DETAIL baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); #endif #if defined(DECAL) && defined(DECAL_AFTER_DETAIL) vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); #include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) #endif #define CUSTOM_FRAGMENT_UPDATE_DIFFUSE vec3 baseAmbientColor=vec3(1.,1.,1.); #ifdef AMBIENT baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; #endif #define CUSTOM_FRAGMENT_BEFORE_LIGHTS #ifdef SPECULARTERM float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; #ifdef SPECULAR vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; #ifdef GLOSSINESS glossiness=glossiness*specularMapColor.a; #endif #endif #else float glossiness=0.; #endif vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; #ifdef SPECULARTERM vec3 specularBase=vec3(0.,0.,0.); #endif float shadow=1.;float aggShadow=0.;float numLights=0.; #ifdef LIGHTMAP vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor.rgb=fromRGBD(lightmapColor); #endif lightmapColor.rgb*=vLightmapInfos.y; #endif #include[0..maxSimultaneousLights] aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); #ifdef REFRACTION vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); #ifdef REFRACTIONMAP_3D #ifdef USE_LOCAL_REFRACTIONMAP_CUBIC refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); #endif refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} #else vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); #endif #ifdef RGBDREFRACTION refractionColor.rgb=fromRGBD(refractionColor); #endif #ifdef IS_REFRACTION_LINEAR refractionColor.rgb=toGammaSpace(refractionColor.rgb); #endif refractionColor.rgb*=vRefractionInfos.x; #endif vec4 reflectionColor=vec4(0.,0.,0.,1.); #ifdef REFLECTION vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); #ifdef REFLECTIONMAP_OPPOSITEZ vReflectionUVW.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D #ifdef ROUGHNESS float bias=vReflectionInfos.y; #ifdef SPECULARTERM #ifdef SPECULAR #ifdef GLOSSINESS bias*=(1.0-specularMapColor.a); #endif #endif #endif reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); #else reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); #endif #else vec2 coords=vReflectionUVW.xy; #ifdef REFLECTIONMAP_PROJECTION coords/=vReflectionUVW.z; #endif coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); #endif #ifdef RGBDREFLECTION reflectionColor.rgb=fromRGBD(reflectionColor); #endif #ifdef IS_REFLECTION_LINEAR reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); #endif reflectionColor.rgb*=vReflectionInfos.x; #ifdef REFLECTIONFRESNEL float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); #ifdef REFLECTIONFRESNELFROMSPECULAR #ifdef SPECULARTERM reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; #else reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; #endif #else reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; #endif #endif #endif #ifdef REFRACTIONFRESNEL float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; #endif #ifdef OPACITY vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); #ifdef OPACITYRGB opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; #else alpha*=opacityMap.a*vOpacityInfos.y; #endif #endif #if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) alpha*=vColor.a; #endif #ifdef OPACITYFRESNEL float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; #endif #ifdef ALPHATEST #ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS if (alpha #include #ifdef IMAGEPROCESSINGPOSTPROCESS color.rgb=toLinearSpace(color.rgb); #else #ifdef IMAGEPROCESSING color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); #endif #endif color.a*=visibility; #ifdef PREMULTIPLYALPHA color.rgb*=color.a; #endif #define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR #ifdef PREPASS float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; #ifdef PREPASS_POSITION gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); #endif #ifdef PREPASS_VELOCITY vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); #endif #ifdef PREPASS_IRRADIANCE gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_DEPTH gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_NORMAL #ifdef PREPASS_NORMAL_WORLDSPACE gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); #else gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); #endif #endif #ifdef PREPASS_ALBEDO_SQRT gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_REFLECTIVITY #if defined(SPECULARTERM) #if defined(SPECULAR) gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; #else gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; #endif #else gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; #endif #endif #endif #if !defined(PREPASS) || defined(WEBGL2) gl_FragColor=color; #endif #include #if ORDER_INDEPENDENT_TRANSPARENCY if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} #endif #define CUSTOM_FRAGMENT_MAIN_END } `;Re.ShadersStore[tPe]=iPe;const rPe="decalVertexDeclaration",sPe=`#ifdef DECAL uniform vec4 vDecalInfos;uniform mat4 decalMatrix; #endif `;Re.IncludesShadersStore[rPe]=sPe;const nPe="defaultVertexDeclaration",aPe=`uniform mat4 viewProjection;uniform mat4 view; #ifdef DIFFUSE uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; #endif #ifdef AMBIENT uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; #endif #ifdef OPACITY uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; #endif #ifdef EMISSIVE uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; #endif #ifdef LIGHTMAP uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; #endif #if defined(SPECULAR) && defined(SPECULARTERM) uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; #endif #ifdef REFLECTION uniform mat4 reflectionMatrix; #endif #ifdef POINTSIZE uniform float pointSize; #endif #ifdef DETAIL uniform vec4 vDetailInfos;uniform mat4 detailMatrix; #endif #include #define ADDITIONAL_VERTEX_DECLARATION `;Re.IncludesShadersStore[nPe]=aPe;const oPe="uvAttributeDeclaration",lPe=`#ifdef UV{X} attribute vec2 uv{X}; #endif `;Re.IncludesShadersStore[oPe]=lPe;const cPe="bonesDeclaration",hPe=`#if NUM_BONE_INFLUENCERS>0 attribute vec4 matricesIndices;attribute vec4 matricesWeights; #if NUM_BONE_INFLUENCERS>4 attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; #endif #ifndef BAKED_VERTEX_ANIMATION_TEXTURE #ifdef BONETEXTURE uniform highp sampler2D boneSampler;uniform float boneTextureWidth; #else uniform mat4 mBones[BonesPerMesh]; #endif #ifdef BONES_VELOCITY_ENABLED uniform mat4 mPreviousBones[BonesPerMesh]; #endif #ifdef BONETEXTURE #define inline mat4 readMatrixFromRawSampler(sampler2D smp,float index) {float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} #endif #endif #endif `;Re.IncludesShadersStore[cPe]=hPe;const uPe="bakedVertexAnimationDeclaration",dPe=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; #ifdef INSTANCES attribute vec4 bakedVertexAnimationSettingsInstanced; #endif #define inline mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) {float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} #endif `;Re.IncludesShadersStore[uPe]=dPe;const fPe="instancesDeclaration",pPe=`#ifdef INSTANCES attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; #ifdef INSTANCESCOLOR attribute vec4 instanceColor; #endif #if defined(THIN_INSTANCES) && !defined(WORLD_UBO) uniform mat4 world; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; #ifdef THIN_INSTANCES uniform mat4 previousWorld; #endif #endif #else #if !defined(WORLD_UBO) uniform mat4 world; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) uniform mat4 previousWorld; #endif #endif `;Re.IncludesShadersStore[fPe]=pPe;const _Pe="prePassVertexDeclaration",mPe=`#ifdef PREPASS #ifdef PREPASS_DEPTH varying vec3 vViewPos; #endif #ifdef PREPASS_VELOCITY uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #endif `;Re.IncludesShadersStore[_Pe]=mPe;const gPe="samplerVertexDeclaration",vPe=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 varying vec2 v_VARYINGNAME_UV; #endif `;Re.IncludesShadersStore[gPe]=vPe;const xPe="bumpVertexDeclaration",yPe=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif #endif `;Re.IncludesShadersStore[xPe]=yPe;const APe="clipPlaneVertexDeclaration",CPe=`#ifdef CLIPPLANE uniform vec4 vClipPlane;varying float fClipDistance; #endif #ifdef CLIPPLANE2 uniform vec4 vClipPlane2;varying float fClipDistance2; #endif #ifdef CLIPPLANE3 uniform vec4 vClipPlane3;varying float fClipDistance3; #endif #ifdef CLIPPLANE4 uniform vec4 vClipPlane4;varying float fClipDistance4; #endif #ifdef CLIPPLANE5 uniform vec4 vClipPlane5;varying float fClipDistance5; #endif #ifdef CLIPPLANE6 uniform vec4 vClipPlane6;varying float fClipDistance6; #endif `;Re.IncludesShadersStore[APe]=CPe;const bPe="fogVertexDeclaration",EPe=`#ifdef FOG varying vec3 vFogDistance; #endif `;Re.IncludesShadersStore[bPe]=EPe;const TPe="lightVxFragmentDeclaration",SPe=`#ifdef LIGHT{X} uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; #ifdef SPECULARTERM uniform vec4 vLightSpecular{X}; #else vec4 vLightSpecular{X}=vec4(0.); #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #elif defined(SHADOWCUBE{X}) #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; #endif uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; #endif #ifdef SPOTLIGHT{X} uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; #elif defined(POINTLIGHT{X}) uniform vec4 vLightFalloff{X}; #elif defined(HEMILIGHT{X}) uniform vec3 vLightGround{X}; #endif #endif `;Re.IncludesShadersStore[TPe]=SPe;const MPe="lightVxUboDeclaration",RPe=`#ifdef LIGHT{X} uniform Light{X} {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; #ifdef SPOTLIGHT{X} vec4 vLightDirection;vec4 vLightFalloff; #elif defined(POINTLIGHT{X}) vec4 vLightFalloff; #elif defined(HEMILIGHT{X}) vec3 vLightGround; #endif vec4 shadowsInfo;vec2 depthValues;} light{X}; #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #elif defined(SHADOWCUBE{X}) #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; #endif #endif #endif `;Re.IncludesShadersStore[MPe]=RPe;const IPe="morphTargetsVertexGlobalDeclaration",PPe=`#ifdef MORPHTARGETS uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; #ifdef MORPHTARGETS_TEXTURE uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) { float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} #endif #endif `;Re.IncludesShadersStore[IPe]=PPe;const wPe="morphTargetsVertexDeclaration",DPe=`#ifdef MORPHTARGETS #ifndef MORPHTARGETS_TEXTURE attribute vec3 position{X}; #ifdef MORPHTARGETS_NORMAL attribute vec3 normal{X}; #endif #ifdef MORPHTARGETS_TANGENT attribute vec3 tangent{X}; #endif #ifdef MORPHTARGETS_UV attribute vec2 uv_{X}; #endif #elif {X}==0 uniform int morphTargetCount; #endif #endif `;Re.IncludesShadersStore[wPe]=DPe;const OPe="morphTargetsVertexGlobal",LPe=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE float vertexID; #endif #endif `;Re.IncludesShadersStore[OPe]=LPe;const NPe="morphTargetsVertex",BPe=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE #if {X}==0 for (int i=0; i=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];vertexID+=1.0; #ifdef MORPHTARGETS_NORMAL normalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];vertexID+=1.0; #endif #ifdef MORPHTARGETS_UV uvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];vertexID+=1.0; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i]; #endif } #endif #else positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; #ifdef MORPHTARGETS_NORMAL normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_UV uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; #endif #endif #endif `;Re.IncludesShadersStore[NPe]=BPe;const FPe="instancesVertex",UPe=`#ifdef INSTANCES mat4 finalWorld=mat4(world0,world1,world2,world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); #endif #ifdef THIN_INSTANCES finalWorld=world*finalWorld; #if defined(PREPASS_VELOCITY) || defined(VELOCITY) finalPreviousWorld=previousWorld*finalPreviousWorld; #endif #endif #else mat4 finalWorld=world; #if defined(PREPASS_VELOCITY) || defined(VELOCITY) mat4 finalPreviousWorld=previousWorld; #endif #endif `;Re.IncludesShadersStore[FPe]=UPe;const kPe="bonesVertex",VPe=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE #if NUM_BONE_INFLUENCERS>0 mat4 influence; #ifdef BONETEXTURE influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; #endif #else influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif #endif finalWorld=finalWorld*influence; #endif #endif `;Re.IncludesShadersStore[kPe]=VPe;const zPe="bakedVertexAnimation",HPe=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE { #ifdef INSTANCES #define BVASNAME bakedVertexAnimationSettingsInstanced #else #define BVASNAME bakedVertexAnimationSettings #endif float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; #endif finalWorld=finalWorld*VATInfluence;} #endif `;Re.IncludesShadersStore[zPe]=HPe;const GPe="prePassVertex",KPe=`#ifdef PREPASS_DEPTH vViewPos=(view*worldPos).rgb; #endif #if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*worldPos; #if NUM_BONE_INFLUENCERS>0 mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); #else vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #endif `;Re.IncludesShadersStore[GPe]=KPe;const WPe="uvVariableDeclaration",jPe=`#if !defined(UV{X}) && defined(MAINUV{X}) vec2 uv{X}=vec2(0.,0.); #endif #ifdef MAINUV{X} vMainUV{X}=uv{X}; #endif `;Re.IncludesShadersStore[WPe]=jPe;const XPe="samplerVertexImplementation",YPe=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 if (v_INFONAME_==0.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} #ifdef UV2 else if (v_INFONAME_==1.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));} #endif #ifdef UV3 else if (v_INFONAME_==2.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} #endif #ifdef UV4 else if (v_INFONAME_==3.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} #endif #ifdef UV5 else if (v_INFONAME_==4.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} #endif #ifdef UV6 else if (v_INFONAME_==5.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} #endif #endif `;Re.IncludesShadersStore[XPe]=YPe;const QPe="bumpVertex",$Pe=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); #endif #endif `;Re.IncludesShadersStore[QPe]=$Pe;const ZPe="clipPlaneVertex",qPe=`#ifdef CLIPPLANE fClipDistance=dot(worldPos,vClipPlane); #endif #ifdef CLIPPLANE2 fClipDistance2=dot(worldPos,vClipPlane2); #endif #ifdef CLIPPLANE3 fClipDistance3=dot(worldPos,vClipPlane3); #endif #ifdef CLIPPLANE4 fClipDistance4=dot(worldPos,vClipPlane4); #endif #ifdef CLIPPLANE5 fClipDistance5=dot(worldPos,vClipPlane5); #endif #ifdef CLIPPLANE6 fClipDistance6=dot(worldPos,vClipPlane6); #endif `;Re.IncludesShadersStore[ZPe]=qPe;const JPe="fogVertex",e7e=`#ifdef FOG vFogDistance=(view*worldPos).xyz; #endif `;Re.IncludesShadersStore[JPe]=e7e;const t7e="shadowsVertex",i7e=`#ifdef SHADOWS #if defined(SHADOWCSM{X}) vPositionFromCamera{X}=view*worldPos;for (int i=0; i #define CUSTOM_VERTEX_BEGIN attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #ifdef TANGENT attribute vec4 tangent; #endif #ifdef UV1 attribute vec2 uv; #endif #include[2..7] #ifdef VERTEXCOLOR attribute vec4 color; #endif #include #include #include #include #include #include[1..7] #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) #endif #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) varying vec3 vPositionW; #ifdef NORMAL varying vec3 vNormalW; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif #include #include #include #include<__decl__lightVxFragment>[0..maxSimultaneousLights] #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 positionUpdated=position; #ifdef NORMAL vec3 normalUpdated=normal; #endif #ifdef TANGENT vec4 tangentUpdated=tangent; #endif #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX vPositionUVW=positionUpdated; #endif #define CUSTOM_VERTEX_UPDATE_POSITION #define CUSTOM_VERTEX_UPDATE_NORMAL #include #if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #ifdef NORMAL mat3 normalWorld=mat3(finalWorld); #if defined(INSTANCES) && defined(THIN_INSTANCES) vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); #else #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vNormalW=normalize(normalWorld*normalUpdated); #endif #endif #define CUSTOM_VERTEX_UPDATE_WORLDPOS #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} #else gl_Position=viewProjection*worldPos; #endif vPositionW=vec3(worldPos); #include #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); #endif #ifndef UV1 vec2 uvUpdated=vec2(0.,0.); #endif #ifdef MAINUV1 vMainUV1=uvUpdated; #endif #include[2..7] #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) #endif #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) #include #include #include #include[0..maxSimultaneousLights] #include #include #include #define CUSTOM_VERTEX_MAIN_END } `;Re.ShadersStore[c7e]=h7e;const u7e=new RegExp("^([gimus]+)!");class wm{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let r=0;rthis._handlePluginEvent(r,s),this._plugins.push(e),this._plugins.sort((r,s)=>r.priority-s.priority),this._codeInjectionPoints={};const i={};i[wm._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const r of this._plugins)r.collectDefines(i),this._collectPointNames("vertex",r.getCustomCode("vertex")),this._collectPointNames("fragment",r.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&i.uniforms.push(...this._uniformList),this._samplerList.length>0&&i.samplers.push(...this._samplerList),this._uboList.length>0&&i.uniformBuffersNames.push(...this._uboList),i.customCode=this._injectCustomCode(i,i.customCode);break}case Ko.PrepareUniformBuffer:{const i=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const r of this._plugins){const s=r.getUniforms();if(s){if(s.ubo)for(const a of s.ubo){if(a.size&&a.type){const o=a.arraySize??0;i.ubo.addUniform(a.name,a.size,o),this._uboDeclaration+=`${a.type} ${a.name}${o>0?`[${o}]`:""}; `}this._uniformList.push(a.name)}s.vertex&&(this._vertexDeclaration+=s.vertex+` `),s.fragment&&(this._fragmentDeclaration+=s.fragment+` `)}r.getSamplers(this._samplerList),r.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var o,c;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const s=(o=this._codeInjectionPoints)==null?void 0:o[i];if(!s)return r;let a=null;for(let l in s){let h="";for(const u of this._activePlugins){let d=(c=u.getCustomCode(i))==null?void 0:c[l];if(d){if(u.resolveIncludes){if(a===null){const f=Vs.GLSL;a={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Re.GetShadersRepository(f),includesShadersStore:Re.GetIncludesShadersStore(f),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}a.isFragment=i==="fragment",Cd._ProcessIncludes(d,a,f=>d=f)}h+=d+` `}}if(h.length>0)if(l.charAt(0)==="!"){l=l.substring(1);let u="g";if(l.charAt(0)==="!")u="",l=l.substring(1);else{const _=u7e.exec(l);_&&_.length>=2&&(u=_[1],l=l.substring(u.length+1))}u.indexOf("g")<0&&(u+="g");const d=r,f=new RegExp(l,u);let p=f.exec(d);for(;p!==null;){let _=h;for(let m=0;m{ree()});const I3=[];let B$=!1,F$=null;function d7e(n,e){B$||(F$=Ye.OnEventObservable.add(i=>{for(const[,r]of I3)r(i)},Ko.Created),B$=!0);const t=I3.filter(([i,r])=>i===n);t.length>0?t[0][1]=e:I3.push([n,e])}function f7e(n){for(let e=0;e{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),a&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if(t[0]==="_")continue;const i=typeof this._pluginDefineNames[t];e[t]={type:i==="number"?"number":i==="string"?"string":i==="boolean"?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){Qe.Clone(()=>e,this)}serialize(){return Qe.Serialize(this)}parse(e,t,i){Qe.Parse(()=>this,e,t,i)}}B([K()],Wc.prototype,"name",void 0);B([K()],Wc.prototype,"priority",void 0);B([K()],Wc.prototype,"resolveIncludes",void 0);B([K()],Wc.prototype,"registerForExtraEvents",void 0);class c2e extends Kr{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class a_ extends Wc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new c2e,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Ye.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&$e.DetailTextureEnabled&&!this._texture.isReady()):!0}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&$e.DetailTextureEnabled&&this._isEnabled?(ks(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&this._texture&&$e.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),ms(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&$e.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&((t=this._texture)==null||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}B([$t("detailTexture"),ze("_markAllSubMeshesAsTexturesDirty")],a_.prototype,"texture",void 0);B([K()],a_.prototype,"diffuseBlendLevel",void 0);B([K()],a_.prototype,"roughnessBlendLevel",void 0);B([K()],a_.prototype,"bumpLevel",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],a_.prototype,"normalBlendMethod",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],a_.prototype,"isEnabled",void 0);const fY={effect:null,subMesh:null};class h2e extends Kr{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class tt extends Rn{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new Me(0,0,0),this.diffuseColor=new Me(1,1,1),this.specularColor=new Me(1,1,1),this.emissiveColor=new Me(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new ba(16),this._worldViewProjectionMatrix=ce.Zero(),this._globalAmbientColor=new Me(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new a_(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new Uz,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),tt.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),tt.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return tt.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||tt.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled}needAlphaTesting(){return this._forceAlphaTest?!0:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===Ye.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Ye.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Ko.GetDefineNames,this._eventInfo),t.materialDefines=new h2e(this._eventInfo.defineNames));const s=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();a._needNormals=vc(s,e,a,!0,this._maxSimultaneousLights,this._disableLighting),N5(s,a);const c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(KO(s,a,this.canRenderToMRT&&!c),hG(s,a,c),a._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a._needUVs=!1;for(let h=1;h<=6;++h)a["MAINUV"+h]=!1;if(s.texturesEnabled){if(a.DIFFUSEDIRECTUV=0,a.BUMPDIRECTUV=0,a.AMBIENTDIRECTUV=0,a.OPACITYDIRECTUV=0,a.EMISSIVEDIRECTUV=0,a.SPECULARDIRECTUV=0,a.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&tt.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())ks(this._diffuseTexture,a,"DIFFUSE");else return!1;else a.DIFFUSE=!1;if(this._ambientTexture&&tt.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())ks(this._ambientTexture,a,"AMBIENT");else return!1;else a.AMBIENT=!1;if(this._opacityTexture&&tt.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())ks(this._opacityTexture,a,"OPACITY"),a.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else a.OPACITY=!1;if(this._reflectionTexture&&tt.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(a._needNormals=!0,a.REFLECTION=!0,a.ROUGHNESS=this._roughness>0,a.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,a.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===ve.INVCUBIC_MODE,a.REFLECTIONMAP_3D=this._reflectionTexture.isCube,a.REFLECTIONMAP_OPPOSITEZ=a.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,a.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case ve.EXPLICIT_MODE:a.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case ve.PLANAR_MODE:a.setReflectionMode("REFLECTIONMAP_PLANAR");break;case ve.PROJECTION_MODE:a.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case ve.SKYBOX_MODE:a.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case ve.SPHERICAL_MODE:a.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case ve.EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case ve.FIXED_EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case ve.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case ve.CUBIC_MODE:case ve.INVCUBIC_MODE:default:a.setReflectionMode("REFLECTIONMAP_CUBIC");break}a.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else a.REFLECTION=!1,a.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&tt.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())ks(this._emissiveTexture,a,"EMISSIVE");else return!1;else a.EMISSIVE=!1;if(this._lightmapTexture&&tt.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())ks(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,a.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else a.LIGHTMAP=!1;if(this._specularTexture&&tt.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())ks(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else a.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&tt.BumpTextureEnabled){if(this._bumpTexture.isReady())ks(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAX_RHS=s.useRightHandedSystem,a.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;a.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else a.BUMP=!1,a.PARALLAX=!1,a.PARALLAX_RHS=!1,a.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&tt.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())a._needUVs=!0,a.REFRACTION=!0,a.REFRACTIONMAP_3D=this._refractionTexture.isCube,a.RGBDREFRACTION=this._refractionTexture.isRGBD,a.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else a.REFRACTION=!1;a.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else a.DIFFUSE=!1,a.AMBIENT=!1,a.OPACITY=!1,a.REFLECTION=!1,a.EMISSIVE=!1,a.LIGHTMAP=!1,a.BUMP=!1,a.REFRACTION=!1;a.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),a.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,a.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,a.SPECULAROVERALPHA=this._useSpecularOverAlpha,a.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,a.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,a.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=a,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a),a.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,a.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}a._areFresnelDirty&&(tt.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(a.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,a.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,a.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,a.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,a.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,a.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,a._needNormals=!0,a.FRESNEL=!0):a.FRESNEL=!1),Ql(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,a,this._applyDecalMapAfterDetailMap),$l(s,o,this,a,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=a,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),qn(e,a,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(a.isDirty){const h=a._areLightsDisposed;a.markAsProcessed();const u=new Hn;a.REFLECTION&&u.addFallback(0,"REFLECTION"),a.SPECULAR&&u.addFallback(0,"SPECULAR"),a.BUMP&&u.addFallback(0,"BUMP"),a.PARALLAX&&u.addFallback(1,"PARALLAX"),a.PARALLAX_RHS&&u.addFallback(1,"PARALLAX_RHS"),a.PARALLAXOCCLUSION&&u.addFallback(0,"PARALLAXOCCLUSION"),a.SPECULAROVERALPHA&&u.addFallback(0,"SPECULAROVERALPHA"),a.FOG&&u.addFallback(1,"FOG"),a.POINTSIZE&&u.addFallback(0,"POINTSIZE"),a.LOGARITHMICDEPTH&&u.addFallback(0,"LOGARITHMICDEPTH"),uo(a,u,this._maxSimultaneousLights),a.SPECULARTERM&&u.addFallback(0,"SPECULARTERM"),a.DIFFUSEFRESNEL&&u.addFallback(1,"DIFFUSEFRESNEL"),a.OPACITYFRESNEL&&u.addFallback(2,"OPACITYFRESNEL"),a.REFLECTIONFRESNEL&&u.addFallback(3,"REFLECTIONFRESNEL"),a.EMISSIVEFRESNEL&&u.addFallback(4,"EMISSIVEFRESNEL"),a.FRESNEL&&u.addFallback(4,"FRESNEL"),a.MULTIVIEW&&u.addFallback(0,"MULTIVIEW");const d=[Z.PositionKind];a.NORMAL&&d.push(Z.NormalKind),a.TANGENT&&d.push(Z.TangentKind);for(let b=1;b<=6;++b)a["UV"+b]&&d.push(`uv${b===1?"":b}`);a.VERTEXCOLOR&&d.push(Z.ColorKind),Kc(d,e,a,u),pa(d,a),VO(d,e,a),zO(d,e,a);let f="default";const p=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],_=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],m=["Material","Scene","Mesh"],g={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:a.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=u,this._eventInfo.fallbackRank=0,this._eventInfo.defines=a,this._eventInfo.uniforms=p,this._eventInfo.attributes=d,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=m,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=g,this._callbackPluginEventGeneric(Ko.PrepareEffect,this._eventInfo),Uz.AddUniforms(p),Ji&&(Ji.PrepareUniforms(p,a),Ji.PrepareSamplers(_,a)),Ma({uniformsNames:p,uniformBuffersNames:m,samplers:_,defines:a,maxSimultaneousLights:this._maxSimultaneousLights}),Sa(p);const v={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,p,m,_,a,d,v));const x=a.toString(),y=t.effect;let C=s.getEngine().createEffect(f,{attributes:d,uniformsNames:p,uniformBuffersNames:m,samplers:_,defines:x,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:a.PREPASS},o);if(this._eventInfo.customCode=void 0,C)if(this._onEffectCreatedObservable&&(fY.effect=C,fY.subMesh=t,this._onEffectCreatedObservable.notifyObservers(fY)),this.allowShaderHotSwapping&&y&&!C.isReady()){if(C=y,a.markAsUnprocessed(),l=this.isFrozen,h)return a._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(C,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=s.getRenderId(),r._wasPreviouslyReady=!l,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var l;const r=this.getScene(),s=i.materialDefines;if(!s)return;const a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(r,a,i,t.visibility);Yl(t,a);const c=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!c.useUbo||!this.isFrozen||!c.isSync||i._drawWrapper._forceRebindOnNextCall){if(tt.FresnelEnabled&&s.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(c.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),c.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&c.updateColor4("opacityParts",new Me(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(c.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),c.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(c.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),c.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(c.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),c.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),r.texturesEnabled){if(this._diffuseTexture&&tt.DiffuseTextureEnabled&&(c.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ms(this._diffuseTexture,c,"diffuse")),this._ambientTexture&&tt.AmbientTextureEnabled&&(c.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),ms(this._ambientTexture,c,"ambient")),this._opacityTexture&&tt.OpacityTextureEnabled&&(c.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ms(this._opacityTexture,c,"opacity")),this._hasAlphaChannel()&&c.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&tt.ReflectionTextureEnabled&&(c.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),c.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const h=this._reflectionTexture;c.updateVector3("vReflectionPosition",h.boundingBoxPosition),c.updateVector3("vReflectionSize",h.boundingBoxSize)}if(this._emissiveTexture&&tt.EmissiveTextureEnabled&&(c.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ms(this._emissiveTexture,c,"emissive")),this._lightmapTexture&&tt.LightmapTextureEnabled&&(c.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ms(this._lightmapTexture,c,"lightmap")),this._specularTexture&&tt.SpecularTextureEnabled&&(c.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),ms(this._specularTexture,c,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&tt.BumpTextureEnabled&&(c.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),ms(this._bumpTexture,c,"bump"),r._mirroredCameraPosition?c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&tt.RefractionTextureEnabled){let h=1;if(this._refractionTexture.isCube||(c.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(h=this._refractionTexture.depth)),c.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,h,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const u=this._refractionTexture;c.updateVector3("vRefractionPosition",u.boundingBoxPosition),c.updateVector3("vRefractionSize",u.boundingBoxSize)}}}this.pointsCloud&&c.updateFloat("pointSize",this.pointSize),s.SPECULARTERM&&c.updateColor4("vSpecularColor",this.specularColor,this.specularPower),c.updateColor3("vEmissiveColor",tt.EmissiveTextureEnabled?this.emissiveColor:Me.BlackReadOnly),c.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),c.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&tt.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&tt.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&tt.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&tt.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&tt.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&tt.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&tt.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&tt.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&tt.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),fa(a,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&gc(r,t,a,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==pt.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||s.PREPASS)&&this.bindView(a),Oo(r,t,a),s.NUM_MORPH_INFLUENCERS&&d1(t,a),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((l=t.bakedVertexAnimationManager)==null||l.bind(a,s.INSTANCES)),this.useLogarithmicDepth&&Ha(s,a,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),c.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e)}dispose(e,t){var i,r,s,a,o,c,l,h,u;t&&((i=this._diffuseTexture)==null||i.dispose(),(r=this._ambientTexture)==null||r.dispose(),(s=this._opacityTexture)==null||s.dispose(),(a=this._reflectionTexture)==null||a.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(c=this._specularTexture)==null||c.dispose(),(l=this._bumpTexture)==null||l.dispose(),(h=this._lightmapTexture)==null||h.dispose(),(u=this._refractionTexture)==null||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const r=Qe.Clone(()=>new tt(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){const r=Qe.Parse(()=>new tt(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ye._ParsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return $e.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){$e.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return $e.DetailTextureEnabled}static set DetailTextureEnabled(e){$e.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return $e.AmbientTextureEnabled}static set AmbientTextureEnabled(e){$e.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return $e.OpacityTextureEnabled}static set OpacityTextureEnabled(e){$e.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return $e.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){$e.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return $e.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){$e.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return $e.SpecularTextureEnabled}static set SpecularTextureEnabled(e){$e.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return $e.BumpTextureEnabled}static set BumpTextureEnabled(e){$e.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return $e.LightmapTextureEnabled}static set LightmapTextureEnabled(e){$e.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return $e.RefractionTextureEnabled}static set RefractionTextureEnabled(e){$e.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return $e.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){$e.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return $e.FresnelEnabled}static set FresnelEnabled(e){$e.FresnelEnabled=e}}B([$t("diffuseTexture")],tt.prototype,"_diffuseTexture",void 0);B([ze("_markAllSubMeshesAsTexturesAndMiscDirty")],tt.prototype,"diffuseTexture",void 0);B([$t("ambientTexture")],tt.prototype,"_ambientTexture",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"ambientTexture",void 0);B([$t("opacityTexture")],tt.prototype,"_opacityTexture",void 0);B([ze("_markAllSubMeshesAsTexturesAndMiscDirty")],tt.prototype,"opacityTexture",void 0);B([$t("reflectionTexture")],tt.prototype,"_reflectionTexture",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"reflectionTexture",void 0);B([$t("emissiveTexture")],tt.prototype,"_emissiveTexture",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"emissiveTexture",void 0);B([$t("specularTexture")],tt.prototype,"_specularTexture",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"specularTexture",void 0);B([$t("bumpTexture")],tt.prototype,"_bumpTexture",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"bumpTexture",void 0);B([$t("lightmapTexture")],tt.prototype,"_lightmapTexture",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"lightmapTexture",void 0);B([$t("refractionTexture")],tt.prototype,"_refractionTexture",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"refractionTexture",void 0);B([or("ambient")],tt.prototype,"ambientColor",void 0);B([or("diffuse")],tt.prototype,"diffuseColor",void 0);B([or("specular")],tt.prototype,"specularColor",void 0);B([or("emissive")],tt.prototype,"emissiveColor",void 0);B([K()],tt.prototype,"specularPower",void 0);B([K("useAlphaFromDiffuseTexture")],tt.prototype,"_useAlphaFromDiffuseTexture",void 0);B([ze("_markAllSubMeshesAsTexturesAndMiscDirty")],tt.prototype,"useAlphaFromDiffuseTexture",void 0);B([K("useEmissiveAsIllumination")],tt.prototype,"_useEmissiveAsIllumination",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"useEmissiveAsIllumination",void 0);B([K("linkEmissiveWithDiffuse")],tt.prototype,"_linkEmissiveWithDiffuse",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"linkEmissiveWithDiffuse",void 0);B([K("useSpecularOverAlpha")],tt.prototype,"_useSpecularOverAlpha",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"useSpecularOverAlpha",void 0);B([K("useReflectionOverAlpha")],tt.prototype,"_useReflectionOverAlpha",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"useReflectionOverAlpha",void 0);B([K("disableLighting")],tt.prototype,"_disableLighting",void 0);B([ze("_markAllSubMeshesAsLightsDirty")],tt.prototype,"disableLighting",void 0);B([K("useObjectSpaceNormalMap")],tt.prototype,"_useObjectSpaceNormalMap",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"useObjectSpaceNormalMap",void 0);B([K("useParallax")],tt.prototype,"_useParallax",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"useParallax",void 0);B([K("useParallaxOcclusion")],tt.prototype,"_useParallaxOcclusion",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"useParallaxOcclusion",void 0);B([K()],tt.prototype,"parallaxScaleBias",void 0);B([K("roughness")],tt.prototype,"_roughness",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"roughness",void 0);B([K()],tt.prototype,"indexOfRefraction",void 0);B([K()],tt.prototype,"invertRefractionY",void 0);B([K()],tt.prototype,"alphaCutOff",void 0);B([K("useLightmapAsShadowmap")],tt.prototype,"_useLightmapAsShadowmap",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"useLightmapAsShadowmap",void 0);B([R5("diffuseFresnelParameters")],tt.prototype,"_diffuseFresnelParameters",void 0);B([ze("_markAllSubMeshesAsFresnelDirty")],tt.prototype,"diffuseFresnelParameters",void 0);B([R5("opacityFresnelParameters")],tt.prototype,"_opacityFresnelParameters",void 0);B([ze("_markAllSubMeshesAsFresnelAndMiscDirty")],tt.prototype,"opacityFresnelParameters",void 0);B([R5("reflectionFresnelParameters")],tt.prototype,"_reflectionFresnelParameters",void 0);B([ze("_markAllSubMeshesAsFresnelDirty")],tt.prototype,"reflectionFresnelParameters",void 0);B([R5("refractionFresnelParameters")],tt.prototype,"_refractionFresnelParameters",void 0);B([ze("_markAllSubMeshesAsFresnelDirty")],tt.prototype,"refractionFresnelParameters",void 0);B([R5("emissiveFresnelParameters")],tt.prototype,"_emissiveFresnelParameters",void 0);B([ze("_markAllSubMeshesAsFresnelDirty")],tt.prototype,"emissiveFresnelParameters",void 0);B([K("useReflectionFresnelFromSpecular")],tt.prototype,"_useReflectionFresnelFromSpecular",void 0);B([ze("_markAllSubMeshesAsFresnelDirty")],tt.prototype,"useReflectionFresnelFromSpecular",void 0);B([K("useGlossinessFromSpecularMapAlpha")],tt.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"useGlossinessFromSpecularMapAlpha",void 0);B([K("maxSimultaneousLights")],tt.prototype,"_maxSimultaneousLights",void 0);B([ze("_markAllSubMeshesAsLightsDirty")],tt.prototype,"maxSimultaneousLights",void 0);B([K("invertNormalMapX")],tt.prototype,"_invertNormalMapX",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"invertNormalMapX",void 0);B([K("invertNormalMapY")],tt.prototype,"_invertNormalMapY",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"invertNormalMapY",void 0);B([K("twoSidedLighting")],tt.prototype,"_twoSidedLighting",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],tt.prototype,"twoSidedLighting",void 0);B([K("applyDecalMapAfterDetailMap")],tt.prototype,"_applyDecalMapAfterDetailMap",void 0);B([ze("_markAllSubMeshesAsMiscDirty")],tt.prototype,"applyDecalMapAfterDetailMap",void 0);xe("BABYLON.StandardMaterial",tt);pt.DefaultMaterialFactory=n=>new tt("default material",n);yt.prototype.createDynamicTexture=function(n,e,t,i){const r=new Ar(this,mi.Dynamic);return r.baseWidth=n,r.baseHeight=e,t&&(n=this.needPOTTextures?yt.GetExponentOfTwo(n,this._caps.maxTextureSize):n,e=this.needPOTTextures?yt.GetExponentOfTwo(e,this._caps.maxTextureSize):e),r.width=n,r.height=e,r.isReady=!1,r.generateMipMaps=t,r.samplingMode=i,this.updateTextureSamplingMode(i,r),this._internalTexturesCache.push(r),r};yt.prototype.updateDynamicTexture=function(n,e,t,i=!1,r,s=!1,a=!1){if(!n)return;const o=this._gl,c=o.TEXTURE_2D,l=this._bindTextureDirectly(c,n,!0,s);this._unpackFlipY(t===void 0?n.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const h=this._getWebGLTextureType(n.type),u=this._getInternalFormat(r||n.format),d=this._getRGBABufferInternalSizedFormat(n.type,u);o.texImage2D(c,0,d,u,h,e),n.generateMipMaps&&o.generateMipmap(c),l||this._bindTextureDirectly(c,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(n.format=r),n._dynamicTextureSource=e,n._premulAlpha=i,n.invertY=t||!1,n.isReady=!0};class Id extends ve{constructor(e,t,i=null,r=!1,s=3,a=5,o){super(null,i,!r,o,s,void 0,void 0,void 0,void 0,a),this.name=e,this.wrapU=ve.CLAMP_ADDRESSMODE,this.wrapV=ve.CLAMP_ADDRESSMODE,this._generateMipMaps=r;const c=this._getEngine();if(!c)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=c.createDynamicTexture(t.width,t.height,r,s)):(this._canvas=c.createCanvas(1,1),this._ownCanvas=!0,t.width||t.width===0?this._texture=c.createDynamicTexture(t.width,t.height,r,s):this._texture=c.createDynamicTexture(t,t,r,s));const l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,e===void 0?!0:e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,s,a,o,c=!0){const l=this.getSize();if(a&&(this._context.fillStyle=a,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,t==null){const h=this._context.measureText(e);t=(l.width-h.width)/2}if(i==null){const h=parseInt(r.replace(/\D/g,""));i=l.height/2+h/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),c&&this.update(o)}dispose(){var e,t;super.dispose(),this._ownCanvas&&((t=(e=this._canvas)==null?void 0:e.remove)==null||t.call(e)),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Id(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&de.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Id._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return e.toDataURL!==void 0}_rebuild(){this.update()}}class see{get isFixedFoveationSupported(){return this.layerType=="XRWebGLLayer"&&typeof this.layer.fixedFoveation=="number"}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,r,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this._createRenderTargetTextureProvider=s,this._rttWrapper=null}}class AG{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Ar(this._engine,mi.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new j6(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,s,a){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},c=a?new N$(this._scene,o):new es("XR renderTargetTexture",o,this._scene),l=c.renderTarget;if(l._samples=c.samples,(i||!r)&&(l._framebuffer=i),r)if(a)l._colorTextureArray=r;else{const h=this._createInternalTexture(o,r);l.setTexture(h,0),c._texture=h}return s&&(a?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(o,s)),c.disableRescaling(),this._renderTargetTextures.push(c),c}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.length=0}}class nee extends see{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new p7e(t.scene,this)),this.layer=e}}class p7e extends AG{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const r=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/s,e.width=i.width/r,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return(!this._rtt||t!==this._framebufferDimensions.framebufferWidth||i!==this._framebufferDimensions.framebufferHeight||r!==this._framebuffer)&&(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class l9{static GetDefaults(e){const t=new l9;return t.canvasOptions={antialias:!0,depth:!0,stencil:e?e.isStencilEnable:!0,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class u2e{constructor(e,t=l9.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new Ae,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const i=document.createElement("canvas");i.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(i)}e.onXRSessionInit.add(()=>{this._addCanvas()}),e.onXRSessionEnded.add(()=>{this._removeCanvas()})}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new nee(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{Ee.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")}).then(()=>t()):Promise.resolve(t())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce(()=>{this._setCanvasSize(!0)})}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){!this._canvas||!this._engine||(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class d2e extends see{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new f2e(t,this)),this.layer=e}}class f2e extends AG{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class p2e{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class c9{get worldScalingFactor(){return this._worldScalingFactor}set worldScalingFactor(e){const t=this._worldScalingFactor;this._worldScalingFactor=e,this.onWorldScaleFactorChangedObservable.notifyObservers({previousScaleFactor:t,newScaleFactor:e})}constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new Ae,this.onXRReferenceSpaceChanged=new Ae,this.onXRSessionEnded=new Ae,this.onXRSessionInit=new Ae,this.onXRReferenceSpaceInitialized=new Ae,this.onXRReady=new Ae,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new Ae(void 0,!0),this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),e.onDisposeObservable.addOnce(()=>{this.dispose()})}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),(e=this._engine)==null||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{de.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){var i;return((i=this._baseLayerRTTProvider)==null?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return((t=this._baseLayerRTTProvider)==null?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return((t=this._baseLayerRTTProvider)==null?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new p2e(this):(e=e||l9.GetDefaults(t),e.canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new u2e(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then(i=>(this.session=i,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(i),this.session.addEventListener("end",()=>{var r;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&((r=this._baseLayerRTTProvider)==null||r.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return c9.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;!this.inXRSession||!this._engine||(this._engine.customAnimationFrameRequester={requestAnimationFrame:t=>this.session.requestAnimationFrame(t),renderFunction:(t,i)=>{var r;if(!(!this.inXRSession||!this._engine)&&(this.currentFrame=i,this.currentTimestamp=t,i)){this.inXRFrameLoop=!0;const s=((r=this._baseLayerRTTProvider)==null?void 0:r.getFramebufferDimensions())||null;this._engine.framebufferDimensionsObject!==s&&(this._engine.framebufferDimensionsObject=s),this.onXRFrameObservable.notifyObservers(i),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=((e=this._baseLayerRTTProvider)==null?void 0:e.getFramebufferDimensions())||null,this.onXRFrameObservable.addOnce(()=>{this.onXRReady.notifyObservers(this)}),typeof window<"u"&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then(t=>t,t=>(de.Error("XR.requestReferenceSpace failed for the following reason: "),de.Error(t),de.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(i=>{const r=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return i.getOffsetReferenceSpace(r)},i=>{throw de.Error(i),'XR initialization failed: required "viewer" reference space type not supported.'}))).then(t=>this.session.requestReferenceSpace("viewer").then(i=>(this.viewerReferenceSpace=i,t))).then(t=>(this.referenceSpace=this.baseReferenceSpace=t,this.onXRReferenceSpaceInitialized.notifyObservers(t),this.referenceSpace))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&((t=this._baseLayerRTTProvider)==null||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=((i=this._baseLayerWrapper)==null?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new d2e(e.baseLayer):new nee(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(i=>{const r=typeof i>"u"?!0:i;return Promise.resolve(r)}).catch(i=>(de.Warn(i),Promise.resolve(!1))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){var e;return(e=this.session)==null?void 0:e.frameRate}get supportedFrameRates(){var e;return(e=this.session)==null?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():(this.inXRSession||!t)&&this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return((e=this._baseLayerWrapper)==null?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return((e=this._baseLayerWrapper)==null?void 0:e.fixedFoveation)||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){var e;return((e=this.session)==null?void 0:e.enabledFeatures)??null}}var to;(function(n){n[n.ENTERING_XR=0]="ENTERING_XR",n[n.EXITING_XR=1]="EXITING_XR",n[n.IN_XR=2]="IN_XR",n[n.NOT_IN_XR=3]="NOT_IN_XR"})(to||(to={}));var Cy;(function(n){n[n.NOT_TRACKING=0]="NOT_TRACKING",n[n.TRACKING_LOST=1]="TRACKING_LOST",n[n.TRACKING=2]="TRACKING"})(Cy||(Cy={}));Se._GroundMeshParser=(n,e)=>F5.Parse(n,e);class F5 extends Se{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);const i=this;i.createOrUpdateSubmeshesOctree&&i.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),r=ie.Matrix[5];i.invertToRef(r);const s=ie.Vector3[8];if(P.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t),o=-(a.x*e+a.z*t+a.w)/a.y;return P.TransformCoordinatesFromFloatsToRef(0,o,0,i,s),s.y}getNormalAtCoordinates(e,t){const i=new P(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const r=this.getWorldMatrix(),s=ie.Matrix[5];r.invertToRef(s);const a=ie.Vector3[8];if(P.TransformCoordinatesFromFloatsToRef(e,0,t,s,a),e=a.x,t=a.z,ethis._maxX||tthis._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return P.TransformNormalFromFloatsToRef(o.x,o.y,o.z,r,i),this}updateCoordinateHeights(){return(!this._heightQuads||this._heightQuads.length==0)&&this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i];let a;return tn.maxHeight){l=!0;const u=n.maxHeight;n.maxHeight=n.minHeight,n.minHeight=u}for(s=0;s<=n.subdivisions;s++)for(a=0;a<=n.subdivisions;a++){const u=new P(a*n.width/n.subdivisions-n.width/2,0,(n.subdivisions-s)*n.height/n.subdivisions-n.height/2),d=(u.x+n.width/2)/n.width*(n.bufferWidth-1)|0,f=(1-(u.z+n.height/2)/n.height)*(n.bufferHeight-1)|0,p=(d+f*n.bufferWidth)*4;let _=n.buffer[p]/255,m=n.buffer[p+1]/255,g=n.buffer[p+2]/255;const v=n.buffer[p+3]/255;l&&(_=1-_,m=1-m,g=1-g);const x=_*o.r+m*o.g+g*o.b;v>=c?u.y=n.minHeight+(n.maxHeight-n.minHeight)*x:u.y=n.minHeight-ni,n.heightBuffer&&(n.heightBuffer[s*(n.subdivisions+1)+a]=u.y),t.push(u.x,u.y,u.z),i.push(0,0,0),r.push(a/n.subdivisions,1-s/n.subdivisions)}for(s=0;s=n.minHeight,m=t[d*3+1]>=n.minHeight,g=t[f*3+1]>=n.minHeight;_&&m&&g&&(e.push(u),e.push(d),e.push(f)),t[p*3+1]>=n.minHeight&&_&&g&&(e.push(p),e.push(u),e.push(f))}et.ComputeNormals(t,e,i);const h=new et;return h.indices=e,h.positions=t,h.normals=i,h.uvs=r,h}function Z6(n,e={},t){const i=new F5(n,t);return i._setReady(!1),i._subdivisionsX=e.subdivisionsX||e.subdivisions||1,i._subdivisionsY=e.subdivisionsY||e.subdivisions||1,i._width=e.width||1,i._height=e.height||1,i._maxX=i._width/2,i._maxZ=i._height/2,i._minX=-i._maxX,i._minZ=-i._maxZ,S0(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function CG(n,e,t=null){const i=new Se(n,t);return aee(e).applyToMesh(i,e.updatable),i}function bG(n,e,t={},i=null){const r=t.width||10,s=t.height||10,a=t.subdivisions||1,o=t.minHeight||0,c=t.maxHeight||1,l=t.colorFilter||new Me(.3,.59,.11),h=t.alphaFilter||0,u=t.updatable,d=t.onReady;i=i||bt.LastCreatedScene;const f=new F5(n,i);f._subdivisionsX=a,f._subdivisionsY=a,f._width=r,f._height=s,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1);let p;t.passHeightBufferInCallback&&(p=new Float32Array((a+1)*(a+1)));const _=(m,g,v)=>{oee({width:r,height:s,subdivisions:a,minHeight:o,maxHeight:c,colorFilter:l,buffer:m,bufferWidth:g,bufferHeight:v,alphaFilter:h,heightBuffer:p}).applyToMesh(f,u),d&&d(f,p),f._setReady(!0)};if(typeof e=="string"){const m=g=>{const v=g.width,x=g.height;if(i.isDisposed)return;const y=i==null?void 0:i.getEngine().resizeImageBitmap(g,v,x);_(y,v,x)};Ee.LoadImage(e,m,t.onError?t.onError:()=>{},i.offlineProvider)}else _(e.data,e.width,e.height);return f}const _7e={CreateGround:Z6,CreateGroundFromHeightMap:bG,CreateTiledGround:CG};et.CreateGround=S0;et.CreateTiledGround=aee;et.CreateGroundFromHeightMap=oee;Se.CreateGround=(n,e,t,i,r,s)=>Z6(n,{width:e,height:t,subdivisions:i,updatable:s},r);Se.CreateTiledGround=(n,e,t,i,r,s,a,o,c)=>CG(n,{xmin:e,zmin:t,xmax:i,zmax:r,subdivisions:s,precision:a,updatable:c},o);Se.CreateGroundFromHeightMap=(n,e,t,i,r,s,a,o,c,l,h)=>bG(n,e,{width:t,height:i,subdivisions:r,minHeight:s,maxHeight:a,updatable:c,onReady:l,alphaFilter:h},o);function EG(n){const e=[],t=[],i=[],r=[],s=n.diameter||1,a=n.thickness||.5,o=(n.tessellation||16)|0,c=n.sideOrientation===0?0:n.sideOrientation||et.DEFAULTSIDE,l=o+1;for(let u=0;u<=o;u++){const d=u/o,f=u*Math.PI*2/o-Math.PI/2,p=ce.Translation(s/2,0,0).multiply(ce.RotationY(f));for(let _=0;_<=o;_++){const m=1-_/o,g=_*Math.PI*2/o+Math.PI,v=Math.cos(g),x=Math.sin(g);let y=new P(v,x,0),C=y.scale(a/2);const b=new Be(d,m);C=P.TransformCoordinates(C,p),y=P.TransformNormal(y,p),t.push(C.x,C.y,C.z),i.push(y.x,y.y,y.z),r.push(b.x,br.UseOpenGLOrientationForUV?1-b.y:b.y);const T=(u+1)%l,S=(_+1)%l;e.push(u*l+_),e.push(u*l+S),e.push(T*l+_),e.push(u*l+S),e.push(T*l+S),e.push(T*l+_)}}et._ComputeSides(c,t,e,i,r,n.frontUVs,n.backUVs);const h=new et;return h.indices=e,h.positions=t,h.normals=i,h.uvs=r,h}function o1(n,e={},t){const i=new Se(n,t);return e.sideOrientation=Se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,EG(e).applyToMesh(i,e.updatable),i}const m7e={CreateTorus:o1};et.CreateTorus=EG;Se.CreateTorus=(n,e,t,i,r,s,a)=>o1(n,{diameter:e,thickness:t,tessellation:i,sideOrientation:a,updatable:s},r);class TG{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=TG._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=o1("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const i=new tt("targetMat",e);i.specularColor=Me.Black(),i.emissiveColor=new Me(.7,.7,.7),i.backFaceCulling=!1,this._gazeTracker.material=i}}_getForwardRay(e){return new Fi(P.Zero(),new P(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}TG._IdCounter=0;class ade extends TG{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new Fi(P.Zero(),P.Forward())}}class g7e{}class eA{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new Ae,this.onAfterEnteringVRObservable=new Ae,this.onExitingVRObservable=new Ae,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=eA.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new P(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new P(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Me(.2,.2,1),this._pickedGazeColor=new Me(0,0,1),this.onNewMeshSelected=new Ae,this.onNewMeshPicked=new Ae,this.onBeforeCameraTeleport=new Ae,this.onAfterCameraTeleport=new Ae,this.onSelectedMeshUnselected=new Ae,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=r=>{r.type!==Io.POSE_ENABLED&&(r.leftStick&&r.onleftstickchanged(s=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(s,this._cameraGazer),this._checkTeleportBackwards(s,this._cameraGazer))}),r.rightStick&&r.onrightstickchanged(s=>{this._teleportationInitialized&&this._checkRotate(s,this._cameraGazer)}),r.type===Io.XBOX&&(r.onbuttondown(s=>{this._interactionsEnabled&&s===Fh.A&&this._cameraGazer._selectionPointerDown()}),r.onbuttonup(s=>{this._interactionsEnabled&&s===Fh.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=P.Zero(),this._workingQuaternion=we.Identity(),this._workingMatrix=ce.Identity(),de.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),!("getVRDisplays"in navigator)&&t.useXR===void 0&&(t.useXR=!0),t.createFallbackVRDeviceOrientationFreeCamera===void 0&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),t.createDeviceOrientationCamera===void 0&&(t.createDeviceOrientationCamera=!0),t.laserToggle===void 0&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new P(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new gG("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof Ln&&this._scene.activeCamera.rotation)){const r=this._scene.activeCamera;r.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(r.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(we.RotationYawPitchRoll(r.rotation.y,r.rotation.x,r.rotation.z)),this._deviceOrientationCamera.rotation=r.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?c9.IsSessionSupportedAsync("immersive-vr").then(r=>{r?(de.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then(s=>{this.xr=s,this.xrTestDone=!0,this._cameraGazer=new ade(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(a=>{switch(a){case to.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case to.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case to.IN_XR:this._hasEnteredVR=!0;break;case to.NOT_IN_XR:this._hasEnteredVR=!1;break}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new yG("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new ade(()=>this.currentVRCamera,e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let s=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+=".babylonVRicon.vrdisplaypresenting { display: none; }";const a=document.createElement("style");a.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(a),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode||this.enterVR()});const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=r=>{r.keyCode===27&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())},ft.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new fme,this._circleEase.setEasingMode(Un.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(r=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&r.event.pointerType==="mouse"&&(r.type===ft.POINTERDOWN?this._cameraGazer._selectionPointerDown():r.type===ft.POINTERUP&&this._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===to.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){!this._useCustomVRButton&&!this._btnVRDisplayed&&this._btnVR&&(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){!this._btnVR||this._useCustomVRButton||(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr){this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){de.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=we.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}exitVR(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){de.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr){this.xr.baseExperience.state===to.IN_XR&&this.xr.pointerSelection.attach();return}this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>this._isTeleportationFloor(e)||e.name.indexOf("gazeTracker")===-1&&e.name.indexOf("teleportationTarget")===-1&&e.name.indexOf("torusTeleportation")===-1?this.raySelectionPredicate(e):!1,this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);t!==-1&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const i=e.floorMeshes||[];if(!i.length){const r=this._scene.getMeshByName(e.floorMeshName);r&&i.push(r)}if(this.xr){i.forEach(r=>{this.xr.teleportation.addFloorMesh(r)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}else if(!this.xrTestDone){const r=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(r),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(r);return}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),e.easingFunction!==void 0&&(this._teleportationEasing=e.easingFunction);const t=new Ji;t.vignetteColor=new Ze(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const i=we.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),r=this.currentVRCamera.position;i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,we.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),P.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const s=new Fi(r,this._workingVector),a=this._scene.pickWithRay(s,this._raySelectionPredicate);a&&a.pickedPoint&&a.pickedMesh&&this._isTeleportationFloor(a.pickedMesh)&&a.distance<5&&this.teleportCamera(a.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=Z6("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=512,t=new Id("DynamicTexture",e,this._scene,!0);t.hasAlpha=!0;const i=t.getContext(),r=e/2,s=e/2,a=200;i.beginPath(),i.arc(r,s,a,0,2*Math.PI,!1),i.fillStyle=this._teleportationFillColor,i.fill(),i.lineWidth=10,i.strokeStyle=this._teleportationBorderColor,i.stroke(),i.closePath(),t.update();const o=new tt("TextPlaneMaterial",this._scene);o.diffuseTexture=t,this._teleportationTarget.material=o;const c=o1("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);c.isPickable=!1,c.parent=this._teleportationTarget;const l=new ke("animationInnerCircle","position.y",30,ke.ANIMATIONTYPE_FLOAT,ke.ANIMATIONLOOPMODE_CYCLE),h=[];h.push({frame:0,value:0}),h.push({frame:30,value:.4}),h.push({frame:60,value:0}),l.setKeys(h);const u=new BJ;u.setEasingMode(Un.EASINGMODE_EASEINOUT),l.setEasingFunction(u),c.animations=[],c.animations.push(l),this._scene.beginAnimation(c,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof El))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=we.FromRotationMatrix(ce.RotationY(Math.PI/4*this._rotationAngle)),i=new ke("animationRotation","rotationQuaternion",90,ke.ANIMATIONTYPE_QUATERNION,ke.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const s=new ke("animationPP","vignetteWeight",90,ke.ANIMATIONTYPE_FLOAT,ke.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:4}),a.push({frame:6,value:0}),s.setKeys(a),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);const o=new ke("animationPP2","vignetteStretch",90,ke.ANIMATIONTYPE_FLOAT,ke.ANIMATIONLOOPMODE_CONSTANT),c=[];c.push({frame:0,value:0}),c.push({frame:3,value:10}),c.push({frame:6,value:0}),o.setKeys(c),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){if(!(this.currentVRCamera instanceof El))return;this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector);const t=90;let i,r;if(this._teleportationMode==eA.TELEPORTATIONMODE_CONSTANTSPEED){r=t;const d=P.Distance(this.currentVRCamera.position,this._workingVector);i=this._teleportationSpeed/d}else r=Math.round(this._teleportationTime*t/1e3),i=1;this.currentVRCamera.animations=[];const s=new ke("animationCameraTeleportation","position",t,ke.ANIMATIONTYPE_VECTOR3,ke.ANIMATIONLOOPMODE_CONSTANT),a=[{frame:0,value:this.currentVRCamera.position},{frame:r,value:this._workingVector}];s.setKeys(a),s.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(s),this._postProcessMove.animations=[];const o=Math.round(r/2),c=new ke("animationPP","vignetteWeight",t,ke.ANIMATIONTYPE_FLOAT,ke.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:o,value:8}),l.push({frame:r,value:0}),c.setKeys(l),this._postProcessMove.animations.push(c);const h=new ke("animationPP2","vignetteStretch",t,ke.ANIMATIONTYPE_FLOAT,ke.ANIMATIONLOOPMODE_CONSTANT),u=[];u.push({frame:0,value:0}),u.push({frame:o,value:10}),u.push({frame:r,value:0}),h.setKeys(u),this._postProcessMove.animations.push(h),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,r,!1,i,()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)}),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}eA.TELEPORTATIONMODE_CONSTANTTIME=0;eA.TELEPORTATIONMODE_CONSTANTSPEED=1;const v7e=(n,e,t,i)=>!(n.x>t.x+i||t.x-i>e.x||n.y>t.y+i||t.y-i>e.y||n.z>t.z+i||t.z-i>e.z),_S=function(){const n={root:0,found:!1};return function(e,t,i,r){n.root=0,n.found=!1;const s=t*t-4*e*i;if(s<0)return n;const a=Math.sqrt(s);let o=(-t-a)/(2*e),c=(-t+a)/(2*e);if(o>c){const l=c;c=o,o=l}return o>0&&o0&&c=0)}_canDoCollision(e,t,i,r){const s=P.Distance(this._basePointWorld,e),a=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+a+t||!v7e(i,r,this._basePointWorld,this._velocityWorldLength+a))}_testTriangle(e,t,i,r,s,a,o){let c,l=!1;t||(t=[]),t[e]||(t[e]=new yl(0,0,0,0),t[e].copyFromPoints(i,r,s));const h=t[e];if(!a&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;const u=h.signedDistanceTo(this._basePoint),d=P.Dot(h.normal,this._velocity);if(h9.DoubleSidedCheck&&d>1e-4)return;if(d==0){if(Math.abs(u)>=1)return;l=!0,c=0}else{c=(-1-u)/d;let _=(1-u)/d;if(c>_){const m=_;_=c,c=m}if(c>1||_<0)return;c<0&&(c=0),c>1&&(c=1)}this._collisionPoint.copyFromFloats(0,0,0);let f=!1,p=1;if(l||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(c,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,s,h.normal)&&(f=!0,p=c,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!f){let _=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let m=2*P.Dot(this._velocity,this._tempVector),g=this._tempVector.lengthSquared()-1,v=_S(_,m,g,p);v.found&&(p=v.root,f=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),m=2*P.Dot(this._velocity,this._tempVector),g=this._tempVector.lengthSquared()-1,v=_S(_,m,g,p),v.found&&(p=v.root,f=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(s,this._tempVector),m=2*P.Dot(this._velocity,this._tempVector),g=this._tempVector.lengthSquared()-1,v=_S(_,m,g,p),v.found&&(p=v.root,f=!0,this._collisionPoint.copyFrom(s)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let x=this._edge.lengthSquared(),y=P.Dot(this._edge,this._velocity),C=P.Dot(this._edge,this._baseToVertex);if(_=x*-this._velocitySquaredLength+y*y,m=2*(x*P.Dot(this._velocity,this._baseToVertex)-y*C),g=x*(1-this._baseToVertex.lengthSquared())+C*C,v=_S(_,m,g,p),v.found){const b=(y*v.root-C)/x;b>=0&&b<=1&&(p=v.root,f=!0,this._edge.scaleInPlace(b),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),x=this._edge.lengthSquared(),y=P.Dot(this._edge,this._velocity),C=P.Dot(this._edge,this._baseToVertex),_=x*-this._velocitySquaredLength+y*y,m=2*(x*P.Dot(this._velocity,this._baseToVertex)-y*C),g=x*(1-this._baseToVertex.lengthSquared())+C*C,v=_S(_,m,g,p),v.found){const b=(y*v.root-C)/x;b>=0&&b<=1&&(p=v.root,f=!0,this._edge.scaleInPlace(b),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),x=this._edge.lengthSquared(),y=P.Dot(this._edge,this._velocity),C=P.Dot(this._edge,this._baseToVertex),_=x*-this._velocitySquaredLength+y*y,m=2*(x*P.Dot(this._velocity,this._baseToVertex)-y*C),g=x*(1-this._baseToVertex.lengthSquared())+C*C,v=_S(_,m,g,p),v.found){const b=(y*v.root-C)/x;b>=0&&b<=1&&(p=v.root,f=!0,this._edge.scaleInPlace(b),s.addToRef(this._edge,this._collisionPoint))}}if(f){const _=p*p*this._velocitySquaredLength;(!this.collisionFound||_=r){s.copyFrom(e);return}const c=a?a.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=a&&a.surroundingMeshes||this._scene.meshes;for(let h=0;hnew _2e;class tA{constructor(e,t,i,r=""){this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new Ae,this.onErrorObservable=new Ae,this.onBindObservable=new Ae,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=Vs.WGSL,this.name=e,this._key=r,this._engine=i,this.uniqueId=tA._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=Re.GetShadersStore(this._shaderLanguage),this._shaderRepository=Re.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Re.GetIncludesShadersStore(this._shaderLanguage);let s;const a=io()?this._engine.getHostDocument():null;e.computeSource?s="source:"+e.computeSource:e.computeElement?(s=a?a.getElementById(e.computeElement):null,s||(s=e.computeElement)):s=e.compute||e;const o={defines:this.defines.split(` `),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(s,"Compute","",c=>{Cd.Initialize(o),Cd.PreProcess(c,o,l=>{this._rawComputeSourceCode=c,t.processFinalCode&&(l=t.processFinalCode(l));const h=Cd.Finalize(l,"",o);this._useFinalCode(h.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+` `+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){if(typeof HTMLElement<"u"&&e instanceof HTMLElement){const a=NO(e);r(a);return}if(e.substr(0,7)==="source:"){r(e.substr(7));return}if(e.substr(0,7)==="base64:"){const a=window.atob(e.substr(7));r(a);return}if(this._shaderStore[e+t+"Shader"]){r(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){r(this._shaderStore[e+i+"Shader"]);return}let s;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?s=e:s=this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}get computeSourceCode(){var e;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:((e=this._pipelineContext)==null?void 0:e._getComputeShaderCode())??this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,()=>{this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t)}),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t){const i=/COMPUTE SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const s=t.match(i);if(s&&s.length===2){const a=parseInt(s[1]),o=e.split(` `,-1);o.length>=a&&(r=`Offending line [${a}] in compute code: ${o[a-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,de.Error("Unable to compile compute effect:"),de.Error(`Defines: `+this.defines),tA.LogShaderCodeOnCompilationError){let r=null,s=null;(i=this._pipelineContext)!=null&&i._getComputeShaderCode()&&([s,r]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),s&&(de.Error("Compute code:"),de.Error(s))),r&&de.Error(r)}de.Error("Error: "+this._compilationError),t&&(this._pipelineContext=t,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this))}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){Re.GetShadersStore(Vs.WGSL)[`${e}ComputeShader`]=t}}tA._UniqueIdSeed=0;tA.LogShaderCodeOnCompilationError=!0;var xs;(function(n){n[n.Texture=0]="Texture",n[n.StorageTexture=1]="StorageTexture",n[n.UniformBuffer=2]="UniformBuffer",n[n.StorageBuffer=3]="StorageBuffer",n[n.TextureWithoutSampler=4]="TextureWithoutSampler",n[n.Sampler=5]="Sampler",n[n.ExternalTexture=6]="ExternalTexture",n[n.DataBuffer=7]="DataBuffer"})(xs||(xs={}));yt.prototype.createComputeEffect=function(n,e){throw new Error("createComputeEffect: This engine does not support compute shaders!")};yt.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")};yt.prototype.createComputeContext=function(){};yt.prototype.computeDispatch=function(n,e,t,i,r,s,a){throw new Error("computeDispatch: This engine does not support compute shaders!")};yt.prototype.areAllComputeEffectsReady=function(){return!0};yt.prototype.releaseComputeEffects=function(){};yt.prototype._prepareComputePipelineContext=function(n,e,t,i,r){};yt.prototype._rebuildComputeEffects=function(){};yt.prototype._executeWhenComputeStateIsCompiled=function(n,e){e()};yt.prototype._releaseComputeEffect=function(n){};yt.prototype._deleteComputePipelineContext=function(n){};class lee{constructor(){this._gpuTimeInFrameId=-1,this.counter=new Fa}_addDuration(e,t){e{const a=()=>{this.dispatch(e,t,i)?s():setTimeout(a,r)};a()})}serialize(){const e=Qe.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],r=i.object;switch(i.type){case xs.Texture:case xs.TextureWithoutSampler:case xs.StorageTexture:{const s=r.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type});break}case xs.UniformBuffer:break}}return e}static Parse(e,t,i){const r=Qe.Parse(()=>new Vm(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(const s in e.textures){const a=e.bindings[s],o=ve.Parse(e.textures[s],t,i);a.type===xs.Texture?r.setTexture(s,o):a.type===xs.TextureWithoutSampler?r.setTexture(s,o,!1):r.setStorageTexture(s,o)}return r}static _BufferIsDataBuffer(e){return e.underlyingResource!==void 0}}B([K()],Vm.prototype,"name",void 0);B([K()],Vm.prototype,"fastMode",void 0);xe("BABYLON.ComputeShader",Vm);class HD{constructor(e,t,i,r,s,a){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=r,this._maxDepth=s,this._creationFunc=a,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks){for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const t=n.getBoundingInfo();!n.isBlocked&&t.boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(n)};iA.CreationFuncForSubMeshes=(n,e)=>{n.getBoundingInfo().boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(n)};pt.prototype.createOrUpdateSelectionOctree=function(n=64,e=2){let t=this._getComponent(it.NAME_OCTREE);t||(t=new cee(this),this._addComponent(t)),this._selectionOctree||(this._selectionOctree=new iA(iA.CreationFuncForMeshes,n,e));const i=this.getWorldExtends();return this._selectionOctree.update(i.min,i.max,this.meshes),this._selectionOctree};Object.defineProperty(pt.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0});di.prototype.createOrUpdateSubmeshesOctree=function(n=64,e=2){const t=this.getScene();let i=t._getComponent(it.NAME_OCTREE);i||(i=new cee(t),t._addComponent(i)),this._submeshesOctree||(this._submeshesOctree=new iA(iA.CreationFuncForSubMeshes,n,e)),this.computeWorldMatrix(!0);const s=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(s.minimumWorld,s.maximumWorld,this.subMeshes),this._submeshesOctree};class cee{constructor(e){this.name=it.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new Fi(P.Zero(),new P(1,1,1)),e=e||bt.LastCreatedScene,e&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=t=>this.getActiveSubMeshCandidates(t),this.scene.getCollidingSubMeshCandidates=(t,i)=>this.getCollidingSubMeshCandidates(t,i),this.scene.getIntersectingSubMeshCandidates=(t,i)=>this.getIntersectingSubMeshCandidates(t,i))}register(){this.scene.onMeshRemovedObservable.add(e=>{const t=this.scene.selectionOctree;if(t!=null){const i=t.dynamicContent.indexOf(e);i!==-1&&t.dynamicContent.splice(i,1)}}),this.scene.onMeshImportedObservable.add(e=>{const t=this.scene.selectionOctree;t!=null&&t.addMesh(e)})}getActiveMeshCandidates(){var e;return((e=this.scene._selectionOctree)==null?void 0:e.select(this.scene.frustumPlanes))||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(Fi.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function SG(n){const e=n.height||2;let t=n.diameterTop===0?0:n.diameterTop||n.diameter||1,i=n.diameterBottom===0?0:n.diameterBottom||n.diameter||1;t=t||1e-5,i=i||1e-5;const r=(n.tessellation||24)|0,s=(n.subdivisions||1)|0,a=!!n.hasRings,o=!!n.enclose,c=n.cap===0?0:n.cap||Se.CAP_ALL,l=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,h=n.sideOrientation===0?0:n.sideOrientation||et.DEFAULTSIDE,u=n.faceUV||new Array(3),d=n.faceColors,f=l!==1&&o?2:0,p=a?s:1,_=2+(1+f)*p;let m;for(m=0;m<_;m++)d&&d[m]===void 0&&(d[m]=new Ze(1,1,1,1));for(m=0;m<_;m++)u&&u[m]===void 0&&(u[m]=new Ct(0,0,1,1));const g=[],v=[],x=[],y=[],C=[],b=Math.PI*2*l/r;let T,S,N;const D=(i-t)/2/e,M=P.Zero(),I=P.Zero(),R=P.Zero(),O=P.Zero(),H=P.Zero(),G=$n.Y;let Q,$,V,j=1,k=1,z=0,Y=0;for(Q=0;Q<=s;Q++)for(S=Q/s,N=(S*(t-i)+i)/2,j=a&&Q!==0&&Q!==s?2:1,V=0;V{const ue=le?t/2:i/2;if(ue===0)return;let L,F,W;const te=le?u[_-1]:u[0];let oe=null;d&&(oe=le?d[_-1]:d[0]);const ne=v.length/3,pe=le?e/2:-e/2,ye=new P(0,pe,0);v.push(ye.x,ye.y,ye.z),x.push(0,le?1:-1,0);const Pe=te.y+(te.w-te.y)*.5;y.push(te.x+(te.z-te.x)*.5,br.UseOpenGLOrientationForUV?1-Pe:Pe),oe&&C.push(oe.r,oe.g,oe.b,oe.a);const Fe=new Be(.5,.5);for(W=0;W<=r;W++){L=Math.PI*2*W*l/r;const He=Math.cos(-L),ot=Math.sin(-L);F=new P(He*ue,pe,ot*ue);const Xe=new Be(He*Fe.x+.5,ot*Fe.y+.5);v.push(F.x,F.y,F.z),x.push(0,le?1:-1,0);const gt=te.y+(te.w-te.y)*Xe.y;y.push(te.x+(te.z-te.x)*Xe.x,br.UseOpenGLOrientationForUV?1-gt:gt),oe&&C.push(oe.r,oe.g,oe.b,oe.a)}for(W=0;W((a===void 0||!(a instanceof pt))&&(a!==void 0&&(c=o||Se.DEFAULTSIDE,o=a),a=s,s=1),dc(n,{height:e,diameterTop:t,diameterBottom:i,tessellation:r,subdivisions:s,sideOrientation:c,updatable:o},a));Lr.AddNodeConstructor("Light_Type_3",(n,e)=>()=>new Vf(n,P.Zero(),e));class Vf extends Ui{constructor(e,t,i){super(e,i),this.groundColor=new Me(0,0,0),this.direction=t||P.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=P.Normalize(e.subtract(P.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=P.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=P.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=ce.Identity()),this._worldMatrix}getTypeID(){return Ui.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}B([or()],Vf.prototype,"groundColor",void 0);B([Js()],Vf.prototype,"direction",void 0);class Or{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?t=this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:t=this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Vf("shared gizmo light",new P(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Me.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return Or._DefaultUtilityLayer==null?Or._CreateDefaultUtilityLayerFromScene(bt.LastCreatedScene):Or._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Or._DefaultUtilityLayer=new Or(e),Or._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{Or._DefaultUtilityLayer=null}),Or._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return Or._DefaultKeepDepthUtilityLayer==null&&(Or._DefaultKeepDepthUtilityLayer=new Or(bt.LastCreatedScene),Or._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Or._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{Or._DefaultKeepDepthUtilityLayer=null})),Or._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new Ae,this.utilityLayerScene=new pt(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add(i=>{if(!this.utilityLayerScene.activeCamera||!this.pickingEnabled||!this.processAllEvents&&i.type!==ft.POINTERMOVE&&i.type!==ft.POINTERUP&&i.type!==ft.POINTERDOWN&&i.type!==ft.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const r=i.event;if(e.isPointerCaptured(r.pointerId)){this._pointerCaptures[r.pointerId]=!1;return}const s=o=>{let c=null;if(i.nearInteractionPickingInfo)i.nearInteractionPickingInfo.pickedMesh.getScene()==o?c=i.nearInteractionPickingInfo:c=new Ro;else if(o!==this.utilityLayerScene&&i.originalPickingInfo)c=i.originalPickingInfo;else{let l=null;this._renderCamera&&(l=o._activeCamera,o._activeCamera=this._renderCamera,i.ray=null),c=i.ray?o.pickWithRay(i.ray):o.pick(e.pointerX,e.pointerY),l&&(o._activeCamera=l)}return c},a=s(this.utilityLayerScene);if(!i.ray&&a&&(i.ray=a.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(i),this.onlyCheckPointerDownEvents&&i.type!=ft.POINTERDOWN){i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new pd(i.type,i.event,a),i.type),i.type===ft.POINTERUP&&this._pointerCaptures[r.pointerId]&&(this._pointerCaptures[r.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)a&&a.hit&&(i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new pd(i.type,i.event,a),i.type),i.skipOnPointerObservable=!0);else{const o=s(e),c=i.event;o&&a&&(a.distance===0&&o.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(o.pickedMesh)?(this._notifyObservers(i,o,c),i.skipOnPointerObservable=!0):i.type===ft.POINTERDOWN?this._pointerCaptures[c.pointerId]=!0:(i.type===ft.POINTERMOVE||i.type===ft.POINTERUP)&&(this._lastPointerEvents[c.pointerId]&&(this.onPointerOutObservable.notifyObservers(c.pointerId),delete this._lastPointerEvents[c.pointerId]),this._notifyObservers(i,o,c)):!this._pointerCaptures[c.pointerId]&&(a.distance0)):!this._pointerCaptures[c.pointerId]&&a.distance>=o.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(o.pickedMesh)?(this._notifyObservers(i,o,c),i.skipOnPointerObservable=!0):((i.type===ft.POINTERMOVE||i.type===ft.POINTERUP)&&this._lastPointerEvents[c.pointerId]&&(this.onPointerOutObservable.notifyObservers(c.pointerId),delete this._lastPointerEvents[c.pointerId]),this._notifyObservers(i,a,c))),i.type===ft.POINTERUP&&this._pointerCaptures[c.pointerId]&&(this._pointerCaptures[c.pointerId]=!1))}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add(i=>{this.shouldRender&&i==this.getRenderCamera()&&this.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(()=>{this.dispose()}),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new pd(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}Or._DefaultUtilityLayer=null;Or._DefaultKeepDepthUtilityLayer=null;var GD;(function(n){n[n.Origin=0]="Origin",n[n.Pivot=1]="Pivot"})(GD||(GD={}));var t4;(function(n){n[n.World=0]="World",n[n.Local=1]="Local"})(t4||(t4={}));class mn{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach(t=>{t.dispose()}),e.parent=this._rootMesh,this._customMeshSet=!0}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){this._additionalTransformNode=e}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=e==t4.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=Or.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=GD.Origin,this._updateScale=!0,this._coordinatesMode=t4.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=ce.RotationY(Math.PI),this._rootMesh=new Se("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=we.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(()=>{this._update()})}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==GD.Pivot&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new P(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const i=e._isMesh||e.getClassName()==="AbstractMesh"||e.getClassName()==="TransformNode"||e.getClassName()==="InstancedMesh"?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,mn.PreserveScaling?i:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,ie.Vector3[0]);let r=this.scaleRatio;if(t.mode==Rt.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){const s=t.orthoTop-t.orthoBottom;r*=s}}else{const s=t.getScene().useRightHandedSystem?P.RightHandedForwardReadOnly:P.LeftHandedForwardReadOnly,a=t.getDirection(s);r*=P.Dot(ie.Vector3[0],a)}this._rootMesh.scaling.setAll(r),e._getWorldMatrixDeterminant()<0&&!mn.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),ie.Matrix[0]),ie.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix()){e.getPivotMatrix().invertToRef(ie.Matrix[5]),ie.Matrix[5].multiplyToRef(t,i);return}i.copyFrom(t)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const s=ie.Matrix[1];e.parent._worldMatrix.invertToRef(s),this._attachedNode._worldMatrix.multiplyToRef(s,ie.Matrix[0]),t=ie.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,ie.Matrix[1]),i=ie.Matrix[1]):i=t,i.decompose(ie.Vector3[1],ie.Quaternion[0],ie.Vector3[0]),this._attachedNode.getClassName()==="FreeCamera"||this._attachedNode.getClassName()==="FlyCamera"||this._attachedNode.getClassName()==="ArcFollowCamera"||this._attachedNode.getClassName()==="TargetCamera"||this._attachedNode.getClassName()==="TouchCamera"||this._attachedNode.getClassName()==="UniversalCamera"){const s=this._attachedNode;s.rotation=ie.Quaternion[0].toEulerAngles(),s.rotationQuaternion&&(s.rotationQuaternion.copyFrom(ie.Quaternion[0]),s.rotationQuaternion.normalize())}e.position.copyFrom(ie.Vector3[0])}else if(this._attachedNode._isMesh||this._attachedNode.getClassName()==="AbstractMesh"||this._attachedNode.getClassName()==="TransformNode"||this._attachedNode.getClassName()==="InstancedMesh"){const e=this._attachedNode;if(e.parent){const t=ie.Matrix[0],i=ie.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const r=ie.Matrix[4];if(this._handlePivotMatrixInverse(e,i,r),r.decompose(ie.Vector3[0],ie.Quaternion[0],e.position,mn.PreserveScaling?e:void 0,mn.UseAbsoluteScaling),ie.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const s=ie.Quaternion[1];we.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,s);const a=ie.Matrix[2];ce.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,a);const o=ie.Matrix[2];s.toRotationMatrix(o);const c=e.getPivotMatrix(),l=ie.Matrix[3];c.invertToRef(l),c.multiplyToRef(a,ie.Matrix[4]),ie.Matrix[4].multiplyToRef(o,ie.Matrix[5]),ie.Matrix[5].multiplyToRef(l,ie.Matrix[6]),ie.Matrix[6].getTranslationToRef(ie.Vector3[1]),e.position.subtractInPlace(ie.Vector3[1])}}else{const t=ie.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(ie.Vector3[0],ie.Quaternion[0],e.position,mn.PreserveScaling?e:void 0,mn.UseAbsoluteScaling)}ie.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(ie.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(ie.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=ie.Quaternion[0].toEulerAngles())}else if(this._attachedNode.getClassName()==="Bone"){const e=this._attachedNode,t=e.getParent();if(t){const i=ie.Matrix[0],r=ie.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r),e.getLocalMatrix().copyFrom(r)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===Ui.LIGHTTYPEID_DIRECTIONALLIGHT||t===Ui.LIGHTTYPEID_SPOTLIGHT||t===Ui.LIGHTTYPEID_POINTLIGHT){const i=e.parent;if(i){const r=ie.Matrix[0],s=ie.Matrix[1];i.getWorldMatrix().invertToRef(r),e.getWorldMatrix().multiplyToRef(r,s),s.decompose(void 0,ie.Quaternion[0],ie.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,ie.Quaternion[0],ie.Vector3[0]);e.position=new P(ie.Vector3[0].x,ie.Vector3[0].y,ie.Vector3[0].z),e.direction&&(e.direction=new P(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach(i=>{i.material=t,i.color&&(i.color=t.diffuseColor)})}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add(s=>{var a,o;if(s.pickInfo){if(s.type===ft.POINTERMOVE){if(i)return;t.forEach(c=>{var l,h;if(c.colliderMeshes&&c.gizmoMeshes){const u=((h=c.colliderMeshes)==null?void 0:h.indexOf((l=s==null?void 0:s.pickInfo)==null?void 0:l.pickedMesh))!=-1,d=c.dragBehavior.enabled?u||c.active?c.hoverMaterial:c.material:c.disableMaterial;c.gizmoMeshes.forEach(f=>{f.material=d,f.color&&(f.color=d.diffuseColor)})}})}if(s.type===ft.POINTERDOWN&&t.has((a=s.pickInfo.pickedMesh)==null?void 0:a.parent)){i=!0;const c=t.get((o=s.pickInfo.pickedMesh)==null?void 0:o.parent);c.active=!0,t.forEach(l=>{var d,f;const u=(((f=l.colliderMeshes)==null?void 0:f.indexOf((d=s==null?void 0:s.pickInfo)==null?void 0:d.pickedMesh))!=-1||l.active)&&l.dragBehavior.enabled?l.hoverMaterial:l.disableMaterial;l.gizmoMeshes.forEach(p=>{p.material=u,p.color&&(p.color=u.diffuseColor)})})}s.type===ft.POINTERUP&&t.forEach(c=>{c.active=!1,i=!1,c.gizmoMeshes.forEach(l=>{l.material=c.dragBehavior.enabled?c.material:c.disableMaterial,l.color&&(l.color=c.material.diffuseColor)})})}})}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}mn.PreserveScaling=!1;mn.UseAbsoluteScaling=!0;class gd extends mn{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,r=!1){const s=new Et("arrow",e),a=dc("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=dc("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return a.parent=s,a.material=t,a.rotation.x=Math.PI/2,a.position.z+=.3,o.parent=s,o.material=t,o.position.z+=.275/2,o.rotation.x=Math.PI/2,r&&(o.visibility=0,a.visibility=0),s}static _CreateArrowInstance(e,t){const i=new Et("arrow",e);for(const r of t.getChildMeshes()){const s=r.createInstance(r.name);s.parent=i}return i}constructor(e,t=Me.Gray(),i=Or.DefaultUtilityLayer,r=null,s=1,a=Me.Yellow(),o=Me.Gray()){var p;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ae,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=r,this._coloredMaterial=new tt("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Me(.1,.1,.1)),this._hoverMaterial=new tt("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._disableMaterial=new tt("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4;const c=gd._CreateArrow(i.utilityLayerScene,this._coloredMaterial,s),l=gd._CreateArrow(i.utilityLayerScene,this._coloredMaterial,s+4,!0);this._gizmoMesh=new Se("",i.utilityLayerScene),this._gizmoMesh.addChild(c),this._gizmoMesh.addChild(l),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let h=0;const u={snapDistance:0};this.dragBehavior=new Ao({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add(_=>{if(this.attachedNode){let m=!1;if(this.snapDistance==0)this.attachedNode.getWorldMatrix().getTranslationToRef(ie.Vector3[2]),ie.Vector3[2].addInPlace(_.delta),this.dragBehavior.validateDrag(ie.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(_.delta.x,_.delta.y,_.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(_.delta.x,_.delta.y,_.delta.z),this.attachedNode.updateCache(),m=!0);else if(h+=_.dragDistance,Math.abs(h)>this.snapDistance){const g=Math.floor(Math.abs(h)/this.snapDistance);h=h%this.snapDistance,_.delta.normalizeToRef(ie.Vector3[1]),ie.Vector3[1].scaleInPlace(this.snapDistance*g),this.attachedNode.getWorldMatrix().getTranslationToRef(ie.Vector3[2]),ie.Vector3[2].addInPlace(ie.Vector3[1]),this.dragBehavior.validateDrag(ie.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(ie.Vector3[1].x,ie.Vector3[1].y,ie.Vector3[1].z),this.attachedNode.updateCache(),u.snapDistance=this.snapDistance*g*Math.sign(h),this.onSnapObservable.notifyObservers(u),m=!0)}m&&this._matrixChanged()}}),this.dragBehavior.onDragStartObservable.add(()=>{this._dragging=!0}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1});const d=i._getSharedGizmoLight();d.includedOnlyMeshes=d.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const f={gizmoMeshes:c.getChildMeshes(),colliderMeshes:l.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(p=this._parent)==null||p.addToAxisCache(l,f),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(_=>{var m;if(!this._customMeshSet&&(this._isHovered=f.colliderMeshes.indexOf((m=_==null?void 0:_.pickInfo)==null?void 0:m.pickedMesh)!=-1,!this._parent)){const g=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(f.gizmoMeshes,g)}}),this.dragBehavior.onEnabledObservable.add(_=>{this._setGizmoMeshMaterial(f.gizmoMeshes,_?f.material:f.disableMaterial)})}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}}class Dm{get scaleLines(){return this._scaleLines}set scaleLines(e){this._scaleLines=e,this._xAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._yAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._zAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor)}get xAxis(){return this._xAxis}get yAxis(){return this._yAxis}get zAxis(){return this._zAxis}constructor(e,t=1,i=2,r,s,a,o=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this._scaleLines=1,e=e||bt.LastCreatedScene,!!e){if(!r){const c=new tt("xAxisMaterial",e);c.disableLighting=!0,c.emissiveColor=Me.Red().scale(.5),r=gd._CreateArrow(e,c,o)}if(!s){const c=new tt("yAxisMaterial",e);c.disableLighting=!0,c.emissiveColor=Me.Green().scale(.5),s=gd._CreateArrow(e,c,o)}if(!a){const c=new tt("zAxisMaterial",e);c.disableLighting=!0,c.emissiveColor=Me.Blue().scale(.5),a=gd._CreateArrow(e,c,o)}this._xAxis=r,this._yAxis=s,this._zAxis=a,this.scaleLines=t,i!=null&&(Dm._SetRenderingGroupId(this._xAxis,i),Dm._SetRenderingGroupId(this._yAxis,i),Dm._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new P,P.Right(),P.Up(),P.Forward())}}update(e,t,i,r){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(r)}createInstance(){const e=gd._CreateArrowInstance(this.scene,this._xAxis),t=gd._CreateArrowInstance(this.scene,this._yAxis),i=gd._CreateArrowInstance(this.scene,this._zAxis),r=new Dm(this.scene,this.scaleLines,null,e,t,i);return r._instanced=!0,r}dispose(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null}static _SetRenderingGroupId(e,t){e.getChildMeshes().forEach(i=>{i.renderingGroupId=t})}}class y7e extends Dm{constructor(e,t,i,r=1){super(e,r),this.pos=P.Zero(),this.xaxis=P.Zero(),this.yaxis=P.Zero(),this.zaxis=P.Zero(),this.mesh=i,this.bone=t}update(){if(!this.mesh||!this.bone)return;const e=this.bone;e.getAbsolutePositionToRef(this.mesh,this.pos),e.getDirectionToRef($n.X,this.mesh,this.xaxis),e.getDirectionToRef($n.Y,this.mesh,this.yaxis),e.getDirectionToRef($n.Z,this.mesh,this.zaxis),super.update(this.pos,this.xaxis,this.yaxis,this.zaxis)}dispose(){this.mesh&&(this.mesh=null,this.bone=null,super.dispose())}}Object.defineProperty(pt.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new rA(this)),this._debugLayer},enumerable:!0,configurable:!0});var U$;(function(n){n[n.Properties=0]="Properties",n[n.Debug=1]="Debug",n[n.Statistics=2]="Statistics",n[n.Tools=3]="Tools",n[n.Settings=4]="Settings"})(U$||(U$={}));class rA{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new Ae),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new Ae),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||bt.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add(()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()})}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const i of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(i);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const i of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(i);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...rA.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&(Object.prototype.toString.call(t)=="[object String]"?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){if(typeof INSPECTOR<"u")return INSPECTOR;if(typeof BABYLON<"u"&&typeof BABYLON.Inspector<"u")return BABYLON}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise(t=>{if(typeof this.BJSINSPECTOR>"u"){const i=e&&e.inspectorURL?e.inspectorURL:rA.InspectorURL;Ee.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}rA.InspectorURL=`${Ee._DefaultCdnUrl}/v${De.Version}/inspector/babylon.inspector.bundle.js`;rA.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};function MG(n){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[];let s=[];const a=n.width||n.size||1,o=n.height||n.size||1,c=n.depth||n.size||1,l=n.wrap||!1;let h=n.topBaseAt===void 0?1:n.topBaseAt,u=n.bottomBaseAt===void 0?0:n.bottomBaseAt;h=(h+4)%4,u=(u+4)%4;const d=[2,0,3,1],f=[2,0,1,3];let p=d[h],_=f[u],m=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],m=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let T=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],S=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const N=[17,18,19,16],D=[22,23,20,21];for(;p>0;)T.unshift(T.pop()),N.unshift(N.pop()),p--;for(;_>0;)S.unshift(S.pop()),D.unshift(D.pop()),_--;T=T.flat(),S=S.flat(),m=m.concat(T).concat(S),t.push(N[0],N[2],N[3],N[0],N[1],N[2]),t.push(D[0],D[2],D[3],D[0],D[1],D[2])}const g=[a/2,o/2,c/2];s=m.reduce((T,S,N)=>T.concat(S*g[N%3]),[]);const v=n.sideOrientation===0?0:n.sideOrientation||et.DEFAULTSIDE,x=n.faceUV||new Array(6),y=n.faceColors,C=[];for(let T=0;T<6;T++)x[T]===void 0&&(x[T]=new Ct(0,0,1,1)),y&&y[T]===void 0&&(y[T]=new Ze(1,1,1,1));for(let T=0;T<6;T++)if(r.push(x[T].z,br.UseOpenGLOrientationForUV?1-x[T].w:x[T].w),r.push(x[T].x,br.UseOpenGLOrientationForUV?1-x[T].w:x[T].w),r.push(x[T].x,br.UseOpenGLOrientationForUV?1-x[T].y:x[T].y),r.push(x[T].z,br.UseOpenGLOrientationForUV?1-x[T].y:x[T].y),y)for(let S=0;S<4;S++)C.push(y[T].r,y[T].g,y[T].b,y[T].a);et._ComputeSides(v,s,t,i,r,n.frontUVs,n.backUVs);const b=new et;if(b.indices=t,b.positions=s,b.normals=i,b.uvs=r,y){const T=v===et.DOUBLESIDE?C.concat(C):C;b.colors=T}return b}function m2e(n){const e=n.width||n.size||1,t=n.height||n.size||1,i=n.depth||n.size||1,r=(n.widthSegments||n.segments||1)|0,s=(n.heightSegments||n.segments||1)|0,a=(n.depthSegments||n.segments||1)|0,o=new ce,c=new ce,l=new ce,h=S0({width:e,height:i,subdivisionsX:r,subdivisionsY:a});ce.TranslationToRef(0,-t/2,0,c),ce.RotationZToRef(Math.PI,o),o.multiplyToRef(c,l),h.transform(l);const u=S0({width:e,height:i,subdivisionsX:r,subdivisionsY:a});ce.TranslationToRef(0,t/2,0,l),u.transform(l);const d=S0({width:t,height:i,subdivisionsX:s,subdivisionsY:a});ce.TranslationToRef(-e/2,0,0,c),ce.RotationZToRef(Math.PI/2,o),o.multiplyToRef(c,l),d.transform(l);const f=S0({width:t,height:i,subdivisionsX:s,subdivisionsY:a});ce.TranslationToRef(e/2,0,0,c),ce.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(c,l),f.transform(l);const p=S0({width:e,height:t,subdivisionsX:r,subdivisionsY:s});ce.TranslationToRef(0,0,-i/2,c),ce.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(c,l),p.transform(l);const _=S0({width:e,height:t,subdivisionsX:r,subdivisionsY:s});return ce.TranslationToRef(0,0,i/2,c),ce.RotationXToRef(Math.PI/2,o),o.multiplyToRef(c,l),_.transform(l),h.merge([u,f,d,p,_],!0),h}function zf(n,e={},t=null){const i=new Se(n,t);return e.sideOrientation=Se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,MG(e).applyToMesh(i,e.updatable),i}const A7e={CreateBox:zf};et.CreateBox=MG;Se.CreateBox=(n,e,t=null,i,r)=>zf(n,{size:e,sideOrientation:r,updatable:i},t);function RG(n){const e=(n.segments||32)|0,t=n.diameterX||n.diameter||1,i=n.diameterY||n.diameter||1,r=n.diameterZ||n.diameter||1,s=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,a=n.slice&&n.slice<=0?1:n.slice||1,o=n.sideOrientation===0?0:n.sideOrientation||et.DEFAULTSIDE,c=!!n.dedupTopBottomIndices,l=new P(t/2,i/2,r/2),h=2+e,u=2*h,d=[],f=[],p=[],_=[];for(let g=0;g<=h;g++){const v=g/h,x=v*Math.PI*a;for(let y=0;y<=u;y++){const C=y/u,b=C*Math.PI*2*s,T=ce.RotationZ(-x),S=ce.RotationY(b),N=P.TransformCoordinates(P.Up(),T),D=P.TransformCoordinates(N,S),M=D.multiply(l),I=D.divide(l).normalize();f.push(M.x,M.y,M.z),p.push(I.x,I.y,I.z),_.push(C,br.UseOpenGLOrientationForUV?1-v:v)}if(g>0){const y=f.length/3;for(let C=y-2*(u+1);C+u+21&&(d.push(C),d.push(C+1),d.push(C+u+1)),(gTl(n,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:s,updatable:r},i);function IG(n={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(n.subdivisions?n.subdivisions:2,1)|0,t=Math.max(n.tessellation?n.tessellation:16,3)|0,i=Math.max(n.height?n.height:1,0),r=Math.max(n.radius?n.radius:.25,0),s=Math.max(n.capSubdivisions?n.capSubdivisions:6,1)|0,a=t,o=e,c=Math.max(n.radiusTop?n.radiusTop:r,0),l=Math.max(n.radiusBottom?n.radiusBottom:r,0),h=i-(c+l),u=0,d=2*Math.PI,f=Math.max(n.topCapSubdivisions?n.topCapSubdivisions:s,1),p=Math.max(n.bottomCapSubdivisions?n.bottomCapSubdivisions:s,1),_=Math.acos((l-c)/i);let m=[];const g=[],v=[],x=[];let y=0;const C=[],b=h*.5,T=Math.PI*.5;let S,N;const D=P.Zero(),M=P.Zero(),I=Math.cos(_),R=Math.sin(_),O=new Be(c*R,b+c*I).subtract(new Be(l*R,-b+l*I)).length(),H=c*_+O+l*(T-_);let G=0;for(N=0;N<=f;N++){const j=[],k=T-_*(N/f);G+=c*_/f;const z=Math.cos(k),Y=Math.sin(k),J=z*c;for(S=0;S<=a;S++){const re=S/a,he=re*d+u,le=Math.sin(he),ue=Math.cos(he);M.x=J*le,M.y=b+Y*c,M.z=J*ue,g.push(M.x,M.y,M.z),D.set(z*le,Y,z*ue),v.push(D.x,D.y,D.z),x.push(re,br.UseOpenGLOrientationForUV?G/H:1-G/H),j.push(y),y++}C.push(j)}const Q=i-c-l+I*c-I*l,$=R*(l-c)/Q;for(N=1;N<=o;N++){const j=[];G+=O/o;const k=R*(N*(l-c)/o+c);for(S=0;S<=a;S++){const z=S/a,Y=z*d+u,J=Math.sin(Y),re=Math.cos(Y);M.x=k*J,M.y=b+I*c-N*Q/o,M.z=k*re,g.push(M.x,M.y,M.z),D.set(J,$,re).normalize(),v.push(D.x,D.y,D.z),x.push(z,br.UseOpenGLOrientationForUV?G/H:1-G/H),j.push(y),y++}C.push(j)}for(N=1;N<=p;N++){const j=[],k=T-_-(Math.PI-_)*(N/p);G+=l*_/p;const z=Math.cos(k),Y=Math.sin(k),J=z*l;for(S=0;S<=a;S++){const re=S/a,he=re*d+u,le=Math.sin(he),ue=Math.cos(he);M.x=J*le,M.y=-b+Y*l,M.z=J*ue,g.push(M.x,M.y,M.z),D.set(z*le,Y,z*ue),v.push(D.x,D.y,D.z),x.push(re,br.UseOpenGLOrientationForUV?G/H:1-G/H),j.push(y),y++}C.push(j)}for(S=0;Su9(n,e,t);et.CreateCapsule=IG;function hee(n){let e=n.pathArray;const t=n.closeArray||!1,i=n.closePath||!1,r=n.invertUV||!1,s=Math.floor(e[0].length/2);let a=n.offset||s;a=a>s?s:Math.floor(a);const o=n.sideOrientation===0?0:n.sideOrientation||et.DEFAULTSIDE,c=n.uvs,l=n.colors,h=[],u=[],d=[],f=[],p=[],_=[],m=[],g=[];let v;const x=[],y=[];let C,b,T;if(e.length<2){const W=[],te=[];for(b=0;b0&&(I=D[T].subtract(D[T-1]).length(),R=I+m[C],p[C].push(R),m[C]=R),T++;i&&(T--,h.push(D[0].x,D[0].y,D[0].z),I=D[T].subtract(D[0]).length(),R=I+m[C],p[C].push(R),m[C]=R),x[C]=M+N,y[C]=S,S+=M+N}let O,H,G=null,Q=null;for(b=0;b{let p=i[0].length;const _=o;let m=0;const g=_._originalBuilderSideOrientation===Se.DOUBLESIDE?2:1;for(let v=1;v<=g;++v)for(let x=0;xq0(n,{pathArray:e,closeArray:t,closePath:i,offset:r,updatable:a,sideOrientation:o,instance:c},s);function PG(n){const e=[],t=[],i=[],r=[],s=n.radius||.5,a=n.tessellation||64,o=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,c=n.sideOrientation===0?0:n.sideOrientation||et.DEFAULTSIDE;e.push(0,0,0),r.push(.5,.5);const l=Math.PI*2*o,h=o===1?l/a:l/(a-1);let u=0;for(let p=0;pU5(n,{radius:e,tessellation:t,sideOrientation:s,updatable:r},i);function i8(n){const e=n.pattern||Se.NO_FLIP,t=n.tileWidth||n.tileSize||1,i=n.tileHeight||n.tileSize||1,r=n.alignHorizontal||0,s=n.alignVertical||0,a=n.width||n.size||1,o=Math.floor(a/t);let c=a-o*t;const l=n.height||n.size||1,h=Math.floor(l/i);let u=l-h*i;const d=t*o/2,f=i*h/2;let p=0,_=0,m=0,g=0,v=0,x=0;if(c>0||u>0){switch(m=-d,g=-f,v=d,x=f,r){case Se.CENTER:c/=2,m-=c,v+=c;break;case Se.LEFT:v+=c,p=-c/2;break;case Se.RIGHT:m-=c,p=c/2;break}switch(s){case Se.CENTER:u/=2,g-=u,x+=u;break;case Se.BOTTOM:x+=u,_=-u/2;break;case Se.TOP:g-=u,_=u/2;break}}const y=[],C=[],b=[];b[0]=[0,0,1,0,1,1,0,1],b[1]=[0,0,1,0,1,1,0,1],(e===Se.ROTATE_TILE||e===Se.ROTATE_ROW)&&(b[1]=[1,1,0,1,0,0,1,0]),(e===Se.FLIP_TILE||e===Se.FLIP_ROW)&&(b[1]=[1,0,0,0,0,1,1,1]),(e===Se.FLIP_N_ROTATE_TILE||e===Se.FLIP_N_ROTATE_ROW)&&(b[1]=[0,1,1,1,1,0,0,0]);let T=[];const S=[],N=[];let D=0;for(let O=0;O0||u>0){const O=u>0&&(s===Se.CENTER||s===Se.TOP),H=u>0&&(s===Se.CENTER||s===Se.BOTTOM),G=c>0&&(r===Se.CENTER||r===Se.RIGHT),Q=c>0&&(r===Se.CENTER||r===Se.LEFT);let $=[],V,j,k,z;if(O&&G&&(y.push(m+p,g+_,0),y.push(-d+p,g+_,0),y.push(-d+p,g+u+_,0),y.push(m+p,g+u+_,0),N.push(D,D+1,D+3,D+1,D+2,D+3),D+=4,V=1-c/t,j=1-u/i,k=1,z=1,$=[V,j,k,j,k,z,V,z],e===Se.ROTATE_ROW&&($=[1-V,1-j,1-k,1-j,1-k,1-z,1-V,1-z]),e===Se.FLIP_ROW&&($=[1-V,j,1-k,j,1-k,z,1-V,z]),e===Se.FLIP_N_ROTATE_ROW&&($=[V,1-j,k,1-j,k,1-z,V,1-z]),T=T.concat($),S.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),C.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),O&&Q&&(y.push(d+p,g+_,0),y.push(v+p,g+_,0),y.push(v+p,g+u+_,0),y.push(d+p,g+u+_,0),N.push(D,D+1,D+3,D+1,D+2,D+3),D+=4,V=0,j=1-u/i,k=c/t,z=1,$=[V,j,k,j,k,z,V,z],(e===Se.ROTATE_ROW||e===Se.ROTATE_TILE&&o%2===0)&&($=[1-V,1-j,1-k,1-j,1-k,1-z,1-V,1-z]),(e===Se.FLIP_ROW||e===Se.FLIP_TILE&&o%2===0)&&($=[1-V,j,1-k,j,1-k,z,1-V,z]),(e===Se.FLIP_N_ROTATE_ROW||e===Se.FLIP_N_ROTATE_TILE&&o%2===0)&&($=[V,1-j,k,1-j,k,1-z,V,1-z]),T=T.concat($),S.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),C.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),H&&G&&(y.push(m+p,f+_,0),y.push(-d+p,f+_,0),y.push(-d+p,x+_,0),y.push(m+p,x+_,0),N.push(D,D+1,D+3,D+1,D+2,D+3),D+=4,V=1-c/t,j=0,k=1,z=u/i,$=[V,j,k,j,k,z,V,z],(e===Se.ROTATE_ROW&&h%2===1||e===Se.ROTATE_TILE&&h%1===0)&&($=[1-V,1-j,1-k,1-j,1-k,1-z,1-V,1-z]),(e===Se.FLIP_ROW&&h%2===1||e===Se.FLIP_TILE&&h%2===0)&&($=[1-V,j,1-k,j,1-k,z,1-V,z]),(e===Se.FLIP_N_ROTATE_ROW&&h%2===1||e===Se.FLIP_N_ROTATE_TILE&&h%2===0)&&($=[V,1-j,k,1-j,k,1-z,V,1-z]),T=T.concat($),S.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),C.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),H&&Q&&(y.push(d+p,f+_,0),y.push(v+p,f+_,0),y.push(v+p,x+_,0),y.push(d+p,x+_,0),N.push(D,D+1,D+3,D+1,D+2,D+3),D+=4,V=0,j=0,k=c/t,z=u/i,$=[V,j,k,j,k,z,V,z],(e===Se.ROTATE_ROW&&h%2===1||e===Se.ROTATE_TILE&&(h+o)%2===1)&&($=[1-V,1-j,1-k,1-j,1-k,1-z,1-V,1-z]),(e===Se.FLIP_ROW&&h%2===1||e===Se.FLIP_TILE&&(h+o)%2===1)&&($=[1-V,j,1-k,j,1-k,z,1-V,z]),(e===Se.FLIP_N_ROTATE_ROW&&h%2===1||e===Se.FLIP_N_ROTATE_TILE&&(h+o)%2===1)&&($=[V,1-j,k,1-j,k,1-z,V,1-z]),T=T.concat($),S.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),C.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),O){const Y=[];V=0,j=1-u/i,k=1,z=1,Y[0]=[V,j,k,j,k,z,V,z],Y[1]=[V,j,k,j,k,z,V,z],(e===Se.ROTATE_TILE||e===Se.ROTATE_ROW)&&(Y[1]=[1-V,1-j,1-k,1-j,1-k,1-z,1-V,1-z]),(e===Se.FLIP_TILE||e===Se.FLIP_ROW)&&(Y[1]=[1-V,j,1-k,j,1-k,z,1-V,z]),(e===Se.FLIP_N_ROTATE_TILE||e===Se.FLIP_N_ROTATE_ROW)&&(Y[1]=[V,1-j,k,1-j,k,1-z,V,1-z]);for(let J=0;JY+M)),M+=T[k].length,i)for(let Y=0;Y<4;Y++)b.push(i[k].r,i[k].g,i[k].b,i[k].a)}const I=new P(0,0,_),R=ce.RotationY(Math.PI);v=T[0].map(k=>P.TransformNormal(k,R).add(I)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[]),x=S[0].map(k=>P.TransformNormal(k,R)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[]),v=v.concat(T[1].map(k=>k.subtract(I)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[])),x=x.concat(S[1].map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[]));const O=new P(f,0,0),H=ce.RotationY(-Math.PI/2);v=v.concat(T[2].map(k=>P.TransformNormal(k,H).add(O)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[])),x=x.concat(S[2].map(k=>P.TransformNormal(k,H)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[]));const G=ce.RotationY(Math.PI/2);v=v.concat(T[3].map(k=>P.TransformNormal(k,G).subtract(O)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[])),x=x.concat(S[3].map(k=>P.TransformNormal(k,G)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[]));const Q=new P(0,p,0),$=ce.RotationX(Math.PI/2);v=v.concat(T[4].map(k=>P.TransformNormal(k,$).add(Q)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[])),x=x.concat(S[4].map(k=>P.TransformNormal(k,$)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[]));const V=ce.RotationX(-Math.PI/2);v=v.concat(T[5].map(k=>P.TransformNormal(k,V).subtract(Q)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[])),x=x.concat(S[5].map(k=>P.TransformNormal(k,V)).map(k=>[k.x,k.y,k.z]).reduce((k,z)=>k.concat(z),[])),et._ComputeSides(d,v,C,x,y);const j=new et;if(j.indices=C,j.positions=v,j.normals=x,j.uvs=y,i){const k=d===et.DOUBLESIDE?b.concat(b):b;j.colors=k}return j}function fee(n,e,t=null){const i=new Se(n,t);return e.sideOrientation=Se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,dee(e).applyToMesh(i,e.updatable),i}const M7e={CreateTiledBox:fee};et.CreateTiledBox=dee;function pee(n){const e=[],t=[],i=[],r=[],s=n.radius||2,a=n.tube||.5,o=n.radialSegments||32,c=n.tubularSegments||32,l=n.p||2,h=n.q||3,u=n.sideOrientation===0?0:n.sideOrientation||et.DEFAULTSIDE,d=m=>{const g=Math.cos(m),v=Math.sin(m),x=h/l*m,y=Math.cos(x),C=s*(2+y)*.5*g,b=s*(2+y)*v*.5,T=s*Math.sin(x)*.5;return new P(C,b,T)};let f,p;for(f=0;f<=o;f++){const g=f%o/o*2*l*Math.PI,v=d(g),x=d(g+.01),y=x.subtract(v);let C=x.add(v);const b=P.Cross(y,C);for(C=P.Cross(b,y),b.normalize(),C.normalize(),p=0;pwG(n,{radius:e,tube:t,radialSegments:i,tubularSegments:r,p:s,q:a,sideOrientation:l,updatable:c},o);const pY={effect:null,subMesh:null};class kn extends Rn{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new ce,this._cachedWorldViewProjectionMatrix=new ce,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...r}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)}setTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return this._options.externalTextures.indexOf(e)===-1&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((i,r)=>(r.toArray(i,i.length),i),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((i,r)=>(r.toArray(i,i.length),i),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((i,r)=>(r.toArray(i,i.length),i),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(t.length*16);for(let r=0;rs===e||s.startsWith(i));return r>=0&&this.options.defines.splice(r,1),(typeof t!="boolean"||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const r=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const C=r?i._drawWrapper:this._drawWrapper;if(C.effect&&C._wasPreviouslyReady&&C._wasPreviouslyUsingInstances===t)return!0}const s=this.getScene(),a=s.getEngine(),o=[],c=[],l=new Hn;let h=this._shaderPath,u=this._options.uniforms,d=this._options.uniformBuffers,f=this._options.samplers;a.getCaps().multiview&&s.activeCamera&&s.activeCamera.outputRenderTarget&&s.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),u.indexOf("viewProjection")!==-1&&u.indexOf("viewProjectionR")===-1&&u.push("viewProjectionR"));for(let C=0;C4&&(c.push(Z.MatricesIndicesExtraKind),c.push(Z.MatricesWeightsExtraKind));const C=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l.addCPUSkinningFallback(0,e),C.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),u.indexOf("boneTextureWidth")===-1&&u.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(C.bones.length+1)),u.indexOf("mBones")===-1&&u.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let p=0;const _=e?e.morphTargetManager:null;if(_){const C=_.supportsUVs&&o.indexOf("#define UV1")!==-1,b=_.supportsTangents&&o.indexOf("#define TANGENT")!==-1,T=_.supportsNormals&&o.indexOf("#define NORMAL")!==-1;p=_.numMaxInfluencers||_.numInfluencers,C&&o.push("#define MORPHTARGETS_UV"),b&&o.push("#define MORPHTARGETS_TANGENT"),T&&o.push("#define MORPHTARGETS_NORMAL"),p>0&&o.push("#define MORPHTARGETS"),_.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),u.indexOf("morphTargetTextureIndices")===-1&&u.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+p);for(let S=0;S0&&(u=u.slice(),u.push("morphTargetInfluences"),u.push("morphTargetCount"),u.push("morphTargetTextureInfo"),u.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const C=e.bakedVertexAnimationManager;C&&C.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),u.indexOf("bakedVertexAnimationSettings")===-1&&u.push("bakedVertexAnimationSettings"),u.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&u.push("bakedVertexAnimationTextureSizeInverted"),u.indexOf("bakedVertexAnimationTime")===-1&&u.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),zO(c,e,o)}for(const C in this._textures)if(!this._textures[C].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(Sa(u),d2(this,s,o)),s.fogEnabled&&(e!=null&&e.applyFog)&&s.fogMode!==pt.FOGMODE_NONE&&(o.push("#define FOG"),u.indexOf("view")===-1&&u.push("view"),u.indexOf("vFogInfos")===-1&&u.push("vFogInfos"),u.indexOf("vFogColor")===-1&&u.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),u.indexOf("logarithmicDepthConstant")===-1&&u.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(u=u.slice(),d=d.slice(),f=f.slice(),h=this.customShaderNameResolve(h,u,d,f,o,c));const m=r?i._getDrawWrapper(void 0,!0):this._drawWrapper,g=(m==null?void 0:m.effect)??null,v=(m==null?void 0:m.defines)??null,x=o.join(` `);let y=g;return v!==x&&(y=a.createEffect(h,{attributes:c,uniformsNames:u,uniformBuffersNames:d,samplers:f,defines:x,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:p},shaderLanguage:this._options.shaderLanguage},a),r?i.setEffect(y,x,this._materialContext):m&&m.setEffect(y,x),this._onEffectCreatedObservable&&(pY.effect=y,pY.subMesh=i??(e==null?void 0:e.subMeshes[0])??null,this._onEffectCreatedObservable.notifyObservers(pY))),m._wasPreviouslyUsingInstances=!!t,y!=null&&y.isReady()?(g!==y&&s.resetCachedMaterial(),m._wasPreviouslyReady=!0,!0):!1}bindOnlyWorldMatrix(e,t){const i=this.getScene(),r=t??this.getEffect();r&&(this._options.uniforms.indexOf("world")!==-1&&r.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),this._options.uniforms.indexOf("view")!==-1&&r.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){var r;this.bind(e,t,(r=i._drawWrapperOverride)==null?void 0:r.effect,i)}bind(e,t,i,r){var u;const s=r&&this._storeEffectOnSubMeshes,a=i??(s?r.effect:this.getEffect());if(!a)return;const o=this.getScene();this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);const c=this._options.uniformBuffers;let l=!1;if(a&&c&&c.length>0&&o.getEngine().supportsUniformBuffers)for(let d=0;d0&&d1(t,a);const f=t.bakedVertexAnimationManager;if(f&&f.isEnabled){const p=s?r._drawWrapper:this._drawWrapper;(u=t.bakedVertexAnimationManager)==null||u.bind(a,!!p._wasPreviouslyUsingInstances)}}this._afterBind(t,a,r)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let r=0;rnew kn(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach(i=>{const r=this._options[i];Array.isArray(r)&&(this._options[i]=r.slice(0))}),this.stencil.copyTo(t.stencil);for(const i in this._textures)t.setTexture(i,this._textures[i]);for(const i in this._textureArrays)t.setTextureArray(i,this._textureArrays[i]);for(const i in this._externalTextures)t.setExternalTexture(i,this._externalTextures[i]);for(const i in this._ints)t.setInt(i,this._ints[i]);for(const i in this._uints)t.setUInt(i,this._uints[i]);for(const i in this._floats)t.setFloat(i,this._floats[i]);for(const i in this._floatsArrays)t.setFloats(i,this._floatsArrays[i]);for(const i in this._colors3)t.setColor3(i,this._colors3[i]);for(const i in this._colors3Arrays)t._colors3Arrays[i]=this._colors3Arrays[i];for(const i in this._colors4)t.setColor4(i,this._colors4[i]);for(const i in this._colors4Arrays)t._colors4Arrays[i]=this._colors4Arrays[i];for(const i in this._vectors2)t.setVector2(i,this._vectors2[i]);for(const i in this._vectors3)t.setVector3(i,this._vectors3[i]);for(const i in this._vectors4)t.setVector4(i,this._vectors4[i]);for(const i in this._quaternions)t.setQuaternion(i,this._quaternions[i]);for(const i in this._quaternionsArrays)t._quaternionsArrays[i]=this._quaternionsArrays[i];for(const i in this._matrices)t.setMatrix(i,this._matrices[i]);for(const i in this._matrixArrays)t._matrixArrays[i]=this._matrixArrays[i].slice();for(const i in this._matrices3x3)t.setMatrix3x3(i,this._matrices3x3[i]);for(const i in this._matrices2x2)t.setMatrix2x2(i,this._matrices2x2[i]);for(const i in this._vectors2Arrays)t.setArray2(i,this._vectors2Arrays[i]);for(const i in this._vectors3Arrays)t.setArray3(i,this._vectors3Arrays[i]);for(const i in this._vectors4Arrays)t.setArray4(i,this._vectors4Arrays[i]);for(const i in this._uniformBuffers)t.setUniformBuffer(i,this._uniformBuffers[i]);for(const i in this._textureSamplers)t.setTextureSampler(i,this._textureSamplers[i]);for(const i in this._storageBuffers)t.setStorageBuffer(i,this._storageBuffers[i]);return t}dispose(e,t,i){if(t){let r;for(r in this._textures)this._textures[r].dispose();for(r in this._textureArrays){const s=this._textureArrays[r];for(let a=0;anew kn(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);let s;e.stencil&&r.stencil.parse(e.stencil,t,i);for(s in e.textures)r.setTexture(s,ve.Parse(e.textures[s],t,i));for(s in e.textureArrays){const a=e.textureArrays[s],o=[];for(let c=0;c(l%3===0?o.push([c]):o[o.length-1].push(c),o),[]).map(o=>Me.FromArray(o));r.setColor3Array(s,a)}for(s in e.colors4)r.setColor4(s,Ze.FromArray(e.colors4[s]));for(s in e.colors4Arrays){const a=e.colors4Arrays[s].reduce((o,c,l)=>(l%4===0?o.push([c]):o[o.length-1].push(c),o),[]).map(o=>Ze.FromArray(o));r.setColor4Array(s,a)}for(s in e.vectors2)r.setVector2(s,Be.FromArray(e.vectors2[s]));for(s in e.vectors3)r.setVector3(s,P.FromArray(e.vectors3[s]));for(s in e.vectors4)r.setVector4(s,Ct.FromArray(e.vectors4[s]));for(s in e.quaternions)r.setQuaternion(s,we.FromArray(e.quaternions[s]));for(s in e.matrices)r.setMatrix(s,ce.FromArray(e.matrices[s]));for(s in e.matrixArray)r._matrixArrays[s]=new Float32Array(e.matrixArray[s]);for(s in e.matrices3x3)r.setMatrix3x3(s,e.matrices3x3[s]);for(s in e.matrices2x2)r.setMatrix2x2(s,e.matrices2x2[s]);for(s in e.vectors2Arrays)r.setArray2(s,e.vectors2Arrays[s]);for(s in e.vectors3Arrays)r.setArray3(s,e.vectors3Arrays[s]);for(s in e.vectors4Arrays)r.setArray4(s,e.vectors4Arrays[s]);for(s in e.quaternionsArrays)r.setArray4(s,e.quaternionsArrays[s]);return r}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,a)=>{const o=new on;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const c=JSON.parse(o.responseText),l=this.Parse(c,i||bt.LastCreatedScene,r);e&&(l.name=e),s(l)}else a("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((r,s)=>{const a=new on;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),c=JSON.parse(o.shaderMaterial),l=this.Parse(c,t||bt.LastCreatedScene,i);l.snippetId=e,r(l)}else s("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}}kn.SnippetUrl="https://snippet.babylonjs.com";kn.CreateFromSnippetAsync=kn.ParseFromSnippetAsync;xe("BABYLON.ShaderMaterial",kn);const I7e="colorPixelShader",P7e=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) #define VERTEXCOLOR varying vec4 vColor; #else uniform vec4 color; #endif #include #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) gl_FragColor=vColor; #else gl_FragColor=color; #endif #include(color,gl_FragColor) #define CUSTOM_FRAGMENT_MAIN_END }`;Re.ShadersStore[I7e]=P7e;const w7e="colorVertexShader",D7e=`attribute vec3 position; #ifdef VERTEXCOLOR attribute vec4 color; #endif #include #include #include #include #ifdef FOG uniform mat4 view; #endif #include uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN #include #include #include vec4 worldPos=finalWorld*vec4(position,1.0); #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} #else gl_Position=viewProjection*worldPos; #endif #include #include #include #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[w7e]=D7e;Se._LinesMeshParser=(n,e)=>i2.Parse(n,e);class i2 extends Se{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,r=null,s,a,o,c){super(e,t,i,r,s),this.useVertexColor=a,this.useVertexAlpha=o,this.color=new Me(1,1,1),this.alpha=1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;const l=[],h={attributes:[Z.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:l,useClipPlane:null};o===!1?h.needAlphaBlending=!1:h.defines.push("#define VERTEXALPHA"),a?(h.defines.push("#define VERTEXCOLOR"),h.attributes.push(Z.ColorKind)):(h.uniforms.push("color"),this._color4=new Ze),c?this.material=c:(this.material=new kn("colorShader",this.getScene(),"color",h,!1),this.material.doNotSerialize=!0)}isReady(){return this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)?super.isReady():!1}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=Ye.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r,g:s,b:a}=this.color;this._color4.set(r,s,a,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(Ye.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(Ye.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new i2(e,this.getScene(),t,this,i)}createInstance(e){const t=new _ee(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const i in this.instancedBuffers)t.instancedBuffers[i]=this.instancedBuffers[i]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new i2(e.name,t);return i.color=Me.FromArray(e.color),i.alpha=e.alpha,i}}class _ee extends Kf{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function mee(n){const e=[],t=[],i=n.lines,r=n.colors,s=[];let a=0;for(let c=0;c0&&(e.push(a-1),e.push(a)),a++}}const o=new et;return o.indices=e,o.positions=t,r&&(o.colors=s),o}function gee(n){const e=n.dashSize||3,t=n.gapSize||1,i=n.dashNb||200,r=n.points,s=[],a=[],o=P.Zero();let c=0,l=0,h=0,u=0,d=0,f=0,p=0;for(p=0;p{const u=P.Zero(),d=h.length/6;let f=0,p=0,_=0,m=0,g=0,v=0,x=0,y=0;for(x=0;xUs(n,{points:e,updatable:i,instance:r},t);Se.CreateDashedLines=(n,e,t,i,r,s=null,a,o)=>DG(n,{points:e,dashSize:t,gapSize:i,dashNb:r,updatable:a,instance:o},s);class L7e extends Be{constructor(e,t){super(e.x,e.y),this.index=t}}class _Y{constructor(){this.elements=[]}add(e){const t=[];return e.forEach(i=>{const r=new L7e(i,this.elements.length);t.push(r),this.elements.push(r)}),t}computeBounds(){const e=new Be(this.elements[0].x,this.elements[0].y),t=new Be(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class N7e{static Rectangle(e,t,i,r){return[new Be(e,t),new Be(i,t),new Be(i,r),new Be(e,r)]}static Circle(e,t=0,i=0,r=32){const s=[];let a=0;const o=Math.PI*2/r;for(let c=0;c!isNaN(s));let i;const r=[];for(i=0;i<(t.length&2147483646);i+=2)r.push(new Be(t[i],t[i+1]));return r}static StartingAt(e,t){return O5.StartingAt(e,t)}}class g2e{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){this._points=new _Y,this._outlinepoints=new _Y,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=r,this._name=e,this._scene=i||bt.LastCreatedScene;let s;t instanceof O5?s=t.getPoints():s=t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),typeof this.bjsEarcut>"u"&&de.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new _Y;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const r=new Se(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(Z.PositionKind,s.positions,e),r.setVerticesData(Z.NormalKind,s.normals,e),r.setVerticesData(Z.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){const i=new et,r=[],s=[],a=[],o=this._points.computeBounds();this._points.elements.forEach(h=>{r.push(0,1,0),s.push(h.x,0,h.y),a.push((h.x-o.min.x)/o.width,(h.y-o.min.y)/o.height)});const c=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let h=0;h0){const h=s.length/3;this._points.elements.forEach(d=>{r.push(0,-1,0),s.push(d.x,-e,d.y),a.push(1-(d.x-o.min.x)/o.width,1-(d.y-o.min.y)/o.height)});const u=c.length;for(let d=0;d{this._addSide(s,r,a,c,o,d,e,!0,t)})}return i.indices=c,i.positions=s,i.normals=r,i.uvs=a,i}_addSide(e,t,i,r,s,a,o,c,l){let h=e.length/3,u=0;for(let d=0;dl?Tl?Sd9(n,{shape:e,holes:i,updatable:r,sideOrientation:s},t,a);Se.ExtrudePolygon=(n,e,t,i,r,s,a,o=earcut)=>f9(n,{shape:e,holes:r,depth:t,updatable:s,sideOrientation:a},i,o);function p9(n,e,t=null){const i=e.path,r=e.shape,s=e.scale||1,a=e.rotation||0,o=e.cap===0?0:e.cap||Se.NO_CAP,c=e.updatable,l=Se._GetDefaultSideOrientation(e.sideOrientation),h=e.instance||null,u=e.invertUV||!1,d=e.closeShape||!1,f=e.closePath||!1;return v2e(n,r,i,s,a,null,null,f,d,o,!1,t,!!c,l,h,u,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function _9(n,e,t=null){const i=e.path,r=e.shape,s=e.scaleFunction||(()=>1),a=e.rotationFunction||(()=>0),o=e.closePath||e.ribbonCloseArray||!1,c=e.closeShape||e.ribbonClosePath||!1,l=e.cap===0?0:e.cap||Se.NO_CAP,h=e.updatable,u=e.firstNormal||null,d=e.adjustFrame||!1,f=Se._GetDefaultSideOrientation(e.sideOrientation),p=e.instance,_=e.invertUV||!1;return v2e(n,r,i,null,null,s,a,o,c,l,!0,t,!!h,f,p||null,_,e.frontUVs||null,e.backUVs||null,u,d)}function v2e(n,e,t,i,r,s,a,o,c,l,h,u,d,f,p,_,m,g,v,x){const y=(N,D,M,I,R,O,H,G,Q,$,V)=>{const j=M.getTangents(),k=M.getNormals(),z=M.getBinormals(),Y=M.getDistances();if(V){for(let te=0;te0){let oe=j[te-1];P.Dot(oe,j[te])<0&&j[te].scaleInPlace(-1),oe=k[te-1],P.Dot(oe,k[te])<0&&k[te].scaleInPlace(-1),oe=z[te-1],P.Dot(oe,z[te])<0&&z[te].scaleInPlace(-1)}}let J=0;const re=()=>R!==null?R:1,le=$&&G?G:()=>O!==null?O:0,ue=$&&H?H:re;let L=Q===Se.NO_CAP||Q===Se.CAP_END?0:2;const F=ie.Matrix[0];for(let te=0;te{const oe=Array(),ne=P.Zero();let pe;for(pe=0;pe3?0:l,b=y(e,t,C,T,i,r,s,a,l,h,x);const S=q0(n,{pathArray:b,closeArray:o,closePath:c,updatable:d,sideOrientation:f,invertUV:_,frontUVs:m||void 0,backUVs:g||void 0},u);return S._creationDataStorage.pathArray=b,S._creationDataStorage.path3D=C,S._creationDataStorage.cap=l,S}const F7e={ExtrudeShape:p9,ExtrudeShapeCustom:_9};Se.ExtrudeShape=(n,e,t,i,r,s,a=null,o,c,l)=>{const h={shape:e,path:t,scale:i,rotation:r,cap:s===0?0:s||Se.NO_CAP,sideOrientation:c,instance:l,updatable:o};return p9(n,h,a)};Se.ExtrudeShapeCustom=(n,e,t,i,r,s,a,o,c,l,h,u)=>{const d={shape:e,path:t,scaleFunction:i,rotationFunction:r,ribbonCloseArray:s,ribbonClosePath:a,cap:o===0?0:o||Se.NO_CAP,sideOrientation:h,instance:u,updatable:l};return _9(n,d,c)};function OG(n,e,t=null){const i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,r=e.closed===void 0?!0:e.closed,s=e.shape,a=e.radius||1,o=e.tessellation||64,c=e.clip||0,l=e.updatable,h=Se._GetDefaultSideOrientation(e.sideOrientation),u=e.cap||Se.NO_CAP,d=Math.PI*2,f=[],p=e.invertUV||!1;let _=0,m=0;const g=d/o*i;let v,x;for(_=0;_<=o-c;_++){for(x=[],(u==Se.CAP_START||u==Se.CAP_ALL)&&(x.push(new P(0,s[0].y,0)),x.push(new P(Math.cos(_*g)*s[0].x*a,s[0].y,Math.sin(_*g)*s[0].x*a))),m=0;mOG(n,{shape:e,radius:t,tessellation:i,sideOrientation:a,updatable:s},r);function LG(n,e,t=null){const i=e.path;let r=e.instance,s=1;e.radius!==void 0?s=e.radius:r&&(s=r._creationDataStorage.radius);const a=e.tessellation||64,o=e.radiusFunction||null;let c=e.cap||Se.NO_CAP;const l=e.invertUV||!1,h=e.updatable,u=Se._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const d=(g,v,x,y,C,b,T,S)=>{const N=v.getTangents(),D=v.getNormals(),M=v.getDistances(),R=Math.PI*2/C*S,H=b||(()=>y);let G,Q,$,V;const j=ie.Matrix[0];let k=T===Se.NO_CAP||T===Se.CAP_END?0:2;for(let Y=0;Y{const re=Array();for(let he=0;he3?0:c,p=d(i,f,_,s,a,o,c,e.arc);const m=q0(n,{pathArray:p,closePath:!0,closeArray:!1,updatable:h,sideOrientation:u,invertUV:l,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return m._creationDataStorage.pathArray=p,m._creationDataStorage.path3D=f,m._creationDataStorage.tessellation=a,m._creationDataStorage.cap=c,m._creationDataStorage.arc=e.arc,m._creationDataStorage.radius=s,m}const k7e={CreateTube:LG};Se.CreateTube=(n,e,t,i,r,s,a,o,c,l)=>LG(n,{path:e,radius:t,tessellation:i,radiusFunction:r,arc:1,cap:s,updatable:o,sideOrientation:c,instance:l},a);function xee(n){const e=[];e[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},e[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},e[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},e[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},e[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},e[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},e[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},e[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},e[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},e[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},e[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},e[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},e[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},e[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},e[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const t=n.type&&(n.type<0||n.type>=e.length)?0:n.type||0,i=n.size,r=n.sizeX||i||1,s=n.sizeY||i||1,a=n.sizeZ||i||1,o=n.custom||e[t],c=o.face.length,l=n.faceUV||new Array(c),h=n.faceColors,u=n.flat===void 0?!0:n.flat,d=n.sideOrientation===0?0:n.sideOrientation||et.DEFAULTSIDE,f=[],p=[],_=[],m=[],g=[];let v=0,x=0;const y=[];let C=0,b=0,T,S,N,D,M,I;if(u)for(b=0;bsA(n,e,t);const z7e=new P(1,0,0),H7e=new P(-1,0,0),G7e=new P(0,1,0),K7e=new P(0,-1,0),W7e=new P(0,0,1),j7e=new P(0,0,-1);class kz{constructor(e=P.Zero(),t=P.Up(),i=Be.Zero(),r=0,s=0,a=null,o=null,c=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=a,this.localNormalOverride=o,this.matrixIndicesOverride=c,this.matrixWeightsOverride=l}clone(){var e,t,i,r;return new kz(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)==null?void 0:e.slice(),(t=this.localNormalOverride)==null?void 0:t.slice(),(i=this.matrixIndicesOverride)==null?void 0:i.slice(),(r=this.matrixWeightsOverride)==null?void 0:r.slice())}}function NG(n,e,t){var Q,$,V,j;const i=!!e.skeleton,r=t.localMode||i,s=e.overrideMaterialSideOrientation!==null&&e.overrideMaterialSideOrientation!==void 0,a=e.getIndices(),o=i?e.getPositionData(!0,!0):e.getVerticesData(Z.PositionKind),c=i?e.getNormalsData(!0,!0):e.getVerticesData(Z.NormalKind),l=r?i?e.getVerticesData(Z.PositionKind):o:null,h=r?i?e.getVerticesData(Z.NormalKind):c:null,u=e.getVerticesData(Z.UVKind),d=i?e.getVerticesData(Z.MatricesIndicesKind):null,f=i?e.getVerticesData(Z.MatricesWeightsKind):null,p=i?e.getVerticesData(Z.MatricesIndicesExtraKind):null,_=i?e.getVerticesData(Z.MatricesWeightsExtraKind):null,m=t.position||P.Zero();let g=t.normal||P.Up();const v=t.size||P.One(),x=t.angle||0;if(!g){const k=new P(0,0,1),z=e.getScene().activeCamera,Y=P.TransformCoordinates(k,z.getWorldMatrix());g=z.globalPosition.subtract(Y)}const y=-Math.atan2(g.z,g.x)-Math.PI/2,C=Math.sqrt(g.x*g.x+g.z*g.z),b=Math.atan2(g.y,C),T=new et;T.indices=[],T.positions=[],T.normals=[],T.uvs=[],T.matricesIndices=i?[]:null,T.matricesWeights=i?[]:null,T.matricesIndicesExtra=p?[]:null,T.matricesWeightsExtra=_?[]:null;let S=0;const N=(k,z)=>{const Y=new kz;if(!a||!o||!c)return Y;const J=a[k];if(Y.vertexIdx=J*3,Y.vertexIdxForBones=J*4,Y.position=new P(o[J*3],o[J*3+1],o[J*3+2]),P.TransformCoordinatesToRef(Y.position,z,Y.position),Y.normal=new P(c[J*3],c[J*3+1],c[J*3+2]),P.TransformNormalToRef(Y.normal,z,Y.normal),t.captureUVS&&u){const re=u[J*2+1];Y.uv=new Be(u[J*2],br.UseOpenGLOrientationForUV?1-re:re)}return Y},D=[0,0,0,0],M=(k,z)=>{if(k.length===0)return k;const Y=.5*Math.abs(P.Dot(v,z)),J=(le,ue,L,F)=>{for(let W=0;W{const L=P.GetClipFactor(le.position,ue.position,z,Y);let F=D,W=D;if(d&&f){const Xi=le.matrixIndicesOverride?0:le.vertexIdxForBones,Li=le.matrixIndicesOverride??d,Yr=le.matrixWeightsOverride??f,xi=ue.matrixIndicesOverride?0:ue.vertexIdxForBones,Wi=ue.matrixIndicesOverride??d,Ti=ue.matrixWeightsOverride??f;F=[0,0,0,0],W=[0,0,0,0];let zi=0;for(let Ei=0;Ei<4;++Ei)if(Yr[Xi+Ei]>0){const Si=J(Wi,Li[Xi+Ei],xi,4);F[zi]=Li[Xi+Ei],W[zi]=_t.Lerp(Yr[Xi+Ei],Si>=0?Ti[Si]:0,L),zi++}for(let Ei=0;Ei<4&&zi<4;++Ei){const Si=Wi[xi+Ei];J(Li,Si,Xi,4)===-1&&(F[zi]=Si,W[zi]=_t.Lerp(0,Ti[xi+Ei],L),zi++)}const ji=W[0]+W[1]+W[2]+W[3];W[0]/=ji,W[1]/=ji,W[2]/=ji,W[3]/=ji}const te=le.localPositionOverride?le.localPositionOverride[0]:(l==null?void 0:l[le.vertexIdx])??0,oe=le.localPositionOverride?le.localPositionOverride[1]:(l==null?void 0:l[le.vertexIdx+1])??0,ne=le.localPositionOverride?le.localPositionOverride[2]:(l==null?void 0:l[le.vertexIdx+2])??0,pe=ue.localPositionOverride?ue.localPositionOverride[0]:(l==null?void 0:l[ue.vertexIdx])??0,ye=ue.localPositionOverride?ue.localPositionOverride[1]:(l==null?void 0:l[ue.vertexIdx+1])??0,Pe=ue.localPositionOverride?ue.localPositionOverride[2]:(l==null?void 0:l[ue.vertexIdx+2])??0,Fe=le.localNormalOverride?le.localNormalOverride[0]:(h==null?void 0:h[le.vertexIdx])??0,He=le.localNormalOverride?le.localNormalOverride[1]:(h==null?void 0:h[le.vertexIdx+1])??0,ot=le.localNormalOverride?le.localNormalOverride[2]:(h==null?void 0:h[le.vertexIdx+2])??0,Xe=ue.localNormalOverride?ue.localNormalOverride[0]:(h==null?void 0:h[ue.vertexIdx])??0,gt=ue.localNormalOverride?ue.localNormalOverride[1]:(h==null?void 0:h[ue.vertexIdx+1])??0,rt=ue.localNormalOverride?ue.localNormalOverride[2]:(h==null?void 0:h[ue.vertexIdx+2])??0,ut=Fe+(Xe-Fe)*L,Yt=He+(gt-He)*L,ki=ot+(rt-ot)*L,ei=Math.sqrt(ut*ut+Yt*Yt+ki*ki);return new kz(P.Lerp(le.position,ue.position,L),P.Lerp(le.normal,ue.normal,L).normalize(),Be.Lerp(le.uv,ue.uv,L),-1,-1,l?[te+(pe-te)*L,oe+(ye-oe)*L,ne+(Pe-ne)*L]:null,h?[ut/ei,Yt/ei,ki/ei]:null,F,W)};let he=null;k.length>3&&(he=[]);for(let le=0;le0,Pe=ne>0,Fe=pe>0;switch(ue=(ye?1:0)+(Pe?1:0)+(Fe?1:0),ue){case 0:k.length>3?(he.push(k[le]),he.push(k[le+1]),he.push(k[le+2])):he=k;break;case 1:if(he=he??new Array,ye&&(L=k[le+1],F=k[le+2],W=re(k[le],L),te=re(k[le],F)),Pe){L=k[le],F=k[le+2],W=re(k[le+1],L),te=re(k[le+1],F),he.push(W),he.push(F.clone()),he.push(L.clone()),he.push(F.clone()),he.push(W.clone()),he.push(te);break}Fe&&(L=k[le],F=k[le+1],W=re(k[le+2],L),te=re(k[le+2],F)),L&&F&&W&&te&&(he.push(L.clone()),he.push(F.clone()),he.push(W),he.push(te),he.push(W.clone()),he.push(F.clone()));break;case 2:he=he??new Array,ye||(L=k[le].clone(),F=re(L,k[le+1]),W=re(L,k[le+2]),he.push(L),he.push(F),he.push(W)),Pe||(L=k[le+1].clone(),F=re(L,k[le+2]),W=re(L,k[le]),he.push(L),he.push(F),he.push(W)),Fe||(L=k[le+2].clone(),F=re(L,k[le]),W=re(L,k[le+1]),he.push(L),he.push(F),he.push(W));break}}return he},I=e instanceof Se?e:null,R=I==null?void 0:I._thinInstanceDataStorage.matrixData,O=(I==null?void 0:I.thinInstanceCount)||1,H=ie.Matrix[0];H.copyFrom(ce.IdentityReadOnly);for(let k=0;kNG(n,e,{position:t,normal:i,size:r,angle:s});class Dn{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&de.Warn("x is not an integer, floor(x) used"),t!==Math.floor(t)&&de.Warn("y is not an integer, floor(y) used")}clone(){return new Dn(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&de.Warn("m not an integer only floor(m) used"),t!==Math.floor(t)&&de.Warn("n not an integer only floor(n) used");const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&de.Warn("m is not an integer, floor(m) used"),t!==Math.floor(t)&&de.Warn("n is not an integer, floor(n) used");const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=P.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new Dn(0,0)}}class yee{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new Vz("icosahedron","Regular",[[0,Ba,-1],[-Ba,1,0],[-1,0,-Ba],[1,0,-Ba],[Ba,1,0],[0,Ba,1],[-1,0,Ba],[-Ba,-1,0],[0,-Ba,-1],[Ba,-1,0],[1,0,Ba],[0,-Ba,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,r=this.n;let s=i,a=1,o=0;r!==0&&(s=_t.HCF(i,r)),a=i/s,o=r/s;let c,l,h,u,d;const f=Dn.Zero(),p=new Dn(i,r),_=new Dn(-r,i+r),m=Dn.Zero(),g=Dn.Zero(),v=Dn.Zero();let x=[],y,C,b,T;const S=[],N=this.vertByDist,D=(M,I,R,O)=>{y=M+"|"+R,C=I+"|"+O,y in t||C in t?y in t&&!(C in t)?t[C]=t[y]:C in t&&!(y in t)&&(t[y]=t[C]):(t[y]=e,t[C]=e,e++),N[R][0]>2?S[t[y]]=[-N[R][0],N[R][1],t[y]]:S[t[y]]=[x[N[R][0]],N[R][1],t[y]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let M=0;M<20;M++){if(x=this.IDATA.face[M],h=x[2],u=x[1],d=x[0],b=f.x+"|"+f.y,y=M+"|"+b,y in t||(t[y]=h,S[h]=[x[N[b][0]],N[b][1]]),b=p.x+"|"+p.y,y=M+"|"+b,y in t||(t[y]=u,S[u]=[x[N[b][0]],N[b][1]]),b=_.x+"|"+_.y,y=M+"|"+b,y in t||(t[y]=d,S[d]=[x[N[b][0]],N[b][1]]),c=this.IDATA.edgematch[M][0],l=this.IDATA.edgematch[M][1],l==="B")for(let I=1;I2?S[t[y]]=[-N[b][0],N[b][1],t[y]]:S[t[y]]=[x[N[b][0]],N[b][1],t[y]])}this.closestTo=S,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,r=e*e+t*t+e*t;this.coau=(e+t)/r,this.cobu=-t/r,this.coav=-i*(e-t)/r,this.cobv=i*(2*e+t)/r}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&r0){const C=_t.HCF(e,t),b=e/C,T=t/C;for(let N=1;NC.x-b.x),i.sort((C,b)=>C.y-b.y);const o=new Array(e+t+1),c=new Array(e+t+1);for(let C=0;C{const T=C.clone();return b==="A"&&T.rotateNeg120(e,t),b==="B"&&T.rotate120(e,t),T.x<0?T.y:T.x+T.y},f=[],p=[],_=[],m=[],g={},v=[];let x=-1,y=-1;for(let C=0;CC[2]-b[2]),v.sort((C,b)=>C[3]-b[3]),v.sort((C,b)=>C[1]-b[1]),v.sort((C,b)=>C[0]-b[0]);for(let C=0;Ct.vecToidx[e+r]))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let r=0;r-1?i[a][1]>0&&t[i[a][0]].push([a,i[a][1]]):t[12].push([a,i[a][0]]);const r=[];for(let a=0;a<12;a++)r[a]=a;let s=12;for(let a=0;a<12;a++){t[a].sort((o,c)=>o[1]-c[1]);for(let o=0;oa[3]-o[3]);for(let a=0;a0;)s=t[c],this.face[s].indexOf(o)>-1?(a=(this.face[s].indexOf(o)+1)%3,o=this.face[s][a],i.push(o),r.push(s),t.splice(c,1),c=0):c++;return this.adjacentFaces.push(i),r}toGoldbergPolyhedronData(){const e=new Vz("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let l=0;l{r=0,s=0,a=0,o=this.face[h];for(let u=0;u<3;u++)c=this.vertex[o[u]],r+=c[0],s+=c[1],a+=c[2];e.vertex[h]=[r/3,s/3,a/3]});return e}static BuildGeodesicData(e){const t=new m9("Geodesic-m-n","Geodesic",[[0,Ba,-1],[-Ba,1,0],[-1,0,-Ba],[1,0,-Ba],[Ba,1,0],[0,Ba,1],[-1,0,Ba],[-Ba,-1,0],[0,-Ba,-1],[Ba,-1,0],[1,0,Ba],[0,-Ba,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let r=0;ri){const l=r;r=i,i=l,de.Warn("n > m therefore m and n swapped")}const s=new yee;s.build(i,r);const o={custom:m9.BuildGeodesicData(s),size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,faceUV:e.faceUV,faceColors:e.faceColors,flat:e.flat,updatable:e.updatable,sideOrientation:e.sideOrientation,frontUVs:e.frontUVs,backUVs:e.backUVs};return sA(n,o,t)}Se._GoldbergMeshParser=(n,e)=>g9.Parse(n,e);class g9 extends Se{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return t===void 0?(e>this.goldbergData.nbUnsharedFaces-1&&(de.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(de.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(de.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i1&&(u=1),l.push(u,d);for(let f=0;f<6;f++)u=a.x+o*Math.cos(c+f*Math.PI/3),d=a.y+o*Math.sin(c+f*Math.PI/3),u<0&&(u=0),u>1&&(u=1),h.push(u,d);for(let f=r;fZe.FromArray(s)),i.faceCenters=i.faceCenters.map(s=>P.FromArray(s)),i.faceZaxis=i.faceZaxis.map(s=>P.FromArray(s)),i.faceXaxis=i.faceXaxis.map(s=>P.FromArray(s)),i.faceYaxis=i.faceYaxis.map(s=>P.FromArray(s));const r=new g9(e.name,t);return r.goldbergData=i,r}}function y2e(n,e){const t=n.size,i=n.sizeX||t||1,r=n.sizeY||t||1,s=n.sizeZ||t||1,a=n.sideOrientation===0?0:n.sideOrientation||et.DEFAULTSIDE,o=[],c=[],l=[],h=[];let u=1/0,d=-1/0,f=1/0,p=-1/0;for(let g=0;go){const p=c;c=o,o=p,de.Warn("n > m therefore m and n swapped")}const l=new yee;l.build(o,c);const h=m9.BuildGeodesicData(l),u=h.toGoldbergPolyhedronData(),d=new g9(n,t);e.sideOrientation=Se._GetDefaultSideOrientation(e.sideOrientation),d._originalBuilderSideOrientation=e.sideOrientation,y2e(e,u).applyToMesh(d,e.updatable),d.goldbergData.nbSharedFaces=h.sharedNodes,d.goldbergData.nbUnsharedFaces=h.poleNodes,d.goldbergData.adjacentFaces=h.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let p=0;p0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function Q7e(n,e,t,i,r,s){const a=s.glyphs[n]||s.glyphs["?"];if(!a)return null;const o=new Y7e(r);if(a.o){const c=a.o.split(" ");for(let l=0,h=c.length;lni&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>ni&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>ni&&(e.z=1*Math.sign(e.z))}_updateDebugConstraint(e,t){if(!e._initOptions)return;const{pivotA:i,pivotB:r,axisA:s,axisB:a,perpAxisA:o,perpAxisB:c}=e._initOptions;!i||!r||!s||!a||!o||!c||t.getDescendants(!0).forEach(l=>{const h=l.getDescendants(!0)[0],u=l.getDescendants(!0)[1],{parentBody:d,parentBodyIndex:f}=h.metadata,{childBody:p,childBodyIndex:_}=u.metadata,m=this._getTransformFromBodyToRef(d,ie.Matrix[0],f),g=this._getTransformFromBodyToRef(p,ie.Matrix[1],_);m.decomposeToTransformNode(h),this._makeScalingUnitInPlace(h.scaling),g.decomposeToTransformNode(u),this._makeScalingUnitInPlace(u.scaling);const v=h.getDescendants(!0)[0];v.position.copyFrom(i);const x=u.getDescendants(!0)[0];x.position.copyFrom(r),we.FromRotationMatrixToRef(ce.FromXYZAxesToRef(s,o,P.CrossToRef(s,o,ie.Vector3[0]),ie.Matrix[0]),v.rotationQuaternion),we.FromRotationMatrixToRef(ce.FromXYZAxesToRef(a,c,P.CrossToRef(a,c,ie.Vector3[1]),ie.Matrix[1]),x.rotationQuaternion)})}showImpostor(e,t){if(!this._scene)return null;for(let r=0;rthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),i}showBody(e){if(!this._scene)return null;for(let i=0;ithis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numBodies++),t}showInertia(e){if(!this._scene)return null;for(let i=0;ithis._updateInertiaMeshes(),this._scene.registerBeforeRender(this._inertiaRenderFunction)),this._numInertiaBodies++),t}showConstraint(e){if(!this._scene)return null;for(let i=0;ithis._updateDebugConstraints(),this._scene.registerBeforeRender(this._constraintRenderFunction)),this._numConstraints++),t}hideImpostor(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r-1&&this._debugMeshMeshes.splice(a,1),this._numMeshes--,this._numMeshes>0?(this._meshes[r]=this._meshes[this._numMeshes],this._impostors[r]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&this._numMeshes===0&&this._scene.unregisterBeforeRender(this._renderFunction)}hideBody(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r0?(this._bodyMeshes[r]=this._bodyMeshes[this._numBodies],this._bodies[r]=this._bodies[this._numBodies],this._bodyMeshes[this._numBodies]=null,this._bodies[this._numBodies]=null):(this._bodyMeshes[0]=null,this._bodies[0]=null),t=!0;break}t&&this._numBodies===0&&this._scene.unregisterBeforeRender(this._renderFunction)}hideInertia(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r0?(this._constraints[r]=this._constraints[this._numConstraints],this._constraintMeshes[r]=this._constraintMeshes[this._numConstraints],this._constraints[this._numConstraints]=null,this._constraintMeshes[this._numConstraints]=null):(this._constraints[0]=null,this._constraintMeshes[0]=null),t=!0;break}t&&this._numConstraints===0&&this._scene.unregisterBeforeRender(this._constraintRenderFunction)}_getDebugMaterial(e){return this._debugMaterial||(this._debugMaterial=new tt("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=Me.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugInertiaMaterial(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new tt("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=zf("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=we.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=Tl("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=we.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=u9("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=we.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=dc("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=we.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new Se(e.name,t,null,e);return i.setParent(e),i.position=P.Zero(),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i}_getDebugMesh(e,t){if(!this._utilityLayer||t&&t.parent&&t.parent.physicsImpostor)return null;let i=null;const r=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return de.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case Zt.BoxImpostor:i=this._getDebugBoxMesh(r),e.getBoxSizeToRef(i.scaling);break;case Zt.SphereImpostor:{i=this._getDebugSphereMesh(r);const s=e.getRadius();i.scaling.x=s*2,i.scaling.y=s*2,i.scaling.z=s*2;break}case Zt.CapsuleImpostor:{i=this._getDebugCapsuleMesh(r);const s=e.object.getBoundingInfo();i.scaling.x=(s.boundingBox.maximum.x-s.boundingBox.minimum.x)*2*e.object.scaling.x,i.scaling.y=(s.boundingBox.maximum.y-s.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(s.boundingBox.maximum.z-s.boundingBox.minimum.z)*2*e.object.scaling.z;break}case Zt.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,r));break;case Zt.NoImpostor:t?t.getChildMeshes().filter(a=>a.physicsImpostor?1:0).forEach(a=>{if(a.physicsImpostor&&a.getClassName()==="Mesh"){const o=a.getBoundingInfo(),c=o.boundingBox.minimum,l=o.boundingBox.maximum;switch(a.physicsImpostor.type){case Zt.BoxImpostor:i=this._getDebugBoxMesh(r),i.position.copyFrom(c),i.position.addInPlace(l),i.position.scaleInPlace(.5);break;case Zt.SphereImpostor:i=this._getDebugSphereMesh(r);break;case Zt.CylinderImpostor:i=this._getDebugCylinderMesh(r);break;default:i=null;break}i&&(i.scaling.x=l.x-c.x,i.scaling.y=l.y-c.y,i.scaling.z=l.z-c.z,i.parent=a)}}):de.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case Zt.CylinderImpostor:{i=this._getDebugCylinderMesh(r);const s=e.object.getBoundingInfo();i.scaling.x=(s.boundingBox.maximum.x-s.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(s.boundingBox.maximum.y-s.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(s.boundingBox.maximum.z-s.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new Se("custom",t),r=new et,s=e.getGeometry();if(r.positions=s.positions,r.indices=s.indices,r.applyToMesh(i),e._pluginDataInstances){const a=new Float32Array(e._pluginDataInstances.length*16);i.thinInstanceSetBuffer("matrix",a,16,!1)}return i.material=this._getDebugMaterial(t),i}_getMeshDebugInertiaMatrixToRef(e,t){const i=e.inertiaOrientation??we.Identity(),r=e.inertia??P.Zero(),s=e.centerOfMass??P.Zero(),a=(r.x-r.y+r.z)*6,o=Math.sqrt(Math.max(a,0)),c=r.x*12-a,l=Math.sqrt(Math.max(c,0)),h=r.z*12-a,u=Math.sqrt(Math.max(h,0)),d=ie.Vector3[0];d.set(u,o,l);const f=ce.ScalingToRef(d.x,d.y,d.z,ie.Matrix[0]),p=i.toRotationMatrix(ie.Matrix[1]),_=ce.TranslationToRef(s.x,s.y,s.z,ie.Matrix[2]);return f.multiplyToRef(p,t),t.multiplyToRef(_,t),t}_getDebugInertiaMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=kh.CreateBox("custom",{size:1},t),r=ce.Identity();if(e._pluginDataInstances.length){const s=new Float32Array(e._pluginDataInstances.length*16);for(let a=0;a=0?ce.FromArrayToRef(r._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(r.getWorldMatrix())}_getDebugConstraintMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;const{pivotA:i,pivotB:r,axisA:s,axisB:a,perpAxisA:o,perpAxisB:c}=e._initOptions;if(!i||!r||!s||!a||!o||!c)return null;const l=new Se("parentingDebugConstraint",t),h=e.getBodiesUsingConstraint();for(const u of h){const d=new Et("parentOfPair",t);d.parent=l;const{parentBody:f,parentBodyIndex:p,childBody:_,childBodyIndex:m}=u,g=this._getTransformFromBodyToRef(f,ie.Matrix[0],p),v=this._getTransformFromBodyToRef(_,ie.Matrix[1],m),x=new Et("parentCoordSystem",t);x.parent=d,x.metadata={parentBody:f,parentBodyIndex:p},g.decomposeToTransformNode(x);const y=new Et("childCoordSystem",t);y.parent=d,y.metadata={childBody:_,childBodyIndex:m},v.decomposeToTransformNode(y);const C=we.FromRotationMatrix(ce.FromXYZAxesToRef(s,o,s.cross(o),ie.Matrix[0])),b=we.FromRotationMatrix(ce.FromXYZAxesToRef(a,c,a.cross(c),ie.Matrix[0])),T=i,S=r,N=new Et("constraint_parent",t);N.position.copyFrom(T),N.rotationQuaternion=C,N.parent=x;const D=new Et("constraint_child",t);D.parent=y,D.position.copyFrom(S),D.rotationQuaternion=b;const M=new Dm(t,this._constraintAxesSize);M.xAxis.parent=N,M.yAxis.parent=N,M.zAxis.parent=N;const I=new Dm(t,this._constraintAxesSize);I.xAxis.parent=D,I.yAxis.parent=D,I.zAxis.parent=D}return l}dispose(){for(let e=this._numMeshes-1;e>=0;e--)this.hideImpostor(this._impostors[0]);for(let e=this._numBodies-1;e>=0;e--)this.hideBody(this._bodies[0]);for(let e=this._numInertiaBodies-1;e>=0;e--)this.hideInertia(this._inertiaBodies[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)}}class Cee{static CreateAndShow(e,t,i){const r=new Cee(e);return r.show(t,i),r}constructor(e){this.ray=e}show(e,t){if(!this._renderFunction&&this.ray){const i=this.ray;this._renderFunction=()=>this._render(),this._scene=e,this._renderPoints=[i.origin,i.origin.add(i.direction.scale(i.length))],this._renderLine=Us("ray",{points:this._renderPoints,updatable:!0},e),this._renderLine.isPickable=!1,this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)}hide(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])}_render(){var r;const e=this.ray;if(!e)return;const t=this._renderPoints[1],i=Math.min(e.length,1e6);t.copyFrom(e.direction),t.scaleInPlace(i),t.addInPlace(e.origin),this._renderPoints[0].copyFrom(e.origin),Us("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),(r=this._renderLine)==null||r.refreshBoundingInfo()}attachToMesh(e,t,i,r){this._attachedToMesh=e;const s=this.ray;s&&(s.direction||(s.direction=P.Zero()),s.origin||(s.origin=P.Zero()),r&&(s.length=r),i||(i=P.Zero()),t||(t=new P(0,0,-1)),this._scene||(this._scene=e.getScene()),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._onAfterRenderObserver||(this._onAfterRenderObserver=this._scene.onBeforeRenderObservable.add(()=>this._updateToMesh()),this._onAfterStepObserver=this._scene.onAfterStepObservable.add(()=>this._updateToMesh())),this._attachedToMesh.computeWorldMatrix(!0),this._updateToMesh())}detachFromMesh(){this._attachedToMesh&&this._scene&&(this._onAfterRenderObserver&&(this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver),this._scene.onAfterStepObservable.remove(this._onAfterStepObserver)),this._attachedToMesh=null,this._onAfterRenderObserver=null,this._onAfterStepObserver=null,this._scene=null)}_updateToMesh(){const e=this.ray;if(!(!this._attachedToMesh||!e)){if(this._attachedToMesh.isDisposed()){this.detachFromMesh();return}this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),P.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)}}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}class dh{static CreateBoneWeightShader(e,t){const i=e.skeleton,r=e.colorBase??Me.Black(),s=e.colorZero??Me.Blue(),a=e.colorQuarter??Me.Green(),o=e.colorHalf??Me.Yellow(),c=e.colorFull??Me.Red(),l=e.targetBoneIndex??0;bi.ShadersStore["boneWeights:"+i.name+"VertexShader"]=`precision highp float; attribute vec3 position; attribute vec2 uv; uniform mat4 view; uniform mat4 projection; uniform mat4 worldViewProjection; #include #if NUM_BONE_INFLUENCERS == 0 attribute vec4 matricesIndices; attribute vec4 matricesWeights; #endif #include #include varying vec3 vColor; uniform vec3 colorBase; uniform vec3 colorZero; uniform vec3 colorQuarter; uniform vec3 colorHalf; uniform vec3 colorFull; uniform float targetBoneIndex; void main() { vec3 positionUpdated = position; #include #include #include vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); vec3 color = colorBase; float totalWeight = 0.; if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){ totalWeight += matricesWeights[0]; } if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){ totalWeight += matricesWeights[1]; } if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){ totalWeight += matricesWeights[2]; } if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){ totalWeight += matricesWeights[3]; } color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight)); color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight)); color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight)); color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight)); vColor = color; gl_Position = projection * view * worldPos; }`,bi.ShadersStore["boneWeights:"+i.name+"FragmentShader"]=` precision highp float; varying vec3 vPosition; varying vec3 vColor; void main() { vec4 color = vec4(vColor, 1.0); gl_FragColor = color; } `;const h=new kn("boneWeight:"+i.name,t,{vertex:"boneWeights:"+i.name,fragment:"boneWeights:"+i.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return h.setColor3("colorBase",r),h.setColor3("colorZero",s),h.setColor3("colorQuarter",a),h.setColor3("colorHalf",o),h.setColor3("colorFull",c),h.setFloat("targetBoneIndex",l),h.getClassName=()=>"BoneWeightShader",h.transparencyMode=Ye.MATERIAL_OPAQUE,h}static CreateSkeletonMapShader(e,t){const i=e.skeleton,r=e.colorMap??[{color:new Me(1,.38,.18),location:0},{color:new Me(.59,.18,1),location:.2},{color:new Me(.59,1,.18),location:.4},{color:new Me(1,.87,.17),location:.6},{color:new Me(1,.17,.42),location:.8},{color:new Me(.17,.68,1),location:1}],s=i.bones.length+1,a=dh._CreateBoneMapColorBuffer(s,r,t),o=new kn("boneWeights:"+i.name,t,{vertexSource:`precision highp float; attribute vec3 position; attribute vec2 uv; uniform mat4 view; uniform mat4 projection; uniform mat4 worldViewProjection; uniform float colorMap[`+i.bones.length*4+`]; #include #if NUM_BONE_INFLUENCERS == 0 attribute vec4 matricesIndices; attribute vec4 matricesWeights; #endif #include #include varying vec3 vColor; void main() { vec3 positionUpdated = position; #include #include #include vec3 color = vec3(0.); bool first = true; for (int i = 0; i < 4; i++) { int boneIdx = int(matricesIndices[i]); float boneWgt = matricesWeights[i]; vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]); if (boneWgt > 0.) { if (first) { first = false; color = c; } else { color = mix(color, c, boneWgt); } } } vColor = color; vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); gl_Position = projection * view * worldPos; }`,fragmentSource:` precision highp float; varying vec3 vColor; void main() { vec4 color = vec4( vColor, 1.0 ); gl_FragColor = color; } `},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",a),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=Ye.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const r=new Id("temp",{width:e,height:1},i,!1),s=r.getContext(),a=s.createLinearGradient(0,0,e,0);t.forEach(h=>{a.addColorStop(h.location,h.color.toHexString())}),s.fillStyle=a,s.fillRect(0,0,e,1),r.update();const o=[],c=s.getImageData(0,0,e,1).data,l=1/255;for(let h=0;hdh.DISPLAY_SPHERE_AND_SPURS&&(e=dh.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,s=3,a={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=s,this.options=a,this.color=Me.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,a.pauseAnimations=a.pauseAnimations??!0,a.returnToRest=a.returnToRest??!1,a.displayMode=a.displayMode??dh.DISPLAY_LINES,a.displayOptions=a.displayOptions??{},a.displayOptions.midStep=a.displayOptions.midStep??.235,a.displayOptions.midStepFactor=a.displayOptions.midStepFactor??.155,a.displayOptions.sphereBaseSize=a.displayOptions.sphereBaseSize??.15,a.displayOptions.sphereScaleUnit=a.displayOptions.sphereScaleUnit??2,a.displayOptions.sphereFactor=a.displayOptions.sphereFactor??.865,a.displayOptions.spurFollowsChild=a.displayOptions.spurFollowsChild??!1,a.displayOptions.showLocalAxes=a.displayOptions.showLocalAxes??!1,a.displayOptions.localAxesSize=a.displayOptions.localAxesSize??.075,a.computeBonesUsingShaders=a.computeBonesUsingShaders??!0,a.useAllBones=a.useAllBones??!0,this._boneIndices=new Set,!a.useAllBones){const c=t==null?void 0:t.getVerticesData(Z.MatricesIndicesKind),l=t==null?void 0:t.getVerticesData(Z.MatricesWeightsKind);if(c&&l)for(let h=0;hdh.DISPLAY_SPHERE_AND_SPURS&&(o=dh.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){switch(this.displayMode){case dh.DISPLAY_LINES:{this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()});break}}}update(){switch(this.displayMode){case dh.DISPLAY_LINES:{this._displayLinesUpdate();break}case dh.DISPLAY_SPHERES:{this._buildSpheresAndSpurs(!0);break}case dh.DISPLAY_SPHERE_AND_SPURS:{this._buildSpheresAndSpurs(!1);break}}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,s=0,a=0){const o=ie.Matrix[0],c=t.getParent();if(o.copyFrom(t.getLocalMatrix()),r!==0||s!==0||a!==0){const l=ie.Matrix[1];ce.IdentityToRef(l),l.setTranslationFromFloats(r,s,a),l.multiplyToRef(o,o)}c&&o.multiplyToRef(c.getAbsoluteMatrix(),o),o.multiplyToRef(i,o),e.x=o.m[12],e.y=o.m[13],e.z=o.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length;let r,s;t?(r=t.getWorldMatrix(),s=t.position):(r=new ce,s=e[0].position);let a=0;for(let o=0;o=0;o--){const c=e[o],l=c.getParent();if(!l||!this._boneIndices.has(c.getIndex())&&!this.options.useAllBones)continue;let h=this._debugLines[i];h||(h=[P.Zero(),P.Zero()],this._debugLines[i]=h),c.getAbsolutePositionToRef(s,h[0]),l.getAbsolutePositionToRef(s,h[1]),h[0].subtractInPlace(a),h[1].subtractInPlace(a),i++}r||s.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){if(e===null||e._index===-1){t.copyFrom(ce.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_createSpur(e,t,i,r,s,a){const o=i.subtract(e),c=o.length(),l=o.normalize().scale(c),h=s.midStep||.165,u=s.midStepFactor||.215,d=l.scale(h),f=_9("skeletonViewer",{shape:[new P(1,-1,0),new P(1,1,0),new P(-1,1,0),new P(-1,-1,0),new P(1,-1,0)],path:[P.Zero(),d,l],scaleFunction:g=>{switch(g){case 0:case 2:return 0;case 1:return c*u}return 0},sideOrientation:Se.DEFAULTSIDE,updatable:!1},a),p=f.getTotalVertices(),_=[],m=[];for(let g=0;g9?m.push(r.getIndex(),0,0,0):m.push(t.getIndex(),0,0,0);return f.position=e.clone(),f.setVerticesData(Z.MatricesWeightsKind,_,!1),f.setVerticesData(Z.MatricesIndicesKind,m,!1),f.convertToFlatShadedMesh(),f}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData(Z.PositionKind),i=this.mesh.getIndices(),r=this.mesh.getVerticesData(Z.MatricesWeightsKind),s=this.mesh.getVerticesData(Z.MatricesIndicesKind);if(!t||!i||!r||!s)return null;const a=new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let c=0;for(let l=0;l1e-5){P.FromArrayToRef(t,h*3,ie.Vector3[0]),a.minimizeInPlace(ie.Vector3[0]),o.maximizeInPlace(ie.Vector3[0]),c++;break}}}return c>1?{center:P.Center(a,o),radius:P.Distance(a,o)/2}:null}_buildSpheresAndSpurs(e=!0){var o;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const t=(o=this.utilityLayer)==null?void 0:o.utilityLayerScene,i=this.skeleton.bones,r=[],s=[],a=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,t.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let c=Number.NEGATIVE_INFINITY;const l=this.options.displayOptions||{};for(let p=0;p0)_.children.forEach(T=>{const S=new ce;T.getLocalMatrix().multiplyToRef(m,S);const N=new P;S.decompose(void 0,void 0,N);const D=P.Distance(g,N);D>c&&(c=D),!e&&s.push(this._createSpur(g,_,N,T,l,t))});else{const T=this._getBoundingSphereForBone(_.getIndex());if(T&&(T.radius>c&&(c=T.radius),!e)){let S;const N=_.getParent();N?(this._getAbsoluteBindPoseToRef(N,m),m.decompose(void 0,void 0,ie.Vector3[0]),S=g.subtract(ie.Vector3[0]).normalize().scale(T.radius).add(g)):S=T.center.subtract(g).normalize().scale(T.radius).add(g),s.push(this._createSpur(g,_,S,null,l,t))}}const v=l.sphereBaseSize||.2,x=Tl("skeletonViewer",{segments:6,diameter:v,updatable:!0},t),y=x.getTotalVertices(),C=[],b=[];for(let T=0;T{e.setEnabled(t<6&&this._showLines||t>=6&&this._showPlanes)}),this._oldPosition.set(Number.NaN,Number.NaN,Number.NaN),this._visible=!0}hide(){this._lightHelperFrustumMeshes.forEach(e=>{e.setEnabled(!1)}),this._visible=!1}update(){var t,i,r,s,a,o;if(!this._visible||this._oldPosition.equals(this._light.position)&&this._oldDirection.equals(this._light.direction)&&this._oldAutoCalc===this._light.autoCalcShadowZBounds&&this._oldMinZ===this._light.shadowMinZ&&this._oldMaxZ===this._light.shadowMaxZ)return;this._oldPosition.copyFrom(this._light.position),this._oldDirection.copyFrom(this._light.direction),this._oldAutoCalc=this._light.autoCalcShadowZBounds,this._oldMinZ=this._light.shadowMinZ,this._oldMaxZ=this._light.shadowMaxZ,ie.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,this._light.shadowMinZ!==void 0?this._light.shadowMinZ:this._camera.minZ),ie.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,this._light.shadowMaxZ!==void 0?this._light.shadowMaxZ:this._camera.maxZ);const e=this._getInvertViewMatrix();ie.Vector3[2].copyFromFloats(ie.Vector3[1].x,ie.Vector3[1].y,ie.Vector3[0].z),ie.Vector3[3].copyFromFloats(ie.Vector3[1].x,ie.Vector3[0].y,ie.Vector3[0].z),ie.Vector3[4].copyFromFloats(ie.Vector3[0].x,ie.Vector3[0].y,ie.Vector3[0].z),ie.Vector3[5].copyFromFloats(ie.Vector3[0].x,ie.Vector3[1].y,ie.Vector3[0].z),P.TransformCoordinatesToRef(ie.Vector3[2],e,ie.Vector3[2]),P.TransformCoordinatesToRef(ie.Vector3[3],e,ie.Vector3[3]),P.TransformCoordinatesToRef(ie.Vector3[4],e,ie.Vector3[4]),P.TransformCoordinatesToRef(ie.Vector3[5],e,ie.Vector3[5]),ie.Vector3[6].copyFromFloats(ie.Vector3[1].x,ie.Vector3[1].y,ie.Vector3[1].z),ie.Vector3[7].copyFromFloats(ie.Vector3[1].x,ie.Vector3[0].y,ie.Vector3[1].z),ie.Vector3[8].copyFromFloats(ie.Vector3[0].x,ie.Vector3[0].y,ie.Vector3[1].z),ie.Vector3[9].copyFromFloats(ie.Vector3[0].x,ie.Vector3[1].y,ie.Vector3[1].z),P.TransformCoordinatesToRef(ie.Vector3[6],e,ie.Vector3[6]),P.TransformCoordinatesToRef(ie.Vector3[7],e,ie.Vector3[7]),P.TransformCoordinatesToRef(ie.Vector3[8],e,ie.Vector3[8]),P.TransformCoordinatesToRef(ie.Vector3[9],e,ie.Vector3[9]),Us("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),Us("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),Us("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),Us("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),Us("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),Us("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),ie.Vector3[2].toArray(this._nearPlaneVertices,0),ie.Vector3[3].toArray(this._nearPlaneVertices,3),ie.Vector3[4].toArray(this._nearPlaneVertices,6),ie.Vector3[5].toArray(this._nearPlaneVertices,9),(t=this._lightHelperFrustumMeshes[6].geometry)==null||t.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),ie.Vector3[6].toArray(this._farPlaneVertices,0),ie.Vector3[7].toArray(this._farPlaneVertices,3),ie.Vector3[8].toArray(this._farPlaneVertices,6),ie.Vector3[9].toArray(this._farPlaneVertices,9),(i=this._lightHelperFrustumMeshes[7].geometry)==null||i.updateVerticesDataDirectly("position",this._farPlaneVertices,0),ie.Vector3[2].toArray(this._rightPlaneVertices,0),ie.Vector3[6].toArray(this._rightPlaneVertices,3),ie.Vector3[7].toArray(this._rightPlaneVertices,6),ie.Vector3[3].toArray(this._rightPlaneVertices,9),(r=this._lightHelperFrustumMeshes[8].geometry)==null||r.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),ie.Vector3[5].toArray(this._leftPlaneVertices,0),ie.Vector3[9].toArray(this._leftPlaneVertices,3),ie.Vector3[8].toArray(this._leftPlaneVertices,6),ie.Vector3[4].toArray(this._leftPlaneVertices,9),(s=this._lightHelperFrustumMeshes[9].geometry)==null||s.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),ie.Vector3[2].toArray(this._topPlaneVertices,0),ie.Vector3[6].toArray(this._topPlaneVertices,3),ie.Vector3[9].toArray(this._topPlaneVertices,6),ie.Vector3[5].toArray(this._topPlaneVertices,9),(a=this._lightHelperFrustumMeshes[10].geometry)==null||a.updateVerticesDataDirectly("position",this._topPlaneVertices,0),ie.Vector3[3].toArray(this._bottomPlaneVertices,0),ie.Vector3[7].toArray(this._bottomPlaneVertices,3),ie.Vector3[8].toArray(this._bottomPlaneVertices,6),ie.Vector3[4].toArray(this._bottomPlaneVertices,9),(o=this._lightHelperFrustumMeshes[11].geometry)==null||o.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}dispose(){this._lightHelperFrustumMeshes.forEach(e=>{var t;(t=e.material)==null||t.dispose(),e.dispose()}),this._rootNode.dispose()}_createGeometry(){this._rootNode=new Et("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[ie.Vector3[0],ie.Vector3[1],ie.Vector3[2],ie.Vector3[3],ie.Vector3[4]];const e=Us("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[ie.Vector3[5],ie.Vector3[6],ie.Vector3[7],ie.Vector3[8],ie.Vector3[9]];const t=Us("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[ie.Vector3[10],ie.Vector3[11]];const i=Us("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[ie.Vector3[12],ie.Vector3[0]];const r=Us("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[ie.Vector3[1],ie.Vector3[2]];const s=Us("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[ie.Vector3[3],ie.Vector3[4]];const a=Us("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);a.parent=this._rootNode,a.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,r,s,a);const o=(c,l,h)=>{const u=new Se(c+"plane",this._scene),d=new tt(c+"PlaneMat",this._scene);u.material=d,u.parent=this._rootNode,u.alwaysSelectAsActiveMesh=!0,d.emissiveColor=l,d.alpha=this.transparency,d.backFaceCulling=!1,d.disableLighting=!0;const f=[0,1,2,0,2,3],p=new et;p.positions=h,p.indices=f,p.applyToMesh(u,!0),this._lightHelperFrustumMeshes.push(u)};this._nearPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._farPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._rightPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._leftPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._topPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._bottomPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],o("near",new Me(1,0,0),this._nearPlaneVertices),o("far",new Me(.3,0,0),this._farPlaneVertices),o("right",new Me(0,1,0),this._rightPlaneVertices),o("left",new Me(0,.3,0),this._leftPlaneVertices),o("top",new Me(0,0,1),this._topPlaneVertices),o("bottom",new Me(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=ie.Vector3[2],this._nearLinesPoints[1]=ie.Vector3[3],this._nearLinesPoints[2]=ie.Vector3[4],this._nearLinesPoints[3]=ie.Vector3[5],this._nearLinesPoints[4]=ie.Vector3[2],this._farLinesPoints[0]=ie.Vector3[6],this._farLinesPoints[1]=ie.Vector3[7],this._farLinesPoints[2]=ie.Vector3[8],this._farLinesPoints[3]=ie.Vector3[9],this._farLinesPoints[4]=ie.Vector3[6],this._trLinesPoints[0]=ie.Vector3[2],this._trLinesPoints[1]=ie.Vector3[6],this._brLinesPoints[0]=ie.Vector3[3],this._brLinesPoints[1]=ie.Vector3[7],this._tlLinesPoints[0]=ie.Vector3[4],this._tlLinesPoints[1]=ie.Vector3[8],this._blLinesPoints[0]=ie.Vector3[5],this._blLinesPoints[1]=ie.Vector3[9]}_getInvertViewMatrix(){return ce.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),P.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}class Le{}Le.ALPHA_DISABLE=0;Le.ALPHA_ADD=1;Le.ALPHA_COMBINE=2;Le.ALPHA_SUBTRACT=3;Le.ALPHA_MULTIPLY=4;Le.ALPHA_MAXIMIZED=5;Le.ALPHA_ONEONE=6;Le.ALPHA_PREMULTIPLIED=7;Le.ALPHA_PREMULTIPLIED_PORTERDUFF=8;Le.ALPHA_INTERPOLATE=9;Le.ALPHA_SCREENMODE=10;Le.ALPHA_ONEONE_ONEONE=11;Le.ALPHA_ALPHATOCOLOR=12;Le.ALPHA_REVERSEONEMINUS=13;Le.ALPHA_SRC_DSTONEMINUSSRCALPHA=14;Le.ALPHA_ONEONE_ONEZERO=15;Le.ALPHA_EXCLUSION=16;Le.ALPHA_LAYER_ACCUMULATE=17;Le.ALPHA_EQUATION_ADD=0;Le.ALPHA_EQUATION_SUBSTRACT=1;Le.ALPHA_EQUATION_REVERSE_SUBTRACT=2;Le.ALPHA_EQUATION_MAX=3;Le.ALPHA_EQUATION_MIN=4;Le.ALPHA_EQUATION_DARKEN=5;Le.DELAYLOADSTATE_NONE=0;Le.DELAYLOADSTATE_LOADED=1;Le.DELAYLOADSTATE_LOADING=2;Le.DELAYLOADSTATE_NOTLOADED=4;Le.NEVER=512;Le.ALWAYS=519;Le.LESS=513;Le.EQUAL=514;Le.LEQUAL=515;Le.GREATER=516;Le.GEQUAL=518;Le.NOTEQUAL=517;Le.KEEP=7680;Le.ZERO=0;Le.REPLACE=7681;Le.INCR=7682;Le.DECR=7683;Le.INVERT=5386;Le.INCR_WRAP=34055;Le.DECR_WRAP=34056;Le.TEXTURE_CLAMP_ADDRESSMODE=0;Le.TEXTURE_WRAP_ADDRESSMODE=1;Le.TEXTURE_MIRROR_ADDRESSMODE=2;Le.TEXTURE_CREATIONFLAG_STORAGE=1;Le.TEXTUREFORMAT_ALPHA=0;Le.TEXTUREFORMAT_LUMINANCE=1;Le.TEXTUREFORMAT_LUMINANCE_ALPHA=2;Le.TEXTUREFORMAT_RGB=4;Le.TEXTUREFORMAT_RGBA=5;Le.TEXTUREFORMAT_RED=6;Le.TEXTUREFORMAT_R=6;Le.TEXTUREFORMAT_RG=7;Le.TEXTUREFORMAT_RED_INTEGER=8;Le.TEXTUREFORMAT_R_INTEGER=8;Le.TEXTUREFORMAT_RG_INTEGER=9;Le.TEXTUREFORMAT_RGB_INTEGER=10;Le.TEXTUREFORMAT_RGBA_INTEGER=11;Le.TEXTUREFORMAT_BGRA=12;Le.TEXTUREFORMAT_DEPTH24_STENCIL8=13;Le.TEXTUREFORMAT_DEPTH32_FLOAT=14;Le.TEXTUREFORMAT_DEPTH16=15;Le.TEXTUREFORMAT_DEPTH24=16;Le.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17;Le.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18;Le.TEXTUREFORMAT_STENCIL8=19;Le.TEXTUREFORMAT_UNDEFINED=4294967295;Le.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492;Le.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493;Le.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495;Le.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494;Le.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779;Le.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919;Le.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778;Le.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918;Le.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777;Le.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776;Le.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917;Le.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916;Le.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808;Le.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840;Le.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196;Le.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492;Le.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493;Le.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494;Le.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495;Le.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496;Le.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497;Le.TEXTURETYPE_UNSIGNED_BYTE=0;Le.TEXTURETYPE_UNSIGNED_INT=0;Le.TEXTURETYPE_FLOAT=1;Le.TEXTURETYPE_HALF_FLOAT=2;Le.TEXTURETYPE_BYTE=3;Le.TEXTURETYPE_SHORT=4;Le.TEXTURETYPE_UNSIGNED_SHORT=5;Le.TEXTURETYPE_INT=6;Le.TEXTURETYPE_UNSIGNED_INTEGER=7;Le.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;Le.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;Le.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;Le.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;Le.TEXTURETYPE_UNSIGNED_INT_24_8=12;Le.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;Le.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;Le.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;Le.TEXTURETYPE_UNDEFINED=16;Le.TEXTURE_2D=3553;Le.TEXTURE_2D_ARRAY=35866;Le.TEXTURE_CUBE_MAP=34067;Le.TEXTURE_CUBE_MAP_ARRAY=3735928559;Le.TEXTURE_3D=32879;Le.TEXTURE_NEAREST_SAMPLINGMODE=1;Le.TEXTURE_NEAREST_NEAREST=1;Le.TEXTURE_BILINEAR_SAMPLINGMODE=2;Le.TEXTURE_LINEAR_LINEAR=2;Le.TEXTURE_TRILINEAR_SAMPLINGMODE=3;Le.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;Le.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;Le.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;Le.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;Le.TEXTURE_NEAREST_LINEAR=7;Le.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;Le.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;Le.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;Le.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;Le.TEXTURE_LINEAR_NEAREST=12;Le.TEXTURE_EXPLICIT_MODE=0;Le.TEXTURE_SPHERICAL_MODE=1;Le.TEXTURE_PLANAR_MODE=2;Le.TEXTURE_CUBIC_MODE=3;Le.TEXTURE_PROJECTION_MODE=4;Le.TEXTURE_SKYBOX_MODE=5;Le.TEXTURE_INVCUBIC_MODE=6;Le.TEXTURE_EQUIRECTANGULAR_MODE=7;Le.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;Le.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;Le.TEXTURE_FILTERING_QUALITY_OFFLINE=4096;Le.TEXTURE_FILTERING_QUALITY_HIGH=64;Le.TEXTURE_FILTERING_QUALITY_MEDIUM=16;Le.TEXTURE_FILTERING_QUALITY_LOW=8;Le.SCALEMODE_FLOOR=1;Le.SCALEMODE_NEAREST=2;Le.SCALEMODE_CEILING=3;Le.MATERIAL_TextureDirtyFlag=1;Le.MATERIAL_LightDirtyFlag=2;Le.MATERIAL_FresnelDirtyFlag=4;Le.MATERIAL_AttributesDirtyFlag=8;Le.MATERIAL_MiscDirtyFlag=16;Le.MATERIAL_PrePassDirtyFlag=32;Le.MATERIAL_AllDirtyFlag=63;Le.MATERIAL_TriangleFillMode=0;Le.MATERIAL_WireFrameFillMode=1;Le.MATERIAL_PointFillMode=2;Le.MATERIAL_PointListDrawMode=3;Le.MATERIAL_LineListDrawMode=4;Le.MATERIAL_LineLoopDrawMode=5;Le.MATERIAL_LineStripDrawMode=6;Le.MATERIAL_TriangleStripDrawMode=7;Le.MATERIAL_TriangleFanDrawMode=8;Le.MATERIAL_ClockWiseSideOrientation=0;Le.MATERIAL_CounterClockWiseSideOrientation=1;Le.ACTION_NothingTrigger=0;Le.ACTION_OnPickTrigger=1;Le.ACTION_OnLeftPickTrigger=2;Le.ACTION_OnRightPickTrigger=3;Le.ACTION_OnCenterPickTrigger=4;Le.ACTION_OnPickDownTrigger=5;Le.ACTION_OnDoublePickTrigger=6;Le.ACTION_OnPickUpTrigger=7;Le.ACTION_OnPickOutTrigger=16;Le.ACTION_OnLongPressTrigger=8;Le.ACTION_OnPointerOverTrigger=9;Le.ACTION_OnPointerOutTrigger=10;Le.ACTION_OnEveryFrameTrigger=11;Le.ACTION_OnIntersectionEnterTrigger=12;Le.ACTION_OnIntersectionExitTrigger=13;Le.ACTION_OnKeyDownTrigger=14;Le.ACTION_OnKeyUpTrigger=15;Le.PARTICLES_BILLBOARDMODE_Y=2;Le.PARTICLES_BILLBOARDMODE_ALL=7;Le.PARTICLES_BILLBOARDMODE_STRETCHED=8;Le.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9;Le.MESHES_CULLINGSTRATEGY_STANDARD=0;Le.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;Le.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;Le.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;Le.SCENELOADER_NO_LOGGING=0;Le.SCENELOADER_MINIMAL_LOGGING=1;Le.SCENELOADER_SUMMARY_LOGGING=2;Le.SCENELOADER_DETAILED_LOGGING=3;Le.PREPASS_IRRADIANCE_TEXTURE_TYPE=0;Le.PREPASS_POSITION_TEXTURE_TYPE=1;Le.PREPASS_VELOCITY_TEXTURE_TYPE=2;Le.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3;Le.PREPASS_COLOR_TEXTURE_TYPE=4;Le.PREPASS_DEPTH_TEXTURE_TYPE=5;Le.PREPASS_NORMAL_TEXTURE_TYPE=6;Le.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7;Le.BUFFER_CREATIONFLAG_READ=1;Le.BUFFER_CREATIONFLAG_WRITE=2;Le.BUFFER_CREATIONFLAG_READWRITE=3;Le.BUFFER_CREATIONFLAG_UNIFORM=4;Le.BUFFER_CREATIONFLAG_VERTEX=8;Le.BUFFER_CREATIONFLAG_INDEX=16;Le.BUFFER_CREATIONFLAG_STORAGE=32;Le.RENDERPASS_MAIN=0;Le.INPUT_ALT_KEY=18;Le.INPUT_CTRL_KEY=17;Le.INPUT_META_KEY1=91;Le.INPUT_META_KEY2=92;Le.INPUT_META_KEY3=93;Le.INPUT_SHIFT_KEY=16;Le.SNAPSHOTRENDERING_STANDARD=0;Le.SNAPSHOTRENDERING_FAST=1;Le.PERSPECTIVE_CAMERA=0;Le.ORTHOGRAPHIC_CAMERA=1;Le.FOVMODE_VERTICAL_FIXED=0;Le.FOVMODE_HORIZONTAL_FIXED=1;Le.RIG_MODE_NONE=0;Le.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;Le.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;Le.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;Le.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;Le.RIG_MODE_STEREOSCOPIC_INTERLACED=14;Le.RIG_MODE_VR=20;Le.RIG_MODE_CUSTOM=22;Le.MAX_SUPPORTED_UV_SETS=6;Le.GL_ALPHA_EQUATION_ADD=32774;Le.GL_ALPHA_EQUATION_MIN=32775;Le.GL_ALPHA_EQUATION_MAX=32776;Le.GL_ALPHA_EQUATION_SUBTRACT=32778;Le.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779;Le.GL_ALPHA_FUNCTION_SRC=768;Le.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769;Le.GL_ALPHA_FUNCTION_SRC_ALPHA=770;Le.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771;Le.GL_ALPHA_FUNCTION_DST_ALPHA=772;Le.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773;Le.GL_ALPHA_FUNCTION_DST_COLOR=774;Le.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775;Le.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776;Le.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769;Le.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770;Le.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771;Le.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772;Le.SnippetUrl="https://snippet.babylonjs.com";Le.FOGMODE_NONE=0;Le.FOGMODE_EXP=1;Le.FOGMODE_EXP2=2;Le.FOGMODE_LINEAR=3;Le.BYTE=5120;Le.UNSIGNED_BYTE=5121;Le.SHORT=5122;Le.UNSIGNED_SHORT=5123;Le.INT=5124;Le.UNSIGNED_INT=5125;Le.FLOAT=5126;Le.PositionKind="position";Le.NormalKind="normal";Le.TangentKind="tangent";Le.UVKind="uv";Le.UV2Kind="uv2";Le.UV3Kind="uv3";Le.UV4Kind="uv4";Le.UV5Kind="uv5";Le.UV6Kind="uv6";Le.ColorKind="color";Le.ColorInstanceKind="instanceColor";Le.MatricesIndicesKind="matricesIndices";Le.MatricesWeightsKind="matricesWeights";Le.MatricesIndicesExtraKind="matricesIndicesExtra";Le.MatricesWeightsExtraKind="matricesWeightsExtra";class b2e{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class E2e extends De{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new b2e){super(null),De.Instances.push(this),e.deterministicLockstep===void 0&&(e.deterministicLockstep=!1),e.timeStep!==void 0&&(this._timeStep=e.timeStep),e.lockstepMaxSteps===void 0&&(e.lockstepMaxSteps=4),this._options=e,bo.SetMatrixPrecision(!!e.useHighPrecisionMatrix),this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:128,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},de.Log(`Babylon.js v${De.Version} - Null engine`);const t=typeof self<"u"?self:typeof global<"u"?global:window;typeof URL>"u"&&(t.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(t.Blob=function(){})}createVertexBuffer(e){const t=new Jp;return t.references=1,t}createIndexBuffer(e){const t=new Jp;return t.references=1,t}clear(e,t,i,r=!1){}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight}setViewport(e,t,i){this._cachedViewport=e}createShaderProgram(e,t,i,r,s){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=e!==null&&Sn.IsWrapper(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setState(e,t=0,i,r=!1,s,a,o=0){}setIntArray(e,t){return!0}setIntArray2(e,t){return!0}setIntArray3(e,t){return!0}setIntArray4(e,t){return!0}setFloatArray(e,t){return!0}setFloatArray2(e,t){return!0}setFloatArray3(e,t){return!0}setFloatArray4(e,t){return!0}setArray(e,t){return!0}setArray2(e,t){return!0}setArray3(e,t){return!0}setArray4(e,t){return!0}setMatrices(e,t){return!0}setMatrix3x3(e,t){return!0}setMatrix2x2(e,t){return!0}setFloat(e,t){return!0}setFloat2(e,t,i){return!0}setFloat3(e,t,i,r){return!0}setBool(e,t){return!0}setFloat4(e,t,i,r,s){return!0}setAlphaMode(e,t=!1){this._alphaMode!==e&&(this.alphaState.alphaBlend=e!==0,t||this.setDepthWrite(e===0),this._alphaMode=e)}bindBuffers(e,t,i){}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}draw(e,t,i,r){}drawElementsType(e,t,i,r){}drawArraysType(e,t,i,r){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,r,s=3,a=null,o=null,c=null,l=null,h=null,u=null,d){const f=new Ar(this,mi.Url),p=String(e);return f.url=p,f.generateMipMaps=!t,f.samplingMode=s,f.invertY=i,f.baseWidth=this._options.textureSize,f.baseHeight=this._options.textureSize,f.width=this._options.textureSize,f.height=this._options.textureSize,h&&(f.format=h),f.isReady=!0,a&&setTimeout(()=>{a(f)}),this._internalTexturesCache.push(f),f}_createHardwareRenderTargetWrapper(e,t,i){const r=new XO(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),r={};t!==void 0&&typeof t=="object"?(r.generateMipMaps=t.generateMipMaps,r.generateDepthBuffer=t.generateDepthBuffer===void 0?!0:t.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&t.generateStencilBuffer,r.type=t.type===void 0?0:t.type,r.samplingMode=t.samplingMode===void 0?3:t.samplingMode):(r.generateMipMaps=t,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.type=0,r.samplingMode=3);const s=new Ar(this,mi.RenderTarget),a=e.width||e,o=e.height||e;return i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer,s.baseWidth=a,s.baseHeight=o,s.width=a,s.height=o,s.isReady=!0,s.samples=1,s.generateMipMaps=!!r.generateMipMaps,s.samplingMode=r.samplingMode,s.type=r.type,this._internalTexturesCache.push(s),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),r={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(r.type===1&&!this._caps.textureFloatLinearFiltering||r.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(r.samplingMode=1),i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer;const s=new Ar(this,mi.RenderTarget);return s.baseWidth=e,s.baseHeight=e,s.width=e,s.height=e,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=!!r.generateMipMaps,s.samplingMode=r.samplingMode,s.type=r.type,this._internalTexturesCache.push(s),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,r,s,a,o,c=null,l=0,h=0,u=!1){const d=new Ar(this,mi.Raw);return d.baseWidth=t,d.baseHeight=i,d.width=t,d.height=i,d.format=r,d.generateMipMaps=s,d.samplingMode=o,d.invertY=a,d._compression=c,d.type=l,d._useSRGBBuffer=u,this._doNotHandleContextLost||(d._bufferView=e),d}updateRawTexture(e,t,i,r,s=null,a=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s,e.type=a,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,r,s){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!s&&this.setViewport(this._cachedViewport,i,r)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new Jp;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,r=!1,s){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,r){}_bindTextureDirectly(e,t){return this._boundTexturesCache[this._activeChannel]!==t?(this._boundTexturesCache[this._activeChannel]=t,!0):!1}_bindTexture(e,t){e<0||this._bindTextureDirectly(0,t)}_deleteBuffer(e){}releaseEffects(){}displayLoadingUI(){}hideLoadingUI(){}set loadingUIText(e){}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,r=0){}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){}_uploadImageToTexture(e,t,i=0,r=0){}}yt.prototype._debugPushGroup=function(n,e){};yt.prototype._debugPopGroup=function(n){};yt.prototype._debugInsertMarker=function(n,e){};yt.prototype._debugFlushPendingCommands=function(){};class T2e{constructor(){this._timeElapsedQueryEnded=!1}}class S2e{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=di.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=di.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}De.prototype.createQuery=function(){const n=this._gl.createQuery();if(!n)throw new Error("Unable to create Occlusion Query");return n};De.prototype.deleteQuery=function(n){return this._gl.deleteQuery(n),this};De.prototype.isQueryResultAvailable=function(n){return this._gl.getQueryParameter(n,this._gl.QUERY_RESULT_AVAILABLE)};De.prototype.getQueryResult=function(n){return this._gl.getQueryParameter(n,this._gl.QUERY_RESULT)};De.prototype.beginOcclusionQuery=function(n,e){const t=this._getGlAlgorithmType(n);return this._gl.beginQuery(t,e),!0};De.prototype.endOcclusionQuery=function(n){const e=this._getGlAlgorithmType(n);return this._gl.endQuery(e),this};De.prototype._createTimeQuery=function(){const n=this.getCaps().timerQuery;return n.createQueryEXT?n.createQueryEXT():this.createQuery()};De.prototype._deleteTimeQuery=function(n){const e=this.getCaps().timerQuery;if(e.deleteQueryEXT){e.deleteQueryEXT(n);return}this.deleteQuery(n)};De.prototype._getTimeQueryResult=function(n){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(n,e.QUERY_RESULT_EXT):this.getQueryResult(n)};De.prototype._getTimeQueryAvailability=function(n){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(n,e.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(n)};De.prototype.startTimeQuery=function(){const n=this.getCaps(),e=n.timerQuery;if(!e)return null;const t=new T2e;if(this._gl.getParameter(e.GPU_DISJOINT_EXT),n.canUseTimestampForTimerQuery)t._startTimeQuery=this._createTimeQuery(),e.queryCounterEXT(t._startTimeQuery,e.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;t._timeElapsedQuery=this._createTimeQuery(),e.beginQueryEXT?e.beginQueryEXT(e.TIME_ELAPSED_EXT,t._timeElapsedQuery):this._gl.beginQuery(e.TIME_ELAPSED_EXT,t._timeElapsedQuery),this._currentNonTimestampToken=t}return t};De.prototype.endTimeQuery=function(n){const e=this.getCaps(),t=e.timerQuery;if(!t||!n)return-1;if(e.canUseTimestampForTimerQuery){if(!n._startTimeQuery)return-1;n._endTimeQuery||(n._endTimeQuery=this._createTimeQuery(),t.queryCounterEXT(n._endTimeQuery,t.TIMESTAMP_EXT))}else if(!n._timeElapsedQueryEnded){if(!n._timeElapsedQuery)return-1;t.endQueryEXT?t.endQueryEXT(t.TIME_ELAPSED_EXT):(this._gl.endQuery(t.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),n._timeElapsedQueryEnded=!0}const i=this._gl.getParameter(t.GPU_DISJOINT_EXT);let r=!1;if(n._endTimeQuery?r=this._getTimeQueryAvailability(n._endTimeQuery):n._timeElapsedQuery&&(r=this._getTimeQueryAvailability(n._timeElapsedQuery)),r&&!i){let s=0;if(e.canUseTimestampForTimerQuery){if(!n._startTimeQuery||!n._endTimeQuery)return-1;const a=this._getTimeQueryResult(n._startTimeQuery);s=this._getTimeQueryResult(n._endTimeQuery)-a,this._deleteTimeQuery(n._startTimeQuery),this._deleteTimeQuery(n._endTimeQuery),n._startTimeQuery=null,n._endTimeQuery=null}else{if(!n._timeElapsedQuery)return-1;s=this._getTimeQueryResult(n._timeElapsedQuery),this._deleteTimeQuery(n._timeElapsedQuery),n._timeElapsedQuery=null,n._timeElapsedQueryEnded=!1}return s}return-1};De.prototype._captureGPUFrameTime=!1;De.prototype._gpuFrameTime=new Fa;De.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime};De.prototype.captureGPUFrameTime=function(n){n!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=n,n?(this._onBeginFrameObserver=this.onBeginFrameObservable.add(()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))})):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))};De.prototype._getGlAlgorithmType=function(n){return n===di.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};Object.defineProperty(di.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(n){this._occlusionDataStorage.isOcclusionQueryInProgress=n},enumerable:!1,configurable:!0});Object.defineProperty(di.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new S2e),this.__occlusionDataStorage},enumerable:!1,configurable:!0});Object.defineProperty(di.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(n){this._occlusionDataStorage.isOccluded=n},enumerable:!0,configurable:!0});Object.defineProperty(di.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(n){this._occlusionDataStorage.occlusionQueryAlgorithmType=n},enumerable:!0,configurable:!0});Object.defineProperty(di.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(n){this._occlusionDataStorage.occlusionType=n},enumerable:!0,configurable:!0});Object.defineProperty(di.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(n){this._occlusionDataStorage.occlusionRetryCount=n},enumerable:!0,configurable:!0});Object.defineProperty(di.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(n){this._occlusionDataStorage.forceRenderingWhenOccluded=n},enumerable:!0,configurable:!0});di.prototype._checkOcclusionQuery=function(){const n=this._occlusionDataStorage;if(n.occlusionType===di.OCCLUSION_TYPE_NONE)return n.isOccluded=!1,!1;const e=this.getEngine();if(!e.getCaps().supportOcclusionQuery||!e.isQueryResultAvailable)return n.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery!==null&&this._occlusionQuery!==void 0)if(e.isQueryResultAvailable(this._occlusionQuery)){const r=e.getQueryResult(this._occlusionQuery);n.isOcclusionQueryInProgress=!1,n.occlusionInternalRetryCounter=0,n.isOccluded=!(r>0)}else if(n.occlusionInternalRetryCounter++,n.occlusionRetryCount!==-1&&n.occlusionInternalRetryCounter>n.occlusionRetryCount)n.isOcclusionQueryInProgress=!1,n.occlusionInternalRetryCounter=0,n.isOccluded=n.occlusionType===di.OCCLUSION_TYPE_OPTIMISTIC?!1:n.isOccluded;else return n.occlusionType===di.OCCLUSION_TYPE_OPTIMISTIC?!1:n.isOccluded;const t=this.getScene();if(t.getBoundingBoxRenderer){const i=t.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=e.createQuery()),e.beginOcclusionQuery(n.occlusionQueryAlgorithmType,this._occlusionQuery)&&(i.renderOcclusionBoundingBox(this),e.endOcclusionQuery(n.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return n.isOccluded};var q7e=!0;De.prototype.createTransformFeedback=function(){const n=this._gl.createTransformFeedback();if(!n)throw new Error("Unable to create Transform Feedback");return n};De.prototype.deleteTransformFeedback=function(n){this._gl.deleteTransformFeedback(n)};De.prototype.bindTransformFeedback=function(n){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,n)};De.prototype.beginTransformFeedback=function(n=!0){this._gl.beginTransformFeedback(n?this._gl.POINTS:this._gl.TRIANGLES)};De.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()};De.prototype.setTranformFeedbackVaryings=function(n,e){this._gl.transformFeedbackVaryings(n,e,this._gl.INTERLEAVED_ATTRIBS)};De.prototype.bindTransformFeedbackBuffer=function(n){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,n?n.underlyingResource:null)};yt.prototype.createExternalTexture=function(n){return null};yt.prototype.setExternalTexture=function(n,e){throw new Error("setExternalTexture: This engine does not support external textures!")};yt.prototype.updateVideoTexture=function(n,e,t){if(!n||n._isDisabled)return;const i=this._getInternalFormat(n.format),r=this._getRGBABufferInternalSizedFormat(0,n.format),s=this._bindTextureDirectly(this._gl.TEXTURE_2D,n,!0);this._unpackFlipY(!t);try{if(this._videoTextureSupported===void 0&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,i,this._gl.UNSIGNED_BYTE,e),this._gl.getError()!==0?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,i,this._gl.UNSIGNED_BYTE,e);else{if(!n._workingCanvas){n._workingCanvas=this.createCanvas(n.width,n.height);const a=n._workingCanvas.getContext("2d");if(!a)throw new Error("Unable to get 2d context");n._workingContext=a,n._workingCanvas.width=n.width,n._workingCanvas.height=n.height}n._workingContext.clearRect(0,0,n.width,n.height),n._workingContext.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,n.width,n.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,i,this._gl.UNSIGNED_BYTE,n._workingCanvas)}n.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),s||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),n.isReady=!0}catch{n._isDisabled=!0}};yt.prototype.restoreSingleAttachment=function(){const n=this._gl;this.bindAttachments([n.BACK])};yt.prototype.restoreSingleAttachmentForRenderTarget=function(){const n=this._gl;this.bindAttachments([n.COLOR_ATTACHMENT0])};yt.prototype.buildTextureLayout=function(n){const e=this._gl,t=[];for(let i=0;i1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"],i.readBuffer(r[a]),i.drawBuffers(r),i.blitFramebuffer(0,0,o.width,o.height,0,0,o.width,o.height,i.COLOR_BUFFER_BIT,i.NEAREST)}for(let a=0;a1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"];i.drawBuffers(r)}for(let a=0;a1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(o=e.depthTextureFormat)),b.label=(e==null?void 0:e.label)??"MultiRenderTargetWrapper";const T=this._gl,S=T.createFramebuffer();this._bindUnboundFramebuffer(S);const N=n.width||n,D=n.height||n,M=[],I=[],R=this.webGLVersion>1&&a&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===18),O=this._setupFramebufferDepthAttachments(!R&&s,!a&&r,N,D);b._framebuffer=S,b._depthStencilBuffer=O,b._generateDepthBuffer=!a&&r,b._generateStencilBuffer=!R&&s,b._attachments=I;for(let H=0;H1||this.isWebGPU);const Y=this.webGLVersion>1,J=T[Y?"COLOR_ATTACHMENT"+H:"COLOR_ATTACHMENT"+H+"_WEBGL"];if(I.push(J),j===-1)continue;const re=new Ar(this,mi.MultiRenderTarget);M[H]=re,T.activeTexture(T["TEXTURE"+H]),T.bindTexture(j,re._hardwareTexture.underlyingResource),T.texParameteri(j,T.TEXTURE_MAG_FILTER,z.mag),T.texParameteri(j,T.TEXTURE_MIN_FILTER,z.min),T.texParameteri(j,T.TEXTURE_WRAP_S,T.CLAMP_TO_EDGE),T.texParameteri(j,T.TEXTURE_WRAP_T,T.CLAMP_TO_EDGE);const he=this._getRGBABufferInternalSizedFormat(Q,V,$),le=this._getInternalFormat(V),ue=this._getWebGLTextureType(Q);if(Y&&(j===35866||j===32879))j===35866?re.is2DArray=!0:re.is3D=!0,re.baseDepth=re.depth=k,T.texImage3D(j,0,he,N,D,k,0,le,ue,null);else if(j===34067){for(let L=0;L<6;L++)T.texImage2D(T.TEXTURE_CUBE_MAP_POSITIVE_X+L,0,he,N,D,0,le,ue,null);re.isCube=!0}else T.texImage2D(T.TEXTURE_2D,0,he,N,D,0,le,ue,null);i&&T.generateMipmap(j),this._bindTextureDirectly(j,null),re.baseWidth=N,re.baseHeight=D,re.width=N,re.height=D,re.isReady=!0,re.samples=1,re.generateMipMaps=i,re.samplingMode=G,re.type=Q,re._useSRGBBuffer=$,re.format=V,this._internalTexturesCache.push(re)}if(a&&this._caps.depthTextureExtension){const H=new Ar(this,mi.Depth);let G=5,Q=T.DEPTH_COMPONENT16,$=T.DEPTH_COMPONENT,V=T.UNSIGNED_SHORT,j=T.DEPTH_ATTACHMENT;this.webGLVersion<2?Q=T.DEPTH_COMPONENT:o===14?(G=1,V=T.FLOAT,Q=T.DEPTH_COMPONENT32F):o===18?(G=0,V=T.FLOAT_32_UNSIGNED_INT_24_8_REV,Q=T.DEPTH32F_STENCIL8,$=T.DEPTH_STENCIL,j=T.DEPTH_STENCIL_ATTACHMENT):o===16?(G=0,V=T.UNSIGNED_INT,Q=T.DEPTH_COMPONENT24,j=T.DEPTH_ATTACHMENT):(o===13||o===17)&&(G=12,V=T.UNSIGNED_INT_24_8,Q=T.DEPTH24_STENCIL8,$=T.DEPTH_STENCIL,j=T.DEPTH_STENCIL_ATTACHMENT),T.activeTexture(T.TEXTURE0),T.bindTexture(T.TEXTURE_2D,H._hardwareTexture.underlyingResource),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_MAG_FILTER,T.NEAREST),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_MIN_FILTER,T.NEAREST),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_WRAP_S,T.CLAMP_TO_EDGE),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_WRAP_T,T.CLAMP_TO_EDGE),T.texImage2D(T.TEXTURE_2D,0,Q,N,D,0,$,V,null),T.framebufferTexture2D(T.FRAMEBUFFER,j,T.TEXTURE_2D,H._hardwareTexture.underlyingResource,0),H.baseWidth=N,H.baseHeight=D,H.width=N,H.height=D,H.isReady=!0,H.samples=1,H.generateMipMaps=i,H.samplingMode=1,H.format=o,H.type=G,M[c]=H,this._internalTexturesCache.push(H)}return b.setTextures(M),t&&T.drawBuffers(I),this._bindUnboundFramebuffer(null),b.setLayerAndFaceIndices(y,x),this.resetTextureCache(),b};yt.prototype.updateMultipleRenderTargetTextureSampleCount=function(n,e,t=!0){if(this.webGLVersion<2||!n||!n.texture)return 1;if(n.samples===e)return e;const i=n._attachments.length;if(i===0)return 1;const r=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples);const s=!!n._depthStencilBuffer;if(s&&(r.deleteRenderbuffer(n._depthStencilBuffer),n._depthStencilBuffer=null),n._MSAAFramebuffer&&(r.deleteFramebuffer(n._MSAAFramebuffer),n._MSAAFramebuffer=null),e>1&&typeof r.renderbufferStorageMultisample=="function"){const a=r.createFramebuffer();if(!a)throw new Error("Unable to create multi sampled framebuffer");n._MSAAFramebuffer=a,this._bindUnboundFramebuffer(a);const o=[];for(let c=0;c1?"COLOR_ATTACHMENT"+c:"COLOR_ATTACHMENT"+c+"_WEBGL"],d=this._createRenderBuffer(l.width,l.height,e,-1,this._getRGBABufferInternalSizedFormat(l.type,l.format,l._useSRGBBuffer),u);if(!d)throw new Error("Unable to create multi sampled framebuffer");h.addMSAARenderBuffer(d),l.samples=e,o.push(u)}t&&r.drawBuffers(o)}else this._bindUnboundFramebuffer(n._framebuffer);return s&&(n._depthStencilBuffer=this._setupFramebufferDepthAttachments(n._generateStencilBuffer,n._generateDepthBuffer,n.texture.width,n.texture.height,e)),this._bindUnboundFramebuffer(null),e};yt.prototype._createDepthStencilCubeTexture=function(n,e){const t=new Ar(this,mi.DepthStencil);if(t.isCube=!0,this.webGLVersion===1)return de.Error("Depth cube texture is not supported by WebGL 1."),t;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,t,!0),this._setupDepthStencilTexture(t,n,i.generateStencil,i.bilinearFiltering,i.comparisonFunction);for(let s=0;s<6;s++)i.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,r.DEPTH24_STENCIL8,n,n,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,r.DEPTH_COMPONENT24,n,n,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(t),t};yt.prototype._partialLoadFile=function(n,e,t,i,r=null){const s=o=>{t[e]=o,t._internalCount++,t._internalCount===6&&i(t)},a=(o,c)=>{r&&o&&r(o.status+" "+o.statusText,c)};this._loadFile(n,s,void 0,void 0,!0,a)};yt.prototype._cascadeLoadFiles=function(n,e,t,i=null){const r=[];r._internalCount=0;for(let s=0;s<6;s++)this._partialLoadFile(t[s],s,r,e,i)};yt.prototype._cascadeLoadImgs=function(n,e,t,i,r=null,s){const a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(i[o],o,a,n,e,t,r,s)};yt.prototype._partialLoadImg=function(n,e,t,i,r,s,a=null,o){const c=mh();w5(n,u=>{t[e]=u,t._internalCount++,i&&i.removePendingData(c),t._internalCount===6&&s&&s(r,t)},(u,d)=>{i&&i.removePendingData(c),a&&a(u,d)},i?i.offlineProvider:null,o),i&&i.addPendingData(c)};yt.prototype._setCubeMapTextureParams=function(n,e,t){const i=this._gl;i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MIN_FILTER,e?i.LINEAR_MIPMAP_LINEAR:i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),n.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),n._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};yt.prototype.createCubeTextureBase=function(n,e,t,i,r=null,s=null,a,o=null,c=!1,l=0,h=0,u=null,d=null,f=null,p=!1){const _=u||new Ar(this,mi.Cube);_.isCube=!0,_.url=n,_.generateMipMaps=!i,_._lodGenerationScale=l,_._lodGenerationOffset=h,_._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!i),_!==u&&(_.label=n.substring(0,60)),this._doNotHandleContextLost||(_._extension=o,_._files=t);const m=n;this._transformTextureUrl&&!u&&(n=this._transformTextureUrl(n));const g=n.split("?")[0],v=g.lastIndexOf("."),x=o||(v>-1?g.substring(v).toLowerCase():"");let y=null;for(const b of yt._TextureLoaders)if(b.canLoad(x)){y=b;break}const C=(b,T)=>{n===m?s&&b&&s(b.status+" "+b.statusText,T):(de.Warn(`Failed to load ${n}, falling back to the ${m}`),this.createCubeTextureBase(m,e,t,!!i,r,s,a,o,c,l,h,_,d,f,p))};if(y){const b=T=>{d&&d(_,T),y.loadCubeData(T,_,c,r,s)};t&&t.length===6?y.supportCascades?this._cascadeLoadFiles(e,T=>b(T.map(S=>new Uint8Array(S))),t,s):s?s("Textures type does not support cascades."):de.Warn("Texture loader does not support cascades."):this._loadFile(n,T=>b(new Uint8Array(T)),void 0,void 0,!0,C)}else{if(!t||t.length===0)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(e,_,(b,T)=>{f&&f(b,T)},t,s)}return this._internalTexturesCache.push(_),_};yt.prototype.createCubeTexture=function(n,e,t,i,r=null,s=null,a,o=null,c=!1,l=0,h=0,u=null,d,f=!1){const p=this._gl;return this.createCubeTextureBase(n,e,t,!!i,r,s,a,o,c,l,h,u,_=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,_,!0),(_,m)=>{const g=this.needPOTTextures?yt.GetExponentOfTwo(m[0].width,this._caps.maxCubemapTextureSize):m[0].width,v=g,x=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);const y=a?this._getInternalFormat(a,_._useSRGBBuffer):_._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA;let C=a?this._getInternalFormat(a):p.RGBA;_._useSRGBBuffer&&this.webGLVersion===1&&(C=y);for(let b=0;b{this.unRegisterView(n)}),r};De.prototype.unRegisterView=function(n){if(!this.views||this.views.length===0)return this;for(const e of this.views)if(e.target===n){const t=this.views.indexOf(e);t!==-1&&this.views.splice(t,1);break}return this};De.prototype._renderViewStep=function(n){const e=n.target,t=e.getContext("2d");if(!t)return!0;const i=this.getRenderingCanvas();M2e.notifyObservers(n);const r=n.camera;let s=null,a=null,o=null;if(r&&(o=Array.isArray(r)?r[0].getScene():r.getScene(),s=o.activeCamera,a=o.activeCameras,this.activeView=n,Array.isArray(r)?o.activeCameras=r:(o.activeCamera=r,o.activeCameras=null)),n.customResize)n.customResize(e);else{const c=Math.floor(e.clientWidth/this._hardwareScalingLevel),l=Math.floor(e.clientHeight/this._hardwareScalingLevel),h=c!==e.width||i.width!==e.width||l!==e.height||i.height!==e.height;e.clientWidth&&e.clientHeight&&h&&(e.width=c,e.height=l,this.setSize(c,l))}return!i.width||!i.height?!1:(this._renderFrame(),this.flushFramebuffer(),n.clearBeforeCopy&&t.clearRect(0,0,i.width,i.height),t.drawImage(i,0,0),o&&(o.activeCameras=a,o.activeCamera=s),R2e.notifyObservers(n),!0)};De.prototype._renderViews=function(){if(!this.views||this.views.length===0||!this.getRenderingCanvas())return!1;let e;for(const t of this.views){if(!t.enabled)continue;if(t.target===this.inputElement){e=t;continue}if(!this._renderViewStep(t))return!1}return e&&!this._renderViewStep(e)?!1:(this.activeView=null,!0)};yt.prototype.createStorageBuffer=function(n,e){throw new Error("createStorageBuffer: Unsupported method in this engine!")};yt.prototype.updateStorageBuffer=function(n,e,t,i){};yt.prototype.readFromStorageBuffer=function(n,e,t,i){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")};yt.prototype.setStorageBuffer=function(n,e){throw new Error("setStorageBuffer: Unsupported method in this engine!")};function ewe(n){const e=s=>{const a="\\b"+s+"\\b";return n&&(n===s||n.match(new RegExp(a,"g")))};if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(e))return n;const t=n.lastIndexOf("."),i=n.lastIndexOf("?"),r=i>-1?n.substring(i,n.length):"";return(t>-1?n.substring(0,t):n)+this._textureFormatInUse+r}Object.defineProperty(De.prototype,"texturesSupported",{get:function(){const n=[];return this._caps.astc&&n.push("-astc.ktx"),this._caps.s3tc&&n.push("-dxt.ktx"),this._caps.pvrtc&&n.push("-pvrtc.ktx"),this._caps.etc2&&n.push("-etc2.ktx"),this._caps.etc1&&n.push("-etc1.ktx"),n},enumerable:!0,configurable:!0});Object.defineProperty(De.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0});De.prototype.setCompressedTextureExclusions=function(n){this._excludedCompressedTextures=n};De.prototype.setTextureFormatToUse=function(n){const e=this.texturesSupported;for(let t=0,i=e.length;t{this._flush()})}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}i4.DEFAULT_BUFFER_SIZE=65536;const g0=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],twe=[()=>1,n=>n.y,n=>n.z,n=>n.x,n=>n.x*n.y,n=>n.y*n.z,n=>3*n.z*n.z-1,n=>n.x*n.z,n=>n.x*n.x-n.y*n.y],nm=(n,e)=>g0[n]*twe[n](e),am=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class r4{constructor(){this.preScaled=!1,this.l00=P.Zero(),this.l1_1=P.Zero(),this.l10=P.Zero(),this.l11=P.Zero(),this.l2_2=P.Zero(),this.l2_1=P.Zero(),this.l20=P.Zero(),this.l21=P.Zero(),this.l22=P.Zero()}addLight(e,t,i){ie.Vector3[0].set(t.r,t.g,t.b);const r=ie.Vector3[0],s=ie.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(nm(0,e),ie.Vector3[2]),this.l00.addInPlace(ie.Vector3[2]),s.scaleToRef(nm(1,e),ie.Vector3[2]),this.l1_1.addInPlace(ie.Vector3[2]),s.scaleToRef(nm(2,e),ie.Vector3[2]),this.l10.addInPlace(ie.Vector3[2]),s.scaleToRef(nm(3,e),ie.Vector3[2]),this.l11.addInPlace(ie.Vector3[2]),s.scaleToRef(nm(4,e),ie.Vector3[2]),this.l2_2.addInPlace(ie.Vector3[2]),s.scaleToRef(nm(5,e),ie.Vector3[2]),this.l2_1.addInPlace(ie.Vector3[2]),s.scaleToRef(nm(6,e),ie.Vector3[2]),this.l20.addInPlace(ie.Vector3[2]),s.scaleToRef(nm(7,e),ie.Vector3[2]),this.l21.addInPlace(ie.Vector3[2]),s.scaleToRef(nm(8,e),ie.Vector3[2]),this.l22.addInPlace(ie.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(am[0]),this.l1_1.scaleInPlace(am[1]),this.l10.scaleInPlace(am[2]),this.l11.scaleInPlace(am[3]),this.l2_2.scaleInPlace(am[4]),this.l2_1.scaleInPlace(am[5]),this.l20.scaleInPlace(am[6]),this.l21.scaleInPlace(am[7]),this.l22.scaleInPlace(am[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(g0[0]),this.l1_1.scaleInPlace(g0[1]),this.l10.scaleInPlace(g0[2]),this.l11.scaleInPlace(g0[3]),this.l2_2.scaleInPlace(g0[4]),this.l2_1.scaleInPlace(g0[5]),this.l20.scaleInPlace(g0[6]),this.l21.scaleInPlace(g0[7]),this.l22.scaleInPlace(g0[8])}updateFromArray(e){return P.FromArrayToRef(e[0],0,this.l00),P.FromArrayToRef(e[1],0,this.l1_1),P.FromArrayToRef(e[2],0,this.l10),P.FromArrayToRef(e[3],0,this.l11),P.FromArrayToRef(e[4],0,this.l2_2),P.FromArrayToRef(e[5],0,this.l2_1),P.FromArrayToRef(e[6],0,this.l20),P.FromArrayToRef(e[7],0,this.l21),P.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return P.FromFloatsToRef(e[0],e[1],e[2],this.l00),P.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),P.FromFloatsToRef(e[6],e[7],e[8],this.l10),P.FromFloatsToRef(e[9],e[10],e[11],this.l11),P.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),P.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),P.FromFloatsToRef(e[18],e[19],e[20],this.l20),P.FromFloatsToRef(e[21],e[22],e[23],this.l21),P.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new r4().updateFromArray(e)}static FromPolynomial(e){const t=new r4;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class J0{constructor(){this.x=P.Zero(),this.y=P.Zero(),this.z=P.Zero(),this.xx=P.Zero(),this.yy=P.Zero(),this.zz=P.Zero(),this.xy=P.Zero(),this.yz=P.Zero(),this.zx=P.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=r4.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){ie.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=ie.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),ie.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),ie.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(ie.Vector3[0]).addInPlace(ie.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(ie.Vector3[0]).subtractInPlace(ie.Vector3[1]),this.zz.copyFrom(e.l00),ie.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(ie.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return new J0().updateFromHarmonics(e)}static FromArray(e){const t=new J0;return P.FromArrayToRef(e[0],0,t.x),P.FromArrayToRef(e[1],0,t.y),P.FromArrayToRef(e[2],0,t.z),P.FromArrayToRef(e[3],0,t.xx),P.FromArrayToRef(e[4],0,t.yy),P.FromArrayToRef(e[5],0,t.zz),P.FromArrayToRef(e[6],0,t.yz),P.FromArrayToRef(e[7],0,t.zx),P.FromArrayToRef(e[8],0,t.xy),t}}const iwe="rgbdDecodePixelShader",rwe=`varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;Re.ShadersStore[iwe]=rwe;function I2e(n,e,t,i=!0){const r=n.getScene(),s=r.getEngine(),a=new es("resized"+n.name,{width:e,height:t},r,!n.noMipmap,!0,n._texture.type,!1,n.samplingMode,!1);a.wrapU=n.wrapU,a.wrapV=n.wrapV,a.uOffset=n.uOffset,a.vOffset=n.vOffset,a.uScale=n.uScale,a.vScale=n.vScale,a.uAng=n.uAng,a.vAng=n.vAng,a.wAng=n.wAng,a.coordinatesIndex=n.coordinatesIndex,a.level=n.level,a.anisotropicFilteringLevel=n.anisotropicFilteringLevel,a._texture.isReady=!1,n.wrapU=ve.CLAMP_ADDRESSMODE,n.wrapV=ve.CLAMP_ADDRESSMODE;const o=new Zf("pass",1,null,i?ve.BILINEAR_SAMPLINGMODE:ve.NEAREST_SAMPLINGMODE,s,!1,0);return o.externalTextureSamplerBinding=!0,o.getEffect().executeWhenCompiled(()=>{o.onApply=function(l){l.setTexture("textureSampler",n)};const c=a.renderTarget;c&&(r.postProcessManager.directRender([o],c),s.unBindFramebuffer(c),a.disposeFramebufferObjects(),o.dispose(),a.getInternalTexture().isReady=!0)}),a}function BG(n,e,t,i,r,s,a,o){const c=e.getEngine();return e.isReady=!1,r=r??e.samplingMode,i=i??e.type,s=s??e.format,a=a??e.width,o=o??e.height,i===-1&&(i=0),new Promise(l=>{const h=new Pt("postprocess",n,null,null,1,null,r,c,!1,void 0,i,void 0,null,!1,s);h.externalTextureSamplerBinding=!0;const u=c.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:i,format:s});h.getEffect().executeWhenCompiled(()=>{h.onApply=d=>{d._bindTexture("textureSampler",e),d.setFloat2("scale",1,1)},t.postProcessManager.directRender([h],u,!0),c.restoreDefaultFramebuffer(),c._releaseTexture(e),h&&h.dispose(),u._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,l(e)})})}let _V,ode;function Gp(n){_V||(_V=new Float32Array(1),ode=new Int32Array(_V.buffer)),_V[0]=n;const e=ode[0];let t=e>>16&32768,i=e>>12&2047;const r=e>>23&255;return r<103?t:r>142?(t|=31744,t|=(r==255?0:1)&&e&8388607,t):r<113?(i|=2048,t|=(i>>114-r)+(i>>113-r&1),t):(t|=r-112<<10|i>>1,t+=i&1,t)}function Np(n){const e=(n&32768)>>15,t=(n&31744)>>10,i=n&1023;return t===0?(e?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):t==31?i?NaN:(e?-1:1)*(1/0):(e?-1:1)*Math.pow(2,t-15)*(1+i/Math.pow(2,10))}const swe=async(n,e,t,i,r)=>{const s=n.getScene(),a=s.getEngine();let o;if(!n.isCube)o=new Pt("lod","lod",["lod","gamma"],null,1,null,ve.NEAREST_NEAREST_MIPNEAREST,a);else{const h=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];o=new Pt("lodCube","lodCube",["lod","gamma"],null,1,null,ve.NEAREST_NEAREST_MIPNEAREST,a,!1,h[i])}await new Promise(h=>{o.getEffect().executeWhenCompiled(()=>{h(0)})});const c=new es("temp",{width:e,height:t},s,!1);o.onApply=function(h){h.setTexture("textureSampler",n),h.setFloat("lod",r),h.setBool("gamma",n.gammaSpace)};const l=n.getInternalTexture();try{if(c.renderTarget&&l){const h=l.samplingMode;r!==0?n.updateSamplingMode(ve.NEAREST_NEAREST_MIPNEAREST):n.updateSamplingMode(ve.NEAREST_NEAREST),s.postProcessManager.directRender([o],c.renderTarget,!0),n.updateSamplingMode(h);const u=await a.readPixels(0,0,e,t),d=new Uint8Array(u.buffer,0,u.byteLength);return a.unBindFramebuffer(c.renderTarget),d}else throw Error("Render to texture failed.")}finally{c.dispose(),o.dispose()}};async function P2e(n,e,t,i=0,r=0){return!n.isReady()&&n._texture&&await new Promise((s,a)=>{if(n._texture===null){a(0);return}n._texture.onLoadedObservable.addOnce(()=>{s(0)})}),await swe(n,e,t,i,r)}const w2e={CreateResizedCopy:I2e,ApplyPostProcess:BG,ToHalfFloat:Gp,FromHalfFloat:Np,GetTextureDataAsync:P2e};class zz{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),r=i.getCaps(),s=t.isReady;let a=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(a=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(a=!0,t.type=1),a&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{const c=new Pt("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);c.externalTextureSamplerBinding=!0;const l=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});c.getEffect().executeWhenCompiled(()=>{c.onApply=h=>{h._bindTexture("textureSampler",t),h.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([c],l,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),c&&c.dispose(),l._swapAndDie(t),t.isReady=!0})};a&&(s?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return BG("rgbdEncode",e,t,i,1,5)}}class mS{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}}class q6{static ConvertCubeMapTextureToSphericalPolynomial(e){var d;if(!e.isCube)return null;(d=e.getScene())==null||d.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),r=e.readPixels(1,void 0,void 0,!1);let s,a;e.isRenderTarget?(s=e.readPixels(3,void 0,void 0,!1),a=e.readPixels(2,void 0,void 0,!1)):(s=e.readPixels(2,void 0,void 0,!1),a=e.readPixels(3,void 0,void 0,!1));const o=e.readPixels(4,void 0,void 0,!1),c=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace,h=5;let u=0;return(e.textureType==1||e.textureType==2)&&(u=1),new Promise(f=>{Promise.all([r,i,s,a,o,c]).then(([p,_,m,g,v,x])=>{const y={size:t,right:_,left:p,up:m,down:g,front:v,back:x,format:h,type:u,gammaSpace:l};f(this.ConvertCubeMapToSphericalPolynomial(y))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new r4;let i=0;const r=2/e.size,s=r,a=.5*r,o=a-1;for(let d=0;d<6;d++){const f=this._FileFaces[d],p=e[f.name];let _=o;const m=e.format===5?4:3;for(let g=0;gN){const I=N/M;b*=I,T*=I,S*=I}}else b=_t.Clamp(b,0,N),T=_t.Clamp(T,0,N),S=_t.Clamp(S,0,N);const D=new Me(b,T,S);t.addLight(y,D,C),i+=C,v+=r}_+=s}}const u=4*Math.PI*6/6/i;return t.scaleInPlace(u),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),J0.FromHarmonics(t)}}q6._FileFaces=[new mS("right",new P(1,0,0),new P(0,0,-1),new P(0,-1,0)),new mS("left",new P(-1,0,0),new P(0,0,1),new P(0,-1,0)),new mS("up",new P(0,1,0),new P(1,0,0),new P(0,0,1)),new mS("down",new P(0,-1,0),new P(1,0,0),new P(0,0,-1)),new mS("front",new P(0,0,1),new P(1,0,0),new P(0,-1,0)),new mS("back",new P(0,0,-1),new P(-1,0,0),new P(0,-1,0))];q6.MAX_HDRI_VALUE=4096;q6.PRESERVE_CLAMPED_COLORS=!1;Er.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(Er.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=q6.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(n=>{this._texture._sphericalPolynomial=n,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(n){this._texture&&(this._texture._sphericalPolynomial=n)},enumerable:!0,configurable:!0});const nwe="rgbdEncodePixelShader",awe=`varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;Re.ShadersStore[nwe]=awe;const bee="image/png",k$=2,mD=[134,22,135,150,246,214,150,54];function FG(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength);let t=0;for(let a=0;ak$)throw new Error(`Unsupported babylon environment map version "${n.version}". Latest supported version is "${k$}".`);return n.version===2||(n={...n,version:2,imageType:bee}),n}async function D2e(n,e={}){var C;const t=n.getInternalTexture();if(!t)return Promise.reject("The cube texture is invalid.");const i=e.imageType??bee,r=t.getEngine();if(n.textureType!==2&&n.textureType!==1&&n.textureType!==0&&n.textureType!==0&&n.textureType!==7&&n.textureType!==-1)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let s=1;if(!r.getCaps().textureFloatRender&&(s=2,!r.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");n.sphericalPolynomial;const a=(C=n.getInternalTexture())==null?void 0:C._sphericalPolynomialPromise,o=t.width,c=new pt(r),l={};r.flushFramebuffer();const h=_t.ILog2(t.width);for(let b=0;b<=h;b++){const T=Math.pow(2,h-b);for(let S=0;S<6;S++){let N=await n.readPixels(S,b,void 0,!1);if(N&&N.byteLength===N.length){const R=new Float32Array(N.byteLength*4);for(let O=0;O{if(t){const f=e.createTexture(null,!0,!0,null,1,null,p=>{d(p)},n);i.getEffect().executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=p=>{p._bindTexture("textureSampler",f),p.setFloat2("scale",1,e._features.needsInvertingBitmap&&n instanceof ImageBitmap?-1:1)},e.scenes.length&&(e.scenes[0].postProcessManager.directRender([i],l,!0,s,a),e.restoreDefaultFramebuffer(),f.dispose(),URL.revokeObjectURL(r),u())})}else{if(e._uploadImageToTexture(h,n,s,a),o){const f=c[a];f&&e._uploadImageToTexture(f._texture,n,s,0)}u()}})}function KD(n,e,t=bee){if(!Ee.IsExponentOfTwo(n.width))throw new Error("Texture size must be a power of two");const i=_t.ILog2(n.width)+1,r=n.getEngine();let s=!1,a=!1,o=null,c=null,l=null;const h=r.getCaps();if(n.format=5,n.type=0,n.generateMipMaps=!0,n._cachedAnisotropicFilteringLevel=null,r.updateTextureSamplingMode(3,n),h.textureLOD?r._features.supportRenderAndCopyToLodForFloatTextures?h.textureHalfFloatRender&&h.textureHalfFloatLinearFiltering?(s=!0,n.type=2):h.textureFloatRender&&h.textureFloatLinearFiltering&&(s=!0,n.type=1):s=!1:(s=!1,a=!0,l={}),s)o=new Pt("rgbdDecode","rgbdDecode",null,null,1,null,3,r,!1,void 0,n.type,void 0,null,!1),n._isRGBD=!1,n.invertY=!1,c=r.createRenderTargetCubeTexture(n.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:n.type,format:5});else if(n._isRGBD=!0,n.invertY=!0,a){const f=n._lodGenerationScale,p=n._lodGenerationOffset;for(let _=0;_<3;_++){const g=1-_/2,v=p,x=(i-1)*f+p,y=v+(x-v)*g,C=Math.round(Math.min(Math.max(y,0),x)),b=new Ar(r,mi.Temp);b.isCube=!0,b.invertY=!0,b.generateMipMaps=!1,r.updateTextureSamplingMode(2,b);const T=new Er(null);switch(T._isCube=!0,T._texture=b,l[C]=T,_){case 0:n._lodTextureLow=T;break;case 1:n._lodTextureMid=T;break;case 2:n._lodTextureHigh=T;break}}}const u=[];for(let d=0;dlde(v,r,s,o,m,f,d,a,l,c,n));else{const v=new Image;v.src=m,g=new Promise((x,y)=>{v.onload=()=>{lde(v,r,s,o,m,f,d,a,l,c,n).then(()=>x()).catch(C=>{y(C)})},v.onerror=C=>{y(C)}})}u.push(g)}if(e.length{c&&(r._releaseTexture(n),c._swapAndDie(n)),o&&o.dispose(),a&&(n._lodTextureHigh&&n._lodTextureHigh._texture&&(n._lodTextureHigh._texture.isReady=!0),n._lodTextureMid&&n._lodTextureMid._texture&&(n._lodTextureMid._texture.isReady=!0),n._lodTextureLow&&n._lodTextureLow._texture&&(n._lodTextureLow._texture.isReady=!0))})}function kG(n,e){e=v9(e);const t=e.irradiance;if(!t)return;const i=new J0;P.FromArrayToRef(t.x,0,i.x),P.FromArrayToRef(t.y,0,i.y),P.FromArrayToRef(t.z,0,i.z),P.FromArrayToRef(t.xx,0,i.xx),P.FromArrayToRef(t.yy,0,i.yy),P.FromArrayToRef(t.zz,0,i.zz),P.FromArrayToRef(t.yz,0,i.yz),P.FromArrayToRef(t.zx,0,i.zx),P.FromArrayToRef(t.xy,0,i.xy),n._sphericalPolynomial=i}function O2e(n,e,t,i,r){const s=n.getEngine().createRawCubeTexture(null,n.width,n.format,n.type,n.generateMipMaps,n.invertY,n.samplingMode,n._compression),a=KD(s,e).then(()=>n);return n.onRebuildCallback=o=>({proxy:a,isReady:!0,isAsync:!0}),n._source=mi.CubeRawRGBD,n._bufferViewArrayArray=e,n._lodGenerationScale=i,n._lodGenerationOffset=r,n._sphericalPolynomial=t,KD(n,e).then(()=>(n.isReady=!0,n))}const lwe={GetEnvInfo:FG,CreateEnvTextureAsync:D2e,CreateImageDataArrayBufferViews:UG,UploadEnvLevelsAsync:Eee,UploadLevelsAsync:KD,UploadEnvSpherical:kG};function mV(n,e,t,i){let r=i,s=0,a="";for(;r=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e==95}function V$(n){let e=0,t="",i=!1;const r=[];for(;e=0&&n.charAt(e)!==t&&(!i||n.charAt(e)!==i);)e--;return e}function hwe(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}class zm{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&de.Log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&de.Log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&f.push(g.substring(v+1))}s!=="void"&&f.push("return"),this._functionDescr.push({name:a,type:s,parameters:f,body:u,callIndex:0}),e=h+1;const p=t>0?this._sourceCode.substring(0,t):"",_=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&de.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:r,parameters:s,body:a}=t;let o=0;for(;o{const y=[];let C=0,b=0;for(;C0?this._sourceCode.substring(0,c):"";const v=h+1{const h=l[0];return mY(e.charAt(h-1))||mY(e.charAt(h+a))?t[r]:o})}return e}}zm._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class uwe{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+(typeof e=="string"?` `+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t){this.isCompiled=!1,this._valueCache={},this._engine=e,this.isAsync=t}_fillEffectInformation(e,t,i,r,s,a,o,c){const l=this._engine;if(l.supportsUniformBuffers)for(const d in t)e.bindUniformBlock(d,t[d]);this._engine.getUniforms(this,i).forEach((d,f)=>{r[i[f]]=d}),this._uniforms=r;let u;for(u=0;u{a[d]=f}),c.push(...l.getAttributes(this,o))}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],r=t.updateFlag;return i!==void 0&&i===r?!1:(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s)return s=[t,i,r],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==r&&(s[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,s){let a=this._valueCache[e];if(!a)return a=[t,i,r,s],this._valueCache[e]=a,!0;let o=!1;return a[0]!==t&&(a[0]=t,o=!0),a[1]!==i&&(a[1]=i,o=!0),a[2]!==r&&(a[2]=r,o=!0),a[3]!==s&&(a[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this._engine.setInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this._engine.setUInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this._engine.setFloat4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class dwe extends XO{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class hde{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function gY(n,e){switch(n){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:return _native.Engine.TEXTURE_FORMAT_BC1;case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break}case 5:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break}case 6:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break}case 7:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break}case 12:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_BGRA8}break}}throw new kf(`Unsupported texture format or type: format ${n}, type ${e}.`,z0.UnsupportedTextureError)}function ww(n){switch(n){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${n}.`)}}function vY(n){switch(n){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+n+".")}}function fwe(n){switch(n){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${n}.`)}}function pwe(n){switch(n){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${n}.`)}}function _we(n){switch(n){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${n}.`)}}function mwe(n){switch(n){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${n}.`)}}function gwe(n){switch(n){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${n}.`)}}function vwe(n){switch(n){case Z.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case Z.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case Z.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case Z.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case Z.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${n}.`)}}const L2e=new Ae;if(typeof self<"u"&&!Object.prototype.hasOwnProperty.call(self,"_native")){let n;Object.defineProperty(self,"_native",{get:()=>n,set:e=>{n=e,n&&L2e.notifyObservers(n)}})}function N2e(){return new Promise(n=>{typeof _native>"u"?L2e.addOnce(e=>n(e)):n(_native)})}async function B2e(n,e){(await N2e())[n]=e}class ude extends Jp{}class xwe{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=nA._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}class nA extends De{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new xwe(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==nA.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${nA.PROTOCOL_VERSION} (JS)`);this._engine.setDeviceLostCallback&&this._engine.setDeviceLostCallback(()=>{this.onContextLostObservable.notifyObservers(this),this._contextWasLost=!0,this._restoreEngineAfterContextLost()}),this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},Ee.Log("Babylon Native (v"+De.Version+") launched"),Ee.LoadScript=function(r,s,a,o){Ee.LoadFile(r,c=>{Function(c).apply(null),s&&s()},void 0,void 0,!1,(c,l)=>{a&&a("LoadScript Error",l)})},typeof URL>"u"&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(window.Blob=function(r){return r}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function r(){const s=isNaN(arguments[0])?1:Number(arguments[0]);return s?Array.prototype.reduce.call(this,function(a,o){return Array.isArray(o)?a.push.apply(a,r.call(o,s-1)):a.push(o),a},[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new IJ,this.onNewSceneAddedObservable.add(r=>{const s=r.render;r.render=(...a)=>{this._commandBufferEncoder.beginCommandScope(),s.apply(r,a),this._commandBufferEncoder.endCommandScope()}})}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new i4}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=r,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,r=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const r=this._normalizeIndexData(e),s=new ude;return s.references=1,s.is32Bits=r.BYTES_PER_ELEMENT===4,r.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,s.is32Bits,t??!1)),s}createVertexBuffer(e,t,i){const r=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new ude;return s.references=1,r.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,t??!1)),s}_recordVertexArrayObject(e,t,i,r,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const a=r.getAttributesNames();for(let o=0;o=0){const l=a[o];let h=null;if(s&&(h=s[l]),h||(h=t[l]),h){const u=h.getBuffer();u&&u.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,u.nativeVertexBuffer,c,h.byteOffset,h.byteStride,h.getSize(),vwe(h.type),h.normalized,h.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){const s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,r),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e;return this._engine.getAttributes(i.program,t)}drawElementsType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){const e=!!(this._caps.parallelShaderCompile&&this._engine.createProgramAsync);return new uwe(this,e)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,r,s,a,o,c){r?this.createRawShaderProgram():this.createShaderProgram(e,t,i,c)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(i.isAsync)if(i.onCompiled){const r=i.onCompiled;i.onCompiled=()=>{r(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,r){const s=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=new zm(t);a.processCode(),t=a.code;const o=new zm(i);o.processCode(),i=o.code,t=yt._ConcatenateShader(t,r),i=yt._ConcatenateShader(i,r);const c=()=>{var l;s.isCompiled=!0,(l=s.onCompiled)==null||l.call(s),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)s.program=this._engine.createProgramAsync(t,i,c,l=>{s.compilationError=l});else try{s.program=this._engine.createProgram(t,i),c()}catch(l){const h=l==null?void 0:l.message;throw new Error("SHADER ERROR"+(typeof h=="string"?` `+h:""))}return s.program}inlineShaderCode(e){const t=new zm(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.program&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.program),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.program,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let r=0;r{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL;break}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,pwe(this._stencilOpStencilFail),_we(this._stencilOpDepthFail),mwe(this._stencilOpStencilDepthPass),fwe(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,r,s,a){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(a),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,r){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=gwe(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(e===0),this._alphaMode=e}getAlphaMode(){return this._alphaMode}setInt(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray2(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray3(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray4(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray2(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray3(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray4(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setArray(e,t){return e?this.setFloatArray(e,new Float32Array(t)):!1}setArray2(e,t){return e?this.setFloatArray2(e,new Float32Array(t)):!1}setArray3(e,t){return e?this.setFloatArray3(e,new Float32Array(t)):!1}setArray4(e,t){return e?this.setFloatArray4(e,new Float32Array(t)):!1}setMatrices(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setMatrix3x3(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setMatrix2x2(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat2(e,t,i){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat3(e,t,i,r){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat4(e,t,i,r,s){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setColor3(e,t){return e?(this.setFloat3(e,t.r,t.g,t.b),!0):!1}setColor4(e,t,i){return e?(this.setFloat4(e,t.r,t.g,t.b,i),!0):!1}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,r=!1,s){if(r===void 0&&(r=!1),e&&e._hardwareTexture){const a=t.getCanvasTexture(),o=e._hardwareTexture.underlyingResource;this._engine.copyTexture(o,a),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,s,a,o,c=null,l=0,h=0,u=!1){const d=new Ar(this,mi.Raw);if(d.format=r,d.generateMipMaps=s,d.samplingMode=o,d.invertY=a,d.baseWidth=t,d.baseHeight=i,d.width=d.baseWidth,d.height=d.baseHeight,d._compression=c,d.type=l,d._useSRGBBuffer=this._getUseSRGBBuffer(u,!s),this.updateRawTexture(d,e,r,a,c,l,d._useSRGBBuffer),d._hardwareTexture){const f=d._hardwareTexture.underlyingResource,p=ww(o);this._setTextureSampling(f,p)}return this._internalTexturesCache.push(d),d}createRawTexture2DArray(e,t,i,r,s,a,o,c,l=null,h=0){const u=new Ar(this,mi.Raw2DArray);if(u.baseWidth=t,u.baseHeight=i,u.baseDepth=r,u.width=t,u.height=i,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=a,u.samplingMode=c,u.is2DArray=!0,u._hardwareTexture){const d=u._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(d,e,t,i,r,gY(s,h),a,o);const f=ww(c);this._setTextureSampling(d,f)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,r,s=null,a=0,o=!1){if(e){if(t&&e._hardwareTexture){const c=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(c,t,e.width,e.height,gY(i,a),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,s=3,a=null,o=null,c=null,l=null,h=null,u=null,d,f,p,_=!1){e=e||"";const m=e.substr(0,5)==="data:",g=m&&e.indexOf(";base64,")!==-1,v=l||new Ar(this,mi.Url),x=e;this._transformTextureUrl&&!g&&!l&&!c&&(e=this._transformTextureUrl(e));const y=e.lastIndexOf("."),C=u||(y>-1?e.substring(y).toLowerCase():"");let b=null;for(const N of De._TextureLoaders)if(N.canLoad(C)){b=N;break}r&&r.addPendingData(v),v.url=e,v.generateMipMaps=!t,v.samplingMode=s,v.invertY=i,v._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(v._buffer=c);let T=null;a&&!l&&(T=v.onLoadedObservable.add(a)),l||this._internalTexturesCache.push(v);const S=(N,D)=>{r&&r.removePendingData(v),e===x?(T&&v.onLoadedObservable.remove(T),bt.UseFallbackTexture&&this.createTexture(bt.FallbackTexture,t,v.invertY,r,s,null,o,c,v),o&&o((N||"Unknown error")+(bt.UseFallbackTexture?" - Fallback texture was used":""),D)):(de.Warn(`Failed to load ${e}, falling back to ${x}`),this.createTexture(x,t,v.invertY,r,s,a,o,c,v,h,u,d,f))};if(b)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const N=D=>{if(!v._hardwareTexture){r&&r.removePendingData(v);return}const M=v._hardwareTexture.underlyingResource;this._engine.loadTexture(M,D,!t,i,v._useSRGBBuffer,()=>{v.baseWidth=this._engine.getTextureWidth(M),v.baseHeight=this._engine.getTextureHeight(M),v.width=v.baseWidth,v.height=v.baseHeight,v.isReady=!0;const I=ww(s);this._setTextureSampling(M,I),r&&r.removePendingData(v),v.onLoadedObservable.notifyObservers(v),v.onLoadedObservable.clear()},()=>{throw new Error("Could not load a native texture.")})};if(m&&c)if(c instanceof ArrayBuffer)N(new Uint8Array(c));else if(ArrayBuffer.isView(c))N(c);else if(typeof c=="string")N(new Uint8Array(Ee.DecodeBase64(c)));else throw new Error("Unsupported buffer type");else g?N(new Uint8Array(Ee.DecodeBase64(e))):this._loadFile(e,D=>N(new Uint8Array(D)),void 0,void 0,!0,(D,M)=>{S("Unable to load "+(D&&D.responseURL,M))})}return v}wrapNativeTexture(e,t=!1,i=3){const r=new hde(e,this._engine),s=new Ar(this,mi.Unknown,!0);return s._hardwareTexture=r,s.baseWidth=this._engine.getTextureWidth(e),s.baseHeight=this._engine.getTextureHeight(e),s.width=s.baseWidth,s.height=s.baseHeight,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const r=t.generateStencil||!1,s=t.samples||1,a=i,o=new Ar(this,mi.DepthStencil),c=e.width??e,l=e.height??e,h=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,c,l,r,!0,s);return a._framebufferDepthStencil=h,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise((r,s)=>{const a=this.createCanvasImage();a.onload=()=>{try{const o=this._engine.createImageBitmap(a);r(o)}catch(o){s(`Error loading image ${a.src} with exception: ${o}`)}},a.onerror=o=>{s(`Error loading image ${a.src} with exception: ${o}`)},a.src=e})}createImageBitmap(e,t){return new Promise((i,r)=>{if(Array.isArray(e)){const s=e;if(s.length){const a=this._engine.createImageBitmap(s[0]);if(a){i(a);return}}}r("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,s=null,a=null,o,c=null,l=!1,h=0,u=0,d=null,f,p=!1){const _=d||new Ar(this,mi.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!r,_._lodGenerationScale=h,_._lodGenerationOffset=u,_._useSRGBBuffer=this._getUseSRGBBuffer(p,!!r),this._doNotHandleContextLost||(_._extension=c,_._files=i);const m=e.lastIndexOf(".");if((c||(m>-1?e.substring(m).toLowerCase():""))===".env"){const v=x=>{const y=FG(x);_.width=y.width,_.height=y.width,kG(_,y);const C=y.specular;if(!C)throw new Error("Nothing else parsed so far");_._lodGenerationScale=C.lodGenerationScale;const b=UG(x,y);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(ve.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,b,!1,_._useSRGBBuffer,()=>{_.isReady=!0,s&&s()},()=>{throw new Error("Could not load a native cube texture.")})};if(i&&i.length===6)throw new Error("Multi-file loading not allowed on env files.");{const x=(y,C)=>{a&&y&&a(y.status+" "+y.statusText,C)};this._loadFile(e,y=>{v(new Uint8Array(y,0,y.byteLength))},void 0,void 0,!0,x)}}else{if(!i||i.length!==6)throw new Error("Cannot load cubemap because 6 files were not defined");const v=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(v.map(x=>this._loadFileAsync(x,void 0,!0).then(y=>new Uint8Array(y,0,y.byteLength)))).then(x=>new Promise((y,C)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,x,!r,!0,_._useSRGBBuffer,y,C)})).then(()=>{_.isReady=!0,s&&s()},x=>{a&&a(`Failed to load cubemap: ${x.message}`,x)})}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new hde(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const r=new dwe(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=mi.Unknown){let s=!1,a=0,o=3,c=5,l=!1,h=1,u;t!==void 0&&typeof t=="object"?(s=!!t.generateMipMaps,a=t.type===void 0?0:t.type,o=t.samplingMode===void 0?3:t.samplingMode,c=t.format===void 0?5:t.format,l=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,h=t.samples??1,u=t.label):s=!!t,l=this._getUseSRGBBuffer(l,!s),(a===1&&!this._caps.textureFloatLinearFiltering||a===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),a===1&&!this._caps.textureFloat&&(a=0,de.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=new Ar(this,r),f=e.width??e,p=e.height??e,_=e.layers||0;if(_!==0)throw new Error("Texture layers are not supported in Babylon Native");const m=d._hardwareTexture.underlyingResource,g=gY(c,a);return this._engine.initializeTexture(m,f,p,s,g,!0,l,h),this._setTextureSampling(m,ww(o)),d._useSRGBBuffer=l,d.baseWidth=f,d.baseHeight=p,d.width=f,d.height=p,d.depth=_,d.isReady=!0,d.samples=h,d.generateMipMaps=s,d.samplingMode=o,d.type=a,d.format=c,d.label=u,this._internalTexturesCache.push(d),d}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let r=!0,s=!1,a=!1,o,c=1;t!==void 0&&typeof t=="object"&&(r=t.generateDepthBuffer??!0,s=!!t.generateStencilBuffer,a=!!t.noColorAttachment,o=t.colorAttachment,c=t.samples??1);const l=o||(a?null:this._createInternalTexture(e,t,!0,mi.RenderTarget)),h=e.width??e,u=e.height??e,d=this._engine.createFrameBuffer(l?l._hardwareTexture.underlyingResource:null,h,u,s,r,c);return i._framebuffer=d,i._generateDepthBuffer=r,i._generateStencilBuffer=s,i._samples=c,i.setTextures(l),i}updateRenderTargetTextureSampleCount(e,t){return de.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=ww(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,s){const a=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||r)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");a._framebufferDepthStencil?this._bindUnboundFramebuffer(a._framebufferDepthStencil):this._bindUnboundFramebuffer(a._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const r=e,s=this._normalizeIndexData(t);r.is32Bits=s.BYTES_PER_ELEMENT===4,this._engine.updateDynamicIndexBuffer(r.nativeIndexBuffer,s.buffer,s.byteOffset,s.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,r){const s=e,a=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(a.buffer,a.byteOffset,r??a.byteLength);this._engine.updateDynamicVertexBuffer(s.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,r=!1){const s=this._boundUniforms[e];if(!s)return!1;if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===4)return t.delayLoad(),!1;let a;return r?a=t.depthStencilTexture:t.isReady()?a=t.getInternalTexture():t.isCube?a=this.emptyCubeTexture:t.is3D?a=this.emptyTexture3D:t.is2DArray?a=this.emptyTexture2DArray:a=this.emptyTexture,this._activeChannel=e,!a||!a._hardwareTexture?!1:(this._setTextureWrapMode(a._hardwareTexture.underlyingResource,vY(t.wrapU),vY(t.wrapV),vY(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(s,a._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;!t||!t._hardwareTexture||t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){const r=t._hardwareTexture.underlyingResource;this._setTextureCore(i,r)}}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,r,s,a,o=0,c=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,r,s,a,o,c,l,h){var u;if(r!==void 0&&r!==-1)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);return this._engine.readTexture((u=e._hardwareTexture)==null?void 0:u.underlyingResource,s??0,l??0,h??0,t,i,(a==null?void 0:a.buffer)??null,(a==null?void 0:a.byteOffset)??0,(a==null?void 0:a.byteLength)??0).then(d=>(a||(a=new Uint8Array(d)),a))}}nA.PROTOCOL_VERSION=8;nA._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new F2e:new i4};class F2e extends i4{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var z$;(function(n){n.LowPower="low-power",n.HighPerformance="high-performance"})(z$||(z$={}));var kp;(function(n){n.DepthClipControl="depth-clip-control",n.Depth32FloatStencil8="depth32float-stencil8",n.TextureCompressionBC="texture-compression-bc",n.TextureCompressionETC2="texture-compression-etc2",n.TextureCompressionASTC="texture-compression-astc",n.TimestampQuery="timestamp-query",n.IndirectFirstInstance="indirect-first-instance",n.ShaderF16="shader-f16",n.RG11B10UFloatRenderable="rg11b10ufloat-renderable",n.BGRA8UnormStorage="bgra8unorm-storage",n.Float32Filterable="float32-filterable"})(kp||(kp={}));var H$;(function(n){n.Unmapped="unmapped",n.Pending="pending",n.Mapped="mapped"})(H$||(H$={}));var ys;(function(n){n[n.MapRead=1]="MapRead",n[n.MapWrite=2]="MapWrite",n[n.CopySrc=4]="CopySrc",n[n.CopyDst=8]="CopyDst",n[n.Index=16]="Index",n[n.Vertex=32]="Vertex",n[n.Uniform=64]="Uniform",n[n.Storage=128]="Storage",n[n.Indirect=256]="Indirect",n[n.QueryResolve=512]="QueryResolve"})(ys||(ys={}));var z3;(function(n){n[n.Read=1]="Read",n[n.Write=2]="Write"})(z3||(z3={}));var bd;(function(n){n.E1d="1d",n.E2d="2d",n.E3d="3d"})(bd||(bd={}));var rn;(function(n){n[n.CopySrc=1]="CopySrc",n[n.CopyDst=2]="CopyDst",n[n.TextureBinding=4]="TextureBinding",n[n.StorageBinding=8]="StorageBinding",n[n.RenderAttachment=16]="RenderAttachment"})(rn||(rn={}));var Jr;(function(n){n.E1d="1d",n.E2d="2d",n.E2dArray="2d-array",n.Cube="cube",n.CubeArray="cube-array",n.E3d="3d"})(Jr||(Jr={}));var If;(function(n){n.All="all",n.StencilOnly="stencil-only",n.DepthOnly="depth-only"})(If||(If={}));var me;(function(n){n.R8Unorm="r8unorm",n.R8Snorm="r8snorm",n.R8Uint="r8uint",n.R8Sint="r8sint",n.R16Uint="r16uint",n.R16Sint="r16sint",n.R16Float="r16float",n.RG8Unorm="rg8unorm",n.RG8Snorm="rg8snorm",n.RG8Uint="rg8uint",n.RG8Sint="rg8sint",n.R32Uint="r32uint",n.R32Sint="r32sint",n.R32Float="r32float",n.RG16Uint="rg16uint",n.RG16Sint="rg16sint",n.RG16Float="rg16float",n.RGBA8Unorm="rgba8unorm",n.RGBA8UnormSRGB="rgba8unorm-srgb",n.RGBA8Snorm="rgba8snorm",n.RGBA8Uint="rgba8uint",n.RGBA8Sint="rgba8sint",n.BGRA8Unorm="bgra8unorm",n.BGRA8UnormSRGB="bgra8unorm-srgb",n.RGB9E5UFloat="rgb9e5ufloat",n.RGB10A2UINT="rgb10a2uint",n.RGB10A2Unorm="rgb10a2unorm",n.RG11B10UFloat="rg11b10ufloat",n.RG32Uint="rg32uint",n.RG32Sint="rg32sint",n.RG32Float="rg32float",n.RGBA16Uint="rgba16uint",n.RGBA16Sint="rgba16sint",n.RGBA16Float="rgba16float",n.RGBA32Uint="rgba32uint",n.RGBA32Sint="rgba32sint",n.RGBA32Float="rgba32float",n.Stencil8="stencil8",n.Depth16Unorm="depth16unorm",n.Depth24Plus="depth24plus",n.Depth24PlusStencil8="depth24plus-stencil8",n.Depth32Float="depth32float",n.BC1RGBAUnorm="bc1-rgba-unorm",n.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",n.BC2RGBAUnorm="bc2-rgba-unorm",n.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",n.BC3RGBAUnorm="bc3-rgba-unorm",n.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",n.BC4RUnorm="bc4-r-unorm",n.BC4RSnorm="bc4-r-snorm",n.BC5RGUnorm="bc5-rg-unorm",n.BC5RGSnorm="bc5-rg-snorm",n.BC6HRGBUFloat="bc6h-rgb-ufloat",n.BC6HRGBFloat="bc6h-rgb-float",n.BC7RGBAUnorm="bc7-rgba-unorm",n.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",n.ETC2RGB8Unorm="etc2-rgb8unorm",n.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",n.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",n.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",n.ETC2RGBA8Unorm="etc2-rgba8unorm",n.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",n.EACR11Unorm="eac-r11unorm",n.EACR11Snorm="eac-r11snorm",n.EACRG11Unorm="eac-rg11unorm",n.EACRG11Snorm="eac-rg11snorm",n.ASTC4x4Unorm="astc-4x4-unorm",n.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",n.ASTC5x4Unorm="astc-5x4-unorm",n.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",n.ASTC5x5Unorm="astc-5x5-unorm",n.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",n.ASTC6x5Unorm="astc-6x5-unorm",n.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",n.ASTC6x6Unorm="astc-6x6-unorm",n.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",n.ASTC8x5Unorm="astc-8x5-unorm",n.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",n.ASTC8x6Unorm="astc-8x6-unorm",n.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",n.ASTC8x8Unorm="astc-8x8-unorm",n.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",n.ASTC10x5Unorm="astc-10x5-unorm",n.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",n.ASTC10x6Unorm="astc-10x6-unorm",n.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",n.ASTC10x8Unorm="astc-10x8-unorm",n.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",n.ASTC10x10Unorm="astc-10x10-unorm",n.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",n.ASTC12x10Unorm="astc-12x10-unorm",n.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",n.ASTC12x12Unorm="astc-12x12-unorm",n.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",n.Depth32FloatStencil8="depth32float-stencil8"})(me||(me={}));var by;(function(n){n.ClampToEdge="clamp-to-edge",n.Repeat="repeat",n.MirrorRepeat="mirror-repeat"})(by||(by={}));var fr;(function(n){n.Nearest="nearest",n.Linear="linear"})(fr||(fr={}));var G$;(function(n){n.Nearest="nearest",n.Linear="linear"})(G$||(G$={}));var zo;(function(n){n.Never="never",n.Less="less",n.Equal="equal",n.LessEqual="less-equal",n.Greater="greater",n.NotEqual="not-equal",n.GreaterEqual="greater-equal",n.Always="always"})(zo||(zo={}));var gm;(function(n){n[n.Vertex=1]="Vertex",n[n.Fragment=2]="Fragment",n[n.Compute=4]="Compute"})(gm||(gm={}));var Hm;(function(n){n.Uniform="uniform",n.Storage="storage",n.ReadOnlyStorage="read-only-storage"})(Hm||(Hm={}));var r2;(function(n){n.Filtering="filtering",n.NonFiltering="non-filtering",n.Comparison="comparison"})(r2||(r2={}));var jh;(function(n){n.Float="float",n.UnfilterableFloat="unfilterable-float",n.Depth="depth",n.Sint="sint",n.Uint="uint"})(jh||(jh={}));var Hz;(function(n){n.WriteOnly="write-only",n.ReadOnly="read-only",n.ReadWrite="read-write"})(Hz||(Hz={}));var K$;(function(n){n.Error="error",n.Warning="warning",n.Info="info"})(K$||(K$={}));var W$;(function(n){n.Validation="validation",n.Internal="internal"})(W$||(W$={}));var j8;(function(n){n.Auto="auto"})(j8||(j8={}));var Uh;(function(n){n.PointList="point-list",n.LineList="line-list",n.LineStrip="line-strip",n.TriangleList="triangle-list",n.TriangleStrip="triangle-strip"})(Uh||(Uh={}));var WD;(function(n){n.CCW="ccw",n.CW="cw"})(WD||(WD={}));var r8;(function(n){n.None="none",n.Front="front",n.Back="back"})(r8||(r8={}));var j$;(function(n){n[n.Red=1]="Red",n[n.Green=2]="Green",n[n.Blue=4]="Blue",n[n.Alpha=8]="Alpha",n[n.All=15]="All"})(j$||(j$={}));var Ul;(function(n){n.Zero="zero",n.One="one",n.Src="src",n.OneMinusSrc="one-minus-src",n.SrcAlpha="src-alpha",n.OneMinusSrcAlpha="one-minus-src-alpha",n.Dst="dst",n.OneMinusDst="one-minus-dst",n.DstAlpha="dst-alpha",n.OneMinusDstAlpha="one-minus-dst-alpha",n.SrcAlphaSaturated="src-alpha-saturated",n.Constant="constant",n.OneMinusConstant="one-minus-constant"})(Ul||(Ul={}));var vm;(function(n){n.Add="add",n.Subtract="subtract",n.ReverseSubtract="reverse-subtract",n.Min="min",n.Max="max"})(vm||(vm={}));var gf;(function(n){n.Keep="keep",n.Zero="zero",n.Replace="replace",n.Invert="invert",n.IncrementClamp="increment-clamp",n.DecrementClamp="decrement-clamp",n.IncrementWrap="increment-wrap",n.DecrementWrap="decrement-wrap"})(gf||(gf={}));var s2;(function(n){n.Uint16="uint16",n.Uint32="uint32"})(s2||(s2={}));var dn;(function(n){n.Uint8x2="uint8x2",n.Uint8x4="uint8x4",n.Sint8x2="sint8x2",n.Sint8x4="sint8x4",n.Unorm8x2="unorm8x2",n.Unorm8x4="unorm8x4",n.Snorm8x2="snorm8x2",n.Snorm8x4="snorm8x4",n.Uint16x2="uint16x2",n.Uint16x4="uint16x4",n.Sint16x2="sint16x2",n.Sint16x4="sint16x4",n.Unorm16x2="unorm16x2",n.Unorm16x4="unorm16x4",n.Snorm16x2="snorm16x2",n.Snorm16x4="snorm16x4",n.Float16x2="float16x2",n.Float16x4="float16x4",n.Float32="float32",n.Float32x2="float32x2",n.Float32x3="float32x3",n.Float32x4="float32x4",n.Uint32="uint32",n.Uint32x2="uint32x2",n.Uint32x3="uint32x3",n.Uint32x4="uint32x4",n.Sint32="sint32",n.Sint32x2="sint32x2",n.Sint32x3="sint32x3",n.Sint32x4="sint32x4",n.UNORM10x10x10x2="unorm10-10-10-2"})(dn||(dn={}));var jD;(function(n){n.Vertex="vertex",n.Instance="instance"})(jD||(jD={}));var X$;(function(n){n.Beginning="beginning",n.End="end"})(X$||(X$={}));var Y$;(function(n){n.Beginning="beginning",n.End="end"})(Y$||(Y$={}));var Ja;(function(n){n.Load="load",n.Clear="clear"})(Ja||(Ja={}));var bu;(function(n){n.Store="store",n.Discard="discard"})(bu||(bu={}));var XD;(function(n){n.Occlusion="occlusion",n.Timestamp="timestamp"})(XD||(XD={}));var YD;(function(n){n.Opaque="opaque",n.Premultiplied="premultiplied"})(YD||(YD={}));var Q$;(function(n){n.Unknown="unknown",n.Destroyed="destroyed"})(Q$||(Q$={}));var $$;(function(n){n.Validation="validation",n.OutOfMemory="out-of-memory",n.Internal="internal"})($$||($$={}));class _n{constructor(){this.shaderLanguage=Vs.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let r=0;[e,t,r]=this._getArraySize(e,t,i);for(let s=0;s=0&&(d.push(o[u]),f.push(p))}this.shaderProcessingContext.attributeNamesFromEffect=d,this.shaderProcessingContext.attributeLocationsFromEffect=f}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new Ft(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=_n.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt4(e,t,i,r,s)}setIntArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt4(e,t,i,r,s)}setUIntArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat4(e,t,i,r,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){var e;return(e=this.sources)==null?void 0:e.vertex}_getFragmentShaderCode(){var e;return(e=this.sources)==null?void 0:e.fragment}}const Awe=4,Cwe=65536,dde={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Ed{static get KnownUBOs(){return Ed._SimplifiedKnownBindings?Ed._SimplifiedKnownUBOs:Ed._KnownUBOs}constructor(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=Ed.KnownUBOs,t=[];for(const i in e){const r=e[i].binding;r.groupIndex!==-1&&(t[r.groupIndex]===void 0?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,this.freeGroupIndex===0?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(dde[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(dde[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>Cwe-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===Awe)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}Ed._SimplifiedKnownBindings=!0;Ed._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}};Ed._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class bwe extends _n{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=Vs.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0;const s=e.indexOf("["),a=e.indexOf("]");if(s>0&&a>0){const o=e.substring(s+1,a);r=+o,isNaN(r)&&(r=+i[o.trim()]),e=e.substr(0,s)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO uniform ${_n.InternalsUBOName} { float yFactor_; float textureOutputHeight_; }; `,r=e.indexOf("// Internals UBO")!==-1;return t?(this._fragmentIsGLES3=e.indexOf("#version 3")!==-1,this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+`##INJECTCODE## `+e):(this._vertexIsGLES3=e.indexOf("#version 3")!==-1,this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){const i=/(flat\s)?\s*\bout\b/,r=/(flat\s)?\s*\bin\b/,s=/(flat\s)?\s*\bvarying\b/;return(t&&this._fragmentIsGLES3?r:!t&&this._vertexIsGLES3?i:s).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const r=/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,s=/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,a=/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,c=(t&&this._fragmentIsGLES3?s:!t&&this._vertexIsGLES3?r:a).exec(e);if(c!==null){const l=c[1]??"",h=c[2],u=c[3];let d;t?(d=this._webgpuProcessingContext.availableVaryings[u],this._missingVaryings[d]="",d===void 0&&de.Warn(`Invalid fragment shader: The varying named "${u}" is not declared in the vertex shader! This declaration will be ignored.`)):(d=this._webgpuProcessingContext.getVaryingNextLocation(h,this._getArraySize(u,h,i)[2]),this._webgpuProcessingContext.availableVaryings[u]=d,this._missingVaryings[d]=`layout(location = ${d}) ${l} in ${h} ${u};`),e=e.replace(c[0],d===void 0?"":`layout(location = ${d}) ${l} ${t?"in":"out"} ${h} ${u};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=/\s*in\s+(\S+)\s+(\S+)\s*;/gm,r=/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,a=(this._vertexIsGLES3?i:r).exec(e);if(a!==null){const o=a[1],c=a[2],l=this._webgpuProcessingContext.getAttributeNextLocation(o,this._getArraySize(c,o,t)[2]);this._webgpuProcessingContext.availableAttributes[c]=l,this._webgpuProcessingContext.orderedAttributes[l]=c;const h=this.vertexBufferKindToNumberOfComponents[c];if(h!==void 0){const u=h<0?h===-1?"int":"ivec"+-h:h===1?"uint":"uvec"+h,d=`_int_${c}_`;e=e.replace(a[0],`layout(location = ${l}) in ${u} ${d}; ${o} ${c} = ${o}(${d});`)}else e=e.replace(a[0],`layout(location = ${l}) in ${o} ${c};`)}return e}uniformProcessor(e,t,i){this._preProcessors=i;const s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(s!==null){let a=s[1],o=s[2];if(a.indexOf("sampler")===0||a.indexOf("sampler")===1){let c=0;[o,a,c]=this._getArraySize(o,a,i);let l=this._webgpuProcessingContext.availableTextures[o];if(!l){l={autoBindSampler:!0,isTextureArray:c>0,isStorageTexture:!1,textures:[],sampleType:jh.Float};for(let T=0;T<(c||1);++T)l.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const h=_n._SamplerTypeByWebGLSamplerType[a]??"sampler",u=!!_n._IsComparisonSamplerByWebGPUSamplerType[h],d=u?r2.Comparison:r2.Filtering,f=o+_n.AutoSamplerSuffix;let p=this._webgpuProcessingContext.availableSamplers[f];p||(p={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:d});const _=a.charAt(0)==="u"?"u":a.charAt(0)==="i"?"i":"";_&&(a=a.substr(1));const m=u?jh.Depth:_==="u"?jh.Uint:_==="i"?jh.Sint:jh.Float;l.sampleType=m;const g=c>0,v=p.binding.groupIndex,x=p.binding.bindingIndex,y=_n._SamplerFunctionByWebGLSamplerType[a],C=_n._TextureTypeByWebGLSamplerType[a],b=_n._GpuTextureViewDimensionByWebGPUTextureType[C];if(!g)c=1,e=`layout(set = ${v}, binding = ${x}) uniform ${h} ${f}; layout(set = ${l.textures[0].groupIndex}, binding = ${l.textures[0].bindingIndex}) uniform ${_}${C} ${o}Texture; #define ${o} ${_}${y}(${o}Texture, ${f})`;else{const T=[];T.push(`layout(set = ${v}, binding = ${x}) uniform ${_}${h} ${f};`),e=` `;for(let S=0;S0?` `:""}#define ${o}${S} ${_}${y}(${o}Texture${S}, ${f})`}e=T.join(` `)+e,this._textureArrayProcessing.push(o)}this._webgpuProcessingContext.availableTextures[o]=l,this._webgpuProcessingContext.availableSamplers[f]=p,this._addSamplerBindingDescription(f,p,!t);for(let T=0;T=0,l=` glFragCoord_ = gl_FragCoord; if (yFactor_ == 1.) { glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; } `,h=c?`vec4 glFragCoord_; `:"",u=e.search(/layout *\(location *= *0\) *out/g)!==-1;if(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/gl_FragCoord/g,"glFragCoord_"),!this._fragmentIsGLES3)e=e.replace(/void\s+?main\s*\(/g,(a||u?"":`layout(location = 0) out vec4 glFragColor; `)+"void main(");else{const d=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);d!==null&&(e=e.substring(0,d.index)+"layout(location = 0) "+e.substring(d.index))}e=e.replace(/dFdy/g,"(-yFactor_)*dFdy"),e=e.replace("##INJECTCODE##",h),c&&(e=this._injectStartingAndEndingCode(e,"void main",l))}else if(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex"),e=e.replace(/gl_VertexID/g,"gl_VertexIndex"),t.indexOf("#define MULTIVIEW")!==-1)return`#extension GL_OVR_multiview2 : require layout (num_views = 2) in; `+e;if(!i){const c=e.lastIndexOf("}");e=e.substring(0,c),e+=`gl_Position.y *= yFactor_; `,s.isNDCHalfZRange||(e+=`gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0; `),e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let r=i.exec(e);for(;r!==null;){const s=r[1];let a=+s;this._preProcessors&&isNaN(a)&&(a=+this._preProcessors[s.trim()]),e=e.replace(r[0],t+a),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { `;for(const r of this._webgpuProcessingContext.leftOverUniforms)r.length>0?i+=` ${r.type} ${r.name}[${r.length}]; `:i+=` ${r.type} ${r.name}; `;return i+=`}; `,i}finalizeShaders(e,t){for(let r=0;r0&&(t=s+` `+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}const Ewe="bonesDeclaration",Twe=`#if NUM_BONE_INFLUENCERS>0 attribute matricesIndices : vec4;attribute matricesWeights : vec4; #if NUM_BONE_INFLUENCERS>4 attribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4; #endif #ifndef BAKED_VERTEX_ANIMATION_TEXTURE #ifdef BONETEXTURE var boneSampler : texture_2d;uniform boneTextureWidth : f32; #else uniform mBones : array; #ifdef BONES_VELOCITY_ENABLED uniform mPreviousBones : array; #endif #endif #ifdef BONETEXTURE fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4 {let offset=i32(index) *4; let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);} #endif #endif #endif `;Re.IncludesShadersStoreWGSL[Ewe]=Twe;const Swe="bonesVertex",Mwe=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE #if NUM_BONE_INFLUENCERS>0 var influence : mat4x4; #ifdef BONETEXTURE influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; #endif #else influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; #endif #endif finalWorld=finalWorld*influence; #endif #endif `;Re.IncludesShadersStoreWGSL[Swe]=Mwe;const Rwe="bakedVertexAnimationDeclaration",Iwe=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d; #ifdef INSTANCES attribute bakedVertexAnimationSettingsInstanced : vec4; #endif fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4 {let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);} #endif `;Re.IncludesShadersStoreWGSL[Rwe]=Iwe;const Pwe="bakedVertexAnimation",wwe=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE { #ifdef INSTANCES let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; #else let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; #endif let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; #endif finalWorld=finalWorld*VATInfluence;} #endif `;Re.IncludesShadersStoreWGSL[Pwe]=wwe;const Dwe="clipPlaneFragment",Owe=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) if (false) {} #endif #ifdef CLIPPLANE else if (fragmentInputs.fClipDistance>0.0) {discard;} #endif #ifdef CLIPPLANE2 else if (fragmentInputs.fClipDistance2>0.0) {discard;} #endif #ifdef CLIPPLANE3 else if (fragmentInputs.fClipDistance3>0.0) {discard;} #endif #ifdef CLIPPLANE4 else if (fragmentInputs.fClipDistance4>0.0) {discard;} #endif #ifdef CLIPPLANE5 else if (fragmentInputs.fClipDistance5>0.0) {discard;} #endif #ifdef CLIPPLANE6 else if (fragmentInputs.fClipDistance6>0.0) {discard;} #endif `;Re.IncludesShadersStoreWGSL[Dwe]=Owe;const Lwe="clipPlaneFragmentDeclaration",Nwe=`#ifdef CLIPPLANE varying fClipDistance: f32; #endif #ifdef CLIPPLANE2 varying fClipDistance2: f32; #endif #ifdef CLIPPLANE3 varying fClipDistance3: f32; #endif #ifdef CLIPPLANE4 varying fClipDistance4: f32; #endif #ifdef CLIPPLANE5 varying fClipDistance5: f32; #endif #ifdef CLIPPLANE6 varying fClipDistance6: f32; #endif `;Re.IncludesShadersStoreWGSL[Lwe]=Nwe;const Bwe="clipPlaneVertex",Fwe=`#ifdef CLIPPLANE vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); #endif #ifdef CLIPPLANE2 vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); #endif #ifdef CLIPPLANE3 vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); #endif #ifdef CLIPPLANE4 vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); #endif #ifdef CLIPPLANE5 vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); #endif #ifdef CLIPPLANE6 vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); #endif `;Re.IncludesShadersStoreWGSL[Bwe]=Fwe;const Uwe="clipPlaneVertexDeclaration",kwe=`#ifdef CLIPPLANE uniform vClipPlane: vec4;varying fClipDistance: f32; #endif #ifdef CLIPPLANE2 uniform vClipPlane2: vec4;varying fClipDistance2: f32; #endif #ifdef CLIPPLANE3 uniform vClipPlane3: vec4;varying fClipDistance3: f32; #endif #ifdef CLIPPLANE4 uniform vClipPlane4: vec4;varying fClipDistance4: f32; #endif #ifdef CLIPPLANE5 uniform vClipPlane5: vec4;varying fClipDistance5: f32; #endif #ifdef CLIPPLANE6 uniform vClipPlane6: vec4;varying fClipDistance6: f32; #endif `;Re.IncludesShadersStoreWGSL[Uwe]=kwe;const Vwe="instancesDeclaration",zwe=`#ifdef INSTANCES attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; #ifdef INSTANCESCOLOR attribute instanceColor : vec4; #endif #if defined(THIN_INSTANCES) && !defined(WORLD_UBO) uniform world : mat4x4; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) attribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4; #ifdef THIN_INSTANCES uniform previousWorld : mat4x4; #endif #endif #else #if !defined(WORLD_UBO) uniform world : mat4x4; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) uniform previousWorld : mat4x4; #endif #endif `;Re.IncludesShadersStoreWGSL[Vwe]=zwe;const Hwe="instancesVertex",Gwe=`#ifdef INSTANCES var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) var finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); #endif #ifdef THIN_INSTANCES #if !defined(WORLD_UBO) finalWorld=uniforms.world*finalWorld; #else finalWorld=mesh.world*finalWorld; #endif #if defined(PREPASS_VELOCITY) || defined(VELOCITY) finalPreviousWorld=previousWorld*finalPreviousWorld; #endif #endif #else #if !defined(WORLD_UBO) var finalWorld=uniforms.world; #else var finalWorld=mesh.world; #endif #if defined(PREPASS_VELOCITY) || defined(VELOCITY) var finalPreviousWorld=previousWorld; #endif #endif `;Re.IncludesShadersStoreWGSL[Hwe]=Gwe;const Kwe="meshUboDeclaration",Wwe=`struct Mesh {world : mat4x4, visibility : f32,};var mesh : Mesh; #define WORLD_UBO `;Re.IncludesShadersStoreWGSL[Kwe]=Wwe;const jwe="morphTargetsVertex",Xwe=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE #if {X}==0 for (var i=0; i<$NUM_MORPH_INFLUENCERS$; i=i+1) {if (i>=uniforms.morphTargetCount) {break;} vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; #ifdef MORPHTARGETS_NORMAL normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; #endif #ifdef MORPHTARGETS_UV uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; #endif } #endif #else positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; #ifdef MORPHTARGETS_NORMAL normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_UV uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; #endif #endif #endif `;Re.IncludesShadersStoreWGSL[jwe]=Xwe;const Ywe="morphTargetsVertexDeclaration",Qwe=`#ifdef MORPHTARGETS #ifndef MORPHTARGETS_TEXTURE attribute position{X} : vec3; #ifdef MORPHTARGETS_NORMAL attribute normal{X} : vec3; #endif #ifdef MORPHTARGETS_TANGENT attribute tangent{X} : vec3; #endif #ifdef MORPHTARGETS_UV attribute uv_{X} : vec2; #endif #elif {X}==0 uniform morphTargetCount: i32; #endif #endif `;Re.IncludesShadersStoreWGSL[Ywe]=Qwe;const $we="morphTargetsVertexGlobal",Zwe=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE var vertexID : f32; #endif #endif `;Re.IncludesShadersStoreWGSL[$we]=Zwe;const qwe="morphTargetsVertexGlobalDeclaration",Jwe=`#ifdef MORPHTARGETS uniform morphTargetInfluences : array; #ifdef MORPHTARGETS_TEXTURE uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3 { let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} #endif #endif `;Re.IncludesShadersStoreWGSL[qwe]=Jwe;const eDe="sceneUboDeclaration",tDe=`struct Scene {viewProjection : mat4x4, #ifdef MULTIVIEW viewProjectionR : mat4x4, #endif view : mat4x4, projection : mat4x4, vEyePosition : vec4,};var scene : Scene; `;Re.IncludesShadersStoreWGSL[eDe]=tDe;const fde="fragmentOutputs.fragDepth",iDe="uniforms",rDe="internals",sDe={texture_1d:Jr.E1d,texture_2d:Jr.E2d,texture_2d_array:Jr.E2dArray,texture_3d:Jr.E3d,texture_cube:Jr.Cube,texture_cube_array:Jr.CubeArray,texture_multisampled_2d:Jr.E2d,texture_depth_2d:Jr.E2d,texture_depth_2d_array:Jr.E2dArray,texture_depth_cube:Jr.Cube,texture_depth_cube_array:Jr.CubeArray,texture_depth_multisampled_2d:Jr.E2d,texture_storage_1d:Jr.E1d,texture_storage_2d:Jr.E2d,texture_storage_2d_array:Jr.E2dArray,texture_storage_3d:Jr.E3d,texture_external:null};class nDe extends _n{constructor(){super(...arguments),this.shaderLanguage=Vs.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}_getArraySize(e,t,i){let r=0;const s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let a=s;for(;a>0&&t.charAt(a)!==" "&&t.charAt(a)!==",";)a--;const o=t.substring(a+1,s);for(r=+o,isNaN(r)&&(r=+i[o.trim()]);a>0&&(t.charAt(a)===" "||t.charAt(a)===",");)a--;t=t.substring(t.indexOf("<")+1,a+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=`struct ${_n.InternalsUBOName} { yFactor_: f32, textureOutputHeight_: f32, }; var ${rDe} : ${_n.InternalsUBOName}; `;return e.indexOf(t)!==-1?e:t+V$(e)}varyingProcessor(e,t,i){const s=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(s!==null){const a=s[2],o=s[1];let c;t?(c=this._webgpuProcessingContext.availableVaryings[o],c===void 0&&de.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(c=this._webgpuProcessingContext.getVaryingNextLocation(a,this._getArraySize(o,a,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=c,this._varyingsWGSL.push(` @location(${c}) ${o} : ${a},`),this._varyingNamesWGSL.push(o)),e=""}return e}attributeProcessor(e,t){const r=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(r!==null){const s=r[2],a=r[1],o=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(a,s,t)[2]);this._webgpuProcessingContext.availableAttributes[a]=o,this._webgpuProcessingContext.orderedAttributes[o]=a;const c=this.vertexBufferKindToNumberOfComponents[a];if(c!==void 0){const l=c<0?c===-1?"i32":"vec"+-c+"":c===1?"u32":"vec"+c+"",h=`_int_${a}_`;this._attributesInputWGSL.push(`@location(${o}) ${h} : ${l},`),this._attributesWGSL.push(`${a} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${a} = ${s}(vertexInputs_.${h});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${o}) ${a} : ${s},`),this._attributesWGSL.push(`${a} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${a} = vertexInputs_.${a};`);e=""}return e}uniformProcessor(e,t,i){const r=this.uniformRegexp.exec(e);if(r!==null){const s=r[2],a=r[1];this._addUniformToLeftOverUBO(a,s,i),e=""}return e}textureProcessor(e,t,i){const r=this.textureRegexp.exec(e);if(r!==null){const s=r[1],a=r[2],o=!!r[3],c=r[4],l=c.indexOf("storage")>0,h=r[6],u=l?h.substring(0,h.indexOf(",")).trim():null;let d=o?this._getArraySize(s,a,i)[2]:0,f=this._webgpuProcessingContext.availableTextures[s];if(f)d=f.textures.length;else{f={isTextureArray:d>0,isStorageTexture:l,textures:[],sampleType:jh.Float},d=d||1;for(let g=0;g0,_=sDe[c],m=p?jh.Depth:h==="u32"?jh.Uint:h==="i32"?jh.Sint:jh.Float;if(f.sampleType=m,_===void 0)throw`Can't get the texture dimension corresponding to the texture function "${c}"!`;for(let g=0;g2?s[2]:""}return e.replace(/\$(\w+)\$/g,(r,s)=>i[s]??s)}finalizeShaders(e,t){const i=t.indexOf("fragmentInputs.position")>=0?` if (internals.yFactor_ == 1.) { fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; } `:"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const r=this._buildLeftOverUBO();e=r+e,t=r+t,e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s=`struct VertexInputs { @builtin(vertex_index) vertexIndex : u32, @builtin(instance_index) instanceIndex : u32, `;this._attributesInputWGSL.length>0&&(s+=this._attributesInputWGSL.join(` `)),s+=` }; var vertexInputs`+(this._hasNonFloatAttribute?"_":"")+` : VertexInputs; `,this._hasNonFloatAttribute&&(s+=`struct VertexInputs_ { vertexIndex : u32, instanceIndex : u32, `,s+=this._attributesWGSL.join(` `),s+=` }; var vertexInputs : VertexInputs_; `);let a=`struct FragmentInputs { @builtin(position) position : vec4, `;this._varyingsWGSL.length>0&&(a+=this._varyingsWGSL.join(` `)),a+=` }; var vertexOutputs : FragmentInputs; `,e=s+a+e;let o=` vertexInputs${this._hasNonFloatAttribute?"_":""} = input; `;this._hasNonFloatAttribute&&(o+=`vertexInputs.vertexIndex = vertexInputs_.vertexIndex; vertexInputs.instanceIndex = vertexInputs_.instanceIndex; `,o+=this._attributesConversionCodeWGSL.join(` `),o+=` `),e=this._injectStartingAndEndingCode(e,"fn main",o,` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; return vertexOutputs;`),t=t.replace(/#define /g,"//#define "),t=this._processStridedUniformArrays(t),t=t.replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l=`struct FragmentInputs { @builtin(position) position : vec4, @builtin(front_facing) frontFacing : bool, `;this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join(` `)),l+=` }; var fragmentInputs : FragmentInputs; `;let h=`struct FragmentOutputs { @location(0) color : vec4, `,u=!1,d=0;for(;!u&&(d=t.indexOf(fde,d),!(d<0));){const _=d;for(u=!0;d>1&&t.charAt(d)!==` `;){if(t.charAt(d)==="/"&&t.charAt(d-1)==="/"){u=!1;break}d--}d=_+fde.length}u&&(h+=` @builtin(frag_depth) fragDepth: f32, `),h+=`}; var fragmentOutputs : FragmentOutputs; `,t=l+h+t;const f=` fragmentInputs = input; `+i;return t=this._injectStartingAndEndingCode(t,"fn main",f," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} { `;for(const s of this._webgpuProcessingContext.leftOverUniforms){const a=s.type.replace(/^(.*?)(<.*>)?$/,"$1"),o=_n.UniformSizes[a];if(s.length>0)if(o<=2){const c=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${c} { @size(16) el: ${a}, }`,this._stridedUniformArrays.push(s.name),r+=` @align(16) ${s.name} : array<${c}, ${s.length}>, `}else r+=` ${s.name} : array<${s.type}, ${s.length}>, `;else r+=` ${s.name} : ${s.type}, `}return r+=`}; `,r=`${i} ${r}`,r+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var ${iDe} : ${e}; `,r}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const r=i.exec(e);if(r===null)break;const s=r[1],a=r[2],o=s.indexOf(_n.AutoSamplerSuffix)===s.length-_n.AutoSamplerSuffix.length?s.substring(0,s.indexOf(_n.AutoSamplerSuffix)):null,c=a==="sampler_comparison"?r2.Comparison:r2.Filtering;if(o){const f=this._webgpuProcessingContext.availableTextures[o];f&&(f.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:c},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);const h=e.substring(0,r.index),u=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,d=e.substring(r.index);e=h+u+d,i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const r=i.exec(e);if(r===null)break;const s=r[1],a=r[3];let o=r[4];const c=r[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const _=s==="uniform"?Ed.KnownUBOs[c]:null;let m;_?(o=c,m=_.binding,m.groupIndex===-1&&(m=this._webgpuProcessingContext.getNextFreeUBOBinding())):m=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:m},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],a==="read_write"?Hm.Storage:s==="storage"?Hm.ReadOnlyStorage:Hm.Uniform,t);const h=l.binding.groupIndex,u=l.binding.bindingIndex,d=e.substring(0,r.index),f=`@group(${h}) @binding(${u}) `,p=e.substring(r.index);e=d+f+p,i.lastIndex+=f.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}}class Ur{static ComputeNumMipmapLevels(e,t){return _t.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case me.R8Unorm:case me.R8Snorm:case me.R8Uint:case me.R8Sint:case me.RG8Unorm:case me.RG8Snorm:case me.RG8Uint:case me.RG8Sint:case me.RGBA8Unorm:case me.RGBA8UnormSRGB:case me.RGBA8Snorm:case me.RGBA8Uint:case me.RGBA8Sint:case me.BGRA8Unorm:case me.BGRA8UnormSRGB:case me.RGB10A2UINT:case me.RGB10A2Unorm:case me.RGB9E5UFloat:case me.RG11B10UFloat:case me.BC7RGBAUnorm:case me.BC7RGBAUnormSRGB:case me.BC6HRGBUFloat:case me.BC6HRGBFloat:case me.BC5RGUnorm:case me.BC5RGSnorm:case me.BC3RGBAUnorm:case me.BC3RGBAUnormSRGB:case me.BC2RGBAUnorm:case me.BC2RGBAUnormSRGB:case me.BC4RUnorm:case me.BC4RSnorm:case me.BC1RGBAUnorm:case me.BC1RGBAUnormSRGB:case me.ETC2RGB8Unorm:case me.ETC2RGB8UnormSRGB:case me.ETC2RGB8A1Unorm:case me.ETC2RGB8A1UnormSRGB:case me.ETC2RGBA8Unorm:case me.ETC2RGBA8UnormSRGB:case me.EACR11Unorm:case me.EACR11Snorm:case me.EACRG11Unorm:case me.EACRG11Snorm:case me.ASTC4x4Unorm:case me.ASTC4x4UnormSRGB:case me.ASTC5x4Unorm:case me.ASTC5x4UnormSRGB:case me.ASTC5x5Unorm:case me.ASTC5x5UnormSRGB:case me.ASTC6x5Unorm:case me.ASTC6x5UnormSRGB:case me.ASTC6x6Unorm:case me.ASTC6x6UnormSRGB:case me.ASTC8x5Unorm:case me.ASTC8x5UnormSRGB:case me.ASTC8x6Unorm:case me.ASTC8x6UnormSRGB:case me.ASTC8x8Unorm:case me.ASTC8x8UnormSRGB:case me.ASTC10x5Unorm:case me.ASTC10x5UnormSRGB:case me.ASTC10x6Unorm:case me.ASTC10x6UnormSRGB:case me.ASTC10x8Unorm:case me.ASTC10x8UnormSRGB:case me.ASTC10x10Unorm:case me.ASTC10x10UnormSRGB:case me.ASTC12x10Unorm:case me.ASTC12x10UnormSRGB:case me.ASTC12x12Unorm:case me.ASTC12x12UnormSRGB:case me.Stencil8:return 0;case me.R16Uint:case me.R16Sint:case me.RG16Uint:case me.RG16Sint:case me.RGBA16Uint:case me.RGBA16Sint:case me.Depth16Unorm:return 5;case me.R16Float:case me.RG16Float:case me.RGBA16Float:return 2;case me.R32Uint:case me.R32Sint:case me.RG32Uint:case me.RG32Sint:case me.RGBA32Uint:case me.RGBA32Sint:return 7;case me.R32Float:case me.RG32Float:case me.RGBA32Float:case me.Depth32Float:case me.Depth32FloatStencil8:case me.Depth24Plus:case me.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case me.R8Unorm:case me.R8Snorm:case me.R8Uint:case me.R8Sint:return{width:1,height:1,length:1};case me.R16Uint:case me.R16Sint:case me.R16Float:case me.RG8Unorm:case me.RG8Snorm:case me.RG8Uint:case me.RG8Sint:return{width:1,height:1,length:2};case me.R32Uint:case me.R32Sint:case me.R32Float:case me.RG16Uint:case me.RG16Sint:case me.RG16Float:case me.RGBA8Unorm:case me.RGBA8UnormSRGB:case me.RGBA8Snorm:case me.RGBA8Uint:case me.RGBA8Sint:case me.BGRA8Unorm:case me.BGRA8UnormSRGB:case me.RGB9E5UFloat:case me.RGB10A2UINT:case me.RGB10A2Unorm:case me.RG11B10UFloat:return{width:1,height:1,length:4};case me.RG32Uint:case me.RG32Sint:case me.RG32Float:case me.RGBA16Uint:case me.RGBA16Sint:case me.RGBA16Float:return{width:1,height:1,length:8};case me.RGBA32Uint:case me.RGBA32Sint:case me.RGBA32Float:return{width:1,height:1,length:16};case me.Stencil8:throw"No fixed size for Stencil8 format!";case me.Depth16Unorm:return{width:1,height:1,length:2};case me.Depth24Plus:throw"No fixed size for Depth24Plus format!";case me.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case me.Depth32Float:return{width:1,height:1,length:4};case me.Depth32FloatStencil8:return{width:1,height:1,length:5};case me.BC7RGBAUnorm:case me.BC7RGBAUnormSRGB:case me.BC6HRGBUFloat:case me.BC6HRGBFloat:case me.BC5RGUnorm:case me.BC5RGSnorm:case me.BC3RGBAUnorm:case me.BC3RGBAUnormSRGB:case me.BC2RGBAUnorm:case me.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case me.BC4RUnorm:case me.BC4RSnorm:case me.BC1RGBAUnorm:case me.BC1RGBAUnormSRGB:return{width:4,height:4,length:8};case me.ETC2RGB8Unorm:case me.ETC2RGB8UnormSRGB:case me.ETC2RGB8A1Unorm:case me.ETC2RGB8A1UnormSRGB:case me.EACR11Unorm:case me.EACR11Snorm:return{width:4,height:4,length:8};case me.ETC2RGBA8Unorm:case me.ETC2RGBA8UnormSRGB:case me.EACRG11Unorm:case me.EACRG11Snorm:return{width:4,height:4,length:16};case me.ASTC4x4Unorm:case me.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case me.ASTC5x4Unorm:case me.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case me.ASTC5x5Unorm:case me.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case me.ASTC6x5Unorm:case me.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case me.ASTC6x6Unorm:case me.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case me.ASTC8x5Unorm:case me.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case me.ASTC8x6Unorm:case me.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case me.ASTC8x8Unorm:case me.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case me.ASTC10x5Unorm:case me.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case me.ASTC10x6Unorm:case me.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case me.ASTC10x8Unorm:case me.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case me.ASTC10x10Unorm:case me.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case me.ASTC12x10Unorm:case me.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case me.ASTC12x12Unorm:case me.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return e.close!==void 0}static IsImageBitmapArray(e){return Array.isArray(e)&&e[0].close!==void 0}static IsCompressedFormat(e){switch(e){case me.BC7RGBAUnormSRGB:case me.BC7RGBAUnorm:case me.BC6HRGBFloat:case me.BC6HRGBUFloat:case me.BC5RGSnorm:case me.BC5RGUnorm:case me.BC4RSnorm:case me.BC4RUnorm:case me.BC3RGBAUnormSRGB:case me.BC3RGBAUnorm:case me.BC2RGBAUnormSRGB:case me.BC2RGBAUnorm:case me.BC1RGBAUnormSRGB:case me.BC1RGBAUnorm:case me.ETC2RGB8Unorm:case me.ETC2RGB8UnormSRGB:case me.ETC2RGB8A1Unorm:case me.ETC2RGB8A1UnormSRGB:case me.ETC2RGBA8Unorm:case me.ETC2RGBA8UnormSRGB:case me.EACR11Unorm:case me.EACR11Snorm:case me.EACRG11Unorm:case me.EACRG11Snorm:case me.ASTC4x4Unorm:case me.ASTC4x4UnormSRGB:case me.ASTC5x4Unorm:case me.ASTC5x4UnormSRGB:case me.ASTC5x5Unorm:case me.ASTC5x5UnormSRGB:case me.ASTC6x5Unorm:case me.ASTC6x5UnormSRGB:case me.ASTC6x6Unorm:case me.ASTC6x6UnormSRGB:case me.ASTC8x5Unorm:case me.ASTC8x5UnormSRGB:case me.ASTC8x6Unorm:case me.ASTC8x6UnormSRGB:case me.ASTC8x8Unorm:case me.ASTC8x8UnormSRGB:case me.ASTC10x5Unorm:case me.ASTC10x5UnormSRGB:case me.ASTC10x6Unorm:case me.ASTC10x6UnormSRGB:case me.ASTC10x8Unorm:case me.ASTC10x8UnormSRGB:case me.ASTC10x10Unorm:case me.ASTC10x10UnormSRGB:case me.ASTC12x10Unorm:case me.ASTC12x10UnormSRGB:case me.ASTC12x12Unorm:case me.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return me.Depth16Unorm;case 16:return me.Depth24Plus;case 13:return me.Depth24PlusStencil8;case 14:return me.Depth32Float;case 18:return me.Depth32FloatStencil8;case 19:return me.Stencil8;case 36492:return i?me.BC7RGBAUnormSRGB:me.BC7RGBAUnorm;case 36495:return me.BC6HRGBUFloat;case 36494:return me.BC6HRGBFloat;case 33779:return i?me.BC3RGBAUnormSRGB:me.BC3RGBAUnorm;case 33778:return i?me.BC2RGBAUnormSRGB:me.BC2RGBAUnorm;case 33777:case 33776:return i?me.BC1RGBAUnormSRGB:me.BC1RGBAUnorm;case 37808:return i?me.ASTC4x4UnormSRGB:me.ASTC4x4Unorm;case 36196:case 37492:return i?me.ETC2RGB8UnormSRGB:me.ETC2RGB8Unorm;case 37496:return i?me.ETC2RGBA8UnormSRGB:me.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return me.R8Snorm;case 7:return me.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return me.R8Sint;case 9:return me.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return me.RGBA8Sint;default:return me.RGBA8Snorm}case 0:switch(t){case 6:return me.R8Unorm;case 7:return me.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?me.RGBA8UnormSRGB:me.RGBA8Unorm;case 12:return i?me.BGRA8UnormSRGB:me.BGRA8Unorm;case 8:return me.R8Uint;case 9:return me.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return me.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return me.RGBA8Unorm}case 4:switch(t){case 8:return me.R16Sint;case 9:return me.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return me.RGBA16Sint;default:return me.RGBA16Sint}case 5:switch(t){case 8:return me.R16Uint;case 9:return me.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return me.RGBA16Uint;default:return me.RGBA16Uint}case 6:switch(t){case 8:return me.R32Sint;case 9:return me.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return me.RGBA32Sint;default:return me.RGBA32Sint}case 7:switch(t){case 8:return me.R32Uint;case 9:return me.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return me.RGBA32Uint;default:return me.RGBA32Uint}case 1:switch(t){case 6:return me.R32Float;case 7:return me.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return me.RGBA32Float;default:return me.RGBA32Float}case 2:switch(t){case 6:return me.R16Float;case 7:return me.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return me.RGBA16Float;default:return me.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:return me.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return me.RG11B10UFloat}case 14:switch(t){case 5:return me.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV";default:return me.RGB9E5UFloat}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:return me.RGB10A2Unorm;case 11:return me.RGB10A2UINT;default:return me.RGB10A2Unorm}}return i?me.RGBA8UnormSRGB:me.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case me.R8Unorm:case me.R8Snorm:case me.R8Uint:case me.R8Sint:case me.BC4RUnorm:case me.BC4RSnorm:case me.R16Uint:case me.R16Sint:case me.Depth16Unorm:case me.R16Float:case me.R32Uint:case me.R32Sint:case me.R32Float:case me.Depth32Float:case me.Stencil8:case me.Depth24Plus:case me.EACR11Unorm:case me.EACR11Snorm:return 1;case me.RG8Unorm:case me.RG8Snorm:case me.RG8Uint:case me.RG8Sint:case me.Depth32FloatStencil8:case me.BC5RGUnorm:case me.BC5RGSnorm:case me.RG16Uint:case me.RG16Sint:case me.RG16Float:case me.RG32Uint:case me.RG32Sint:case me.RG32Float:case me.Depth24PlusStencil8:case me.EACRG11Unorm:case me.EACRG11Snorm:return 2;case me.RGB9E5UFloat:case me.RG11B10UFloat:case me.BC6HRGBUFloat:case me.BC6HRGBFloat:case me.ETC2RGB8Unorm:case me.ETC2RGB8UnormSRGB:return 3;case me.RGBA8Unorm:case me.RGBA8UnormSRGB:case me.RGBA8Snorm:case me.RGBA8Uint:case me.RGBA8Sint:case me.BGRA8Unorm:case me.BGRA8UnormSRGB:case me.RGB10A2UINT:case me.RGB10A2Unorm:case me.BC7RGBAUnorm:case me.BC7RGBAUnormSRGB:case me.BC3RGBAUnorm:case me.BC3RGBAUnormSRGB:case me.BC2RGBAUnorm:case me.BC2RGBAUnormSRGB:case me.BC1RGBAUnorm:case me.BC1RGBAUnormSRGB:case me.RGBA16Uint:case me.RGBA16Sint:case me.RGBA16Float:case me.RGBA32Uint:case me.RGBA32Sint:case me.RGBA32Float:case me.ETC2RGB8A1Unorm:case me.ETC2RGB8A1UnormSRGB:case me.ETC2RGBA8Unorm:case me.ETC2RGBA8UnormSRGB:case me.ASTC4x4Unorm:case me.ASTC4x4UnormSRGB:case me.ASTC5x4Unorm:case me.ASTC5x4UnormSRGB:case me.ASTC5x5Unorm:case me.ASTC5x5UnormSRGB:case me.ASTC6x5Unorm:case me.ASTC6x5UnormSRGB:case me.ASTC6x6Unorm:case me.ASTC6x6UnormSRGB:case me.ASTC8x5Unorm:case me.ASTC8x5UnormSRGB:case me.ASTC8x6Unorm:case me.ASTC8x6UnormSRGB:case me.ASTC8x8Unorm:case me.ASTC8x8UnormSRGB:case me.ASTC10x5Unorm:case me.ASTC10x5UnormSRGB:case me.ASTC10x6Unorm:case me.ASTC10x6UnormSRGB:case me.ASTC10x8Unorm:case me.ASTC10x8UnormSRGB:case me.ASTC10x10Unorm:case me.ASTC10x10UnormSRGB:case me.ASTC12x10Unorm:case me.ASTC12x10UnormSRGB:case me.ASTC12x12Unorm:case me.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case me.Stencil8:case me.Depth32FloatStencil8:case me.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case me.Depth32FloatStencil8:case me.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case me.Depth16Unorm:return me.Depth16Unorm;case me.Depth24Plus:return me.Depth24Plus;case me.Depth24PlusStencil8:return me.Depth24Plus;case me.Depth32Float:return me.Depth32Float;case me.Depth32FloatStencil8:return me.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class jV{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t;return((t=this._webgpuMSAATexture)==null?void 0:t[e])??null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),t===-1&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e==null||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=me.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,s,a,o,c){let l=Jr.E2d,h=1;r?(l=i?Jr.CubeArray:Jr.Cube,h=6*(c||1)):s?l=Jr.E3d:i&&(l=Jr.E2dArray,h=c);const u=Ur.GetDepthFormatOnly(this.format),d=Ur.HasDepthAndStencilAspects(this.format)?If.DepthOnly:If.All;this.createView({label:`TextureView${s?"3D":r?"Cube":"2D"}${i?"_Array"+h:""}_${a}x${o}_${t?"wmips":"womips"}_${this.format}_${l}`,format:u,dimension:l,mipLevelCount:t?_t.ILog2(Math.max(a,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:d})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const i=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=i}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;(e=this._webgpuTexture)==null||e.destroy(),this.releaseMSAATexture(),(t=this._copyInvertYTempTexture)==null||t.destroy(),this.reset()}}const aDe=` const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); layout(location = 0) out vec2 vTex; void main() { vTex = tex[gl_VertexIndex]; gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); } `,oDe=` layout(set = 0, binding = 0) uniform sampler imgSampler; layout(set = 0, binding = 1) uniform texture2D img; layout(location = 0) in vec2 vTex; layout(location = 0) out vec4 outColor; void main() { outColor = texture(sampler2D(img, imgSampler), vTex); } `,U2e=` #extension GL_EXT_samplerless_texture_functions : enable const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); layout(set = 0, binding = 0) uniform texture2D img; #ifdef INVERTY layout(location = 0) out flat ivec2 vTextureSize; #endif void main() { #ifdef INVERTY vTextureSize = textureSize(img, 0); #endif gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); } `,lDe=` #extension GL_EXT_samplerless_texture_functions : enable layout(set = 0, binding = 0) uniform texture2D img; #ifdef INVERTY layout(location = 0) in flat ivec2 vTextureSize; #endif layout(location = 0) out vec4 outColor; void main() { #ifdef INVERTY vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0); #else vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); #endif #ifdef PREMULTIPLYALPHA color.rgb *= color.a; #endif outColor = color; } `,cDe=U2e,hDe=` #extension GL_EXT_samplerless_texture_functions : enable layout(set = 0, binding = 0) uniform texture2D img; layout(set = 0, binding = 1) uniform Params { float ofstX; float ofstY; float width; float height; }; #ifdef INVERTY layout(location = 0) in flat ivec2 vTextureSize; #endif layout(location = 0) out vec4 outColor; void main() { if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) { discard; } if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) { discard; } #ifdef INVERTY vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0); #else vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); #endif #ifdef PREMULTIPLYALPHA color.rgb *= color.a; #endif outColor = color; } `,uDe=` const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); void main() { gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); } `,dDe=` layout(set = 0, binding = 0) uniform Uniforms { uniform vec4 color; }; layout(location = 0) out vec4 outColor; void main() { outColor = color; } `,fDe=` struct VertexOutput { @builtin(position) Position : vec4, @location(0) fragUV : vec2 } @vertex fn main( @builtin(vertex_index) VertexIndex : u32 ) -> VertexOutput { var pos = array, 4>( vec2(-1.0, 1.0), vec2( 1.0, 1.0), vec2(-1.0, -1.0), vec2( 1.0, -1.0) ); var tex = array, 4>( vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0) ); var output: VertexOutput; output.Position = vec4(pos[VertexIndex], 0.0, 1.0); output.fragUV = tex[VertexIndex]; return output; } `,pDe=` @group(0) @binding(0) var videoSampler: sampler; @group(0) @binding(1) var videoTexture: texture_external; @fragment fn main( @location(0) fragUV: vec2 ) -> @location(0) vec4 { return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); } `,_De=` @group(0) @binding(0) var videoSampler: sampler; @group(0) @binding(1) var videoTexture: texture_external; @fragment fn main( @location(0) fragUV: vec2 ) -> @location(0) vec4 { return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y)); } `;var pf;(function(n){n[n.MipMap=0]="MipMap",n[n.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",n[n.Clear=2]="Clear",n[n.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(pf||(pf={}));var NS;(function(n){n[n.DontInvertY=0]="DontInvertY",n[n.InvertY=1]="InvertY"})(NS||(NS={}));const pde=[{vertex:aDe,fragment:oDe},{vertex:U2e,fragment:lDe},{vertex:uDe,fragment:dDe},{vertex:cDe,fragment:hDe}],P0={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class mDe{constructor(e,t,i,r,s,a){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=r,this._bufferManager=s,a.indexOf(kp.RG11B10UFloatRenderable)!==-1){const o=Object.keys(P0);P0[me.RG11B10UFloat]=P0[o[o.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:fr.Linear}),this._videoSampler=t.createSampler({minFilter:fr.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,ys.Uniform|ys.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(me.RGBA8Unorm),this._getVideoPipeline(me.RGBA8Unorm)}_getPipeline(e,t=pf.MipMap,i){const r=t===pf.MipMap?1:t===pf.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===pf.Clear?8:t===pf.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][r];if(!s){let a=`#version 450 `;(t===pf.InvertYPremultiplyAlpha||t===pf.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(a+=`#define INVERTY `),i.premultiplyAlpha&&(a+=`#define PREMULTIPLYALPHA `));let o=this._compiledShaders[r];if(!o){let l=this._glslang.compileGLSL(a+pde[t].vertex,"vertex"),h=this._glslang.compileGLSL(a+pde[t].fragment,"fragment");this._tintWASM&&(l=this._tintWASM.convertSpirV2WGSL(l),h=this._tintWASM.convertSpirV2WGSL(h));const u=this._device.createShaderModule({code:l}),d=this._device.createShaderModule({code:h});o=this._compiledShaders[r]=[u,d]}const c=this._device.createRenderPipeline({layout:j8.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Uh.TriangleStrip,stripIndexFormat:s2.Uint16}});s=this._pipelines[e][r]=[c,c.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=NS.DontInvertY){const i=t===NS.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let s=this._videoCompiledShaders[i];if(!s){const o=this._device.createShaderModule({code:fDe}),c=this._device.createShaderModule({code:i===0?pDe:_De});s=this._videoCompiledShaders[i]=[o,c]}const a=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${i===0?"DontInvertY":"InvertY"}`,layout:j8.Auto,vertex:{module:s[0],entryPoint:"main"},fragment:{module:s[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Uh.TriangleStrip,stripIndexFormat:s2.Uint16}});r=this._videoPipelines[e][i]=[a,a.getBindGroupLayout(0)]}return r}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,r=!1,s){var p,_;const a=s===void 0,[o,c]=this._getVideoPipeline(i,r?NS.InvertY:NS.DontInvertY);a&&(s=this._device.createCommandEncoder({})),(p=s.pushDebugGroup)==null||p.call(s,`copy video to texture - invertY=${r}`);const l=t._hardwareTexture,h={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${r?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:l.underlyingResource.createView({format:i,dimension:Jr.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:If.All}),loadOp:Ja.Load,storeOp:bu.Store}]},u=s.beginRenderPass(h),d={layout:c,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},f=this._device.createBindGroup(d);u.setPipeline(o),u.setBindGroup(0,f),u.draw(4,1,0,0),u.end(),(_=s.popDebugGroup)==null||_.call(s),a&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,r,s=!1,a=!1,o=0,c=0,l=1,h=0,u=0,d=0,f=0,p,_){var D,M;const m=d!==0,g=p===void 0,[v,x]=this._getPipeline(r,m?pf.InvertYPremultiplyAlphaWithOfst:pf.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:a});o=Math.max(o,0),g&&(p=this._device.createCommandEncoder({})),(D=p.pushDebugGroup)==null||D.call(p,`internal process texture - invertY=${s} premultiplyAlpha=${a}`);let y;if(Ur.IsHardwareTexture(e)?(y=e.underlyingResource,s&&!a&&l===1&&o===0||(e=void 0)):(y=e,e=void 0),!y)return;m&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,u,d,f]),0,4*4);const C=e,b=(C==null?void 0:C._copyInvertYTempTexture)??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,p,rn.CopySrc|rn.RenderAttachment|rn.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),T=(C==null?void 0:C._copyInvertYRenderPassDescr)??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${r}_${s?"InvertY":"DontInvertY"}_${a?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:b.createView({format:r,dimension:Jr.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Ja.Load,storeOp:bu.Store}]},S=p.beginRenderPass(T);let N=m?C==null?void 0:C._copyInvertYBindGroupWithOfst:C==null?void 0:C._copyInvertYBindGroup;if(!N){const I={layout:x,entries:[{binding:0,resource:y.createView({format:r,dimension:Jr.E2d,baseMipLevel:c,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};m&&I.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),N=this._device.createBindGroup(I)}S.setPipeline(v),S.setBindGroup(0,N),S.draw(4,1,0,0),S.end(),p.copyTextureToTexture({texture:b},{texture:y,mipLevel:c,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),C?(C._copyInvertYTempTexture=b,C._copyInvertYRenderPassDescr=T,m?C._copyInvertYBindGroupWithOfst=N:C._copyInvertYBindGroup=N):this._deferredReleaseTextures.push([b,null]),(M=p.popDebugGroup)==null||M.call(p),g&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,r){var h,u;const s=r===void 0,[a,o]=this._getPipeline(t,pf.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});s&&(r=this._device.createCommandEncoder({})),(h=r.pushDebugGroup)==null||h.call(r,"internal copy texture with invertY");const c=r.beginRenderPass(i),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});c.setPipeline(a),c.setBindGroup(0,l),c.draw(4,1,0,0),c.end(),(u=r.popDebugGroup)==null||u.call(r),s&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,s=!1,a=!1,o=me.RGBA8Unorm,c=1,l,h=-1,u=0,d){c=Ur.GetSample(c);const f=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:f},_=P0[o]?rn.RenderAttachment:0,m=Ur.IsCompressedFormat(o),g=t?Ur.ComputeNumMipmapLevels(e.width,e.height):1,v=h>=0?h:rn.CopySrc|rn.CopyDst|rn.TextureBinding;u|=t&&!m?rn.CopySrc|_:0,!m&&!a&&(u|=_|rn.CopyDst);const x=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${a?"3D":"2D"}_${d?d+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${c}`,size:p,dimension:a?bd.E3d:bd.E2d,format:o,usage:v|u,sampleCount:c,mipLevelCount:g});return Ur.IsImageBitmap(e)&&(this.updateTexture(e,x,e.width,e.height,f,o,0,0,r,s,0,0),t&&i&&this.generateMipmaps(x,o,g,0,l)),x}createCubeTexture(e,t=!1,i=!1,r=!1,s=!1,a=me.RGBA8Unorm,o=1,c,l=-1,h=0,u){o=Ur.GetSample(o);const d=Ur.IsImageBitmapArray(e)?e[0].width:e.width,f=Ur.IsImageBitmapArray(e)?e[0].height:e.height,p=P0[a]?rn.RenderAttachment:0,_=Ur.IsCompressedFormat(a),m=t?Ur.ComputeNumMipmapLevels(d,f):1,g=l>=0?l:rn.CopySrc|rn.CopyDst|rn.TextureBinding;h|=t&&!_?rn.CopySrc|p:0,_||(h|=p|rn.CopyDst);const v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${u?u+"_":""}${d}x${f}x6_${t?"wmips":"womips"}_${a}_samples${o}`,size:{width:d,height:f,depthOrArrayLayers:6},dimension:bd.E2d,format:a,usage:g|h,sampleCount:o,mipLevelCount:m});return Ur.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,v,d,f,a,r,s,0,0),t&&i&&this.generateCubeMipmaps(v,a,m,c)),v}generateCubeMipmaps(e,t,i,r){var a,o;const s=r===void 0;s&&(r=this._device.createCommandEncoder({})),(a=r.pushDebugGroup)==null||a.call(r,`create cube mipmaps - ${i} levels`);for(let c=0;c<6;++c)this.generateMipmaps(e,t,i,c,r);(o=r.popDebugGroup)==null||o.call(r),s&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,s){var u,d,f,p;const a=s===void 0,[o,c]=this._getPipeline(t);r=Math.max(r,0),a&&(s=this._device.createCommandEncoder({})),(u=s.pushDebugGroup)==null||u.call(s,`create mipmaps for face #${r} - ${i} levels`);let l;if(Ur.IsHardwareTexture(e)?(l=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(l=e,e=void 0),!l)return;const h=e;for(let _=1;_h;)this._device.queue.writeBuffer(a,t+u,i.buffer,o+u,h),u+=h;this._device.queue.writeBuffer(a,t+u,i.buffer,o+u,s-u)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const r=new Uint16Array(t);for(;e--;)i[e]=Np(r[e]);return i}readDataFromBuffer(e,t,i,r,s,a,o=0,c=0,l=null,h=!0,u=!1){const d=o===1?2:o===2?1:0,f=this._engine.uniqueId;return new Promise((p,_)=>{e.mapAsync(z3.Read,c,t).then(()=>{const m=e.getMappedRange(c,t);let g=l;if(u)g===null?g=Nz(o,t,!0,m):g=Nz(o,g.buffer,void 0,m);else if(g===null)switch(d){case 0:g=new Uint8Array(t),g.set(new Uint8Array(m));break;case 1:g=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,m);break;case 2:g=new Float32Array(t/4),g.set(new Float32Array(m));break}else switch(d){case 0:g=new Uint8Array(g.buffer),g.set(new Uint8Array(m));break;case 1:g=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,m,l);break;case 2:g=new Float32Array(g.buffer),g.set(new Float32Array(m));break}if(s!==a){d===1&&!u&&(s*=2,a*=2);const v=new Uint8Array(g.buffer);let x=s,y=0;for(let C=1;C{this._engine.isDisposed||this._engine.uniqueId!==f?p(new Uint8Array):_(m)})})}releaseBuffer(e){return Gz._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,e.references===0?(this._deferredReleaseBuffers.push(e.underlyingResource),!0):!1)}destroyDeferredBuffers(){for(let e=0;e1?4:1;return gDe[e.samplingMode]+vDe[(e._comparisonFunction||514)-512+1]+xDe[e.samplingMode]+((e._cachedWrapU??1)<<8)+((e._cachedWrapV??1)<<10)+((e._cachedWrapR??1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,t){let i,r,s,a,o;const c=e.useMipMaps;switch(e.samplingMode){case 11:i=fr.Linear,r=fr.Linear,s=fr.Nearest,c||(a=o=0);break;case 3:case 3:i=fr.Linear,r=fr.Linear,c?s=fr.Linear:(s=fr.Nearest,a=o=0);break;case 8:i=fr.Nearest,r=fr.Nearest,c?s=fr.Linear:(s=fr.Nearest,a=o=0);break;case 4:i=fr.Nearest,r=fr.Nearest,s=fr.Nearest,c||(a=o=0);break;case 5:i=fr.Nearest,r=fr.Linear,s=fr.Nearest,c||(a=o=0);break;case 6:i=fr.Nearest,r=fr.Linear,c?s=fr.Linear:(s=fr.Nearest,a=o=0);break;case 7:i=fr.Nearest,r=fr.Linear,s=fr.Nearest,a=o=0;break;case 1:case 1:i=fr.Nearest,r=fr.Nearest,s=fr.Nearest,a=o=0;break;case 9:i=fr.Linear,r=fr.Nearest,s=fr.Nearest,c||(a=o=0);break;case 10:i=fr.Linear,r=fr.Nearest,c?s=fr.Linear:(s=fr.Nearest,a=o=0);break;case 2:case 2:i=fr.Linear,r=fr.Linear,s=fr.Nearest,a=o=0;break;case 12:i=fr.Linear,r=fr.Nearest,s=fr.Nearest,a=o=0;break;default:i=fr.Nearest,r=fr.Nearest,s=fr.Nearest,a=o=0;break}return t>1&&(a!==0||o!==0)&&s!==fr.Nearest?{magFilter:fr.Linear,minFilter:fr.Linear,mipmapFilter:fr.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:s,lodMinClamp:a,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return by.Repeat;case 0:return by.ClampToEdge;case 2:return by.MirrorRepeat}return by.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,r=this._GetSamplerFilterDescriptor(e,i);return{label:t,...r,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?P3.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:r.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return zo.Always;case 514:return zo.Equal;case 516:return zo.Greater;case 518:return zo.GreaterEqual;case 513:return zo.Less;case 515:return zo.LessEqual;case 512:return zo.Never;case 517:return zo.NotEqual;default:return zo.Less}}getSampler(e,t=!1,i=0,r){if(this.disabled)return this._device.createSampler(P3._GetSamplerDescriptor(e,r));t?i=0:i===0&&(i=P3.GetSamplerHashCode(e));let s=t?void 0:this._samplers[i];return s||(s=this._device.createSampler(P3._GetSamplerDescriptor(e,r)),t||(this._samplers[i]=s)),s}}var xa;(function(n){n[n.StencilReadMask=0]="StencilReadMask",n[n.StencilWriteMask=1]="StencilWriteMask",n[n.DepthBias=2]="DepthBias",n[n.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",n[n.DepthStencilState=4]="DepthStencilState",n[n.MRTAttachments1=5]="MRTAttachments1",n[n.MRTAttachments2=6]="MRTAttachments2",n[n.RasterizationState=7]="RasterizationState",n[n.ColorStates=8]="ColorStates",n[n.ShaderStage=9]="ShaderStage",n[n.TextureStage=10]="TextureStage",n[n.VertexState=11]="VertexState",n[n.NumStates=12]="NumStates"})(xa||(xa={}));const gV={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},gS={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},yDe={[Z.PositionKind]:!0,[Z.NormalKind]:!0,[Z.TangentKind]:!0,[Z.UVKind]:!0,[Z.UV2Kind]:!0,[Z.UV3Kind]:!0,[Z.UV4Kind]:!0,[Z.UV5Kind]:!0,[Z.UV6Kind]:!0,[Z.ColorKind]:!0,[Z.ColorInstanceKind]:!0,[Z.MatricesIndicesKind]:!0,[Z.MatricesWeightsKind]:!0,[Z.MatricesIndicesExtraKind]:!0,[Z.MatricesWeightsExtraKind]:!0};class sn{static _IsSignedType(e){switch(e){case Z.BYTE:case Z.SHORT:case Z.INT:case Z.FLOAT:return!0;case Z.UNSIGNED_BYTE:case Z.UNSIGNED_SHORT:case Z.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[me.BGRA8Unorm],this.setColorFormat(me.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(me.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,r=0){if(i=Ur.GetSample(i),this.disabled){const a=sn._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,a,i),sn.NumCacheMiss++,sn._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,sn.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return sn.NumCacheHitWithHash++,this._parameter.pipeline;const s=sn._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),sn.NumCacheMiss++,sn._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){sn.NumPipelineCreationLastFrame=sn._NumPipelineCreationCurrentFrame,sn._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,s,a,o,c){this._depthWriteEnabled=o,this._depthTestEnabled=a,this._depthCompare=(c??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[xa.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,xa.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[xa.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,xa.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=P0[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let r=0,s=0,a=0;for(let o=0;o=32&&(s=0,r++)}this._mrtFormats.length=a,(this._mrtAttachments1!==i[0]||this._mrtAttachments2!==i[1])&&(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[xa.MRTAttachments1]=i[0],this._states[xa.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,xa.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=e===void 0?0:P0[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e??519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e??519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=e===null?1:gS[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:gS[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:gS[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[xa.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,xa.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[xa.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,xa.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,s,a,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=i===null?1:gS[i],this._stencilFrontPassOp=r===null?2:gS[r],this._stencilFrontFailOp=s===null?1:gS[s],this.setStencilReadMask(a),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:return Uh.TriangleList;case 2:return Uh.PointList;case 1:return Uh.LineList;case 3:return Uh.PointList;case 4:return Uh.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return Uh.LineStrip;case 7:return Uh.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return Uh.TriangleList}}static _GetAphaBlendOperation(e){switch(e){case 32774:return vm.Add;case 32778:return vm.Subtract;case 32779:return vm.ReverseSubtract;case 32775:return vm.Min;case 32776:return vm.Max;default:return vm.Add}}static _GetAphaBlendFactor(e){switch(e){case 0:return Ul.Zero;case 1:return Ul.One;case 768:return Ul.Src;case 769:return Ul.OneMinusSrc;case 770:return Ul.SrcAlpha;case 771:return Ul.OneMinusSrcAlpha;case 772:return Ul.DstAlpha;case 773:return Ul.OneMinusDstAlpha;case 774:return Ul.Dst;case 775:return Ul.OneMinusDst;case 776:return Ul.SrcAlphaSaturated;case 32769:return Ul.Constant;case 32770:return Ul.OneMinusConstant;case 32771:return Ul.Constant;case 32772:return Ul.OneMinusConstant;default:return Ul.One}}static _GetCompareFunction(e){switch(e){case 0:return zo.Never;case 1:return zo.Less;case 2:return zo.Equal;case 3:return zo.LessEqual;case 4:return zo.Greater;case 5:return zo.NotEqual;case 6:return zo.GreaterEqual;case 7:return zo.Always}return zo.Never}static _GetStencilOpFunction(e){switch(e){case 0:return gf.Zero;case 1:return gf.Keep;case 2:return gf.Replace;case 3:return gf.IncrementClamp;case 4:return gf.DecrementClamp;case 5:return gf.Invert;case 6:return gf.IncrementWrap;case 7:return gf.DecrementWrap}return gf.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,r=e.getSize();switch(t){case Z.BYTE:switch(r){case 1:case 2:return i?dn.Snorm8x2:dn.Sint8x2;case 3:case 4:return i?dn.Snorm8x4:dn.Sint8x4}break;case Z.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?dn.Unorm8x2:dn.Uint8x2;case 3:case 4:return i?dn.Unorm8x4:dn.Uint8x4}break;case Z.SHORT:switch(r){case 1:case 2:return i?dn.Snorm16x2:dn.Sint16x2;case 3:case 4:return i?dn.Snorm16x4:dn.Sint16x4}break;case Z.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?dn.Unorm16x2:dn.Uint16x2;case 3:case 4:return i?dn.Unorm16x4:dn.Uint16x4}break;case Z.INT:switch(r){case 1:return dn.Sint32;case 2:return dn.Sint32x2;case 3:return dn.Sint32x3;case 4:return dn.Sint32x4}break;case Z.UNSIGNED_INT:switch(r){case 1:return dn.Uint32;case 2:return dn.Uint32x2;case 3:return dn.Uint32x3;case 4:return dn.Uint32x4}break;case Z.FLOAT:switch(r){case 1:return dn.Float32;case 2:return dn.Float32x2;case 3:return dn.Float32x3;case 4:return dn.Float32x4}break}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:sn._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:sn._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:sn._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:sn._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:sn._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:sn._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[xa.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,xa.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace,r=this._cullEnabled?this._cullFace:0,s=this._clampDepth?1:0,a=this._alphaToCoverageEnabled?1:0,o=i-1+(r<<1)+(s<<3)+(a<<4)+(e<<5)+(t<<8);this._rasterizationState!==o&&(this._rasterizationState=o,this._states[xa.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,xa.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((this._alphaBlendFuncParams[0]===null?2:gV[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:gV[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:gV[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:gV[this._alphaBlendFuncParams[3]])<<12)+((this._alphaBlendEqParams[0]===null?1:this._alphaBlendEqParams[0]-32773)<<16)+((this._alphaBlendEqParams[1]===null?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[xa.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,xa.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[xa.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,xa.DepthStencilState))}_setVertexState(e){var l;const t=this._statesLength;let i=xa.VertexState;const r=e._pipelineContext,s=r.shaderProcessingContext.attributeNamesFromEffect,a=r.shaderProcessingContext.attributeLocationsFromEffect;let o,c=0;for(let h=0;h0)for(let p=0;p=this._video.HAVE_CURRENT_DATA}dispose(){}}class VG{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=VG._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?P3.GetSamplerHashCode(t):0;const s=r!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var a;let i=this.textures[e],r=-1;i?r=((a=i.texture)==null?void 0:a.uniqueId)??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=t.type===1||t.format>=13&&t.format<=18,i.isExternalTexture=Tee.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const s=r!==((t==null?void 0:t.uniqueId)??-1);s&&this.updateId++,this.isDirty||(this.isDirty=s)}}VG._Counter=0;class x9{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,ys.CopyDst|ys.Indirect|ys.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=x9._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(t==null?void 0:t.uniqueId)!==((i=this.buffers[e])==null?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t===this._currentInstanceCount||!this.indirectDrawBuffer||!this._indirectDrawData||(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}x9._Counter=0;class Zw{constructor(){this.values={}}}class ps{static get Statistics(){return{totalCreated:ps.NumBindGroupsCreatedTotal,lastFrameCreated:ps.NumBindGroupsCreatedLastFrame,lookupLastFrame:ps.NumBindGroupsLookupLastFrame,noLookupLastFrame:ps.NumBindGroupsNoLookupLastFrame}}static ResetCache(){ps._Cache=new Zw,ps.NumBindGroupsCreatedTotal=0,ps.NumBindGroupsCreatedLastFrame=0,ps.NumBindGroupsLookupLastFrame=0,ps.NumBindGroupsNoLookupLastFrame=0,ps._NumBindGroupsCreatedCurrentFrame=0,ps._NumBindGroupsLookupCurrentFrame=0,ps._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){ps.NumBindGroupsCreatedLastFrame=ps._NumBindGroupsCreatedCurrentFrame,ps.NumBindGroupsLookupLastFrame=ps._NumBindGroupsLookupCurrentFrame,ps.NumBindGroupsNoLookupLastFrame=ps._NumBindGroupsNoLookupCurrentFrame,ps._NumBindGroupsCreatedCurrentFrame=0,ps._NumBindGroupsLookupCurrentFrame=0,ps._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var c,l,h,u,d,f;let r,s=ps._Cache;const a=this.disabled||i.forceBindGroupCreation;if(!a){if(!t.isDirty(i.updateId)&&!i.isDirty)return ps._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const p of e.shaderProcessingContext.bufferNames){const _=((c=t.buffers[p])==null?void 0:c.uniqueId)??0;let m=s.values[_];m||(m=new Zw,s.values[_]=m),s=m}for(const p of e.shaderProcessingContext.samplerNames){const _=((l=i.samplers[p])==null?void 0:l.hashCode)??0;let m=s.values[_];m||(m=new Zw,s.values[_]=m),s=m}for(const p of e.shaderProcessingContext.textureNames){const _=((u=(h=i.textures[p])==null?void 0:h.texture)==null?void 0:u.uniqueId)??0;let m=s.values[_];m||(m=new Zw,s.values[_]=m),s=m}r=s.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,r)return t.bindGroups=r,ps._NumBindGroupsLookupCurrentFrame++,r;r=[],t.bindGroups=r,a||(s.bindGroups=r),ps.NumBindGroupsCreatedTotal++,ps._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let p=0;pS==="texture"?"":N)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}m[v].resource=this._cacheSampler.getSampler(T,!1,b.hashCode,T.label)}else de.Error(`Sampler "${C}" could not be bound. entry=${JSON.stringify(x)}, materialContext=${JSON.stringify(i,(T,S)=>T==="texture"||T==="sampler"?"":S)}`,50)}else if(x.texture||x.storageTexture){const b=i.textures[C];if(b){if(this._engine.dbgSanityChecks&&b.texture===null){de.Error(`Trying to bind a null texture! entry=${JSON.stringify(x)}, bindingInfo=${JSON.stringify(b,(S,N)=>S==="texture"?"":N)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const T=b.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!T||x.texture&&!T.view||x.storageTexture&&!T.viewForWriting)){de.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(x)}, name=${C}, bindingInfo=${JSON.stringify(b,(S,N)=>S==="texture"?"":N)}, isReady=${(d=b.texture)==null?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}m[v].resource=x.storageTexture?T.viewForWriting:T.view}else de.Error(`Texture "${C}" could not be bound. entry=${JSON.stringify(x)}, materialContext=${JSON.stringify(i,(T,S)=>T==="texture"||T==="sampler"?"":S)}`,50)}else if(x.externalTexture){const b=i.textures[C];if(b){if(this._engine.dbgSanityChecks&&b.texture===null){de.Error(`Trying to bind a null external texture! entry=${JSON.stringify(x)}, name=${C}, bindingInfo=${JSON.stringify(b,(S,N)=>S==="texture"?"":N)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const T=b.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!T){de.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(x)}, name=${C}, bindingInfo=${JSON.stringify(b,(S,N)=>S==="texture"?"":N)}, isReady=${(f=b.texture)==null?void 0:f.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}m[v].resource=this._device.importExternalTexture({source:T})}else de.Error(`Texture "${C}" could not be bound. entry=${JSON.stringify(x)}, materialContext=${JSON.stringify(i,(T,S)=>T==="texture"||T==="sampler"?"":S)}`,50)}else if(x.buffer){const b=t.buffers[C];if(b){const T=b.underlyingResource;m[v].resource.buffer=T,m[v].resource.size=b.capacity}else de.Error(`Can't find buffer "${C}". entry=${JSON.stringify(x)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const g=o[p];r[p]=this._device.createBindGroup({layout:g,entries:m})}return r}}ps.NumBindGroupsCreatedTotal=0;ps.NumBindGroupsCreatedLastFrame=0;ps.NumBindGroupsLookupLastFrame=0;ps.NumBindGroupsNoLookupLastFrame=0;ps._Cache=new Zw;ps._NumBindGroupsCreatedCurrentFrame=0;ps._NumBindGroupsLookupCurrentFrame=0;ps._NumBindGroupsNoLookupCurrentFrame=0;const bDe="clearQuadVertexShader",EDe=`uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0), vec2(1.0,1.0), vec2(-1.0,-1.0), vec2(1.0,-1.0)}; #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN gl_Position=vec4(pos[gl_VertexID],depthValue,1.0); #define CUSTOM_VERTEX_MAIN_END } `;Re.ShadersStore[bDe]=EDe;const TDe="clearQuadPixelShader",SDe=`uniform vec4 color;void main() {gl_FragColor=color;} `;Re.ShadersStore[TDe]=SDe;class MDe{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new Ef(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"])}clear(e,t,i,r,s=1){let a,o=null,c;const l=!!this._engine._currentRenderTarget;if(e)a=e;else{let m=0;this._keyTemp.length=0;for(let v=0;v1?2**36:0)+g*2**37,c=this._keyTemp.join("_"),o=this._bundleCache[c],o)return o;a=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Ur.GetSample(s)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&Ur.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const h=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),u=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),u.uniformBuffer.update();const d=l?this._engine._ubInvertY:this._engine._ubDontInvertY,f=u.uniformBuffer.getBuffer(),p=f.uniqueId+"-"+d.uniqueId;let _=this._bindGroups[p];if(!_){const m=u.bindGroupLayouts[0];_=this._bindGroups[p]=[],_.push(this._device.createBindGroup({layout:m[0],entries:[]})),Ed._SimplifiedKnownBindings||_.push(this._device.createBindGroup({layout:m[1],entries:[]})),_.push(this._device.createBindGroup({layout:m[Ed._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:d.underlyingResource,size:d.capacity}},{binding:1,resource:{buffer:f.underlyingResource,size:f.capacity}}]}))}a.setPipeline(h);for(let m=0;m<_.length;++m)a.setBindGroup(m,_[m]);return a.draw(4,1,0,0),e||(o=a.finish(),this._bundleCache[c]=o),o}}class See{constructor(e,t,i,r){this.x=Math.floor(e),this.y=Math.floor(t),this.w=Math.floor(i),this.h=Math.floor(r)}run(e){e.setViewport(this.x,this.y,this.w,this.h,0,1)}clone(){return new See(this.x,this.y,this.w,this.h)}}class Mee{constructor(e,t,i,r){this.x=e,this.y=t,this.w=i,this.h=r}run(e){e.setScissorRect(this.x,this.y,this.w,this.h)}clone(){return new Mee(this.x,this.y,this.w,this.h)}}class Kz{constructor(e){this.ref=e}run(e){e.setStencilReference(this.ref)}clone(){return new Kz(this.ref)}}class Ree{constructor(e){this.color=e}run(e){e.setBlendConstant(this.color)}clone(){return new Ree(this.color)}}class Iee{constructor(e){this.query=e}run(e){e.beginOcclusionQuery(this.query)}clone(){return new Iee(this.query)}}class Pee{constructor(){}run(e){e.endOcclusionQuery()}clone(){return new Pee}}class wee{constructor(){this.bundles=[]}run(e){e.executeBundles(this.bundles)}clone(){const e=new wee;return e.bundles=this.bundles,e}}class Dee{constructor(e){this.numDrawCalls=0,this._device=e,this._list=new Array(10),this._listLength=0}addBundle(e){if(!this._currentItemIsBundle){const t=new wee;this._list[this._listLength++]=t,this._currentBundleList=t.bundles,this._currentItemIsBundle=!0}e&&this._currentBundleList.push(e)}_finishBundle(){this._currentItemIsBundle&&this._bundleEncoder&&(this._currentBundleList.push(this._bundleEncoder.finish()),this._bundleEncoder=void 0,this._currentItemIsBundle=!1)}addItem(e){this._finishBundle(),this._list[this._listLength++]=e,this._currentItemIsBundle=!1}getBundleEncoder(e,t,i){return this._currentItemIsBundle||(this.addBundle(),this._bundleEncoder=this._device.createRenderBundleEncoder({colorFormats:e,depthStencilFormat:t,sampleCount:Ur.GetSample(i)})),this._bundleEncoder}close(){this._finishBundle()}run(e){this.close();for(let t=0;t{const s=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,s},s=>{if(this._engine.isDisposed||this._engine.uniqueId!==r)return null;throw s})}async readValue(e=0){const t=this._getBuffer(e,1);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(z3.Read).then(()=>{const r=new BigUint64Array(t.getMappedRange()),s=Number(r[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,s},r=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw r})}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(z3.Read).then(()=>{const r=new BigUint64Array(t.getMappedRange()),s=Number(r[1]-r[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,s},r=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw r})}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{t!==null&&t>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(t,!0)),this._measureDurationState=0}))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then(r=>{t._addDuration(i,r!==null&&r>0?r:0)})}dispose(){var e;(e=this._measureDuration)==null||e.dispose()}}class IDe{constructor(e,t,i,r=2,s){this._count=r,this._querySet=new V2e(e,r,XD.Timestamp,t,i,!0,s)}start(e){var t;(t=e.writeTimestamp)==null||t.call(e,this._querySet.querySet,0)}async stop(e){var t;return(t=e.writeTimestamp)==null||t.call(e,this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class PDe{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet!==void 0;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,r=50,s=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(r)}createQuery(){this._availableIndices.length===0&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e}))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose,1e3)}dispose(){var e;(e=this._querySet)==null||e.dispose(),this._availableIndices.length=0}}class zh{async initTwgsl(e){if(!zh._Twgsl)return e=e||{},e={...zh._TWgslDefaultOptions,...e},e.twgsl?(zh._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await Ee.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(zh._Twgsl=await self.twgsl(Ee.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=zh._Twgsl.convertSpirV2WGSL(e,zh.DisableUniformityAnalysis||t);return zh.ShowWGSLShaderCode&&(de.Log(i),de.Log("***********************************************")),zh.DisableUniformityAnalysis||t?`diagnostic(off, derivative_uniformity); `+i:i}}zh._TWgslDefaultOptions={jsPath:`${Ee._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${Ee._DefaultCdnUrl}/twgsl/twgsl.wasm`};zh.ShowWGSLShaderCode=!1;zh.DisableUniformityAnalysis=!1;zh._Twgsl=null;class wDe{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),this._mode===1&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}const DDe="postprocessVertexShader",ODe=`attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END } `;Re.ShadersStoreWGSL[DDe]=ODe;const _de={label:"TextureView_SwapChain_ResolveTarget",dimension:bd.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},mde={label:"TextureView_SwapChain",dimension:bd.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},vV="/* disable_uniformity_analysis */",LDe=new Ze;class gi extends De{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return this._cacheSampler?this._cacheSampler.disabled:!1}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return this._cacheRenderPipeline?this._cacheRenderPipeline.disabled:!1}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return this._cacheBindGroups?this._cacheBindGroups.disabled:!1}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return de.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new lee:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new gi(e,t);return new Promise(r=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>r(i))})}constructor(e,t={}){if(super(null,t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,de.Log(`Babylon.js v${De.Version} - ${this.description} engine`),!navigator.gpu){de.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new bwe,this._shaderProcessorWGSL=new nDe}initAsync(e,t){var i;return this.uniqueId=gi._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(e??((i=this._options)==null?void 0:i.glslangOptions)).then(r=>{var s;return this._glslang=r,this._tintWASM=gi.UseTWGSL?new zh:null,this._tintWASM?this._tintWASM.initTwgsl(t??((s=this._options)==null?void 0:s.twgslOptions)).then(()=>navigator.gpu.requestAdapter(this._options)):navigator.gpu.requestAdapter(this._options)}).then(r=>{var s;if(r){this._adapter=r,this._adapterSupportedExtensions=[],(s=this._adapter.features)==null||s.forEach(c=>this._adapterSupportedExtensions.push(c)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(c=>{this._adapterInfo=c});const a=this._options.deviceDescriptor??{},o=(a==null?void 0:a.requiredFeatures)??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(o){const c=o,l=[];for(const h of c)this._adapterSupportedExtensions.indexOf(h)!==-1&&l.push(h);a.requiredFeatures=l}if(this._options.setMaximumLimits&&!a.requiredLimits){a.requiredLimits={};for(const c in this._adapterSupportedLimits)c==="minSubgroupSize"||c==="maxSubgroupSize"||(a.requiredLimits[c]=this._adapterSupportedLimits[c])}return a.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(a)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(r=>{var a,o;this._device=r,this._deviceEnabledExtensions=[],(a=this._device.features)==null||a.forEach(c=>this._deviceEnabledExtensions.push(c)),this._deviceLimits=r.limits;let s=-1;this._device.addEventListener("uncapturederror",c=>{++s{this._isDisposed||(this._contextWasLost=!0,de.Warn("WebGPU context lost. "+c),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(async()=>{var _,m;const l=this.snapshotRenderingMode,h=this.snapshotRendering,u=this.disableCacheSamplers,d=this.disableCacheRenderPipelines,f=this.disableCacheBindGroups,p=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??((_=this._options)==null?void 0:_.glslangOptions),this._twgslOptions??((m=this._options)==null?void 0:m.twgslOptions)),this.snapshotRenderingMode=l,this.snapshotRendering=h,this.disableCacheSamplers=u,this.disableCacheRenderPipelines=d,this.disableCacheBindGroups=f,this.enableGPUTimingMeasurements=p,this._currentRenderPass=null}))})}).then(()=>{this._bufferManager=new Gz(this,this._device),this._textureHelper=new mDe(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new P3(this._device),this._cacheBindGroups=new ps(this._device,this._cacheSampler,this),this._timestampQuery=new RDe(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new PDe(this,this._device,this._bufferManager):void 0,this._bundleList=new Dee(this._device),this._snapshotRendering=new wDe(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),ys.Uniform|ys.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),ys.Uniform|ys.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&this._count===void 0&&(this._count=0,de.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new Z(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new Ef(this._device,this._emptyVertexBuffer),this._depthCullingState=new CDe(this._cacheRenderPipeline),this._stencilStateComposer=new ADe(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new MDe(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()}).catch(r=>{throw de.Error("A fatal error occurred during WebGPU creation/initialization."),r})}_initGlslang(e){return e=e||{},e={...gi._GLSLslangDefaultOptions,...e},e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Ee.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(Ee.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage*2,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(kp.TextureCompressionASTC)>=0?!0:void 0,s3tc:this._deviceEnabledExtensions.indexOf(kp.TextureCompressionBC)>=0?!0:void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(kp.TextureCompressionETC2)>=0?!0:void 0,bptc:this._deviceEnabledExtensions.indexOf(kp.TextureCompressionBC)>=0?!0:void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(kp.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(kp.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:typeof BigUint64Array<"u"&&this._deviceEnabledExtensions.indexOf(kp.TimestampQuery)!==-1?!0:void 0,supportOcclusionQuery:typeof BigUint64Array<"u",canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new jV],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e);let t;if(this._options.antialias){const s={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:bd.E2d,format:this._options.swapChainFormat,usage:rn.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(s),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:bd.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Ze(0,0,0,1),loadOp:Ja.Clear,storeOp:bu.Store}]}else t=[{view:void 0,clearValue:new Ze(0,0,0,1),loadOp:Ja.Clear,storeOp:bu.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?me.Depth24PlusStencil8:me.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:bd.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:rn.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:bd.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Ja.Clear,depthStoreOp:bu.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Ja.Clear:void 0,stencilStoreOp:this.isStencilEnable?bu.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:r}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:rn.RenderAttachment|rn.CopySrc,alphaMode:this.premultipliedAlpha?YD.Premultiplied:YD.Opaque})}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){Ef.ResetCache(),ps.ResetCache();const t=r=>{var s;for(const a of r){for(const o of a.meshes){const c=o.subMeshes;if(c)for(const l of c)l._drawWrappers=[]}for(const o of a.materials)(s=o._materialContext)==null||s.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const r of this._uniformBuffers)r.name.indexOf("leftOver")<0&&i.push(r);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return super.setSize(e,t,i)?(this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count=0,s=t.indexOf(vV)>=0,a=i===Vs.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===Vs.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(a,o,i,r,s)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);const s=e.indexOf(vV)>=0,a=t.indexOf(vV)>=0,o=`#version 450 `,c=r===Vs.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=r===Vs.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(c,l,r,s,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new zm(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new ywe(e,this)}createMaterialContext(){return new VG}createDrawContext(){return new x9(this._bufferManager)}_preparePipelineContext(e,t,i,r,s,a,o,c){const l=e,h=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(de.Log(["defines",c]),de.Log(t),de.Log(i),de.Log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:a},r?l.stages=this._compileRawPipelineStageDescriptor(t,i,h):l.stages=this._compilePipelineStageDescriptor(t,i,c,h)}getAttributes(e,t){const i=new Array(t.length),r=e;for(let s=0;s0,a._cachedWrapU=0,a._cachedWrapV=0,a._useSRGBBuffer=s.useSRGBBuffer,a.label=s.label,this._internalTexturesCache.push(a),i||this._textureHelper.createGPUTextureForInternalTexture(a,o,c,l||1,s.creationFlags),a}createTexture(e,t,i,r,s=3,a=null,o=null,c=null,l=null,h=null,u=null,d,f,p,_){return this._createTextureBase(e,t,i,r,s,a,o,(m,g,v,x,y,C,b,T)=>{var N;const S=x;if(m.baseWidth=S.width,m.baseHeight=S.height,m.width=S.width,m.height=S.height,m.format=m.format!==-1?m.format:h??5,m.type=m.type!==-1?m.type:0,m._creationFlags=p??0,T(m.width,m.height,S,g,m,()=>{}),(N=m._hardwareTexture)!=null&&N.underlyingResource)!C&&!b&&this._generateMipmaps(m,this._uploadEncoder);else{const D=this._textureHelper.createGPUTextureForInternalTexture(m,S.width,S.height,void 0,p);Ur.IsImageBitmap(S)&&(this._textureHelper.updateTexture(S,m,S.width,S.height,m.depth,D.format,0,0,y,!1,0,0),!C&&!b&&this._generateMipmaps(m,this._uploadEncoder))}v&&v.removePendingData(m),m.isReady=!0,m.onLoadedObservable.notifyObservers(m),m.onLoadedObservable.clear()},()=>!1,c,l,h,u,d,f,_)}wrapWebGPUTexture(e){const t=new jV(e),i=new Ar(this,mi.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;e.generateMipMaps&&((t=e._hardwareTexture)!=null&&t.underlyingResource||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e))}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,r=null){t!==null&&(e._cachedWrapU=t),i!==null&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&r!==null&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===r)return;const s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,s)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const s=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){const a=i+_n.AutoSamplerSuffix;this._currentMaterialContext.setSampler(a,t)}}}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let s=0;s0;for(const s in e){const a=e[s],o=i[s],c=o.group,l=o.binding,h=a.type,u=a.object;let d=a.indexInGroupEntries,f=this._bindGroupEntries[c];switch(f||(f=this._bindGroupEntries[c]=[]),h){case xs.Sampler:{const p=u;d!==void 0&&r?f[d].resource=this._cacheSampler.getSampler(p):(a.indexInGroupEntries=f.length,f.push({binding:l,resource:this._cacheSampler.getSampler(p)}));break}case xs.Texture:case xs.TextureWithoutSampler:{const p=u,_=p._texture._hardwareTexture;d!==void 0&&r?(h===xs.Texture&&(f[d++].resource=this._cacheSampler.getSampler(p._texture)),f[d].resource=_.view):(a.indexInGroupEntries=f.length,h===xs.Texture&&f.push({binding:l-1,resource:this._cacheSampler.getSampler(p._texture)}),f.push({binding:l,resource:_.view}));break}case xs.StorageTexture:{const p=u,_=p._texture._hardwareTexture;_.textureAdditionalUsages&rn.StorageBinding||de.Error(`computeDispatch: The texture (name=${p.name}, uniqueId=${p.uniqueId}) is not a storage texture!`,50),d!==void 0&&r?f[d].resource=_.viewForWriting:(a.indexInGroupEntries=f.length,f.push({binding:l,resource:_.viewForWriting}));break}case xs.ExternalTexture:{const _=u.underlyingResource;d!==void 0&&r?f[d].resource=this._device.importExternalTexture({source:_}):(a.indexInGroupEntries=f.length,f.push({binding:l,resource:this._device.importExternalTexture({source:_})}));break}case xs.UniformBuffer:case xs.StorageBuffer:case xs.DataBuffer:{const p=h===xs.DataBuffer?u:(h===xs.UniformBuffer,u.getBuffer()),_=p.underlyingResource;d!==void 0&&r?(f[d].resource.buffer=_,f[d].resource.size=p.capacity):(a.indexInGroupEntries=f.length,f.push({binding:l,resource:{buffer:_,offset:0,size:p.capacity}}));break}}}for(let s=0;s0&&h.dispatchWorkgroups(i,r,s),h.end(),o&&(this._timestampQuery.endPass(this._timestampIndex,o),this._timestampIndex+=2)};gi.prototype.releaseComputeEffects=function(){for(const n in this._compiledComputeEffects){const e=this._compiledComputeEffects[n].getPipelineContext();this._deleteComputePipelineContext(e)}this._compiledComputeEffects={}};gi.prototype._prepareComputePipelineContext=function(n,e,t,i,r){const s=n;this.dbgShowShaderCode&&(de.Log(i),de.Log(e)),s.sources={compute:e,rawCompute:t},s.stage=this._createComputePipelineStageDescriptor(e,i,r)};gi.prototype._releaseComputeEffect=function(n){this._compiledComputeEffects[n._key]&&(delete this._compiledComputeEffects[n._key],this._deleteComputePipelineContext(n.getPipelineContext()))};gi.prototype._rebuildComputeEffects=function(){for(const n in this._compiledComputeEffects){const e=this._compiledComputeEffects[n];e._pipelineContext=null,e._wasPreviouslyReady=!1,e._prepareEffect()}};gi.prototype._deleteComputePipelineContext=function(n){n&&n.dispose()};gi.prototype._createComputePipelineStageDescriptor=function(n,e,t){return e?e="//"+e.split(` `).join(` //`)+` `:e="",{module:this._device.createShaderModule({code:e+n}),entryPoint:t}};gi.prototype._createDepthStencilCubeTexture=function(n,e){const t=new Ar(this,e.generateStencil?mi.DepthStencil:mi.Depth);t.isCube=!0,t.label=e.label;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:e.generateStencil?13:14,...e};t.format=i.depthTextureFormat,this._setupDepthStencilTexture(t,n,i.generateStencil,i.bilinearFiltering,i.comparisonFunction,i.samples),this._textureHelper.createGPUTextureForInternalTexture(t);const r=t._hardwareTexture;return t.type=Ur.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(t),t};gi.prototype.createCubeTexture=function(n,e,t,i,r=null,s=null,a,o=null,c=!1,l=0,h=0,u=null,d=!1){return this.createCubeTextureBase(n,e,t,!!i,r,s,a,o,c,l,h,u,null,(f,p)=>{const _=p,m=_[0].width,g=m;this._setCubeMapTextureParams(f,!i),f.format=a??-1;const v=this._textureHelper.createGPUTextureForInternalTexture(f,m,g);this._textureHelper.updateCubeTextures(_,v.underlyingResource,m,g,v.format,!1,!1,0,0),i||this._generateMipmaps(f,this._uploadEncoder),f.isReady=!0,f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),r&&r()},!!d)};gi.prototype._setCubeMapTextureParams=function(n,e,t){n.samplingMode=e?3:2,n._cachedWrapU=0,n._cachedWrapV=0,t&&(n._maxLodLevel=t)};gi.prototype._debugPushGroup=function(n,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.pushDebugGroup(n):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(n):this._pendingDebugCommands.push(["push",n]))};gi.prototype._debugPopGroup=function(n){this._options.enableGPUDebugMarkers&&(n===0||n===1?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))};gi.prototype._debugInsertMarker=function(n,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.insertDebugMarker(n):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(n):this._pendingDebugCommands.push(["insert",n]))};gi.prototype._debugFlushPendingCommands=function(){for(let n=0;n{e==null||e.removePendingData(d),l&&_&&l(_.status+" "+_.statusText,m)},p=_=>{const m=d.width,g=a(_);if(!g)return;const v=[0,2,4,1,3,5];if(o){const x=i===4,y=o(g),C=d._hardwareTexture,b=[0,1,2,3,4,5];for(let T=0;T>T,N=[];for(let D=0;D<6;D++){let M=y[T][b[D]];x&&(M=y9(M,S,S,r)),N.push(new Uint8Array(M.buffer,M.byteOffset,M.byteLength))}this._textureHelper.updateCubeTextures(N,C.underlyingResource,S,S,C.format,u,!1,0,0)}}else{const x=[];for(let y=0;y<6;y++)x.push(g[v[y]]);this.updateRawCubeTexture(d,x,i,r,u)}d.isReady=!0,e==null||e.removePendingData(d),c&&c()};return this._loadFile(n,_=>{p(_)},void 0,e==null?void 0:e.offlineProvider,!0,f),d};gi.prototype.createRawTexture3D=function(n,e,t,i,r,s,a,o,c=null,l=0,h=0){const u=mi.Raw3D,d=new Ar(this,u);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=r,d.type=l,d.generateMipMaps=s,d.samplingMode=o,d.is3D=!0,d._creationFlags=h,this._doNotHandleContextLost||(d._bufferView=n),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,void 0,h),this.updateRawTexture3D(d,n,r,a,c,l),this._internalTexturesCache.push(d),d};gi.prototype.updateRawTexture3D=function(n,e,t,i,r=null,s=0){if(this._doNotHandleContextLost||(n._bufferView=e,n.format=t,n.invertY=i,n._compression=r),e){const a=n._hardwareTexture;t===4&&(e=y9(e,n.width,n.height,s));const c=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(c,n,n.width,n.height,n.depth,a.format,0,0,i,!1,0,0),n.generateMipMaps&&this._generateMipmaps(n,this._uploadEncoder)}n.isReady=!0};gi.prototype.createRawTexture2DArray=function(n,e,t,i,r,s,a,o,c=null,l=0,h=0){const u=mi.Raw2DArray,d=new Ar(this,u);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=r,d.type=l,d.generateMipMaps=s,d.samplingMode=o,d.is2DArray=!0,d._creationFlags=h,this._doNotHandleContextLost||(d._bufferView=n),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,i,h),this.updateRawTexture2DArray(d,n,r,a,c,l),this._internalTexturesCache.push(d),d};gi.prototype.updateRawTexture2DArray=function(n,e,t,i,r=null,s=0){if(this._doNotHandleContextLost||(n._bufferView=e,n.format=t,n.invertY=i,n._compression=r),e){const a=n._hardwareTexture;t===4&&(e=y9(e,n.width,n.height,s));const c=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(c,n,n.width,n.height,n.depth,a.format,0,0,i,!1,0,0),n.generateMipMaps&&this._generateMipmaps(n,this._uploadEncoder)}n.isReady=!0};function y9(n,e,t,i){let r,s=1;i===1?r=new Float32Array(e*t*4):i===2?(r=new Uint16Array(e*t*4),s=15360):i===7?r=new Uint32Array(e*t*4):r=new Uint8Array(e*t*4);for(let a=0;a0,n.depth=c,n.isReady=!0,n.samples=s,n.generateMipMaps=!1,n.samplingMode=i?2:1,n.type=1,n._comparisonFunction=r,n._cachedWrapU=0,n._cachedWrapV=0};gi.prototype.updateRenderTargetTextureSampleCount=function(n,e){return!n||!n.texture||n.samples===e||(e=Math.min(e,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(n.texture,e),n._depthStencilTexture&&(this._textureHelper.createMSAATexture(n._depthStencilTexture,e),n._depthStencilTexture.samples=e),n._samples=e,n.texture.samples=e),e};gi.prototype.createRenderTargetCubeTexture=function(n,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,n),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,t.label=i.label??"RenderTargetWrapper",t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer;const r=new Ar(this,mi.RenderTarget);return r.width=n,r.height=n,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=i.samples,r.generateMipMaps=i.generateMipMaps,r.samplingMode=i.samplingMode,r.type=i.type,r.format=i.format,this._internalTexturesCache.push(r),t.setTextures(r),(t._generateDepthBuffer||t._generateStencilBuffer)&&t.createDepthStencilTexture(0,i.samplingMode===void 0||i.samplingMode===2||i.samplingMode===2||i.samplingMode===3||i.samplingMode===3||i.samplingMode===5||i.samplingMode===6||i.samplingMode===7||i.samplingMode===11,t._generateStencilBuffer,t.samples),e&&e.createMipMaps&&!i.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),e&&e.createMipMaps&&!i.generateMipMaps&&(r.generateMipMaps=!1),t};bi.prototype.setTextureSampler=function(n,e){this._engine.setTextureSampler(n,e)};gi.prototype.setTextureSampler=function(n,e){var t;(t=this._currentMaterialContext)==null||t.setSampler(n,e)};bi.prototype.setStorageBuffer=function(n,e){this._engine.setStorageBuffer(n,e)};gi.prototype.createStorageBuffer=function(n,e,t){return this._createBuffer(n,e|32,t)};gi.prototype.updateStorageBuffer=function(n,e,t,i){const r=n;t===void 0&&(t=0);let s;i===void 0?(e instanceof Array?s=new Float32Array(e):e instanceof ArrayBuffer?s=new Uint8Array(e):s=e,i=s.byteLength):e instanceof Array?s=new Float32Array(e):e instanceof ArrayBuffer?s=new Uint8Array(e):s=e,this._bufferManager.setSubData(r,t,s,0,i)};gi.prototype.readFromStorageBuffer=function(n,e,t,i,r){t=t||n.capacity;const s=this._bufferManager.createRawBuffer(t,ys.MapRead|ys.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(n.underlyingResource,e??0,s,0,t),new Promise((a,o)=>{const c=()=>{s.mapAsync(z3.Read,0,t).then(()=>{const l=s.getMappedRange(0,t);let h=i;if(h===void 0)h=new Uint8Array(t),h.set(new Uint8Array(l));else{const u=h.constructor;h=new u(h.buffer),h.set(new u(l))}s.unmap(),this._bufferManager.releaseBuffer(s),a(h)},l=>{this.isDisposed?a(new Uint8Array):o(l)})};r?(this.flushFramebuffer(),c()):this.onEndFrameObservable.addOnce(()=>{c()})})};gi.prototype.setStorageBuffer=function(n,e){var t;(t=this._currentDrawContext)==null||t.setBuffer(n,(e==null?void 0:e.getBuffer())??null)};function FDe(n){return!!(n&&n.underlyingResource!==void 0)}gi.prototype.updateVideoTexture=function(n,e,t){var r;if(!n||n._isDisabled)return;this._videoTextureSupported===void 0&&(this._videoTextureSupported=!0);let i=n._hardwareTexture;(r=n._hardwareTexture)!=null&&r.underlyingResource||(i=this._textureHelper.createGPUTextureForInternalTexture(n)),FDe(e)?(this._textureHelper.copyVideoToTexture(e,n,i.format,!t),n.generateMipMaps&&this._generateMipmaps(n),n.isReady=!0):e&&this.createImageBitmap(e).then(s=>{this._textureHelper.updateTexture(s,n,n.width,n.height,n.depth,i.format,0,0,!t,!1,0,0),n.generateMipMaps&&this._generateMipmaps(n),n.isReady=!0}).catch(()=>{n.isReady=!0})};class UDe{static async CreateAsync(e,t){return await gi.IsSupportedAsync?gi.CreateAsync(e,t):De.IsSupported?new De(e,void 0,t):new E2e(t)}}class Pd{}Pd.COPY=1;Pd.CUT=2;Pd.PASTE=3;class XV{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return Pd.COPY;case 86:return Pd.PASTE;case 88:return Pd.CUT;default:return-1}}}class vd extends mn{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Me.Gray(),i=Or.DefaultUtilityLayer,r=null,s=1,a=Me.Yellow(),o=Me.Gray()){var C,b,T,S,N,D,M;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ae,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new P(0,0,0),this._incrementalStartupValue=P.Zero(),this._parent=r,this._coloredMaterial=new tt("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Me(.1,.1,.1)),this._hoverMaterial=new tt("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._disableMaterial=new tt("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new Se("axis",i.utilityLayerScene);const{arrowMesh:c,arrowTail:l}=this._createGizmoMesh(this._gizmoMesh,s),h=this._createGizmoMesh(this._gizmoMesh,s+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,mn.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const u=c.position.clone(),d=l.position.clone(),f=l.scaling.clone(),p=I=>{const R=I*(3/this._rootMesh.scaling.length())*6;c.position.z+=R/3.5,l.scaling.y+=R,this.dragScale=l.scaling.y,l.position.z=c.position.z/2},_=()=>{c.position.set(u.x,u.y,u.z),l.position.set(d.x,d.y,d.z),l.scaling.set(f.x,f.y,f.z),this.dragScale=l.scaling.y,this._dragging=!1};this.dragBehavior=new Ao({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let m=0,g=0;const v={snapDistance:0};this.dragBehavior.onDragObservable.add(I=>{if(this.attachedNode){const R=this.sensitivity*I.dragDistance*(this.scaleRatio*3/this._rootMesh.scaling.length()),O=this._tmpVector;let H=!1,G=0;if(this.uniformScaling?O.setAll(.57735):O.copyFrom(e),this.snapDistance==0)O.scaleToRef(R,O);else{m+=R,g+=R;const V=this.incrementalSnap?g:m;Math.abs(V)>this.snapDistance?(G=Math.floor(Math.abs(V)/this.snapDistance),V<0&&(G*=-1),m=m%this.snapDistance,O.scaleToRef(this.snapDistance*G,O),H=!0):O.scaleInPlace(0)}O.addInPlaceFromFloats(1,1,1),O.x=Math.abs(O.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,ie.Quaternion[0],ie.Vector3[2],mn.PreserveScaling?Q:void 0),O.addInPlace(this._incrementalStartupValue),O.addInPlaceFromFloats(-1,-1,-1),O.x=Math.abs(O.x)*(this._incrementalStartupValue.x>0?1:-1),O.y=Math.abs(O.y)*(this._incrementalStartupValue.y>0?1:-1),O.z=Math.abs(O.z)*(this._incrementalStartupValue.z>0?1:-1),ce.ComposeToRef(O,ie.Quaternion[0],ie.Vector3[2],ie.Matrix[1])):(ce.ScalingToRef(O.x,O.y,O.z,ie.Matrix[2]),ie.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),ie.Matrix[1])),ie.Matrix[1].decompose(ie.Vector3[1],void 0,void 0,mn.PreserveScaling?Q:void 0);const $=1e5;Math.abs(ie.Vector3[1].x)<$&&Math.abs(ie.Vector3[1].y)<$&&Math.abs(ie.Vector3[1].z)<$&&this.attachedNode.getWorldMatrix().copyFrom(ie.Matrix[1]),H&&(v.snapDistance=this.snapDistance*G,this.onSnapObservable.notifyObservers(v)),this._matrixChanged()}}),this.dragBehavior.onDragStartObservable.add(()=>{var R;this._dragging=!0;const I=this.attachedNode._isMesh?this.attachedNode:void 0;(R=this.attachedNode)==null||R.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,mn.PreserveScaling?I:void 0),m=0,g=0}),this.dragBehavior.onDragObservable.add(I=>p(I.dragDistance)),this.dragBehavior.onDragEndObservable.add(_),(T=(b=(C=r==null?void 0:r.uniformScaleGizmo)==null?void 0:C.dragBehavior)==null?void 0:b.onDragObservable)==null||T.add(I=>p(I.delta.y)),(D=(N=(S=r==null?void 0:r.uniformScaleGizmo)==null?void 0:S.dragBehavior)==null?void 0:N.onDragEndObservable)==null||D.add(_);const x={gizmoMeshes:[c,l],colliderMeshes:[h.arrowMesh,h.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(M=this._parent)==null||M.addToAxisCache(this._gizmoMesh,x),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(I=>{var R;if(!this._customMeshSet&&(this._isHovered=x.colliderMeshes.indexOf((R=I==null?void 0:I.pickInfo)==null?void 0:R.pickedMesh)!=-1,!this._parent)){const O=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(x.gizmoMeshes,O)}}),this.dragBehavior.onEnabledObservable.add(I=>{this._setGizmoMeshMaterial(x.gizmoMeshes,I?this._coloredMaterial:this._disableMaterial)});const y=i._getSharedGizmoLight();y.includedOnlyMeshes=y.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const r=zf("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),s=dc("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return r.scaling.scaleInPlace(.1),r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,r.position.z+=.3,s.material=this._coloredMaterial,s.position.z+=.275/2,s.rotation.x=Math.PI/2,i&&(r.visibility=0,s.visibility=0),e.addChild(r),e.addChild(s),{arrowMesh:r,arrowTail:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach(i=>{i.material=this._coloredMaterial,i.color&&(i.color=this._coloredMaterial.diffuseColor)}),this._customMeshSet=!1)}}vd.MinimumAbsoluteScale=ni;class Oee extends mn{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let r=0;r<3;r++)for(let s=0;s<3;s++)for(let a=0;a<3;a++){const o=(r===1?1:0)+(s===1?1:0)+(a===1?1:0);if(!(o===1||o===3)){if(t[i]){const c=new P(r-1,s-1,a-1);c.multiplyInPlace(this._axisFactor),t[i].setEnabled(c.lengthSquared()>ni)}i++}}}get axisFactor(){return this._axisFactor}set scaleDragSpeed(e){this._scaleDragSpeed=e}get scaleDragSpeed(){return this._scaleDragSpeed}get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverColoredMaterial}get pointerDragBehavior(){return this._pointerDragBehavior}get isDragging(){return this._dragging||this._pointerDragBehavior.dragging}setColor(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new Me(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach(t=>{t.color&&(t.color=e)})}constructor(e=Me.Gray(),t=Or.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new P(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._dragging=!1,this._tmpQuaternion=new we,this._tmpVector=new P(0,0,0),this._tmpRotationMatrix=new ce,this._incrementalStartupValue=P.Zero(),this._incrementalAnchorStartupValue=P.Zero(),this.ignoreChildren=!1,this.includeChildPredicate=null,this.rotationSphereSize=.1,this.scaleBoxSize=.1,this.fixedDragMeshScreenSize=!1,this.fixedDragMeshBoundsSize=!1,this.fixedDragMeshScreenSizeDistanceFactor=10,this.scalingSnapDistance=0,this.rotationSnapDistance=0,this.onDragStartObservable=new Ae,this.onScaleBoxDragObservable=new Ae,this.onScaleBoxDragEndObservable=new Ae,this.onRotationSphereDragObservable=new Ae,this.onRotationSphereDragEndObservable=new Ae,this.scalePivot=null,this._axisFactor=new P(1,1,1),this.incrementalSnap=!1,this._existingMeshScale=new P,this._dragMesh=null,this._pointerDragBehavior=new Ao,this.updateScale=!1,this._anchorMesh=new di("anchor",t.utilityLayerScene),this._coloredMaterial=new tt("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new tt("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new di("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new we;const i=[];i.push(Us("lines",{points:[new P(0,0,0),new P(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(0,0,0),new P(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(0,0,0),new P(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(this._boundingDimensions.x,0,0),new P(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(this._boundingDimensions.x,0,0),new P(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(0,this._boundingDimensions.y,0),new P(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(0,this._boundingDimensions.y,0),new P(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(0,0,this._boundingDimensions.z),new P(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(0,0,this._boundingDimensions.z),new P(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new P(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new P(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Us("lines",{points:[new P(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new P(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach(s=>{s.color=e,s.position.addInPlace(new P(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),s.isPickable=!1,this._lineBoundingBox.addChild(s)}),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateSpheresParent=new di("",t.utilityLayerScene),this._rotateSpheresParent.rotationQuaternion=new we;for(let s=0;s<12;s++){const a=Tl("",{diameter:1},t.utilityLayerScene);a.rotationQuaternion=new we,a.material=this._coloredMaterial,a.isNearGrabbable=!0,this._rotateSpheresDragBehavior=new Ao({}),this._rotateSpheresDragBehavior.moveAttached=!1,this._rotateSpheresDragBehavior.updateDragPlane=!1,a.addBehavior(this._rotateSpheresDragBehavior);const o=new P(1,0,0);let c=0,l=0;this._rotateSpheresDragBehavior.onDragStartObservable.add(()=>{o.copyFrom(a.forward),c=0,l=0}),this._rotateSpheresDragBehavior.onDragObservable.add(h=>{if(this.onRotationSphereDragObservable.notifyObservers({}),this.attachedMesh){const u=this.attachedMesh.parent;if(u&&u.scaling&&u.scaling.isNonUniformWithinEpsilon(.001)){de.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");return}Vr._RemoveAndStorePivotPoint(this.attachedMesh);const d=o,f=h.dragPlaneNormal.scale(P.Dot(h.dragPlaneNormal,d)),p=d.subtract(f).normalizeToNew();let _=P.Dot(p,h.delta)<0?Math.abs(h.delta.length()):-Math.abs(h.delta.length());if(_=_/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=we.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=we.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),c+=_,Math.abs(c)<=2*Math.PI){if(this.rotationSnapDistance>0){const m=Math.floor(Math.abs(c)/this.rotationSnapDistance)*(c<0?-1:1),g=this.rotationSnapDistance*m;_=g-l,l=g}s>=8?we.RotationYawPitchRollToRef(0,0,_,this._tmpQuaternion):s>=4?we.RotationYawPitchRollToRef(_,0,0,this._tmpQuaternion):we.RotationYawPitchRollToRef(0,_,0,this._tmpQuaternion),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.copyFrom(this.attachedMesh.position),this._anchorMesh.addChild(this.attachedMesh),this._anchorMesh.getScene().useRightHandedSystem&&this._tmpQuaternion.conjugateInPlace(),this._tmpQuaternion.normalize(),this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion,this._anchorMesh.rotationQuaternion),this._anchorMesh.rotationQuaternion.normalize(),this._anchorMesh.removeChild(this.attachedMesh),this.attachedMesh.setParent(u)}this.updateBoundingBox(),Vr._RestorePivotPoint(this.attachedMesh)}this._updateDummy()}),this._rotateSpheresDragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(a)}),this._rotateSpheresDragBehavior.onDragEndObservable.add(h=>{this.onRotationSphereDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(h.pointerInfo,a)}),this._rotateSpheresParent.addChild(a)}this._rootMesh.addChild(this._rotateSpheresParent),this._scaleBoxesParent=new di("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new we;for(let s=0;s<3;s++)for(let a=0;a<3;a++)for(let o=0;o<3;o++){const c=(s===1?1:0)+(a===1?1:0)+(o===1?1:0);if(c===1||c===3)continue;const l=zf("",{size:1},t.utilityLayerScene);l.material=this._coloredMaterial,l._internalMetadata=c===2,l.isNearGrabbable=!0;const h=new P(s-1,a-1,o-1).normalize();this._scaleBoxesDragBehavior=new Ao({dragAxis:h}),this._scaleBoxesDragBehavior.updateDragPlane=!1,this._scaleBoxesDragBehavior.moveAttached=!1;let u=0,d=0;l.addBehavior(this._scaleBoxesDragBehavior),this._scaleBoxesDragBehavior.onDragObservable.add(f=>{if(this.onScaleBoxDragObservable.notifyObservers({}),this.attachedMesh){const p=this.attachedMesh.parent;if(p&&p.scaling&&p.scaling.isNonUniformWithinEpsilon(.001)){de.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");return}Vr._RemoveAndStorePivotPoint(this.attachedMesh);let _=f.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length();if(u+=_,this.scalingSnapDistance>0){const v=Math.floor(Math.abs(u)/this.scalingSnapDistance)*(u<0?-1:1),x=this.scalingSnapDistance*v;_=x-d,d=x}const m=new P(_,_,_),g=new P(d,d,d);c===2&&(m.x*=Math.abs(h.x),m.y*=Math.abs(h.y),m.z*=Math.abs(h.z)),m.scaleInPlace(this._scaleDragSpeed),m.multiplyInPlace(this._axisFactor),g.scaleInPlace(this._scaleDragSpeed),g.multiplyInPlace(this._axisFactor),g.addInPlace(this._incrementalStartupValue),this.updateBoundingBox(),this.scalePivot?(this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix),this._boundingDimensions.scaleToRef(.5,this._tmpVector),P.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),P.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.addInPlace(this._tmpVector)):(l.absolutePosition.subtractToRef(this._anchorMesh.position,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.subtractInPlace(this.attachedMesh.getPivotPoint())),this._anchorMesh.addChild(this.attachedMesh),this.incrementalSnap?(g.x/=Math.abs(this._incrementalStartupValue.x){this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(l),u=0,d=0,this._incrementalStartupValue.copyFrom(this.attachedMesh.scaling),this._incrementalAnchorStartupValue.copyFrom(this._anchorMesh.scaling)}),this._scaleBoxesDragBehavior.onDragEndObservable.add(f=>{this.onScaleBoxDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(f.pointerInfo,l)}),this._scaleBoxesParent.addChild(l)}this._rootMesh.addChild(this._scaleBoxesParent);const r=[];this._pointerObserver=t.utilityLayerScene.onPointerObservable.add(s=>{r[s.event.pointerId]?s.pickInfo&&s.pickInfo.pickedMesh!=r[s.event.pointerId]&&(r[s.event.pointerId].material=this._coloredMaterial,delete r[s.event.pointerId],this._isHovered=!1):this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(a=>{s.pickInfo&&s.pickInfo.pickedMesh==a&&(r[s.event.pointerId]=a,a.material=this._hoverColoredMaterial,this._isHovered=!0)})}),this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add(()=>{this.attachedMesh&&!this._existingMeshScale.equals(this.attachedMesh.scaling)?this.updateBoundingBox():(this.fixedDragMeshScreenSize||this.fixedDragMeshBoundsSize)&&(this._updateRotationSpheres(),this._updateScaleBoxes()),this._dragMesh&&this.attachedMesh&&this._pointerDragBehavior.dragging&&(this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion,this._tmpVector),this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1))))}),this.updateBoundingBox()}_attachedNodeChanged(e){if(e){this._anchorMesh.scaling.setAll(1),Vr._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(t),Vr._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach(i=>{i.markAsDirty("scaling")}),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(()=>{this._updateDummy()})}}_selectNode(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(t=>{t.isVisible=!e||t==e})}_unhoverMeshOnTouchUp(e,t){(e==null?void 0:e.event)instanceof PointerEvent&&(e==null?void 0:e.event.pointerType)==="touch"&&(t.material=this._coloredMaterial)}getScaleBoxes(){return this._scaleBoxesParent.getChildMeshes()}updateBoundingBox(){if(this.attachedMesh){Vr._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=we.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=we.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),Vr._RestorePivotPoint(this.attachedMesh))}_updateRotationSpheres(){const e=this._rotateSpheresParent.getChildMeshes();for(let t=0;t<3;t++)for(let i=0;i<2;i++)for(let r=0;r<2;r++){const s=t*4+i*2+r;if(t==0&&(e[s].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*r),e[s].position.addInPlace(new P(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[s].lookAt(P.Cross(e[s].position.normalizeToNew(),P.Right()).normalizeToNew().add(e[s].position))),t==1&&(e[s].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*r),e[s].position.addInPlace(new P(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[s].lookAt(P.Cross(e[s].position.normalizeToNew(),P.Up()).normalizeToNew().add(e[s].position))),t==2&&(e[s].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*r,this._boundingDimensions.z/2),e[s].position.addInPlace(new P(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[s].lookAt(P.Cross(e[s].position.normalizeToNew(),P.Forward()).normalizeToNew().add(e[s].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const a=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[s].scaling.set(a,a,a)}else this.fixedDragMeshBoundsSize?e[s].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[s].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}}_updateScaleBoxes(){const e=this._scaleBoxesParent.getChildMeshes();let t=0;for(let i=0;i<3;i++)for(let r=0;r<3;r++)for(let s=0;s<3;s++){const a=(i===1?1:0)+(r===1?1:0)+(s===1?1:0);if(!(a===1||a===3)){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(r/2),this._boundingDimensions.z*(s/2)),e[t].position.addInPlace(new P(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[t].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition,this._tmpVector);const o=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[t].scaling.set(o,o,o)}else this.fixedDragMeshBoundsSize?e[t].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[t].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);t++}}}setEnabledRotationAxis(e){this._rotateSpheresParent.getChildMeshes().forEach((t,i)=>{i<4?t.setEnabled(e.indexOf("x")!=-1):i<8?t.setEnabled(e.indexOf("y")!=-1):t.setEnabled(e.indexOf("z")!=-1)})}setEnabledScaling(e,t=!1){this._scaleBoxesParent.getChildMeshes().forEach(i=>{let r=e;t&&i._internalMetadata===!0&&(r=!1),i.setEnabled(r)})}_updateDummy(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))}enableDragBehavior(){this._dragMesh=zf("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new we,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)}releaseDrag(){this._scaleBoxesDragBehavior.releaseDrag(),this._rotateSpheresDragBehavior.releaseDrag(),this._pointerDragBehavior.releaseDrag()}dispose(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),super.dispose()}static MakeNotPickableAndWrapInBoundingBox(e){const t=o=>{o.isPickable=!1,o.getChildMeshes().forEach(c=>{t(c)})};t(e),e.rotationQuaternion||(e.rotationQuaternion=we.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),r=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const s=zf("box",{size:1},e.getScene()),a=e.getHierarchyBoundingVectors();return a.max.subtractToRef(a.min,s.scaling),s.scaling.y===0&&(s.scaling.y=ni),s.scaling.x===0&&(s.scaling.x=ni),s.scaling.z===0&&(s.scaling.z=ni),s.position.set((a.max.x+a.min.x)/2,(a.max.y+a.min.y)/2,(a.max.z+a.min.z)/2),e.addChild(s),e.rotationQuaternion.copyFrom(r),e.position.copyFrom(i),e.removeChild(s),s.addChild(e),s.visibility=0,s}setCustomMesh(){de.Error("Custom meshes are not supported on this gizmo")}}class Df extends mn{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=Me.Gray(),i=Or.DefaultUtilityLayer,r=32,s=null,a=!1,o=1,c=Me.Yellow(),l=Me.Gray()){var b;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ae,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new P,this._parent=s,this._coloredMaterial=new tt("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Me(.1,.1,.1)),this._hoverMaterial=new tt("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=c,this._hoverMaterial.specularColor=c,this._disableMaterial=new tt("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new Se("",i.utilityLayerScene);const{rotationMesh:h,collider:u}=this._createGizmoMesh(this._gizmoMesh,o,r);this._rotationDisplayPlane=n_("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=Math.PI*.5,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),bi.ShadersStore.rotationGizmoVertexShader=Df._RotationGizmoVertexShader,bi.ShadersStore.rotationGizmoFragmentShader=Df._RotationGizmoFragmentShader,this._rotationShaderMaterial=new kn("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=c,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,mn.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new Ao({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=Df.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const d=new P,f=new ce,p=new P;let _=new P;this.dragBehavior.onDragStartObservable.add(T=>{this.attachedNode&&(d.copyFrom(T.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(f),P.TransformCoordinatesToRef(T.dragPlanePoint,f,d),this._angles.x=Math.atan2(d.y,d.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,d.copyFrom(T.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});const m={snapDistance:0};let g=0;const v=new ce,x=new we;this.dragBehavior.onDragObservable.add(T=>{if(this.attachedNode){const S=new P(1,1,1),N=new we(0,0,0,1),D=new P(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(S,N,D),!(Math.abs(Math.abs(S.x)-Math.abs(S.y))<=ni&&Math.abs(Math.abs(S.x)-Math.abs(S.z))<=ni)&&this.updateGizmoRotationToMatchAttachedMesh){de.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}N.normalize();const I=this.updateGizmoPositionToMatchAttachedMesh?D:this._rootMesh.absolutePosition,R=T.dragPlanePoint.subtract(I).normalize(),O=d.subtract(I).normalize(),H=P.Cross(R,O),G=P.Dot(R,O);let Q=Math.atan2(H.length(),G)*this.sensitivity;p.copyFrom(e),_.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(N.toRotationMatrix(f),_=P.TransformCoordinates(p,f));let $=!1;if(i.utilityLayerScene.activeCamera){const z=i.utilityLayerScene.activeCamera.position.subtract(I).normalize();P.Dot(z,_)>0&&(p.scaleInPlace(-1),_.scaleInPlace(-1),$=!0)}P.Dot(_,H)>0&&(Q=-Q),ie.Vector3[0].set(Q,0,0),this.dragBehavior.validateDrag(ie.Vector3[0])||(Q=0);let j=!1;if(this.snapDistance!=0)if(g+=Q,Math.abs(g)>this.snapDistance){let z=Math.floor(Math.abs(g)/this.snapDistance);g<0&&(z*=-1),g=g%this.snapDistance,Q=this.snapDistance*z,j=!0}else Q=0;const k=Math.sin(Q/2);if(x.set(p.x*k,p.y*k,p.z*k,Math.cos(Q/2)),v.determinant()>0){const z=new P;x.toEulerAnglesToRef(z),we.RotationYawPitchRollToRef(z.y,-z.x,-z.z,x)}if(this.updateGizmoRotationToMatchAttachedMesh)N.multiplyToRef(x,N),N.normalize(),ce.ComposeToRef(S,N,D,this.attachedNode.getWorldMatrix());else{x.toRotationMatrix(ie.Matrix[0]);const z=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(ie.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(z)}d.copyFrom(T.dragPlanePoint),j&&(m.snapDistance=Q,this.onSnapObservable.notifyObservers(m)),this._angles.y+=Q,this.angle+=$?-Q:Q,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});const y=i._getSharedGizmoLight();y.includedOnlyMeshes=y.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const C={colliderMeshes:[u],gizmoMeshes:[h],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(b=this._parent)==null||b.addToAxisCache(this._gizmoMesh,C),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(T=>{var S;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=Df.MaxDragAngle,this._isHovered=C.colliderMeshes.indexOf((S=T==null?void 0:T.pickInfo)==null?void 0:S.pickedMesh)!=-1,!this._parent)){const N=C.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(C.gizmoMeshes,N)}}),this.dragBehavior.onEnabledObservable.add(T=>{this._setGizmoMeshMaterial(C.gizmoMeshes,T?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){const r=o1("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;const s=o1("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(s,mn.PreserveScaling),e.addChild(r,mn.PreserveScaling),{rotationMesh:s,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}}Df.MaxDragAngle=Math.PI*9/20;Df._RotationGizmoVertexShader=` precision highp float; attribute vec3 position; attribute vec2 uv; uniform mat4 worldViewProjection; varying vec3 vPosition; varying vec2 vUV; void main(void) { gl_Position = worldViewProjection * vec4(position, 1.0); vUV = uv; }`;Df._RotationGizmoFragmentShader=` precision highp float; varying vec2 vUV; varying vec3 vPosition; uniform vec3 angles; uniform vec3 rotationColor; #define twopi 6.283185307 void main(void) { vec2 uv = vUV - vec2(0.5); float angle = atan(uv.y, uv.x) + 3.141592; float delta = gl_FrontFacing ? angles.y : -angles.y; float begin = angles.x - delta * angles.z; float start = (begin < (begin + delta)) ? begin : (begin + delta); float end = (begin > (begin + delta)) ? begin : (begin + delta); float len = sqrt(dot(uv,uv)); float opacity = 1. - step(0.5, len); float base = abs(floor(start / twopi)) * twopi; start += base; end += base; float intensity = 0.; for (int i = 0; i < 5; i++) { intensity += max(step(start, angle) - step(end, angle), 0.); angle += twopi; } gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity; } `;class Lee extends mn{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null})}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null})}_checkBillboardTransform(){this._nodeAttached&&this._nodeAttached.billboardMode&&de.Log("Rotation Gizmo will not work with transforms in billboard mode.")}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t&&(t.sensitivity=e)})}get sensitivity(){return this._sensitivity}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t.additionalTransformNode=e})}constructor(e=Or.DefaultUtilityLayer,t=32,i=!1,r=1,s,a){super(e),this.onDragStartObservable=new Ae,this.onDragObservable=new Ae,this.onDragEndObservable=new Ae,this._observables=[],this._sensitivity=1,this._gizmoAxisCache=new Map;const o=a&&a.xOptions&&a.xOptions.color?a.xOptions.color:Me.Red().scale(.5),c=a&&a.yOptions&&a.yOptions.color?a.yOptions.color:Me.Green().scale(.5),l=a&&a.zOptions&&a.zOptions.color?a.zOptions.color:Me.Blue().scale(.5);this.xGizmo=new Df(new P(1,0,0),o,e,t,this,i,r),this.yGizmo=new Df(new P(0,1,0),c,e,t,this,i,r),this.zGizmo=new Df(new P(0,0,1),l,e,t,this,i,r),this.additionalTransformNode=a==null?void 0:a.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo].forEach(h=>{a&&a.updateScale!=null&&(h.updateScale=a.updateScale),h.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),h.dragBehavior.onDragObservable.add(()=>{this.onDragObservable.notifyObservers({})}),h.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,this.attachedNode=null,s?s.addToAxisCache(this._gizmoAxisCache):mn.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set updateGizmoRotationToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)}get updateGizmoRotationToMatchAttachedMesh(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.yGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.zGizmo.updateGizmoPositionToMatchAttachedMesh=e)}get updateGizmoPositionToMatchAttachedMesh(){return this.xGizmo.updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t.anchorPoint=e})}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t.coordinatesMode=e})}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)}get snapDistance(){return this.xGizmo.snapDistance}set scaleRatio(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)}get scaleRatio(){return this.xGizmo.scaleRatio}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t&&(t.customRotationQuaternion=e)})}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag()}dispose(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach(e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})}setCustomMesh(){de.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")}}class s8 extends mn{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new Et("plane",e),r=n_("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return r.material=t,r.parent=i,i}constructor(e,t=Me.Gray(),i=Or.DefaultUtilityLayer,r=null,s=Me.Yellow(),a=Me.Gray()){var d;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ae,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=r,this._coloredMaterial=new tt("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Me(.1,.1,.1)),this._hoverMaterial=new tt("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=s,this._disableMaterial=new tt("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a,this._disableMaterial.alpha=.4,this._gizmoMesh=s8._CreatePlane(i.utilityLayerScene,this._coloredMaterial),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let o=0;const c=new P,l={snapDistance:0};this.dragBehavior=new Ao({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add(f=>{if(this.attachedNode){if(this.snapDistance==0)this.attachedNode.getWorldMatrix().getTranslationToRef(ie.Vector3[0]),ie.Vector3[0].addToRef(f.delta,ie.Vector3[0]),this.dragBehavior.validateDrag(ie.Vector3[0])&&this.attachedNode.getWorldMatrix().addTranslationFromFloats(f.delta.x,f.delta.y,f.delta.z);else if(o+=f.dragDistance,Math.abs(o)>this.snapDistance){const p=Math.floor(Math.abs(o)/this.snapDistance);o=o%this.snapDistance,f.delta.normalizeToRef(c),c.scaleInPlace(this.snapDistance*p),this.attachedNode.getWorldMatrix().getTranslationToRef(ie.Vector3[0]),ie.Vector3[0].addToRef(c,ie.Vector3[0]),this.dragBehavior.validateDrag(ie.Vector3[0])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(c.x,c.y,c.z),l.snapDistance=this.snapDistance*p,this.onSnapObservable.notifyObservers(l))}this._matrixChanged()}}),this.dragBehavior.onDragStartObservable.add(()=>{this._dragging=!0}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1});const h=i._getSharedGizmoLight();h.includedOnlyMeshes=h.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const u={gizmoMeshes:this._gizmoMesh.getChildMeshes(),colliderMeshes:this._gizmoMesh.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(d=this._parent)==null||d.addToAxisCache(this._gizmoMesh,u),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(f=>{var p;if(!this._customMeshSet&&(this._isHovered=u.colliderMeshes.indexOf((p=f==null?void 0:f.pickInfo)==null?void 0:p.pickedMesh)!=-1,!this._parent)){const _=u.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(u.gizmoMeshes,_)}}),this.dragBehavior.onEnabledObservable.add(f=>{this._setGizmoMeshMaterial(u.gizmoMeshes,f?this._coloredMaterial:this._disableMaterial)})}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),super.dispose(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()})}}class HG extends mn{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null})}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null})}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.xPlaneGizmo.isHovered||this.yPlaneGizmo.isHovered||this.zPlaneGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.xPlaneGizmo.dragBehavior.dragging||this.yPlaneGizmo.dragBehavior.dragging||this.zPlaneGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t.additionalTransformNode=e})}constructor(e=Or.DefaultUtilityLayer,t=1,i,r){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new Ae,this.onDragObservable=new Ae,this.onDragEndObservable=new Ae,this._planarGizmoEnabled=!1,this.xGizmo=new gd(new P(1,0,0),Me.Red().scale(.5),e,this,t),this.yGizmo=new gd(new P(0,1,0),Me.Green().scale(.5),e,this,t),this.zGizmo=new gd(new P(0,0,1),Me.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new s8(new P(1,0,0),Me.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new s8(new P(0,1,0),Me.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new s8(new P(0,0,1),Me.Blue().scale(.5),this.gizmoLayer,this),this.additionalTransformNode=r==null?void 0:r.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(s=>{s.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),s.dragBehavior.onDragObservable.add(()=>{this.onDragObservable.notifyObservers({})}),s.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):mn.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set planarGizmoEnabled(e){this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.isEnabled=e,e&&(t.attachedMesh?t.attachedMesh=this.attachedMesh:t.attachedNode=this.attachedNode))},this)}get planarGizmoEnabled(){return this._planarGizmoEnabled}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.customRotationQuaternion=e)})}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)})}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.updateGizmoPositionToMatchAttachedMesh=e)})}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t.anchorPoint=e})}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t.coordinatesMode=e})}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.snapDistance=e)})}get snapDistance(){return this._snapDistance}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.scaleRatio=e)})}get scaleRatio(){return this._scaleRatio}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.xPlaneGizmo.dragBehavior.releaseDrag(),this.yPlaneGizmo.dragBehavior.releaseDrag(),this.zPlaneGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(e=>{e&&e.dispose()}),this._observables.forEach(e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)}),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear()}setCustomMesh(){de.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")}}class Nee extends mn{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null})}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null})}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.uniformScaleGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t.additionalTransformNode=e})}constructor(e=Or.DefaultUtilityLayer,t=1,i,r){super(e),this._meshAttached=null,this._nodeAttached=null,this._incrementalSnap=!1,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new Ae,this.onDragObservable=new Ae,this.onDragEndObservable=new Ae,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new vd(new P(1,0,0),Me.Red().scale(.5),e,this,t),this.yGizmo=new vd(new P(0,1,0),Me.Green().scale(.5),e,this,t),this.zGizmo=new vd(new P(0,0,1),Me.Blue().scale(.5),e,this,t),this.additionalTransformNode=r==null?void 0:r.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(s=>{s.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),s.dragBehavior.onDragObservable.add(()=>{this.onDragObservable.notifyObservers({})}),s.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):mn.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new tt("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=Me.Gray(),this._hoverMaterial=new tt("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=Me.Yellow(),this._disableMaterial=new tt("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=Me.Gray(),this._disableMaterial.alpha=.4;const e=new vd(new P(0,1,0),Me.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=sA("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=sA("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._octahedron);const i={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,i),e}set updateGizmoRotationToMatchAttachedMesh(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)})):de.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.anchorPoint=e)})}get anchorPoint(){return this._anchorPoint}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.customRotationQuaternion=e)})}set coordinatesMode(e){e==t4.World&&de.Warn("Setting coordinates Mode to world on scaling gizmo is not supported."),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t.coordinatesMode=t4.Local})}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.snapDistance=e)})}get snapDistance(){return this._snapDistance}set incrementalSnap(e){this._incrementalSnap=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.incrementalSnap=e)})}get incrementalSnap(){return this._incrementalSnap}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.scaleRatio=e)})}get scaleRatio(){return this._scaleRatio}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.sensitivity=e)})}get sensitivity(){return this._sensitivity}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.uniformScaleGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(e=>{e&&e.dispose()}),this._observables.forEach(e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)}),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach(e=>{e&&e.dispose()}),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()})}}class kDe{get keepDepthUtilityLayer(){return this._defaultKeepDepthUtilityLayer}get utilityLayer(){return this._defaultUtilityLayer}get isHovered(){let e=!1;for(const t in this.gizmos){const i=this.gizmos[t];if(i&&i.isHovered){e=!0;break}}return e}get isDragging(){let e=!1;return[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach(t=>{t&&t.isDragging&&(e=!0)}),e}set scaleRatio(e){this._scaleRatio=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach(t=>{t&&(t.scaleRatio=e)})}get scaleRatio(){return this._scaleRatio}set coordinatesMode(e){this._coordinatesMode=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach(t=>{t&&(t.coordinatesMode=e)})}get coordinatesMode(){return this._coordinatesMode}get attachedMesh(){return this._attachedMesh}get attachedNode(){return this._attachedNode}get additionalTransformNode(){return this._additionalTransformNode}constructor(e,t=1,i=Or.DefaultUtilityLayer,r=Or.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new Ae,this.onAttachedToNodeObservable=new Ae,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=Me.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=t4.Local,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new Nme,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=r,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const s=this._attachToMeshPointerObserver(e),a=mn.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[s,a]}_attachToMeshPointerObserver(e){return e.onPointerObservable.add(i=>{if(this.usePointerToAttachGizmos&&i.type==ft.POINTERDOWN)if(i.pickInfo&&i.pickInfo.pickedMesh){if(this.enableAutoPicking){let r=i.pickInfo.pickedMesh;if(this.attachableMeshes==null)for(;r&&r.parent!=null;)r=r.parent;else{let s=!1;this.attachableMeshes.forEach(a=>{r&&(r==a||r.isDescendantOf(a))&&(r=a,s=!0)}),s||(r=null)}r instanceof di?this._attachedMesh!=r&&this.attachToMesh(r):this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}}else this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)})}attachToMesh(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this._attachedNode=null;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)}attachToNode(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=e;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedNode=e)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(e)}set positionGizmoEnabled(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new HG(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=e,this._setAdditionalTransformNode()}get positionGizmoEnabled(){return this._gizmosEnabled.positionGizmo}set rotationGizmoEnabled(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new Lee(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=e,this._setAdditionalTransformNode()}get rotationGizmoEnabled(){return this._gizmosEnabled.rotationGizmo}set scaleGizmoEnabled(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new Nee(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=e,this._setAdditionalTransformNode()}get scaleGizmoEnabled(){return this._gizmosEnabled.scaleGizmo}set boundingBoxGizmoEnabled(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new Oee(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=e,this._setAdditionalTransformNode()}get boundingBoxGizmoEnabled(){return this._gizmosEnabled.boundingBoxGizmo}set additionalTransformNode(e){this._additionalTransformNode=e,this._setAdditionalTransformNode()}_setAdditionalTransformNode(){for(const e in this.gizmos){const t=this.gizmos[e];t&&this._gizmosEnabled[e]&&(t.additionalTransformNode=this._additionalTransformNode)}}addToAxisCache(e){e.size>0&&e.forEach((t,i)=>{this._gizmoAxisCache.set(i,t)})}releaseDrag(){[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach(e=>{e==null||e.releaseDrag()})}dispose(){var e,t;this._pointerObservers.forEach(i=>{this._scene.onPointerObservable.remove(i)});for(const i in this.gizmos){const r=this.gizmos[i];r&&r.dispose()}this._defaultKeepDepthUtilityLayer!==Or._DefaultKeepDepthUtilityLayer&&((e=this._defaultKeepDepthUtilityLayer)==null||e.dispose()),this._defaultUtilityLayer!==Or._DefaultUtilityLayer&&((t=this._defaultUtilityLayer)==null||t.dispose()),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}class u4 extends Ui{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=ce.Identity(),this._projectionMatrix=ce.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=P.Zero()),P.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=P.Zero()),P.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0):!1}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=P.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=P.Cross(this.direction,$n.Y),t=P.Cross(e,this.direction);return P.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=P.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=ce.Identity()),ce.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=ie.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),P.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(P.Dot(t,P.Up()))===1&&(t.z=1e-13);const r=ie.Vector3[1];return i.addToRef(t,r),ce.LookAtLHToRef(i,r,P.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}B([Js()],u4.prototype,"position",null);B([Js()],u4.prototype,"direction",null);B([K()],u4.prototype,"shadowMinZ",null);B([K()],u4.prototype,"shadowMaxZ",null);Lr.AddNodeConstructor("Light_Type_1",(n,e)=>()=>new Wl(n,P.Zero(),e));class Wl extends u4{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Ui.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&ce.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,this.shadowMinZ!==void 0?this.shadowMinZ:t.minZ,this.shadowMaxZ!==void 0?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const h=P.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let u=Number.MAX_VALUE,d=-Number.MAX_VALUE;for(let f=0;fthis._orthoRight&&(this._orthoRight=h.x),h.y>this._orthoTop&&(this._orthoTop=h.y),this.autoCalcShadowZBounds&&(h.zd&&(d=h.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=u,this._shadowMaxZ=d)}const s=this._orthoRight-this._orthoLeft,a=this._orthoTop-this._orthoBottom,o=this.shadowMinZ!==void 0?this.shadowMinZ:r.minZ,c=this.shadowMaxZ!==void 0?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;ce.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-a*this.shadowOrthoScale,this._orthoTop+a*this.shadowOrthoScale,l?c:o,l?o:c,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}B([K()],Wl.prototype,"shadowFrustumSize",null);B([K()],Wl.prototype,"shadowOrthoScale",null);B([K()],Wl.prototype,"autoUpdateExtends",void 0);B([K()],Wl.prototype,"autoCalcShadowZBounds",void 0);B([K("orthoLeft")],Wl.prototype,"_orthoLeft",void 0);B([K("orthoRight")],Wl.prototype,"_orthoRight",void 0);B([K("orthoTop")],Wl.prototype,"_orthoTop",void 0);B([K("orthoBottom")],Wl.prototype,"_orthoBottom",void 0);function QD(n,e={},t){e.diameter||(e.diameter=1),e.segments||(e.segments=16);const i=Tl("",{slice:.5,diameter:e.diameter,segments:e.segments},t),r=U5("",{radius:e.diameter/2,tessellation:e.segments*3+(4-e.segments)},t);r.rotation.x=-Math.PI/2,r.parent=i;const s=Se.MergeMeshes([r,i],!0);return s.name=n,s}const VDe={CreateHemisphere:QD};Se.CreateHemisphere=(n,e,t,i)=>QD(n,{segments:e,diameter:t},i);Lr.AddNodeConstructor("Light_Type_2",(n,e)=>()=>new Sl(n,P.Zero(),P.Zero(),0,0,e));class Sl extends u4{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(e*.5),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(Sl._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):Sl._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()})))}static _IsProceduralTexture(e){return e.onGeneratedObservable!==void 0}static _IsTexture(e){return e.onLoadObservable!==void 0}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,r,s,a){super(e,a),this._innerAngle=0,this._projectionTextureMatrix=ce.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=P.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=P.Zero(),this._projectionTextureViewLightMatrix=ce.Zero(),this._projectionTextureProjectionLightMatrix=ce.Zero(),this._projectionTextureScalingMatrix=ce.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return Ui.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;const s=this._shadowAngleScale*this._angle,a=this.shadowMinZ!==void 0?this.shadowMinZ:r.minZ,o=this.shadowMaxZ!==void 0?this.shadowMaxZ:r.maxZ,c=this.getScene().getEngine().useReverseDepthBuffer;ce.PerspectiveFovLHToRef(s,1,c?o:a,c?a:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,c)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),ce.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);ce.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof ve){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;ce.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(this._innerAngle*.5)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightSampler"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=P.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=P.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return this.computeTransformedInformation()?i=P.Normalize(this.transformedDirection):i=P.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!(this.projectionTexture&&this.projectionTexture.isReady())}}B([K()],Sl.prototype,"angle",null);B([K()],Sl.prototype,"innerAngle",null);B([K()],Sl.prototype,"shadowAngleScale",null);B([K()],Sl.prototype,"exponent",void 0);B([K()],Sl.prototype,"projectionTextureLightNear",null);B([K()],Sl.prototype,"projectionTextureLightFar",null);B([K()],Sl.prototype,"projectionTextureUpDirection",null);B([$t("projectedLightTexture")],Sl.prototype,"_projectionTexture",void 0);class Af extends mn{constructor(e=Or.DefaultUtilityLayer){super(e),this._cachedPosition=new P,this._cachedForward=new P(0,0,1),this._pointerObserver=null,this.onClickedObservable=new Ae,this._light=null,this.attachedMesh=new di("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new Et("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new tt("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Me(.5,.5,.5),this._material.specularColor=new Me(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(t=>{this._light&&(this._isHovered=!!(t.pickInfo&&this._rootMesh.getChildMeshes().indexOf(t.pickInfo.pickedMesh)!=-1),this._isHovered&&t.event.button===0&&this.onClickedObservable.notifyObservers(this._light))},ft.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){de.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),e instanceof Vf?this._lightMesh=Af._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof Wl?this._lightMesh=Af._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof Sl?this._lightMesh=Af._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=Af._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(i=>{i.material=this._material}),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new we,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);const i=this._getMeshForward();this._cachedForward.copyFrom(i)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(ie.Vector3[0]),e=ie.Vector3[0]),e}_update(){if(super._update(),!!this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new P(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(P.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new P(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else P.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new Se("hemisphereLight",e),i=QD(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;const r=this._CreateLightLines(3,e);return r.parent=t,t.scaling.scaleInPlace(Af._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new Se("pointLight",e),i=Tl(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;const r=this._CreateLightLines(5,e);return r.parent=t,t.scaling.scaleInPlace(Af._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new Se("spotLight",e),i=Tl(t.name,{segments:10,diameter:1},e);i.parent=t;const r=QD(t.name,{segments:10,diameter:2},e);r.parent=t,r.rotation.x=-Math.PI/2;const s=this._CreateLightLines(2,e);return s.parent=t,t.scaling.scaleInPlace(Af._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new Se("directionalLight",e),i=new Se(t.name,e);i.parent=t;const r=Tl(t.name,{diameter:1.2,segments:10},e);r.parent=i;const s=dc(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let a=s.clone(t.name);a.scaling.y=.5,a.position.x+=1.25;let o=s.clone(t.name);o.scaling.y=.5,o.position.x+=-1.25;const c=dc(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return c.position.y+=3,c.parent=i,a=c.clone(t.name),a.position.y=1.5,a.position.x+=1.25,o=c.clone(t.name),o.position.y=1.5,o.position.x+=-1.25,i.scaling.scaleInPlace(Af._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}Af._Scale=.007;Af._CreateLightLines=(n,e)=>{const i=new Se("root",e);i.rotation.x=Math.PI/2;const r=new Se("linePivot",e);r.parent=i;const s=dc("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},e);if(s.position.y=s.scaling.y/2+1.2,s.parent=r,n<2)return r;for(let o=0;o<4;o++){const c=r.clone("lineParentClone");c.rotation.z=Math.PI/4,c.rotation.y=Math.PI/2+Math.PI/2*o,c.getChildMeshes()[0].scaling.y=.5,c.getChildMeshes()[0].scaling.x=c.getChildMeshes()[0].scaling.z=.8,c.getChildMeshes()[0].position.y=c.getChildMeshes()[0].scaling.y/2+1.2}if(n<3)return i;for(let o=0;o<4;o++){const c=r.clone("linePivotClone");c.rotation.z=Math.PI/2,c.rotation.y=Math.PI/2*o}if(n<4)return i;for(let o=0;o<4;o++){const c=r.clone("linePivotClone");c.rotation.z=Math.PI+Math.PI/4,c.rotation.y=Math.PI/2+Math.PI/2*o,c.getChildMeshes()[0].scaling.y=.5,c.getChildMeshes()[0].scaling.x=c.getChildMeshes()[0].scaling.z=.8,c.getChildMeshes()[0].position.y=c.getChildMeshes()[0].scaling.y/2+1.2}if(n<5)return i;const a=r.clone("linePivotClone");return a.rotation.z=Math.PI,i};class n8 extends mn{constructor(e=Or.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new Ae,this._camera=null,this._invProjection=new ce,this._material=new tt("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new Me(.5,.5,.5),this._material.specularColor=new Me(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(r=>{this._camera&&(this._isHovered=!!(r.pickInfo&&this._rootMesh.getChildMeshes().indexOf(r.pickInfo.pickedMesh)!=-1),this._isHovered&&r.event.button===0&&this.onClickedObservable.notifyObservers(this._camera))},ft.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){var t;if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=n8._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach(s=>{s.material=this._material}),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();const i=((t=this._frustumLinesColor)==null?void 0:t.toColor4(1))??new Ze(1,1,1,1);this._cameraLinesMesh=n8._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,i),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ[0..varyingCount] #ifdef PACKEDFLOAT #include #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float computedWeight=0.0; #ifdef PACKEDFLOAT float blend=0.; #else vec4 blend=vec4(0.); #endif #ifdef DOF float sumOfWeights=CENTER_WEIGHT; float factor=0.0; #ifdef PACKEDFLOAT blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; #else blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; #endif #endif #include[0..varyingCount] #include[0..depCount] #ifdef PACKEDFLOAT gl_FragColor=pack(blend); #else gl_FragColor=blend; #endif #ifdef DOF gl_FragColor/=sumOfWeights; #endif }`;Re.ShadersStore[QDe]=$De;const ZDe="kernelBlurVertex",qDe="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";Re.IncludesShadersStore[ZDe]=qDe;const JDe="kernelBlurVertexShader",eOe=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; #include[0..varyingCount] const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN sampleCenter=(position*madd+madd); #include[0..varyingCount] gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[JDe]=eOe;class ao extends Pt{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,r,s,a=ve.BILINEAR_SAMPLINGMODE,o,c,l=0,h="",u=!1,d=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],r,s,a,o,c,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,d),this._blockCompilation=u,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add(f=>{this._outputTexture?f.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):f.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)}),this.kernel=i}updateEffect(e=null,t=null,i=null,r,s,a){this._updateParameters(s,a)}_updateParameters(e,t){const i=this._kernel,r=(i-1)/2;let s=[],a=[],o=0;for(let m=0;m0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){const t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,r=-(e*e/(2*t*t));return 1/i*Math.exp(r)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,r){return Qe.Parse(()=>new ao(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}}B([K("kernel")],ao.prototype,"_kernel",void 0);B([K("packedFloat")],ao.prototype,"_packedFloat",void 0);B([LO()],ao.prototype,"direction",void 0);xe("BABYLON.BlurPostProcess",ao);class H3 extends es{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,s=0,a=ve.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,r,!0,s,!1,a,o),this.mirrorPlane=new yl(0,1,0,1),this._transformMatrix=ce.Zero(),this._mirrorMatrix=ce.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,i=this.getScene(),!i)return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateGammaSpace()});const c=i.getEngine();c.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add(()=>{var h;(h=c._debugPushGroup)==null||h.call(c,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var h;(h=c._debugPopGroup)==null||h.call(c,1)});let l;this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),ce.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),l=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=P.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=l})}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new ao("horizontal blur",new Be(1,0),this._blurKernelX,this._blurRatio,null,ve.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,this._blurRatio===1&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new ao("vertical blur",new Be(0,1),this._blurKernelY,this._blurRatio,null,ve.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=this._blurRatio!==1,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new H3(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var t;super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),(t=this._sceneUBO)==null||t.dispose()}}ve._CreateMirror=(n,e,t,i)=>new H3(n,e,t,i);class Bn extends Er{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(ce.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let r="";return e.forEach(s=>r+=s),new Bn(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){const s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const a=new Bn(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=s,a}constructor(e,t,i=null,r=!1,s=null,a=null,o=null,c=5,l=!1,h=null,u=!1,d=.8,f=0,p,_){var m;super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new Ae,this.boundingBoxPosition=P.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new ce,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this._format=c,this.isCube=!0,this._textureMatrix=ce.Identity(),this._createPolynomials=u,this.coordinatesMode=ve.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=h,this._loaderOptions=p,this._useSRGBBuffer=_,this._lodScale=d,this._lodOffset=f,!(!e&&!s)&&this.updateURL(e,h,a,l,o,i,(m=this.getScene())==null?void 0:m.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,r=!1,s=null,a=null,o=!1,c=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),u=h.indexOf(".dds")===0,d=h.indexOf(".env")===0,f=h.indexOf(".basis")===0;if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),c)this._files=c;else if(!f&&!d&&!u&&!a&&(a=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,a){for(let p=0;po.getActiveTextures().indexOf(this)!==-1)),this._textureMatrix=e,!((a=this.getScene())!=null&&a.useRightHandedSystem)))return;const t=ie.Vector3[0],i=ie.Quaternion[0],r=ie.Vector3[1];this._textureMatrix.decompose(t,i,r),i.z*=-1,i.w*=-1,ce.ComposeToRef(t,i,r,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return(e=this.getScene())!=null&&e.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var o;const i=this.getScene(),r=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const s=()=>{var c;this.onLoadObservable.notifyObservers(this),r&&(r.dispose(),(c=this.getScene())==null||c.markAllMaterialsAsDirty(1)),e&&e()},a=(c,l)=>{this._loadingError=!0,this._errorObject={message:c,exception:l},t&&t(c,l),ve.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Ee.SetImmediate(()=>s()):this._texture.onLoadedObservable.add(()=>s()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,a,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,a,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),(o=this._texture)==null||o.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){const r=Qe.Parse(()=>{let s=!1;return e.prefiltered&&(s=e.prefiltered),new Bn(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=P.FromArray(e.boundingBoxSize)),e.animations)for(let s=0;s{const i=new Bn(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=i.uniqueId,i},this);return t.uniqueId=e,t}}B([K()],Bn.prototype,"url",void 0);B([Js()],Bn.prototype,"boundingBoxPosition",void 0);B([Js()],Bn.prototype,"boundingBoxSize",null);B([K("rotationY")],Bn.prototype,"rotationY",null);B([K("files")],Bn.prototype,"_files",void 0);B([K("forcedExtension")],Bn.prototype,"_forcedExtension",void 0);B([K("extensions")],Bn.prototype,"_extensions",void 0);B([qH("textureMatrix")],Bn.prototype,"_textureMatrix",void 0);B([qH("textureMatrixRefraction")],Bn.prototype,"_textureMatrixRefraction",void 0);ve._CubeTextureParser=Bn.Parse;xe("BABYLON.CubeTexture",Bn);const tOe="backgroundFragmentDeclaration",iOe=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; #ifdef USEHIGHLIGHTANDSHADOWCOLORS uniform vec4 vPrimaryColorShadow; #endif uniform float shadowLevel;uniform float alpha; #ifdef DIFFUSE uniform vec2 vDiffuseInfos; #endif #ifdef REFLECTION uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; #endif #if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) uniform vec3 vBackgroundCenter; #endif #ifdef REFLECTIONFRESNEL uniform vec4 vReflectionControl; #endif #if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) uniform mat4 view; #endif #ifdef PROJECTED_GROUND uniform vec2 projectedGroundInfos; #endif `;Re.IncludesShadersStore[tOe]=iOe;const rOe="backgroundUboDeclaration",sOe=`layout(std140,column_major) uniform;uniform Material {uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;}; #include `;Re.IncludesShadersStore[rOe]=sOe;const nOe="backgroundPixelShader",aOe=`#ifdef TEXTURELODSUPPORT #extension GL_EXT_shader_texture_lod : enable #endif precision highp float; #include<__decl__backgroundFragment> #include varying vec3 vPositionW; #ifdef MAINUV1 varying vec2 vMainUV1; #endif #ifdef MAINUV2 varying vec2 vMainUV2; #endif #ifdef NORMAL varying vec3 vNormalW; #endif #ifdef DIFFUSE #if DIFFUSEDIRECTUV==1 #define vDiffuseUV vMainUV1 #elif DIFFUSEDIRECTUV==2 #define vDiffuseUV vMainUV2 #else varying vec2 vDiffuseUV; #endif uniform sampler2D diffuseSampler; #endif #ifdef REFLECTION #ifdef REFLECTIONMAP_3D #define sampleReflection(s,c) textureCube(s,c) uniform samplerCube reflectionSampler; #ifdef TEXTURELODSUPPORT #define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) #else uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; #endif #else #define sampleReflection(s,c) texture2D(s,c) uniform sampler2D reflectionSampler; #ifdef TEXTURELODSUPPORT #define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) #else uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; #endif #endif #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #endif #include #endif #ifndef FROMLINEARSPACE #define FROMLINEARSPACE; #endif #ifndef SHADOWONLY #define SHADOWONLY; #endif #include #include<__decl__lightFragment>[0..maxSimultaneousLights] #include #include #include #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif #include #include #include #ifdef REFLECTIONFRESNEL #define FRESNEL_MAXIMUM_ON_ROUGH 0.25 vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) {float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} #endif #ifdef PROJECTED_GROUND float diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; } vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q) vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); #ifdef NORMAL vec3 normalW=normalize(vNormalW); #else vec3 normalW=vec3(0.0,1.0,0.0); #endif float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.; #include[0..maxSimultaneousLights] #ifdef SHADOWINUSE globalShadow/=shadowLightCount; #else globalShadow=1.0; #endif #ifndef BACKMAT_SHADOWONLY vec4 reflectionColor=vec4(1.,1.,1.,1.); #ifdef REFLECTION #ifdef PROJECTED_GROUND vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.)); #else vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); #endif #ifdef REFLECTIONMAP_OPPOSITEZ reflectionVector.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D vec3 reflectionCoords=reflectionVector; #else vec2 reflectionCoords=reflectionVector.xy; #ifdef REFLECTIONMAP_PROJECTION reflectionCoords/=reflectionVector.z; #endif reflectionCoords.y=1.0-reflectionCoords.y; #endif #ifdef REFLECTIONBLUR float reflectionLOD=vReflectionInfos.y; #ifdef TEXTURELODSUPPORT reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); #else float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( sampleReflection(reflectionSamplerHigh,reflectionCoords), reflectionSpecularMid, lodReflectionNormalizedDoubled );} else {reflectionColor=mix( reflectionSpecularMid, sampleReflection(reflectionSamplerLow,reflectionCoords), lodReflectionNormalizedDoubled-1.0 );} #endif #else vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; #endif #ifdef RGBDREFLECTION reflectionColor.rgb=fromRGBD(reflectionColor); #endif #ifdef GAMMAREFLECTION reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); #endif #ifdef REFLECTIONBGR reflectionColor.rgb=reflectionColor.bgr; #endif reflectionColor.rgb*=vReflectionInfos.x; #endif vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; #ifdef DIFFUSE vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); #ifdef GAMMADIFFUSE diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); #endif diffuseMap.rgb*=vDiffuseInfos.y; #ifdef DIFFUSEHASALPHA finalAlpha*=diffuseMap.a; #endif diffuseColor=diffuseMap.rgb; #endif #ifdef REFLECTIONFRESNEL vec3 colorBase=diffuseColor; #else vec3 colorBase=reflectionColor.rgb*diffuseColor; #endif colorBase=max(colorBase,0.0); #ifdef USERGBCOLOR vec3 finalColor=colorBase; #else #ifdef USEHIGHLIGHTANDSHADOWCOLORS vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); #else vec3 mainColor=vPrimaryColor.rgb; #endif vec3 finalColor=colorBase*mainColor; #endif #ifdef REFLECTIONFRESNEL vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; #ifdef REFLECTIONFALLOFF float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; #endif finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); #endif #ifdef OPACITYFRESNEL float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; #endif #ifdef SHADOWINUSE finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); #endif vec4 color=vec4(finalColor,finalAlpha); #else vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); #endif #include #include #ifdef IMAGEPROCESSINGPOSTPROCESS #if !defined(SKIPFINALCOLORCLAMP) color.rgb=clamp(color.rgb,0.,30.0); #endif #else color=applyImageProcessing(color); #endif #ifdef PREMULTIPLYALPHA color.rgb*=color.a; #endif #ifdef NOISE color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); #endif gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END } `;Re.ShadersStore[nOe]=aOe;const oOe="backgroundVertexDeclaration",lOe=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; #ifdef DIFFUSE uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; #endif #ifdef REFLECTION uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; #endif #ifdef POINTSIZE uniform float pointSize; #endif `;Re.IncludesShadersStore[oOe]=lOe;const cOe="backgroundVertexShader",hOe=`precision highp float; #include<__decl__backgroundVertex> #include attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #include #include #include varying vec3 vPositionW; #ifdef NORMAL varying vec3 vNormalW; #endif #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #ifdef MAINUV1 varying vec2 vMainUV1; #endif #ifdef MAINUV2 varying vec2 vMainUV2; #endif #if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 varying vec2 vDiffuseUV; #endif #include #include #include<__decl__lightVxFragment>[0..maxSimultaneousLights] #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN #ifdef REFLECTIONMAP_SKYBOX vPositionUVW=position; #endif #include #include #include #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} #else gl_Position=viewProjection*finalWorld*vec4(position,1.0); #endif vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); #ifdef NORMAL mat3 normalWorld=mat3(finalWorld); #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vNormalW=normalize(normalWorld*normal); #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); #ifdef EQUIRECTANGULAR_RELFECTION_FOV mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} #endif #endif #ifndef UV1 vec2 uv=vec2(0.,0.); #endif #ifndef UV2 vec2 uv2=vec2(0.,0.); #endif #ifdef MAINUV1 vMainUV1=uv; #endif #ifdef MAINUV2 vMainUV2=uv2; #endif #if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 if (vDiffuseInfos.x==0.) {vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} else {vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} #endif #include #include #include[0..maxSimultaneousLights] #ifdef VERTEXCOLOR vColor=color; #endif #if defined(POINTSIZE) && !defined(WEBGPU) gl_PointSize=pointSize; #endif #include #define CUSTOM_VERTEX_MAIN_END } `;Re.ShadersStore[cOe]=hOe;class uOe extends Kr{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class nr extends Rn{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t=t*2,this.reflectionReflectance0=nr.StandardReflectance0*t,this.reflectionReflectance90=nr.StandardReflectance90*t):(t=t*2-1,this.reflectionReflectance0=nr.StandardReflectance0+(1-nr.StandardReflectance0)*t,this.reflectionReflectance90=nr.StandardReflectance90+(1-nr.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()})))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=Me.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=P.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new ba(16),this._reflectionControls=Ct.Zero(),this._white=Me.White(),this._primaryShadowColor=Me.Black(),this._primaryHighlightColor=Me.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!!(this._diffuseTexture&&this._diffuseTexture.isRenderTarget||this._reflectionTexture&&this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new uOe);const s=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(vc(s,e,a,!1,this._maxSimultaneousLights),a._needNormals=!0,N5(s,a),a._areTexturesDirty){if(a._needUVs=!1,s.texturesEnabled){if(s.getEngine().getCaps().textureLOD&&(a.TEXTURELODSUPPORT=!0),this._diffuseTexture&&$e.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;ks(this._diffuseTexture,a,"DIFFUSE"),a.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,a.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,a.OPACITYFRESNEL=this._opacityFresnel}else a.DIFFUSE=!1,a.DIFFUSEDIRECTUV=0,a.DIFFUSEHASALPHA=!1,a.GAMMADIFFUSE=!1,a.OPACITYFRESNEL=!1;const c=this._reflectionTexture;if(c&&$e.ReflectionTextureEnabled){if(!c.isReadyOrNotBlocking())return!1;switch(a.REFLECTION=!0,a.GAMMAREFLECTION=c.gammaSpace,a.RGBDREFLECTION=c.isRGBD,a.REFLECTIONBLUR=this._reflectionBlur>0,a.LODINREFLECTIONALPHA=c.lodLevelInAlpha,a.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,a.REFLECTIONBGR=this.switchToBGR,c.coordinatesMode===ve.INVCUBIC_MODE&&(a.INVERTCUBICMAP=!0),a.REFLECTIONMAP_3D=c.isCube,a.REFLECTIONMAP_OPPOSITEZ=a.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!c.invertZ:c.invertZ,c.coordinatesMode){case ve.EXPLICIT_MODE:a.REFLECTIONMAP_EXPLICIT=!0;break;case ve.PLANAR_MODE:a.REFLECTIONMAP_PLANAR=!0;break;case ve.PROJECTION_MODE:a.REFLECTIONMAP_PROJECTION=!0;break;case ve.SKYBOX_MODE:a.REFLECTIONMAP_SKYBOX=!0;break;case ve.SPHERICAL_MODE:a.REFLECTIONMAP_SPHERICAL=!0;break;case ve.EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case ve.FIXED_EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case ve.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case ve.CUBIC_MODE:case ve.INVCUBIC_MODE:default:a.REFLECTIONMAP_CUBIC=!0;break}this.reflectionFresnel?(a.REFLECTIONFRESNEL=!0,a.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1)}else a.REFLECTION=!1,a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1,a.REFLECTIONBLUR=!1,a.REFLECTIONMAP_3D=!1,a.REFLECTIONMAP_SPHERICAL=!1,a.REFLECTIONMAP_PLANAR=!1,a.REFLECTIONMAP_CUBIC=!1,a.REFLECTIONMAP_PROJECTION=!1,a.REFLECTIONMAP_SKYBOX=!1,a.REFLECTIONMAP_EXPLICIT=!1,a.REFLECTIONMAP_EQUIRECTANGULAR=!1,a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,a.INVERTCUBICMAP=!1,a.REFLECTIONMAP_OPPOSITEZ=!1,a.LODINREFLECTIONALPHA=!1,a.GAMMAREFLECTION=!1,a.RGBDREFLECTION=!1}a.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,a.USERGBCOLOR=this._useRGBColor,a.NOISE=this._enableNoise}if(a._areLightsDirty&&(a.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(this._primaryColorShadowLevel!==0||this._primaryColorHighlightLevel!==0),a.BACKMAT_SHADOWONLY=this._shadowOnly),a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a)}if(a._areMiscDirty&&(a.REFLECTIONMAP_3D&&this._enableGroundProjection?(a.PROJECTED_GROUND=!0,a.REFLECTIONMAP_SKYBOX=!0):a.PROJECTED_GROUND=!1),Ql(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),a),$l(s,o,this,a,i,null,t.getRenderingMesh().hasThinInstances),qn(e,a,!1,!0,!1)&&e&&!s.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(Z.NormalKind)&&(e.createNormals(!0),de.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();const c=new Hn;a.FOG&&c.addFallback(0,"FOG"),a.POINTSIZE&&c.addFallback(1,"POINTSIZE"),a.MULTIVIEW&&c.addFallback(0,"MULTIVIEW"),uo(a,c,this._maxSimultaneousLights);const l=[Z.PositionKind];a.NORMAL&&l.push(Z.NormalKind),a.UV1&&l.push(Z.UVKind),a.UV2&&l.push(Z.UV2Kind),Kc(l,e,a,c),pa(l,a);const h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];Sa(h);const u=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],d=["Material","Scene"];Ji&&(Ji.PrepareUniforms(h,a),Ji.PrepareSamplers(u,a)),Ma({uniformsNames:h,uniformBuffersNames:d,samplers:u,defines:a,maxSimultaneousLights:this._maxSimultaneousLights});const f=a.toString(),p=s.getEngine().createEffect("background",{attributes:l,uniformsNames:h,uniformBuffersNames:d,samplers:u,defines:f,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o);t.setEffect(p,a,this._materialContext),this.buildUniformLayout()}return!t.effect||!t.effect.isReady()?!1:(a._renderId=s.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){this._primaryColorShadowLevel===0&&this._primaryColorHighlightLevel===0||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const a=i.effect;if(!a)return;this._activeEffect=a,this.bindOnlyWorldMatrix(e),Yl(t,this._activeEffect);const o=this._mustRebind(r,a,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(a,"Material"),this.bindViewProjection(a);const c=this._reflectionTexture;(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync||i._drawWrapper._forceRebindOnNextCall)&&(r.texturesEnabled&&(this._diffuseTexture&&$e.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ms(this._diffuseTexture,this._uniformBuffer,"diffuse")),c&&$e.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",c.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",c.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",c.getSize().width,c.lodGenerationScale,c.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&$e.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),c&&$e.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",c):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",c._lodTextureMid||c),this._uniformBuffer.setTexture("reflectionSamplerLow",c._lodTextureLow||c),this._uniformBuffer.setTexture("reflectionSamplerHigh",c._lodTextureHigh||c)):this._uniformBuffer.setTexture("reflectionSampler",c),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),s.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),fa(this._activeEffect,this,r),r.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(a,"Material"),this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(r.lightsEnabled&&gc(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(a),Oo(r,t,this._activeEffect,!0),this._useLogarithmicDepth&&Ha(s,a,r),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!(super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e)}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return Qe.Clone(()=>new nr(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return Qe.Parse(()=>new nr(e.name,t),e,t,i)}}nr.StandardReflectance0=.05;nr.StandardReflectance90=.5;B([or()],nr.prototype,"_primaryColor",void 0);B([ze("_markAllSubMeshesAsLightsDirty")],nr.prototype,"primaryColor",void 0);B([or()],nr.prototype,"__perceptualColor",void 0);B([K()],nr.prototype,"_primaryColorShadowLevel",void 0);B([K()],nr.prototype,"_primaryColorHighlightLevel",void 0);B([ze("_markAllSubMeshesAsLightsDirty")],nr.prototype,"primaryColorHighlightLevel",null);B([$t()],nr.prototype,"_reflectionTexture",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"reflectionTexture",void 0);B([K()],nr.prototype,"_reflectionBlur",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"reflectionBlur",void 0);B([$t()],nr.prototype,"_diffuseTexture",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"diffuseTexture",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"shadowLights",void 0);B([K()],nr.prototype,"_shadowLevel",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"shadowLevel",void 0);B([Js()],nr.prototype,"_sceneCenter",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"sceneCenter",void 0);B([K()],nr.prototype,"_opacityFresnel",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"opacityFresnel",void 0);B([K()],nr.prototype,"_reflectionFresnel",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"reflectionFresnel",void 0);B([K()],nr.prototype,"_reflectionFalloffDistance",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"reflectionFalloffDistance",void 0);B([K()],nr.prototype,"_reflectionAmount",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"reflectionAmount",void 0);B([K()],nr.prototype,"_reflectionReflectance0",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"reflectionReflectance0",void 0);B([K()],nr.prototype,"_reflectionReflectance90",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"reflectionReflectance90",void 0);B([K()],nr.prototype,"_useRGBColor",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"useRGBColor",void 0);B([K()],nr.prototype,"_enableNoise",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"enableNoise",void 0);B([K()],nr.prototype,"_maxSimultaneousLights",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],nr.prototype,"maxSimultaneousLights",void 0);B([K()],nr.prototype,"_shadowOnly",void 0);B([ze("_markAllSubMeshesAsLightsDirty")],nr.prototype,"shadowOnly",void 0);B([xJ()],nr.prototype,"_imageProcessingConfiguration",void 0);B([K(),ze("_markAllSubMeshesAsMiscDirty")],nr.prototype,"enableGroundProjection",void 0);B([K()],nr.prototype,"projectedGroundRadius",void 0);B([K()],nr.prototype,"projectedGroundHeight",void 0);xe("BABYLON.BackgroundMaterial",nr);class s4{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Me(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new Me(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:P.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(i,r)=>{this.onErrorObservable.notifyObservers({message:i,exception:r})},this._options={...s4._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new Ae,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new Ze(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof Er){this._scene.environmentTexture=this._options.environmentTexture;return}const e=Bn.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new Se("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||this._scene.meshes.length===1)return{groundSize:e,skyboxSize:t,rootPosition:i};const r=this._scene.getWorldExtends(a=>a!==this._ground&&a!==this._rootMesh&&a!==this._skybox),s=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Rr&&this._scene.activeCamera.upperRadiusLimit&&(e=this._scene.activeCamera.upperRadiusLimit*2,t=e);const a=s.length();a>e&&(e=a*2,t=e),e*=1.1,t*=1.5,i=r.min.add(s.scale(.5)),i.y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=n_("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(()=>{this._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new nr("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof Er){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new ve(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture}}_setupGroundMirrorTexture(e){const t=ve.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new H3("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,ve.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new yl(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let r=0;r{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new nr("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){if(this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof Er){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new Bn(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=ve.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture}}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}s4._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png";s4._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds";s4._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class gh extends Et{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=ve.CLAMP_ADDRESSMODE,this._texture.wrapV=ve.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=ve.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=ve.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=gh.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new Ae,this.onLoadObservable=new Ae,r=this.getScene(),e=e||"textureDome",i.resolution=Math.abs(i.resolution)|0||32,i.clickToPlay=!!i.clickToPlay,i.autoPlay=i.autoPlay===void 0?!0:!!i.autoPlay,i.loop=i.loop===void 0?!0:!!i.loop,i.size=Math.abs(i.size)||(r.activeCamera?r.activeCamera.maxZ*.48:1e3),i.useDirectMapping===void 0?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,i.faceForward===void 0&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=Tl(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:Se.BACKSIDE},r);const a=this._material=new nr(e+"_material",r);a.useEquirectangularFOV=!0,a.fovMultiplier=1,a.opacityFresnel=!1;const o=this._initTexture(t,r,i);if(this.texture=o,this._mesh.material=a,this._mesh.parent=this,this._halfDomeMask=Tl("",{slice:.5,diameter:i.size*.98,segments:i.resolution*2,sideOrientation:Se.BACKSIDE},r),this._halfDomeMask.rotate($n.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce(()=>{this._setReady(!0)}),i.faceForward&&r.activeCamera){const c=r.activeCamera,l=P.Forward(),h=P.TransformNormal(l,c.getViewMatrix());h.normalize(),this.rotation.y=Math.acos(P.Dot(l,h))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case gh.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case gh.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const t=this._halfDome?0:.5,i=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(r=>{let s=r.isRightCamera;this._crossEye&&(s=!s),s?this._texture.uOffset=t:this._texture.uOffset=i});break}case gh.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(t=>{let i=t.isRightCamera;this._crossEye&&(i=!i),this._texture.vOffset=i?.5:0});break}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}gh.MODE_MONOSCOPIC=0;gh.MODE_TOPBOTTOM=1;gh.MODE_SIDEBYSIDE=2;class X8 extends gh{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new ve(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,()=>{this.onLoadObservable.notifyObservers()},(r,s)=>{this.onLoadErrorObservable.notifyObservers(r||"Unknown error occured"),this.onError&&this.onError(r,s)})}}X8.MODE_MONOSCOPIC=gh.MODE_MONOSCOPIC;X8.MODE_TOPBOTTOM=gh.MODE_TOPBOTTOM;X8.MODE_SIDEBYSIDE=gh.MODE_SIDEBYSIDE;const dOe="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==";let fOe=0;const A9=n=>{if(!n.environmentBRDFTexture){const e=n.useDelayedTextureLoading;n.useDelayedTextureLoading=!1;const t=n._blockEntityCollection;n._blockEntityCollection=!1;const i=ve.CreateFromBase64String(dOe,"EnvironmentBRDFTexture"+fOe++,n,!0,!1,ve.BILINEAR_SAMPLINGMODE);n._blockEntityCollection=t;const r=n.getEngine().getLoadedTexturesCache(),s=r.indexOf(i.getInternalTexture());s!==-1&&r.splice(s,1),i.isRGBD=!0,i.wrapU=ve.CLAMP_ADDRESSMODE,i.wrapV=ve.CLAMP_ADDRESSMODE,n.environmentBRDFTexture=i,n.useDelayedTextureLoading=e,zz.ExpandRGBDTexture(i);const a=n.getEngine().onContextRestoredObservable.add(()=>{i.isRGBD=!0;const o=n.onBeforeRenderObservable.add(()=>{i.isReady()&&(n.onBeforeRenderObservable.remove(o),zz.ExpandRGBDTexture(i))})});n.onDisposeObservable.add(()=>{n.getEngine().onContextRestoredObservable.remove(a)})}return n.environmentBRDFTexture},pOe={GetEnvironmentBRDFTexture:A9};class _Oe extends Kr{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class Vl extends Wc{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new _Oe,t),this._useEnergyConservation=Vl.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Vl.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Vl.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Vl.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Vl.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Vl.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Vl.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Vl.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}Vl.DEFAULT_USE_ENERGY_CONSERVATION=!0;Vl.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;Vl.DEFAULT_USE_SPHERICAL_HARMONICS=!0;Vl.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;B([K(),ze("_markAllSubMeshesAsMiscDirty")],Vl.prototype,"useEnergyConservation",void 0);B([K(),ze("_markAllSubMeshesAsMiscDirty")],Vl.prototype,"useSmithVisibilityHeightCorrelated",void 0);B([K(),ze("_markAllSubMeshesAsMiscDirty")],Vl.prototype,"useSphericalHarmonics",void 0);B([K(),ze("_markAllSubMeshesAsMiscDirty")],Vl.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);const mOe="pbrFragmentDeclaration",gOe=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; #ifdef ALBEDO uniform vec2 vAlbedoInfos; #endif #ifdef AMBIENT uniform vec4 vAmbientInfos; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; #endif #ifdef OPACITY uniform vec2 vOpacityInfos; #endif #ifdef EMISSIVE uniform vec2 vEmissiveInfos; #endif #ifdef LIGHTMAP uniform vec2 vLightmapInfos; #endif #ifdef REFLECTIVITY uniform vec3 vReflectivityInfos; #endif #ifdef MICROSURFACEMAP uniform vec2 vMicroSurfaceSamplerInfos; #endif #if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) uniform mat4 view; #endif #ifdef REFLECTION uniform vec2 vReflectionInfos; #ifdef REALTIME_FILTERING uniform vec2 vReflectionFilteringInfo; #endif uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; #if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; #endif #endif #if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; #endif #ifdef CLEARCOAT uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; #if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) uniform vec4 vClearCoatInfos; #endif #ifdef CLEARCOAT_TEXTURE uniform mat4 clearCoatMatrix; #endif #ifdef CLEARCOAT_TEXTURE_ROUGHNESS uniform mat4 clearCoatRoughnessMatrix; #endif #ifdef CLEARCOAT_BUMP uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; #endif #ifdef CLEARCOAT_TINT uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; #ifdef CLEARCOAT_TINT_TEXTURE uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; #endif #endif #endif #ifdef IRIDESCENCE uniform vec4 vIridescenceParams; #if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) uniform vec4 vIridescenceInfos; #endif #ifdef IRIDESCENCE_TEXTURE uniform mat4 iridescenceMatrix; #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE uniform mat4 iridescenceThicknessMatrix; #endif #endif #ifdef ANISOTROPIC uniform vec3 vAnisotropy; #ifdef ANISOTROPIC_TEXTURE uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; #endif #endif #ifdef SHEEN uniform vec4 vSheenColor; #ifdef SHEEN_ROUGHNESS uniform float vSheenRoughness; #endif #if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) uniform vec4 vSheenInfos; #endif #ifdef SHEEN_TEXTURE uniform mat4 sheenMatrix; #endif #ifdef SHEEN_TEXTURE_ROUGHNESS uniform mat4 sheenRoughnessMatrix; #endif #endif #ifdef SUBSURFACE #ifdef SS_REFRACTION uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; #ifdef REALTIME_FILTERING uniform vec2 vRefractionFilteringInfo; #endif #ifdef SS_DISPERSION uniform float dispersion; #endif #endif #ifdef SS_THICKNESSANDMASK_TEXTURE uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; #endif uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity; #endif #ifdef PREPASS #ifdef SS_SCATTERING uniform float scatteringDiffusionProfile; #endif #endif #if DEBUGMODE>0 uniform vec2 vDebugMode; #endif #ifdef DETAIL uniform vec4 vDetailInfos; #endif #include #ifdef USESPHERICALFROMREFLECTIONMAP #ifdef SPHERICAL_HARMONICS uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; #else uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; #endif #endif #define ADDITIONAL_FRAGMENT_DECLARATION `;Re.IncludesShadersStore[mOe]=gOe;const vOe="pbrUboDeclaration",xOe=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; #define ADDITIONAL_UBO_DECLARATION }; #include #include `;Re.IncludesShadersStore[vOe]=xOe;const yOe="pbrFragmentExtraDeclaration",AOe=`varying vec3 vPositionW; #if DEBUGMODE>0 varying vec4 vClipSpacePosition; #endif #include[1..7] #ifdef NORMAL varying vec3 vNormalW; #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) varying vec3 vEnvironmentIrradiance; #endif #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif `;Re.IncludesShadersStore[yOe]=AOe;const COe="samplerFragmentAlternateDeclaration",bOe=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 #define v_VARYINGNAME_UV vMainUV2 #elif _DEFINENAME_DIRECTUV==3 #define v_VARYINGNAME_UV vMainUV3 #elif _DEFINENAME_DIRECTUV==4 #define v_VARYINGNAME_UV vMainUV4 #elif _DEFINENAME_DIRECTUV==5 #define v_VARYINGNAME_UV vMainUV5 #elif _DEFINENAME_DIRECTUV==6 #define v_VARYINGNAME_UV vMainUV6 #else varying vec2 v_VARYINGNAME_UV; #endif #endif `;Re.IncludesShadersStore[COe]=bOe;const EOe="pbrFragmentSamplersDeclaration",TOe=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) #include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) #include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) #include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) #include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) #ifdef CLEARCOAT #include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) #include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) uniform sampler2D clearCoatRoughnessSampler; #endif #include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) #include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) #endif #ifdef IRIDESCENCE #include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) #include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) #endif #ifdef SHEEN #include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) #include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) #if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) uniform sampler2D sheenRoughnessSampler; #endif #endif #ifdef ANISOTROPIC #include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) #endif #ifdef REFLECTION #ifdef REFLECTIONMAP_3D #define sampleReflection(s,c) textureCube(s,c) uniform samplerCube reflectionSampler; #ifdef LODBASEDMICROSFURACE #define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) #else uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; #endif #ifdef USEIRRADIANCEMAP uniform samplerCube irradianceSampler; #endif #else #define sampleReflection(s,c) texture2D(s,c) uniform sampler2D reflectionSampler; #ifdef LODBASEDMICROSFURACE #define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) #else uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; #endif #ifdef USEIRRADIANCEMAP uniform sampler2D irradianceSampler; #endif #endif #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #endif #endif #ifdef ENVIRONMENTBRDF uniform sampler2D environmentBrdfSampler; #endif #ifdef SUBSURFACE #ifdef SS_REFRACTION #ifdef SS_REFRACTIONMAP_3D #define sampleRefraction(s,c) textureCube(s,c) uniform samplerCube refractionSampler; #ifdef LODBASEDMICROSFURACE #define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) #else uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; #endif #else #define sampleRefraction(s,c) texture2D(s,c) uniform sampler2D refractionSampler; #ifdef LODBASEDMICROSFURACE #define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) #else uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; #endif #endif #endif #include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) #include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) #endif `;Re.IncludesShadersStore[EOe]=TOe;const SOe="subSurfaceScatteringFunctions",MOe=`bool testLightingForSSS(float diffusionProfile) {return diffusionProfile<1.;}`;Re.IncludesShadersStore[SOe]=MOe;const ROe="importanceSampling",IOe=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;Re.IncludesShadersStore[ROe]=IOe;const POe="pbrHelperFunctions",wOe=`#define MINIMUMVARIANCE 0.0005 float convertRoughnessToAverageSlope(float roughness) {return square(roughness)+MINIMUMVARIANCE;} float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} vec2 getAARoughnessFactors(vec3 normalVector) { #ifdef SPECULARAA vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); #else return vec2(0.); #endif } #ifdef ANISOTROPIC #ifdef ANISOTROPIC_LEGACY vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} #else vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} #endif #endif #if defined(CLEARCOAT) || defined(SS_REFRACTION) vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), clearCoatIntensity);return clearCoatAbsorption;} #endif #ifdef MICROSURFACEAUTOMATIC float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) {const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} #endif `;Re.IncludesShadersStore[POe]=wOe;const DOe="harmonicsFunctions",OOe=`#ifdef USESPHERICALFROMREFLECTIONMAP #ifdef SPHERICAL_HARMONICS vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 + vSphericalL1_1*(normal.y) + vSphericalL10*(normal.z) + vSphericalL11*(normal.x) + vSphericalL2_2*(normal.y*normal.x) + vSphericalL2_1*(normal.y*normal.z) + vSphericalL20*((3.0*normal.z*normal.z)-1.0) + vSphericalL21*(normal.z*normal.x) + vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} #else vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} #endif #endif `;Re.IncludesShadersStore[DOe]=OOe;const LOe="pbrDirectLightingSetupFunctions",NOe=`struct preLightingInfo {vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; #ifdef IRIDESCENCE float iridescenceIntensity; #endif };preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; #ifdef SPECULARTERM result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); #endif return result;}`;Re.IncludesShadersStore[LOe]=NOe;const BOe="pbrDirectLightingFalloffFunctions",FOe=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) {return max(0.,1.0-length(lightOffset)/range);} float computeDistanceLightFalloff_Physical(float lightDistanceSquared) {return 1.0/maxEps(lightDistanceSquared);} float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) {float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) { #ifdef USEPHYSICALLIGHTFALLOFF return computeDistanceLightFalloff_Physical(lightDistanceSquared); #elif defined(USEGLTFLIGHTFALLOFF) return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); #else return computeDistanceLightFalloff_Standard(lightOffset,range); #endif } float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) {float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) {falloff=max(0.,pow(cosAngle,exponent));} return falloff;} float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) {const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) {float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) { #ifdef USEPHYSICALLIGHTFALLOFF return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); #elif defined(USEGLTFLIGHTFALLOFF) return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); #else return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); #endif }`;Re.IncludesShadersStore[BOe]=FOe;const UOe="pbrBRDFFunctions",kOe=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 #ifdef MS_BRDF_ENERGY_CONSERVATION vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} #endif #ifdef ENVIRONMENTBRDF vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); #ifdef ENVIRONMENTBRDF_RGBD brdfLookup.rgb=fromRGBD(brdfLookup.rgba); #endif return brdfLookup.rgb;} vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { #ifdef BRDF_V_HEIGHT_CORRELATED vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; #else vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; #endif return reflectance;} vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { #ifdef BRDF_V_HEIGHT_CORRELATED vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); #else vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; #endif return reflectance;} #endif /* NOT USED #if defined(SHEEN) && defined(SHEEN_SOFTER) float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) {float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} #endif */ #if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) {float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} #endif #if defined(SHEEN) && defined(ENVIRONMENTBRDF) /** * The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. * The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table */ vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} #endif vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) {return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) {return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} #ifdef CLEARCOAT vec3 getR0RemappedForClearCoat(vec3 f0) { #ifdef CLEARCOAT_DEFAULTIOR #ifdef MOBILE return saturate(f0*(f0*0.526868+0.529324)-0.0482256); #else return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); #endif #else vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); #endif } #endif #ifdef IRIDESCENCE const mat3 XYZ_TO_REC709=mat3( 3.2404542,-0.9692660, 0.0556434, -1.5371385, 1.8760108,-0.2040259, -0.4985314, 0.0415560, 1.0572252 );vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0 #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) float radicalInverse_VdC(uint bits) {bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } vec2 hammersley(uint i,uint N) {return vec2(float(i)/float(N),radicalInverse_VdC(i));} #else float vanDerCorpus(int n,int base) {float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) {if(n>0) {denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} return result;} vec2 hammersley(int i,int N) {return vec2(float(i)/float(N),vanDerCorpus(i,2));} #endif float log4(float x) {return log2(x)/2.;} const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; #define inline vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) {vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) for(uint i=0u; i0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; #ifdef GAMMA_INPUT c=toLinearSpace(c); #endif result+=c;}} result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} #define inline vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) {vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; if (alphaG==0.) { #ifdef GAMMA_INPUT c=toLinearSpace(c); #endif return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) for(uint i=0u; i0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; #ifdef GAMMA_INPUT c=toLinearSpace(c); #endif result+=c*NoL;}} result=result/weight;return result;}} #endif #endif `;Re.IncludesShadersStore[VOe]=zOe;const HOe="pbrDirectLightingFunctions",GOe=`#define CLEARCOATREFLECTANCE90 1.0 struct lightingInfo {vec3 diffuse; #ifdef SPECULARTERM vec3 specular; #endif #ifdef CLEARCOAT vec4 clearCoat; #endif #ifdef SHEEN vec3 sheen; #endif };float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { #if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; #else return roughness; #endif } vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} #define inline vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} #ifdef SS_TRANSLUCENCY vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} #endif #ifdef SPECULARTERM vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); #ifdef IRIDESCENCE fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); #endif float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); #ifdef BRDF_V_HEIGHT_CORRELATED float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); #else float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); #endif vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} #endif #ifdef ANISOTROPIC vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); #ifdef IRIDESCENCE fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); #endif float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} #endif #ifdef CLEARCOAT vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( clearCoatTerm*info.attenuation*NccdotL*lightColor, 1.0-fresnel );} vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} #endif #ifdef SHEEN vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); #else */ float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} #endif `;Re.IncludesShadersStore[HOe]=GOe;const KOe="pbrIBLFunctions",WOe=`#if defined(REFLECTION) || defined(SS_REFRACTION) float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} #endif #if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} #endif #if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} #endif #if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) #define UNPACK_LOD(x) (1.0-x)*255.0 float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} #endif `;Re.IncludesShadersStore[KOe]=WOe;const jOe="pbrBlockAlbedoOpacity",XOe=`struct albedoOpacityOutParams {vec3 surfaceAlbedo;float alpha;}; #define pbr_inline void albedoOpacityBlock( in vec4 vAlbedoColor, #ifdef ALBEDO in vec4 albedoTexture, in vec2 albedoInfos, #endif #ifdef OPACITY in vec4 opacityMap, in vec2 vOpacityInfos, #endif #ifdef DETAIL in vec4 detailColor, in vec4 vDetailInfos, #endif #ifdef DECAL in vec4 decalColor, in vec4 vDecalInfos, #endif out albedoOpacityOutParams outParams ) {vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; #ifdef ALBEDO #if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) alpha*=albedoTexture.a; #endif #ifdef GAMMAALBEDO surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); #else surfaceAlbedo*=albedoTexture.rgb; #endif surfaceAlbedo*=albedoInfos.y; #endif #ifndef DECAL_AFTER_DETAIL #include #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) surfaceAlbedo*=vColor.rgb; #endif #ifdef DETAIL float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; #endif #ifdef DECAL_AFTER_DETAIL #include #endif #define CUSTOM_FRAGMENT_UPDATE_ALBEDO #ifdef OPACITY #ifdef OPACITYRGB alpha=getLuminance(opacityMap.rgb); #else alpha*=opacityMap.a; #endif alpha*=vOpacityInfos.y; #endif #if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) alpha*=vColor.a; #endif #if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) #ifdef ALPHATEST #if DEBUGMODE != 88 if (alpha0 #ifdef METALLICWORKFLOW vec2 metallicRoughness; #ifdef REFLECTIVITY vec4 surfaceMetallicColorMap; #endif #ifndef FROSTBITE_REFLECTANCE vec3 metallicF0; #endif #else #ifdef REFLECTIVITY vec4 surfaceReflectivityColorMap; #endif #endif #endif }; #define pbr_inline void reflectivityBlock( in vec4 vReflectivityColor, #ifdef METALLICWORKFLOW in vec3 surfaceAlbedo, in vec4 metallicReflectanceFactors, #endif #ifdef REFLECTIVITY in vec3 reflectivityInfos, in vec4 surfaceMetallicOrReflectivityColorMap, #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) in vec3 ambientOcclusionColorIn, #endif #ifdef MICROSURFACEMAP in vec4 microSurfaceTexel, #endif #ifdef DETAIL in vec4 detailColor, in vec4 vDetailInfos, #endif out reflectivityOutParams outParams ) {float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; #ifdef METALLICWORKFLOW vec2 metallicRoughness=surfaceReflectivityColor.rg; #ifdef REFLECTIVITY #if DEBUGMODE>0 outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; #endif #ifdef AOSTOREINMETALMAPRED vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); #endif #ifdef METALLNESSSTOREINMETALMAPBLUE metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; #else metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; #endif #ifdef ROUGHNESSSTOREINMETALMAPALPHA metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; #else #ifdef ROUGHNESSSTOREINMETALMAPGREEN metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; #endif #endif #endif #ifdef DETAIL float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); #endif #ifdef MICROSURFACEMAP metallicRoughness.g*=microSurfaceTexel.r; #endif #if DEBUGMODE>0 outParams.metallicRoughness=metallicRoughness; #endif #define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; #ifdef FROSTBITE_REFLECTANCE outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); #else vec3 metallicF0=metallicReflectanceFactors.rgb; #if DEBUGMODE>0 outParams.metallicF0=metallicF0; #endif outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); #endif #else #ifdef REFLECTIVITY surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; #if DEBUGMODE>0 outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; #endif #ifdef MICROSURFACEFROMREFLECTIVITYMAP microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; #else #ifdef MICROSURFACEAUTOMATIC microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); #endif #ifdef MICROSURFACEMAP microSurface*=microSurfaceTexel.r; #endif #define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE #endif #endif #endif microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;} `;Re.IncludesShadersStore[YOe]=QOe;const $Oe="pbrBlockAmbientOcclusion",ZOe=`struct ambientOcclusionOutParams {vec3 ambientOcclusionColor; #if DEBUGMODE>0 && defined(AMBIENT) vec3 ambientOcclusionColorMap; #endif }; #define pbr_inline void ambientOcclusionBlock( #ifdef AMBIENT in vec3 ambientOcclusionColorMap_, in vec4 vAmbientInfos, #endif out ambientOcclusionOutParams outParams ) {vec3 ambientOcclusionColor=vec3(1.,1.,1.); #ifdef AMBIENT vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; #ifdef AMBIENTINGRAYSCALE ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); #endif ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); #if DEBUGMODE>0 outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; #endif #endif outParams.ambientOcclusionColor=ambientOcclusionColor;} `;Re.IncludesShadersStore[$Oe]=ZOe;const qOe="pbrBlockAlphaFresnel",JOe=`#ifdef ALPHAFRESNEL #if defined(ALPHATEST) || defined(ALPHABLEND) struct alphaFresnelOutParams {float alpha;}; #define pbr_inline void alphaFresnelBlock( in vec3 normalW, in vec3 viewDirectionW, in float alpha, in float microSurface, out alphaFresnelOutParams outParams ) {float opacityPerceptual=alpha; #ifdef LINEARALPHAFRESNEL float opacity0=opacityPerceptual; #else float opacity0=opacityPerceptual*opacityPerceptual; #endif float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; #ifdef ALPHATEST if (outParams.alpha0 && defined(ANISOTROPIC_TEXTURE) vec3 anisotropyMapData; #endif }; #define pbr_inline void anisotropicBlock( in vec3 vAnisotropy, in float roughness, #ifdef ANISOTROPIC_TEXTURE in vec3 anisotropyMapData, #endif in mat3 TBN, in vec3 normalW, in vec3 viewDirectionW, out anisotropicOutParams outParams ) {float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); #ifdef ANISOTROPIC_TEXTURE anisotropy*=anisotropyMapData.b; #if DEBUGMODE>0 outParams.anisotropyMapData=anisotropyMapData; #endif anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; #ifdef ANISOTROPIC_LEGACY anisotropyDirection.rg*=anisotropyMapData.rg; #else anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); #endif #endif mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);} #endif `;Re.IncludesShadersStore[e9e]=t9e;const i9e="pbrBlockReflection",r9e=`#ifdef REFLECTION struct reflectionOutParams {vec4 environmentRadiance;vec3 environmentIrradiance; #ifdef REFLECTIONMAP_3D vec3 reflectionCoords; #else vec2 reflectionCoords; #endif #ifdef SS_TRANSLUCENCY #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) vec3 irradianceVector; #endif #endif #endif }; #define pbr_inline void createReflectionCoords( in vec3 vPositionW, in vec3 normalW, #ifdef ANISOTROPIC in anisotropicOutParams anisotropicOut, #endif #ifdef REFLECTIONMAP_3D out vec3 reflectionCoords #else out vec2 reflectionCoords #endif ) { #ifdef ANISOTROPIC vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); #else vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); #endif #ifdef REFLECTIONMAP_OPPOSITEZ reflectionVector.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D reflectionCoords=reflectionVector; #else reflectionCoords=reflectionVector.xy; #ifdef REFLECTIONMAP_PROJECTION reflectionCoords/=reflectionVector.z; #endif reflectionCoords.y=1.0-reflectionCoords.y; #endif } #define pbr_inline #define inline void sampleReflectionTexture( in float alphaG, in vec3 vReflectionMicrosurfaceInfos, in vec2 vReflectionInfos, in vec3 vReflectionColor, #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) in float NdotVUnclamped, #endif #ifdef LINEARSPECULARREFLECTION in float roughness, #endif #ifdef REFLECTIONMAP_3D in samplerCube reflectionSampler, const vec3 reflectionCoords, #else in sampler2D reflectionSampler, const vec2 reflectionCoords, #endif #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D in samplerCube reflectionSamplerLow, in samplerCube reflectionSamplerHigh, #else in sampler2D reflectionSamplerLow, in sampler2D reflectionSamplerHigh, #endif #endif #ifdef REALTIME_FILTERING in vec2 vReflectionFilteringInfo, #endif out vec4 environmentRadiance ) { #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); #elif defined(LINEARSPECULARREFLECTION) float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); #else float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); #endif #ifdef LODBASEDMICROSFURACE reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; #ifdef LODINREFLECTIONALPHA float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); #else float requestedReflectionLOD=reflectionLOD; #endif #ifdef REALTIME_FILTERING environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); #else environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); #endif #else float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( sampleReflection(reflectionSamplerHigh,reflectionCoords), environmentMid, lodReflectionNormalizedDoubled );} else {environmentRadiance=mix( environmentMid, sampleReflection(reflectionSamplerLow,reflectionCoords), lodReflectionNormalizedDoubled-1.0 );} #endif #ifdef RGBDREFLECTION environmentRadiance.rgb=fromRGBD(environmentRadiance); #endif #ifdef GAMMAREFLECTION environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); #endif environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} #define pbr_inline #define inline void reflectionBlock( in vec3 vPositionW, in vec3 normalW, in float alphaG, in vec3 vReflectionMicrosurfaceInfos, in vec2 vReflectionInfos, in vec3 vReflectionColor, #ifdef ANISOTROPIC in anisotropicOutParams anisotropicOut, #endif #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) in float NdotVUnclamped, #endif #ifdef LINEARSPECULARREFLECTION in float roughness, #endif #ifdef REFLECTIONMAP_3D in samplerCube reflectionSampler, #else in sampler2D reflectionSampler, #endif #if defined(NORMAL) && defined(USESPHERICALINVERTEX) in vec3 vEnvironmentIrradiance, #endif #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) in mat4 reflectionMatrix, #endif #endif #ifdef USEIRRADIANCEMAP #ifdef REFLECTIONMAP_3D in samplerCube irradianceSampler, #else in sampler2D irradianceSampler, #endif #endif #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D in samplerCube reflectionSamplerLow, in samplerCube reflectionSamplerHigh, #else in sampler2D reflectionSamplerLow, in sampler2D reflectionSamplerHigh, #endif #endif #ifdef REALTIME_FILTERING in vec2 vReflectionFilteringInfo, #endif out reflectionOutParams outParams ) {vec4 environmentRadiance=vec4(0.,0.,0.,0.); #ifdef REFLECTIONMAP_3D vec3 reflectionCoords=vec3(0.); #else vec2 reflectionCoords=vec2(0.); #endif createReflectionCoords( vPositionW, normalW, #ifdef ANISOTROPIC anisotropicOut, #endif reflectionCoords );sampleReflectionTexture( alphaG, vReflectionMicrosurfaceInfos, vReflectionInfos, vReflectionColor, #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) NdotVUnclamped, #endif #ifdef LINEARSPECULARREFLECTION roughness, #endif #ifdef REFLECTIONMAP_3D reflectionSampler, reflectionCoords, #else reflectionSampler, reflectionCoords, #endif #ifndef LODBASEDMICROSFURACE reflectionSamplerLow, reflectionSamplerHigh, #endif #ifdef REALTIME_FILTERING vReflectionFilteringInfo, #endif environmentRadiance );vec3 environmentIrradiance=vec3(0.,0.,0.); #ifdef USESPHERICALFROMREFLECTIONMAP #if defined(NORMAL) && defined(USESPHERICALINVERTEX) environmentIrradiance=vEnvironmentIrradiance; #else #ifdef ANISOTROPIC vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; #else vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; #endif #ifdef REFLECTIONMAP_OPPOSITEZ irradianceVector.z*=-1.0; #endif #ifdef INVERTCUBICMAP irradianceVector.y*=-1.0; #endif #if defined(REALTIME_FILTERING) environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo); #else environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); #endif #ifdef SS_TRANSLUCENCY outParams.irradianceVector=irradianceVector; #endif #endif #elif defined(USEIRRADIANCEMAP) vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; #ifdef RGBDREFLECTION environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); #endif #ifdef GAMMAREFLECTION environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); #endif #endif environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;} #endif `;Re.IncludesShadersStore[i9e]=r9e;const s9e="pbrBlockSheen",n9e=`#ifdef SHEEN struct sheenOutParams {float sheenIntensity;vec3 sheenColor;float sheenRoughness; #ifdef SHEEN_LINKWITHALBEDO vec3 surfaceAlbedo; #endif #if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) float sheenAlbedoScaling; #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) vec3 finalSheenRadianceScaled; #endif #if DEBUGMODE>0 #ifdef SHEEN_TEXTURE vec4 sheenMapData; #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) vec3 sheenEnvironmentReflectance; #endif #endif }; #define pbr_inline #define inline void sheenBlock( in vec4 vSheenColor, #ifdef SHEEN_ROUGHNESS in float vSheenRoughness, #if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) in vec4 sheenMapRoughnessData, #endif #endif in float roughness, #ifdef SHEEN_TEXTURE in vec4 sheenMapData, in float sheenMapLevel, #endif in float reflectance, #ifdef SHEEN_LINKWITHALBEDO in vec3 baseColor, in vec3 surfaceAlbedo, #endif #ifdef ENVIRONMENTBRDF in float NdotV, in vec3 environmentBrdf, #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) in vec2 AARoughnessFactors, in vec3 vReflectionMicrosurfaceInfos, in vec2 vReflectionInfos, in vec3 vReflectionColor, in vec4 vLightingIntensity, #ifdef REFLECTIONMAP_3D in samplerCube reflectionSampler, in vec3 reflectionCoords, #else in sampler2D reflectionSampler, in vec2 reflectionCoords, #endif in float NdotVUnclamped, #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D in samplerCube reflectionSamplerLow, in samplerCube reflectionSamplerHigh, #else in sampler2D reflectionSamplerLow, in sampler2D reflectionSamplerHigh, #endif #endif #ifdef REALTIME_FILTERING in vec2 vReflectionFilteringInfo, #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) in float seo, #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) in float eho, #endif #endif out sheenOutParams outParams ) {float sheenIntensity=vSheenColor.a; #ifdef SHEEN_TEXTURE #if DEBUGMODE>0 outParams.sheenMapData=sheenMapData; #endif #endif #ifdef SHEEN_LINKWITHALBEDO float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; #ifdef SHEEN_TEXTURE sheenIntensity*=sheenMapData.a; #endif #else vec3 sheenColor=vSheenColor.rgb; #ifdef SHEEN_TEXTURE #ifdef SHEEN_GAMMATEXTURE sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); #else sheenColor.rgb*=sheenMapData.rgb; #endif sheenColor.rgb*=sheenMapLevel; #endif #ifdef SHEEN_ROUGHNESS float sheenRoughness=vSheenRoughness; #ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE #if defined(SHEEN_TEXTURE) sheenRoughness*=sheenMapData.a; #endif #elif defined(SHEEN_TEXTURE_ROUGHNESS) #ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL sheenRoughness*=sheenMapData.a; #else sheenRoughness*=sheenMapRoughnessData.a; #endif #endif #else float sheenRoughness=roughness; #ifdef SHEEN_TEXTURE sheenIntensity*=sheenMapData.a; #endif #endif #if !defined(SHEEN_ALBEDOSCALING) sheenIntensity*=(1.-reflectance); #endif sheenColor*=sheenIntensity; #endif #ifdef ENVIRONMENTBRDF /*#ifdef SHEEN_SOFTER vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); #else*/ #ifdef SHEEN_ROUGHNESS vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); #else vec3 environmentSheenBrdf=environmentBrdf; #endif /*#endif*/ #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); #ifdef SPECULARAA sheenAlphaG+=AARoughnessFactors.y; #endif vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( sheenAlphaG, vReflectionMicrosurfaceInfos, vReflectionInfos, vReflectionColor, #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) NdotVUnclamped, #endif #ifdef LINEARSPECULARREFLECTION sheenRoughness, #endif reflectionSampler, reflectionCoords, #ifndef LODBASEDMICROSFURACE reflectionSamplerLow, reflectionSamplerHigh, #endif #ifdef REALTIME_FILTERING vReflectionFilteringInfo, #endif environmentSheenRadiance );vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) sheenEnvironmentReflectance*=seo; #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) sheenEnvironmentReflectance*=eho; #endif #if DEBUGMODE>0 outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; #endif outParams.finalSheenRadianceScaled= environmentSheenRadiance.rgb * sheenEnvironmentReflectance * vLightingIntensity.z; #endif #if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; #endif outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;} #endif `;Re.IncludesShadersStore[s9e]=n9e;const a9e="pbrBlockClearcoat",o9e=`struct clearcoatOutParams {vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; #ifdef REFLECTION vec3 finalClearCoatRadianceScaled; #endif #ifdef CLEARCOAT_TINT vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; #endif #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) vec3 energyConservationFactorClearCoat; #endif #if DEBUGMODE>0 #ifdef CLEARCOAT_BUMP mat3 TBNClearCoat; #endif #ifdef CLEARCOAT_TEXTURE vec2 clearCoatMapData; #endif #if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) vec4 clearCoatTintMapData; #endif #ifdef REFLECTION vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; #endif float clearCoatNdotV; #endif }; #ifdef CLEARCOAT #define pbr_inline #define inline void clearcoatBlock( in vec3 vPositionW, in vec3 geometricNormalW, in vec3 viewDirectionW, in vec2 vClearCoatParams, #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) in vec4 clearCoatMapRoughnessData, #endif in vec3 specularEnvironmentR0, #ifdef CLEARCOAT_TEXTURE in vec2 clearCoatMapData, #endif #ifdef CLEARCOAT_TINT in vec4 vClearCoatTintParams, in float clearCoatColorAtDistance, in vec4 vClearCoatRefractionParams, #ifdef CLEARCOAT_TINT_TEXTURE in vec4 clearCoatTintMapData, #endif #endif #ifdef CLEARCOAT_BUMP in vec2 vClearCoatBumpInfos, in vec4 clearCoatBumpMapData, in vec2 vClearCoatBumpUV, #if defined(TANGENT) && defined(NORMAL) in mat3 vTBN, #else in vec2 vClearCoatTangentSpaceParams, #endif #ifdef OBJECTSPACE_NORMALMAP in mat4 normalMatrix, #endif #endif #if defined(FORCENORMALFORWARD) && defined(NORMAL) in vec3 faceNormal, #endif #ifdef REFLECTION in vec3 vReflectionMicrosurfaceInfos, in vec2 vReflectionInfos, in vec3 vReflectionColor, in vec4 vLightingIntensity, #ifdef REFLECTIONMAP_3D in samplerCube reflectionSampler, #else in sampler2D reflectionSampler, #endif #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D in samplerCube reflectionSamplerLow, in samplerCube reflectionSamplerHigh, #else in sampler2D reflectionSamplerLow, in sampler2D reflectionSamplerHigh, #endif #endif #ifdef REALTIME_FILTERING in vec2 vReflectionFilteringInfo, #endif #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) #ifdef RADIANCEOCCLUSION in float ambientMonochrome, #endif #endif #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) in float frontFacingMultiplier, #endif out clearcoatOutParams outParams ) {float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; #ifdef CLEARCOAT_TEXTURE clearCoatIntensity*=clearCoatMapData.x; #ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE clearCoatRoughness*=clearCoatMapData.y; #endif #if DEBUGMODE>0 outParams.clearCoatMapData=clearCoatMapData; #endif #endif #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) #ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL clearCoatRoughness*=clearCoatMapData.y; #else clearCoatRoughness*=clearCoatMapRoughnessData.y; #endif #endif outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; #ifdef CLEARCOAT_TINT vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; #ifdef CLEARCOAT_TINT_TEXTURE #ifdef CLEARCOAT_TINT_GAMMATEXTURE clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); #else clearCoatColor*=clearCoatTintMapData.rgb; #endif clearCoatThickness*=clearCoatTintMapData.a; #if DEBUGMODE>0 outParams.clearCoatTintMapData=clearCoatTintMapData; #endif #endif outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; #endif #ifdef CLEARCOAT_REMAP_F0 vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); #else vec3 specularEnvironmentR0Updated=specularEnvironmentR0; #endif outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; #ifdef CLEARCOAT_BUMP #ifdef NORMALXYSCALE float clearCoatNormalScale=1.0; #else float clearCoatNormalScale=vClearCoatBumpInfos.y; #endif #if defined(TANGENT) && defined(NORMAL) mat3 TBNClearCoat=vTBN; #else vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); #endif #if DEBUGMODE>0 outParams.TBNClearCoat=TBNClearCoat; #endif #ifdef OBJECTSPACE_NORMALMAP clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); #else clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); #endif #endif #if defined(FORCENORMALFORWARD) && defined(NORMAL) clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); #endif #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; #endif outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); #if DEBUGMODE>0 outParams.clearCoatNdotV=clearCoatNdotV; #endif #ifdef CLEARCOAT_TINT vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); #endif #if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); #endif #if defined(REFLECTION) float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); #ifdef SPECULARAA clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; #endif vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); #ifdef REFLECTIONMAP_OPPOSITEZ clearCoatReflectionVector.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D vec3 clearCoatReflectionCoords=clearCoatReflectionVector; #else vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; #ifdef REFLECTIONMAP_PROJECTION clearCoatReflectionCoords/=clearCoatReflectionVector.z; #endif clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; #endif sampleReflectionTexture( clearCoatAlphaG, vReflectionMicrosurfaceInfos, vReflectionInfos, vReflectionColor, #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) clearCoatNdotVUnclamped, #endif #ifdef LINEARSPECULARREFLECTION clearCoatRoughness, #endif reflectionSampler, clearCoatReflectionCoords, #ifndef LODBASEDMICROSFURACE reflectionSamplerLow, reflectionSamplerHigh, #endif #ifdef REALTIME_FILTERING vReflectionFilteringInfo, #endif environmentClearCoatRadiance ); #if DEBUGMODE>0 outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); #ifdef HORIZONOCCLUSION #ifdef BUMP #ifdef REFLECTIONMAP_3D float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; #endif #endif #endif #else vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); #endif clearCoatEnvironmentReflectance*=clearCoatIntensity; #if DEBUGMODE>0 outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; #endif outParams.finalClearCoatRadianceScaled= environmentClearCoatRadiance.rgb * clearCoatEnvironmentReflectance * vLightingIntensity.z; #endif #if defined(CLEARCOAT_TINT) outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); #endif float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); #endif } #endif `;Re.IncludesShadersStore[a9e]=o9e;const l9e="pbrBlockIridescence",c9e=`struct iridescenceOutParams {float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; #ifdef IRIDESCENCE #define pbr_inline #define inline void iridescenceBlock( in vec4 vIridescenceParams, in float viewAngle, in vec3 specularEnvironmentR0, #ifdef IRIDESCENCE_TEXTURE in vec2 iridescenceMapData, #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE in vec2 iridescenceThicknessMapData, #endif #ifdef CLEARCOAT in float NdotVUnclamped, #ifdef CLEARCOAT_TEXTURE in vec2 clearCoatMapData, #endif #endif out iridescenceOutParams outParams ) {float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; #ifdef IRIDESCENCE_TEXTURE iridescenceIntensity*=iridescenceMapData.x; #ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE iridescenceThicknessWeight=iridescenceMapData.g; #endif #endif #if defined(IRIDESCENCE_THICKNESS_TEXTURE) iridescenceThicknessWeight=iridescenceThicknessMapData.g; #endif float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; #ifdef CLEARCOAT float clearCoatIntensity=vClearCoatParams.x; #ifdef CLEARCOAT_TEXTURE clearCoatIntensity*=clearCoatMapData.x; #endif topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); #endif vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;} #endif `;Re.IncludesShadersStore[l9e]=c9e;const h9e="pbrBlockSubSurface",u9e=`struct subSurfaceOutParams {vec3 specularEnvironmentReflectance; #ifdef SS_REFRACTION vec3 finalRefraction;vec3 surfaceAlbedo; #ifdef SS_LINKREFRACTIONTOTRANSPARENCY float alpha; #endif #ifdef REFLECTION float refractionFactorForIrradiance; #endif #endif #ifdef SS_TRANSLUCENCY vec3 transmittance;float translucencyIntensity; #ifdef REFLECTION vec3 refractionIrradiance; #endif #endif #if DEBUGMODE>0 #ifdef SS_THICKNESSANDMASK_TEXTURE vec4 thicknessMap; #endif #ifdef SS_REFRACTION vec4 environmentRefraction;vec3 refractionTransmittance; #endif #endif }; #ifdef SUBSURFACE #ifdef SS_REFRACTION #define pbr_inline #define inline vec4 sampleEnvironmentRefraction( in float ior ,in float thickness ,in float refractionLOD ,in vec3 normalW ,in vec3 vPositionW ,in vec3 viewDirectionW ,in mat4 view ,in vec4 vRefractionInfos ,in mat4 refractionMatrix ,in vec4 vRefractionMicrosurfaceInfos ,in float alphaG #ifdef SS_REFRACTIONMAP_3D ,in samplerCube refractionSampler #ifndef LODBASEDMICROSFURACE ,in samplerCube refractionSamplerLow ,in samplerCube refractionSamplerHigh #endif #else ,in sampler2D refractionSampler #ifndef LODBASEDMICROSFURACE ,in sampler2D refractionSamplerLow ,in sampler2D refractionSamplerHigh #endif #endif #ifdef ANISOTROPIC ,in anisotropicOutParams anisotropicOut #endif #ifdef REALTIME_FILTERING ,in vec2 vRefractionFilteringInfo #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC ,in vec3 refractionPosition ,in vec3 refractionSize #endif ) {vec4 environmentRefraction=vec4(0.,0.,0.,0.); #ifdef ANISOTROPIC vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior); #else vec3 refractionVector=refract(-viewDirectionW,normalW,ior); #endif #ifdef SS_REFRACTIONMAP_OPPOSITEZ refractionVector.z*=-1.0; #endif #ifdef SS_REFRACTIONMAP_3D #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); #endif refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); #else #ifdef SS_USE_THICKNESS_AS_DEPTH vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); #else vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); #endif vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; #endif #ifdef LODBASEDMICROSFURACE refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; #ifdef SS_LODINREFRACTIONALPHA float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); #else float requestedRefractionLOD=refractionLOD; #endif #if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); #else environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); #endif #else float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( sampleRefraction(refractionSamplerHigh,refractionCoords), environmentRefractionMid, lodRefractionNormalizedDoubled );} else {environmentRefraction=mix( environmentRefractionMid, sampleRefraction(refractionSamplerLow,refractionCoords), lodRefractionNormalizedDoubled-1.0 );} #endif #ifdef SS_RGBDREFRACTION environmentRefraction.rgb=fromRGBD(environmentRefraction); #endif #ifdef SS_GAMMAREFRACTION environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); #endif return environmentRefraction;} #endif #define pbr_inline #define inline void subSurfaceBlock( in vec3 vSubSurfaceIntensity, in vec2 vThicknessParam, in vec4 vTintColor, in vec3 normalW, in vec3 specularEnvironmentReflectance, #ifdef SS_THICKNESSANDMASK_TEXTURE in vec4 thicknessMap, #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE in vec4 refractionIntensityMap, #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE in vec4 translucencyIntensityMap, #endif #ifdef REFLECTION #ifdef SS_TRANSLUCENCY in mat4 reflectionMatrix, #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) in vec3 irradianceVector_, #endif #if defined(REALTIME_FILTERING) in samplerCube reflectionSampler, in vec2 vReflectionFilteringInfo, #endif #endif #ifdef USEIRRADIANCEMAP #ifdef REFLECTIONMAP_3D in samplerCube irradianceSampler, #else in sampler2D irradianceSampler, #endif #endif #endif #endif #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) in vec3 surfaceAlbedo, #endif #ifdef SS_REFRACTION in vec3 vPositionW, in vec3 viewDirectionW, in mat4 view, in vec4 vRefractionInfos, in mat4 refractionMatrix, in vec4 vRefractionMicrosurfaceInfos, in vec4 vLightingIntensity, #ifdef SS_LINKREFRACTIONTOTRANSPARENCY in float alpha, #endif #ifdef SS_LODINREFRACTIONALPHA in float NdotVUnclamped, #endif #ifdef SS_LINEARSPECULARREFRACTION in float roughness, #endif in float alphaG, #ifdef SS_REFRACTIONMAP_3D in samplerCube refractionSampler, #ifndef LODBASEDMICROSFURACE in samplerCube refractionSamplerLow, in samplerCube refractionSamplerHigh, #endif #else in sampler2D refractionSampler, #ifndef LODBASEDMICROSFURACE in sampler2D refractionSamplerLow, in sampler2D refractionSamplerHigh, #endif #endif #ifdef ANISOTROPIC in anisotropicOutParams anisotropicOut, #endif #ifdef REALTIME_FILTERING in vec2 vRefractionFilteringInfo, #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC in vec3 refractionPosition, in vec3 refractionSize, #endif #ifdef SS_DISPERSION in float dispersion, #endif #endif #ifdef SS_TRANSLUCENCY in vec3 vDiffusionDistance, #endif out subSurfaceOutParams outParams ) {outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; #ifdef SS_REFRACTION float refractionIntensity=vSubSurfaceIntensity.x; #ifdef SS_LINKREFRACTIONTOTRANSPARENCY refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; #endif #endif #ifdef SS_TRANSLUCENCY float translucencyIntensity=vSubSurfaceIntensity.y; #endif #ifdef SS_THICKNESSANDMASK_TEXTURE #if defined(SS_USE_GLTF_TEXTURES) float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; #else float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; #endif #if DEBUGMODE>0 outParams.thicknessMap=thicknessMap; #endif #ifdef SS_MASK_FROM_THICKNESS_TEXTURE #if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE) #if defined(SS_USE_GLTF_TEXTURES) refractionIntensity*=thicknessMap.r; #else refractionIntensity*=thicknessMap.g; #endif #endif #if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE) translucencyIntensity*=thicknessMap.b; #endif #endif #else float thickness=vThicknessParam.y; #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE #ifdef SS_USE_GLTF_TEXTURES refractionIntensity*=refractionIntensityMap.r; #else refractionIntensity*=refractionIntensityMap.g; #endif #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE translucencyIntensity*=translucencyIntensityMap.b; #endif #ifdef SS_TRANSLUCENCY thickness=maxEps(thickness);vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; #endif #ifdef SS_REFRACTION vec4 environmentRefraction=vec4(0.,0.,0.,0.); #ifdef SS_HAS_THICKNESS float ior=vRefractionInfos.y; #else float ior=vRefractionMicrosurfaceInfos.w; #endif #ifdef SS_LODINREFRACTIONALPHA float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); #elif defined(SS_LINEARSPECULARREFRACTION) float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); #else float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); #endif float refraction_ior=vRefractionInfos.y; #ifdef SS_DISPERSION float realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i]; #endif vec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG #ifdef SS_REFRACTIONMAP_3D ,refractionSampler #ifndef LODBASEDMICROSFURACE ,refractionSamplerLow ,refractionSamplerHigh #endif #else ,refractionSampler #ifndef LODBASEDMICROSFURACE ,refractionSamplerLow ,refractionSamplerHigh #endif #endif #ifdef ANISOTROPIC ,anisotropicOut #endif #ifdef REALTIME_FILTERING ,vRefractionFilteringInfo #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC ,refractionPosition ,refractionSize #endif ); #ifdef SS_DISPERSION environmentRefraction[i]=envSample[i];} #else environmentRefraction=envSample; #endif environmentRefraction.rgb*=vRefractionInfos.x; #endif #ifdef SS_REFRACTION vec3 refractionTransmittance=vec3(refractionIntensity); #ifdef SS_THICKNESSANDMASK_TEXTURE vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); #elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; #else vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); #endif #ifdef SS_ALBEDOFORREFRACTIONTINT environmentRefraction.rgb*=surfaceAlbedo.rgb; #endif outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); #ifdef REFLECTION outParams.refractionFactorForIrradiance=(1.-refractionIntensity); #endif #ifdef UNUSED_MULTIPLEBOUNCES vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); #endif refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; #if DEBUGMODE>0 outParams.refractionTransmittance=refractionTransmittance; #endif outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; #if DEBUGMODE>0 outParams.environmentRefraction=environmentRefraction; #endif #endif #if defined(REFLECTION) && defined(SS_TRANSLUCENCY) #if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; #ifdef REFLECTIONMAP_OPPOSITEZ irradianceVector.z*=-1.0; #endif #ifdef INVERTCUBICMAP irradianceVector.y*=-1.0; #endif #else vec3 irradianceVector=irradianceVector_; #endif #if defined(USESPHERICALFROMREFLECTIONMAP) #if defined(REALTIME_FILTERING) vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo); #else vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); #endif #elif defined(USEIRRADIANCEMAP) #ifdef REFLECTIONMAP_3D vec3 irradianceCoords=irradianceVector; #else vec2 irradianceCoords=irradianceVector.xy; #ifdef REFLECTIONMAP_PROJECTION irradianceCoords/=irradianceVector.z; #endif irradianceCoords.y=1.0-irradianceCoords.y; #endif vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); #ifdef RGBDREFLECTION refractionIrradiance.rgb=fromRGBD(refractionIrradiance); #endif #ifdef GAMMAREFLECTION refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); #endif #else vec4 refractionIrradiance=vec4(0.); #endif refractionIrradiance.rgb*=transmittance; #ifdef SS_ALBEDOFORTRANSLUCENCYTINT refractionIrradiance.rgb*=surfaceAlbedo.rgb; #endif outParams.refractionIrradiance=refractionIrradiance.rgb; #endif } #endif `;Re.IncludesShadersStore[h9e]=u9e;const d9e="pbrBlockNormalGeometric",f9e=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); #ifdef NORMAL vec3 normalW=normalize(vNormalW); #else vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; #endif vec3 geometricNormalW=normalW; #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; #endif `;Re.IncludesShadersStore[d9e]=f9e;const p9e="pbrBlockNormalFinal",_9e=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; #if defined(TWOSIDEDLIGHTING) faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; #endif normalW*=sign(dot(normalW,faceNormal)); #endif #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) normalW=gl_FrontFacing ? normalW : -normalW; #endif `;Re.IncludesShadersStore[p9e]=_9e;const m9e="pbrBlockLightmapInit",g9e=`#ifdef LIGHTMAP vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor.rgb=fromRGBD(lightmapColor); #endif #ifdef GAMMALIGHTMAP lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); #endif lightmapColor.rgb*=vLightmapInfos.y; #endif `;Re.IncludesShadersStore[m9e]=g9e;const v9e="pbrBlockGeometryInfo",x9e=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); #ifdef SPECULARAA alphaG+=AARoughnessFactors.y; #endif #if defined(ENVIRONMENTBRDF) vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) #ifdef RADIANCEOCCLUSION #ifdef AMBIENTINGRAYSCALE float ambientMonochrome=aoOut.ambientOcclusionColor.r; #else float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); #endif float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); #endif #ifdef HORIZONOCCLUSION #ifdef BUMP #ifdef REFLECTIONMAP_3D float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); #endif #endif #endif #endif `;Re.IncludesShadersStore[v9e]=x9e;const y9e="pbrBlockReflectance0",A9e=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; #ifdef METALLICWORKFLOW vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); #else vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); #endif #ifdef ALPHAFRESNEL float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; #endif `;Re.IncludesShadersStore[y9e]=A9e;const C9e="pbrBlockReflectance",b9e=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); #ifdef RADIANCEOCCLUSION specularEnvironmentReflectance*=seo; #endif #ifdef HORIZONOCCLUSION #ifdef BUMP #ifdef REFLECTIONMAP_3D specularEnvironmentReflectance*=eho; #endif #endif #endif #else vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); #endif #ifdef CLEARCOAT specularEnvironmentReflectance*=clearcoatOut.conservationFactor; #if defined(CLEARCOAT_TINT) specularEnvironmentReflectance*=clearcoatOut.absorption; #endif #endif `;Re.IncludesShadersStore[C9e]=b9e;const E9e="pbrBlockDirectLighting",T9e=`vec3 diffuseBase=vec3(0.,0.,0.); #ifdef SPECULARTERM vec3 specularBase=vec3(0.,0.,0.); #endif #ifdef CLEARCOAT vec3 clearCoatBase=vec3(0.,0.,0.); #endif #ifdef SHEEN vec3 sheenBase=vec3(0.,0.,0.); #endif preLightingInfo preInfo;lightingInfo info;float shadow=1.; float aggShadow=0.;float numLights=0.; #if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) vec3 absorption=vec3(0.); #endif `;Re.IncludesShadersStore[E9e]=T9e;const S9e="pbrBlockFinalLitComponents",M9e=`aggShadow=aggShadow/numLights; #if defined(ENVIRONMENTBRDF) #ifdef MS_BRDF_ENERGY_CONSERVATION vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); #endif #endif #ifndef METALLICWORKFLOW #ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; #endif #endif #if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; #endif #ifdef REFLECTION vec3 finalIrradiance=reflectionOut.environmentIrradiance; #if defined(CLEARCOAT) finalIrradiance*=clearcoatOut.conservationFactor; #if defined(CLEARCOAT_TINT) finalIrradiance*=clearcoatOut.absorption; #endif #endif #if defined(SS_REFRACTION) finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; #endif #if defined(SS_TRANSLUCENCY) finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; #endif finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; #endif #ifdef SPECULARTERM vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) finalSpecularScaled*=energyConservationFactor; #endif #if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) finalSpecularScaled*=sheenOut.sheenAlbedoScaling; #endif #endif #ifdef REFLECTION vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) finalRadianceScaled*=energyConservationFactor; #endif #if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) finalRadianceScaled*=sheenOut.sheenAlbedoScaling; #endif #endif #ifdef SHEEN vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; #if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; #if defined(CLEARCOAT_TINT) sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; #endif #endif #endif #ifdef CLEARCOAT vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; #endif #ifdef SS_REFRACTION subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; #ifdef CLEARCOAT_TINT subSurfaceOut.finalRefraction*=clearcoatOut.absorption; #endif #endif #endif #ifdef ALPHABLEND float luminanceOverAlpha=0.0; #if defined(REFLECTION) && defined(RADIANCEOVERALPHA) luminanceOverAlpha+=getLuminance(finalRadianceScaled); #if defined(CLEARCOAT) luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); #endif #endif #if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) luminanceOverAlpha+=getLuminance(finalSpecularScaled); #endif #if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) luminanceOverAlpha+=getLuminance(finalClearCoatScaled); #endif #if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); #endif #endif `;Re.IncludesShadersStore[S9e]=M9e;const R9e="pbrBlockFinalUnlitComponents",I9e=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; #ifdef EMISSIVE vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; #ifdef GAMMAEMISSIVE finalEmissive*=toLinearSpace(emissiveColorTex.rgb); #else finalEmissive*=emissiveColorTex.rgb; #endif finalEmissive*= vEmissiveInfos.y; #endif finalEmissive*=vLightingIntensity.y; #ifdef AMBIENT vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); #else vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; #endif finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; `;Re.IncludesShadersStore[R9e]=I9e;const P9e="pbrBlockFinalColorComposition",w9e=`vec4 finalColor=vec4( #ifndef UNLIT #ifdef REFLECTION finalIrradiance + #endif #ifdef SPECULARTERM finalSpecularScaled + #endif #ifdef SHEEN finalSheenScaled + #endif #ifdef CLEARCOAT finalClearCoatScaled + #endif #ifdef REFLECTION finalRadianceScaled + #if defined(SHEEN) && defined(ENVIRONMENTBRDF) sheenOut.finalSheenRadianceScaled + #endif #ifdef CLEARCOAT clearcoatOut.finalClearCoatRadianceScaled + #endif #endif #ifdef SS_REFRACTION subSurfaceOut.finalRefraction + #endif #endif finalAmbient + finalDiffuse, alpha); #ifdef LIGHTMAP #ifndef LIGHTMAPEXCLUDED #ifdef USELIGHTMAPASSHADOWMAP finalColor.rgb*=lightmapColor.rgb; #else finalColor.rgb+=lightmapColor.rgb; #endif #endif #endif finalColor.rgb+=finalEmissive; #define CUSTOM_FRAGMENT_BEFORE_FOG finalColor=max(finalColor,0.0); `;Re.IncludesShadersStore[P9e]=w9e;const D9e="pbrBlockImageProcessing",O9e=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) #if !defined(SKIPFINALCOLORCLAMP) finalColor.rgb=clamp(finalColor.rgb,0.,30.0); #endif #else finalColor=applyImageProcessing(finalColor); #endif finalColor.a*=visibility; #ifdef PREMULTIPLYALPHA finalColor.rgb*=finalColor.a; #endif `;Re.IncludesShadersStore[D9e]=O9e;const L9e="pbrDebug",N9e=`#if DEBUGMODE>0 if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { #if DEBUGMODE==1 gl_FragColor.rgb=vPositionW.rgb; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==2 && defined(NORMAL) gl_FragColor.rgb=vNormalW.rgb; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) gl_FragColor.rgb=TBN[0]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) gl_FragColor.rgb=TBN[1]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==5 gl_FragColor.rgb=normalW; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==6 && defined(MAINUV1) gl_FragColor.rgb=vec3(vMainUV1,0.0); #elif DEBUGMODE==7 && defined(MAINUV2) gl_FragColor.rgb=vec3(vMainUV2,0.0); #elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==10 && defined(CLEARCOAT) gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==11 && defined(ANISOTROPIC) gl_FragColor.rgb=anisotropicOut.anisotropicNormal; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==12 && defined(ANISOTROPIC) gl_FragColor.rgb=anisotropicOut.anisotropicTangent; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==13 && defined(ANISOTROPIC) gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==20 && defined(ALBEDO) gl_FragColor.rgb=albedoTexture.rgb; #ifndef GAMMAALBEDO #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==21 && defined(AMBIENT) gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; #elif DEBUGMODE==22 && defined(OPACITY) gl_FragColor.rgb=opacityMap.rgb; #elif DEBUGMODE==23 && defined(EMISSIVE) gl_FragColor.rgb=emissiveColorTex.rgb; #ifndef GAMMAEMISSIVE #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==24 && defined(LIGHTMAP) gl_FragColor.rgb=lightmapColor.rgb; #ifndef GAMMALIGHTMAP #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; #elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); #elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; #elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) gl_FragColor.rgb=sheenOut.sheenMapData.rgb; #elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; #elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; #elif DEBUGMODE==32 && defined(BUMP) gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; #elif DEBUGMODE==40 && defined(SS_REFRACTION) gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==41 && defined(REFLECTION) gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; #ifndef GAMMAREFLECTION #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==50 gl_FragColor.rgb=diffuseBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==51 && defined(SPECULARTERM) gl_FragColor.rgb=specularBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==52 && defined(CLEARCOAT) gl_FragColor.rgb=clearCoatBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==53 && defined(SHEEN) gl_FragColor.rgb=sheenBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==54 && defined(REFLECTION) gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; #ifndef GAMMAREFLECTION #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==60 gl_FragColor.rgb=surfaceAlbedo.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==61 gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; #define DEBUGMODE_GAMMA #elif DEBUGMODE==62 && defined(METALLICWORKFLOW) gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); #elif DEBUGMODE==71 && defined(METALLICWORKFLOW) gl_FragColor.rgb=reflectivityOut.metallicF0; #elif DEBUGMODE==63 gl_FragColor.rgb=vec3(roughness); #elif DEBUGMODE==64 gl_FragColor.rgb=vec3(alphaG); #elif DEBUGMODE==65 gl_FragColor.rgb=vec3(NdotV); #elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==67 && defined(CLEARCOAT) gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); #elif DEBUGMODE==68 && defined(CLEARCOAT) gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); #elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) gl_FragColor.rgb=subSurfaceOut.transmittance; #elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; #elif DEBUGMODE==72 gl_FragColor.rgb=vec3(microSurface); #elif DEBUGMODE==73 gl_FragColor.rgb=vAlbedoColor.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) gl_FragColor.rgb=vReflectivityColor.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==75 gl_FragColor.rgb=vEmissiveColor.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) gl_FragColor.rgb=vec3(seo); #elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) gl_FragColor.rgb=vec3(eho); #elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) gl_FragColor.rgb=vec3(energyConservationFactor); #elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) gl_FragColor.rgb=specularEnvironmentReflectance; #define DEBUGMODE_GAMMA #elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; #define DEBUGMODE_GAMMA #elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; #define DEBUGMODE_GAMMA #elif DEBUGMODE==86 && defined(ALPHABLEND) gl_FragColor.rgb=vec3(luminanceOverAlpha); #elif DEBUGMODE==87 gl_FragColor.rgb=vec3(alpha); #elif DEBUGMODE==88 && defined(ALBEDO) gl_FragColor.rgb=vec3(albedoTexture.a); #else float stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); #endif gl_FragColor.rgb*=vDebugMode.y; #ifdef DEBUGMODE_NORMALIZE gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; #endif #ifdef DEBUGMODE_GAMMA gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); #endif gl_FragColor.a=1.0; #ifdef PREPASS gl_FragData[0]=toLinearSpace(gl_FragColor); gl_FragData[1]=vec4(0.,0.,0.,0.); #endif #ifdef DEBUGMODE_FORCERETURN return; #endif } #endif `;Re.IncludesShadersStore[L9e]=N9e;const B9e="pbrPixelShader",F9e=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #extension GL_OES_standard_derivatives : enable #endif #ifdef LODBASEDMICROSFURACE #extension GL_EXT_shader_texture_lod : enable #endif #define CUSTOM_FRAGMENT_BEGIN #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif #include[SCENE_MRT_COUNT] precision highp float; #include #ifndef FROMLINEARSPACE #define FROMLINEARSPACE #endif #include<__decl__pbrFragment> #include #include<__decl__lightFragment>[0..maxSimultaneousLights] #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef REFLECTION #include #endif #define CUSTOM_FRAGMENT_DEFINITIONS #include #include #include #include #include #include #include #include #include #include void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #include #include #include albedoOpacityOutParams albedoOpacityOut; #ifdef ALBEDO vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); #endif #ifdef OPACITY vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); #endif #ifdef DECAL vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); #endif albedoOpacityBlock( vAlbedoColor, #ifdef ALBEDO albedoTexture, vAlbedoInfos, #endif #ifdef OPACITY opacityMap, vOpacityInfos, #endif #ifdef DETAIL detailColor, vDetailInfos, #endif #ifdef DECAL decalColor, vDecalInfos, #endif albedoOpacityOut );vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; #define CUSTOM_FRAGMENT_UPDATE_ALPHA #include #define CUSTOM_FRAGMENT_BEFORE_LIGHTS ambientOcclusionOutParams aoOut; #ifdef AMBIENT vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; #endif ambientOcclusionBlock( #ifdef AMBIENT ambientOcclusionColorMap, vAmbientInfos, #endif aoOut ); #include #ifdef UNLIT vec3 diffuseBase=vec3(1.,1.,1.); #else vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; #if defined(REFLECTIVITY) vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; #ifndef METALLICWORKFLOW #ifdef REFLECTIVITY_GAMMA surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); #endif surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; #endif #endif #if defined(MICROSURFACEMAP) vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; #endif #ifdef METALLICWORKFLOW vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; #ifdef REFLECTANCE vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); #ifdef REFLECTANCE_GAMMA reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); #endif metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; #endif #ifdef METALLIC_REFLECTANCE vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); #ifdef METALLIC_REFLECTANCE_GAMMA metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); #endif #ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; #endif metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; #endif #endif reflectivityBlock( vReflectivityColor, #ifdef METALLICWORKFLOW surfaceAlbedo, metallicReflectanceFactors, #endif #ifdef REFLECTIVITY vReflectivityInfos, surfaceMetallicOrReflectivityColorMap, #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) aoOut.ambientOcclusionColor, #endif #ifdef MICROSURFACEMAP microSurfaceTexel, #endif #ifdef DETAIL detailColor, vDetailInfos, #endif reflectivityOut );float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; #ifdef METALLICWORKFLOW surfaceAlbedo=reflectivityOut.surfaceAlbedo; #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; #endif #ifdef ALPHAFRESNEL #if defined(ALPHATEST) || defined(ALPHABLEND) alphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock( normalW, viewDirectionW, alpha, microSurface, alphaFresnelOut );alpha=alphaFresnelOut.alpha; #endif #endif #include #ifdef ANISOTROPIC anisotropicOutParams anisotropicOut; #ifdef ANISOTROPIC_TEXTURE vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; #endif anisotropicBlock( vAnisotropy, roughness, #ifdef ANISOTROPIC_TEXTURE anisotropyMapData, #endif TBN, normalW, viewDirectionW, anisotropicOut ); #endif #ifdef REFLECTION reflectionOutParams reflectionOut; #ifndef USE_CUSTOM_REFLECTION reflectionBlock( vPositionW, normalW, alphaG, vReflectionMicrosurfaceInfos, vReflectionInfos, vReflectionColor, #ifdef ANISOTROPIC anisotropicOut, #endif #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) NdotVUnclamped, #endif #ifdef LINEARSPECULARREFLECTION roughness, #endif reflectionSampler, #if defined(NORMAL) && defined(USESPHERICALINVERTEX) vEnvironmentIrradiance, #endif #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) reflectionMatrix, #endif #endif #ifdef USEIRRADIANCEMAP irradianceSampler, #endif #ifndef LODBASEDMICROSFURACE reflectionSamplerLow, reflectionSamplerHigh, #endif #ifdef REALTIME_FILTERING vReflectionFilteringInfo, #endif reflectionOut ); #else #define CUSTOM_REFLECTION #endif #endif #include #ifdef SHEEN sheenOutParams sheenOut; #ifdef SHEEN_TEXTURE vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); #endif #if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; #endif sheenBlock( vSheenColor, #ifdef SHEEN_ROUGHNESS vSheenRoughness, #if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) sheenMapRoughnessData, #endif #endif roughness, #ifdef SHEEN_TEXTURE sheenMapData, vSheenInfos.y, #endif reflectance, #ifdef SHEEN_LINKWITHALBEDO baseColor, surfaceAlbedo, #endif #ifdef ENVIRONMENTBRDF NdotV, environmentBrdf, #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) AARoughnessFactors, vReflectionMicrosurfaceInfos, vReflectionInfos, vReflectionColor, vLightingIntensity, reflectionSampler, reflectionOut.reflectionCoords, NdotVUnclamped, #ifndef LODBASEDMICROSFURACE reflectionSamplerLow, reflectionSamplerHigh, #endif #ifdef REALTIME_FILTERING vReflectionFilteringInfo, #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) seo, #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) eho, #endif #endif sheenOut ); #ifdef SHEEN_LINKWITHALBEDO surfaceAlbedo=sheenOut.surfaceAlbedo; #endif #endif #ifdef CLEARCOAT #ifdef CLEARCOAT_TEXTURE vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; #endif #endif #ifdef IRIDESCENCE iridescenceOutParams iridescenceOut; #ifdef IRIDESCENCE_TEXTURE vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; #endif iridescenceBlock( vIridescenceParams, NdotV, specularEnvironmentR0, #ifdef IRIDESCENCE_TEXTURE iridescenceMapData, #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE iridescenceThicknessMapData, #endif #ifdef CLEARCOAT NdotVUnclamped, #ifdef CLEARCOAT_TEXTURE clearCoatMapData, #endif #endif iridescenceOut );float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; #endif clearcoatOutParams clearcoatOut; #ifdef CLEARCOAT #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; #endif #if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); #endif #ifdef CLEARCOAT_BUMP vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); #endif clearcoatBlock( vPositionW, geometricNormalW, viewDirectionW, vClearCoatParams, #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) clearCoatMapRoughnessData, #endif specularEnvironmentR0, #ifdef CLEARCOAT_TEXTURE clearCoatMapData, #endif #ifdef CLEARCOAT_TINT vClearCoatTintParams, clearCoatColorAtDistance, vClearCoatRefractionParams, #ifdef CLEARCOAT_TINT_TEXTURE clearCoatTintMapData, #endif #endif #ifdef CLEARCOAT_BUMP vClearCoatBumpInfos, clearCoatBumpMapData, vClearCoatBumpUV, #if defined(TANGENT) && defined(NORMAL) vTBN, #else vClearCoatTangentSpaceParams, #endif #ifdef OBJECTSPACE_NORMALMAP normalMatrix, #endif #endif #if defined(FORCENORMALFORWARD) && defined(NORMAL) faceNormal, #endif #ifdef REFLECTION vReflectionMicrosurfaceInfos, vReflectionInfos, vReflectionColor, vLightingIntensity, reflectionSampler, #ifndef LODBASEDMICROSFURACE reflectionSamplerLow, reflectionSamplerHigh, #endif #ifdef REALTIME_FILTERING vReflectionFilteringInfo, #endif #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) #ifdef RADIANCEOCCLUSION ambientMonochrome, #endif #endif #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) (gl_FrontFacing ? 1. : -1.), #endif clearcoatOut ); #else clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; #endif #include subSurfaceOutParams subSurfaceOut; #ifdef SUBSURFACE #ifdef SS_THICKNESSANDMASK_TEXTURE vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); #endif subSurfaceBlock( vSubSurfaceIntensity, vThicknessParam, vTintColor, normalW, specularEnvironmentReflectance, #ifdef SS_THICKNESSANDMASK_TEXTURE thicknessMap, #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE refractionIntensityMap, #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE translucencyIntensityMap, #endif #ifdef REFLECTION #ifdef SS_TRANSLUCENCY reflectionMatrix, #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) reflectionOut.irradianceVector, #endif #if defined(REALTIME_FILTERING) reflectionSampler, vReflectionFilteringInfo, #endif #endif #ifdef USEIRRADIANCEMAP irradianceSampler, #endif #endif #endif #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) surfaceAlbedo, #endif #ifdef SS_REFRACTION vPositionW, viewDirectionW, view, vRefractionInfos, refractionMatrix, vRefractionMicrosurfaceInfos, vLightingIntensity, #ifdef SS_LINKREFRACTIONTOTRANSPARENCY alpha, #endif #ifdef SS_LODINREFRACTIONALPHA NdotVUnclamped, #endif #ifdef SS_LINEARSPECULARREFRACTION roughness, #endif alphaG, refractionSampler, #ifndef LODBASEDMICROSFURACE refractionSamplerLow, refractionSamplerHigh, #endif #ifdef ANISOTROPIC anisotropicOut, #endif #ifdef REALTIME_FILTERING vRefractionFilteringInfo, #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC vRefractionPosition, vRefractionSize, #endif #ifdef SS_DISPERSION dispersion, #endif #endif #ifdef SS_TRANSLUCENCY vDiffusionDistance, #endif subSurfaceOut ); #ifdef SS_REFRACTION surfaceAlbedo=subSurfaceOut.surfaceAlbedo; #ifdef SS_LINKREFRACTIONTOTRANSPARENCY alpha=subSurfaceOut.alpha; #endif #endif #else subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; #endif #include #include[0..maxSimultaneousLights] #include #endif #include #define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION #include #include #include(color,finalColor) #include #define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR #ifdef PREPASS float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; #ifdef PREPASS_POSITION gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); #endif #ifdef PREPASS_VELOCITY vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); #endif #ifdef PREPASS_ALBEDO_SQRT vec3 sqAlbedo=sqrt(surfaceAlbedo); #endif #ifdef PREPASS_IRRADIANCE vec3 irradiance=finalDiffuse; #ifndef UNLIT #ifdef REFLECTION irradiance+=finalIrradiance; #endif #endif #ifdef SS_SCATTERING gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); irradiance/=sqAlbedo; #else gl_FragData[0]=finalColor; float scatteringDiffusionProfile=255.; #endif gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); #else gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); #endif #ifdef PREPASS_DEPTH gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_NORMAL #ifdef PREPASS_NORMAL_WORLDSPACE gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); #else gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); #endif #endif #ifdef PREPASS_ALBEDO_SQRT gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); #endif #ifdef PREPASS_REFLECTIVITY #ifndef UNLIT gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; #else gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; #endif #endif #endif #if !defined(PREPASS) || defined(WEBGL2) gl_FragColor=finalColor; #endif #include #if ORDER_INDEPENDENT_TRANSPARENCY if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} #endif #include #define CUSTOM_FRAGMENT_MAIN_END } `;Re.ShadersStore[B9e]=F9e;const U9e="pbrVertexDeclaration",k9e=`uniform mat4 view;uniform mat4 viewProjection; #ifdef ALBEDO uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; #endif #ifdef AMBIENT uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; #endif #ifdef OPACITY uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; #endif #ifdef EMISSIVE uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; #endif #ifdef LIGHTMAP uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; #endif #ifdef REFLECTIVITY uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; #endif #ifdef METALLIC_REFLECTANCE uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; #endif #ifdef REFLECTANCE uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; #endif #ifdef MICROSURFACEMAP uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; #endif #ifdef POINTSIZE uniform float pointSize; #endif #ifdef REFLECTION uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; #endif #ifdef CLEARCOAT #if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) uniform vec4 vClearCoatInfos; #endif #ifdef CLEARCOAT_TEXTURE uniform mat4 clearCoatMatrix; #endif #ifdef CLEARCOAT_TEXTURE_ROUGHNESS uniform mat4 clearCoatRoughnessMatrix; #endif #ifdef CLEARCOAT_BUMP uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; #endif #ifdef CLEARCOAT_TINT_TEXTURE uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; #endif #endif #ifdef IRIDESCENCE #if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) uniform vec4 vIridescenceInfos; #endif #ifdef IRIDESCENCE_TEXTURE uniform mat4 iridescenceMatrix; #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE uniform mat4 iridescenceThicknessMatrix; #endif #endif #ifdef ANISOTROPIC #ifdef ANISOTROPIC_TEXTURE uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; #endif #endif #ifdef SHEEN #if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) uniform vec4 vSheenInfos; #endif #ifdef SHEEN_TEXTURE uniform mat4 sheenMatrix; #endif #ifdef SHEEN_TEXTURE_ROUGHNESS uniform mat4 sheenRoughnessMatrix; #endif #endif #ifdef SUBSURFACE #ifdef SS_REFRACTION uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; #endif #ifdef SS_THICKNESSANDMASK_TEXTURE uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; #endif #endif #ifdef NORMAL #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) #ifdef USESPHERICALFROMREFLECTIONMAP #ifdef SPHERICAL_HARMONICS uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; #else uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; #endif #endif #endif #endif #ifdef DETAIL uniform vec4 vDetailInfos;uniform mat4 detailMatrix; #endif #include #define ADDITIONAL_VERTEX_DECLARATION `;Re.IncludesShadersStore[U9e]=k9e;const V9e="pbrVertexShader",z9e=`precision highp float; #include<__decl__pbrVertex> #define CUSTOM_VERTEX_BEGIN attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #ifdef TANGENT attribute vec4 tangent; #endif #ifdef UV1 attribute vec2 uv; #endif #include[2..7] #include[1..7] #ifdef VERTEXCOLOR attribute vec4 color; #endif #include #include #include #include #include #include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) #include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) #include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) #include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) #include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) #ifdef CLEARCOAT #include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) #include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) #include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) #include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) #endif #ifdef IRIDESCENCE #include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) #include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) #endif #ifdef SHEEN #include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) #include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) #endif #ifdef ANISOTROPIC #include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) #endif #ifdef SUBSURFACE #include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) #include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) #endif varying vec3 vPositionW; #if DEBUGMODE>0 varying vec4 vClipSpacePosition; #endif #ifdef NORMAL varying vec3 vNormalW; #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) varying vec3 vEnvironmentIrradiance; #include #endif #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif #include #include #include #include<__decl__lightVxFragment>[0..maxSimultaneousLights] #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 positionUpdated=position; #ifdef NORMAL vec3 normalUpdated=normal; #endif #ifdef TANGENT vec4 tangentUpdated=tangent; #endif #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX vPositionUVW=positionUpdated; #endif #define CUSTOM_VERTEX_UPDATE_POSITION #define CUSTOM_VERTEX_UPDATE_NORMAL #include #if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); #include #ifdef NORMAL mat3 normalWorld=mat3(finalWorld); #if defined(INSTANCES) && defined(THIN_INSTANCES) vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); #else #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vNormalW=normalize(normalWorld*normalUpdated); #endif #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; #ifdef REFLECTIONMAP_OPPOSITEZ reflectionVector.z*=-1.0; #endif vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); #endif #endif #define CUSTOM_VERTEX_UPDATE_WORLDPOS #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} #else gl_Position=viewProjection*worldPos; #endif #if DEBUGMODE>0 vClipSpacePosition=gl_Position; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); #endif #ifndef UV1 vec2 uvUpdated=vec2(0.,0.); #endif #ifdef MAINUV1 vMainUV1=uvUpdated; #endif #include[2..7] #include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) #include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) #include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) #include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) #include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) #ifdef CLEARCOAT #include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) #include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) #include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) #include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) #endif #ifdef IRIDESCENCE #include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) #include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) #endif #ifdef SHEEN #include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) #include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z) #endif #ifdef ANISOTROPIC #include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) #endif #ifdef SUBSURFACE #include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) #include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) #include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) #endif #include #include #include #include[0..maxSimultaneousLights] #include #if defined(POINTSIZE) && !defined(WEBGPU) gl_PointSize=pointSize; #endif #include #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[V9e]=z9e;class H2e extends Kr{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}}class lo extends Wc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new H2e,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=lo._DefaultIndexOfRefraction,this.indexOfRefraction=lo._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=Me.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;const r=this._material._disableBumpMap;return!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$e.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&$e.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&&$e.ClearCoatBumpTextureEnabled&&!r&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&$e.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking()))}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=this._texture!==null&&this._texture._texture===((i=this._textureRoughness)==null?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$e.ClearCoatTextureEnabled?ks(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&$e.ClearCoatTextureEnabled?ks(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&$e.ClearCoatBumpTextureEnabled?ks(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===lo._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&$e.ClearCoatTintTextureEnabled?(ks(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,r){var u,d,f,p;if(!this._isEnabled)return;const s=r.materialDefines,a=this._material.isFrozen,o=this._material._disableBumpMap,c=this._material._invertNormalMapX,l=this._material._invertNormalMapY,h=s.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!a||!e.isSync){h&&$e.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),ms(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&$e.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",((u=this._texture)==null?void 0:u.coordinatesIndex)??0,((d=this._texture)==null?void 0:d.level)??0,((f=this._textureRoughness)==null?void 0:f.coordinatesIndex)??0,((p=this._textureRoughness)==null?void 0:p.level)??0),this._texture&&ms(this._texture,e,"clearCoat"),this._textureRoughness&&!h&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&ms(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&$e.ClearCoatTextureEnabled&&!o&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),ms(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",c?1:-1,l?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",c?-1:1,l?-1:1)),this._tintTexture&&$e.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),ms(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const _=1-this._indexOfRefraction,m=1+this._indexOfRefraction,g=Math.pow(-_/m,2),v=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",g,v,_,m),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&$e.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!h&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&$e.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&$e.ClearCoatBumpTextureEnabled&&!o&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&$e.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||this._textureRoughness===e||this._bumpTexture===e||this._tintTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,r,s;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose(),(r=this._bumpTexture)==null||r.dispose(),(s=this._tintTexture)==null||s.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}lo._DefaultIndexOfRefraction=1.5;B([K(),ze("_markAllSubMeshesAsTexturesDirty")],lo.prototype,"isEnabled",void 0);B([K()],lo.prototype,"intensity",void 0);B([K()],lo.prototype,"roughness",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],lo.prototype,"indexOfRefraction",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],lo.prototype,"texture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],lo.prototype,"useRoughnessFromMainTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],lo.prototype,"textureRoughness",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],lo.prototype,"remapF0OnInterfaceChange",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],lo.prototype,"bumpTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],lo.prototype,"isTintEnabled",void 0);B([or()],lo.prototype,"tintColor",void 0);B([K()],lo.prototype,"tintColorAtDistance",void 0);B([K()],lo.prototype,"tintThickness",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],lo.prototype,"tintTexture",void 0);class G2e extends Kr{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0,this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1}}class jl extends Wc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new G2e,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=jl._DefaultMinimumThickness,this.maximumThickness=jl._DefaultMaximumThickness,this.indexOfRefraction=jl._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$e.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&&$e.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.IRIDESCENCE=!0,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=this._texture!==null&&this._texture._texture===((i=this._thicknessTexture)==null?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$e.IridescenceTextureEnabled?ks(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&$e.IridescenceTextureEnabled?ks(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,r){var c,l,h,u;if(!this._isEnabled)return;const s=r.materialDefines,a=this._material.isFrozen,o=s.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;(!e.useUbo||!a||!e.isSync)&&(o&&$e.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),ms(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&$e.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",((c=this._texture)==null?void 0:c.coordinatesIndex)??0,((l=this._texture)==null?void 0:l.level)??0,((h=this._thicknessTexture)==null?void 0:h.coordinatesIndex)??0,((u=this._thicknessTexture)==null?void 0:u.level)??0),this._texture&&ms(this._texture,e,"iridescence"),this._thicknessTexture&&!o&&!s.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&ms(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&$e.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!o&&!s.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&$e.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._thicknessTexture)==null||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}jl._DefaultMinimumThickness=100;jl._DefaultMaximumThickness=400;jl._DefaultIndexOfRefraction=1.3;B([K(),ze("_markAllSubMeshesAsTexturesDirty")],jl.prototype,"isEnabled",void 0);B([K()],jl.prototype,"intensity",void 0);B([K()],jl.prototype,"minimumThickness",void 0);B([K()],jl.prototype,"maximumThickness",void 0);B([K()],jl.prototype,"indexOfRefraction",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],jl.prototype,"texture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],jl.prototype,"thicknessTexture",void 0);class K2e extends Kr{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class d4 extends Wc{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new K2e,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new Be(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&$e.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(Z.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$e.AnisotropicTextureEnabled?ks(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&(this._texture&&$e.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),ms(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&$e.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),e.legacy===void 0&&(this.legacy=!0)}}B([K(),ze("_markAllSubMeshesAsTexturesDirty")],d4.prototype,"isEnabled",void 0);B([K()],d4.prototype,"intensity",void 0);B([LO()],d4.prototype,"direction",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],d4.prototype,"texture",void 0);B([K(),ze("_markAllSubMeshesAsMiscDirty")],d4.prototype,"legacy",void 0);class W2e extends Kr{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1}}class qf extends Wc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new W2e,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Me.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$e.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&$e.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=this._roughness!==null,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=this._texture!==null&&this._texture._texture===((i=this._textureRoughness)==null?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$e.SheenTextureEnabled?(ks(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&$e.SheenTextureEnabled?ks(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){var c,l,h,u;if(!this._isEnabled)return;const s=r.materialDefines,a=this._material.isFrozen,o=s.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;(!e.useUbo||!a||!e.isSync)&&(o&&$e.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),ms(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&$e.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",((c=this._texture)==null?void 0:c.coordinatesIndex)??0,((l=this._texture)==null?void 0:l.level)??0,((h=this._textureRoughness)==null?void 0:h.coordinatesIndex)??0,((u=this._textureRoughness)==null?void 0:u.level)??0),this._texture&&ms(this._texture,e,"sheen"),this._textureRoughness&&!o&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ms(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),this._roughness!==null&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&$e.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!o&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&$e.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}B([K(),ze("_markAllSubMeshesAsTexturesDirty")],qf.prototype,"isEnabled",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],qf.prototype,"linkSheenWithAlbedo",void 0);B([K()],qf.prototype,"intensity",void 0);B([or()],qf.prototype,"color",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],qf.prototype,"texture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],qf.prototype,"useRoughnessFromMainTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],qf.prototype,"roughness",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],qf.prototype,"textureRoughness",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],qf.prototype,"albedoScaling",void 0);class j2e extends Kr{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}}class In extends Wc{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new j2e,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=Me.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Me.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&$e.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const i=this._getRefractionTexture(t);if(i&&$e.RefractionTextureEnabled&&!i.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1;return}if(e._areTexturesDirty){e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1;const i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,r=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(r||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&$e.ThicknessTextureEnabled&&ks(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&$e.RefractionIntensityTextureEnabled&&!s&&ks(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&$e.TranslucencyIntensityTextureEnabled&&!s&&ks(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!==0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&s,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&s,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&s,this._isRefractionEnabled&&t.texturesEnabled){const a=this._getRefractionTexture(t);a&&$e.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=a.isCube,e.SS_GAMMAREFRACTION=a.gammaSpace,e.SS_RGBDREFRACTION=a.isRGBD,e.SS_LINEARSPECULARREFRACTION=a.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&a.isCube?!a.invertZ:a.invertZ,e.SS_LODINREFRACTIONALPHA=a.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=a.isCube&&a.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;r.getRenderingMesh().getWorldMatrix().decompose(ie.Vector3[0]);const s=Math.max(Math.abs(ie.Vector3[0].x),Math.abs(ie.Vector3[0].y),Math.abs(ie.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const s=r.materialDefines,a=this._material.isFrozen,o=this._material.realTimeFiltering,c=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!a||!e.isSync){if(this._thicknessTexture&&$e.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),ms(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&$e.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),ms(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&$e.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),ms(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&$e.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let h=1;l.isCube||l.depth&&(h=l.depth);const u=l.getSize().width,d=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/d,h,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",u,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",u,_t.Log2(u)),l.boundingBoxSize){const f=l;e.updateVector3("vRefractionPosition",f.boundingBoxPosition),e.updateVector3("vRefractionSize",f.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&$e.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&$e.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&$e.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&$e.RefractionTextureEnabled&&(c?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){$e.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!($e.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"}]}}}B([K(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"isRefractionEnabled",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"isTranslucencyEnabled",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"isDispersionEnabled",void 0);B([K(),ze("_markScenePrePassDirty")],In.prototype,"isScatteringEnabled",void 0);B([K()],In.prototype,"_scatteringDiffusionProfileIndex",void 0);B([K()],In.prototype,"refractionIntensity",void 0);B([K()],In.prototype,"translucencyIntensity",void 0);B([K()],In.prototype,"useAlbedoToTintRefraction",void 0);B([K()],In.prototype,"useAlbedoToTintTranslucency",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"thicknessTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"refractionTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"indexOfRefraction",void 0);B([K()],In.prototype,"_volumeIndexOfRefraction",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"volumeIndexOfRefraction",null);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"invertRefractionY",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"linkRefractionWithTransparency",void 0);B([K()],In.prototype,"minimumThickness",void 0);B([K()],In.prototype,"maximumThickness",void 0);B([K()],In.prototype,"useThicknessAsDepth",void 0);B([or()],In.prototype,"tintColor",void 0);B([K()],In.prototype,"tintColorAtDistance",void 0);B([K()],In.prototype,"dispersion",void 0);B([or()],In.prototype,"diffusionDistance",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"useMaskFromThicknessTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"refractionIntensityTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"translucencyIntensityTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],In.prototype,"useGltfStyleTextures",void 0);const vS={effect:null,subMesh:null};class q$ extends Kr{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class xr extends Rn{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new Ct(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=xr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=Me.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Me(0,0,0),this._albedoColor=new Me(1,1,1),this._reflectivityColor=new Me(1,1,1),this._reflectionColor=new Me(1,1,1),this._emissiveColor=new Me(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=xr.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new ba(16),this._globalAmbientColor=new Me(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Vl(this),this.clearCoat=new lo(this),this.iridescence=new jl(this),this.anisotropy=new d4(this),this.sheen=new qf(this),this.subSurface=new In(this),this.detailMap=new a_(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),$e.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=A9(this.getScene()),this.prePassConfiguration=new Uz}get hasRenderTargetTextures(){return $e.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===xr.PBRMATERIAL_OPAQUE||this._transparencyMode===xr.PBRMATERIAL_ALPHATEST||((e=this.subSurface)==null?void 0:e.disableAlphaBlending)}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromAlbedoTexture()}needAlphaTesting(){var e;return this._forceAlphaTest?!0:(e=this.subSurface)!=null&&e.disableAlphaBlending?!1:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===xr.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==xr.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var d;this._uniformBufferLayoutBuilt||this.buildUniformLayout();const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Ko.GetDefineNames,this._eventInfo),t.materialDefines=new q$(this._eventInfo.defineNames));const s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=this.getScene(),o=a.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){if(this._albedoTexture&&$e.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&$e.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&$e.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const f=this._getReflectionTexture();if(f&&$e.ReflectionTextureEnabled){if(!f.isReadyOrNotBlocking())return!1;if(f.irradianceTexture){if(!f.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!f.sphericalPolynomial&&((d=f.getInternalTexture())!=null&&d._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&$e.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&$e.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if($e.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&$e.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&$e.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;!o.getCaps().standardDerivatives&&!e.isVerticesDataPresent(Z.NormalKind)&&(e.createNormals(!0),de.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const c=t.effect,l=s._areLightsDisposed;let h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),u=!1;if(h)if(this._onEffectCreatedObservable&&(vS.effect=h,vS.subMesh=t,this._onEffectCreatedObservable.notifyObservers(vS)),this.allowShaderHotSwapping&&c&&!h.isReady()){if(h=c,s.markAsUnprocessed(),u=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else a.resetCachedMaterial(),t.setEffect(h,s,this._materialContext);return!t.effect||!t.effect.isReady()?!1:(s._renderId=a.getRenderId(),r._wasPreviouslyReady=!u,r._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!!(this._metallic!=null||this._roughness!=null||this._metallicTexture)}_prepareEffect(e,t,i=null,r=null,s=null,a=null,o){if(this._prepareDefines(e,t,s,a,o),!t.isDirty)return null;t.markAsProcessed();const l=this.getScene().getEngine(),h=new Hn;let u=0;t.USESPHERICALINVERTEX&&h.addFallback(u++,"USESPHERICALINVERTEX"),t.FOG&&h.addFallback(u,"FOG"),t.SPECULARAA&&h.addFallback(u,"SPECULARAA"),t.POINTSIZE&&h.addFallback(u,"POINTSIZE"),t.LOGARITHMICDEPTH&&h.addFallback(u,"LOGARITHMICDEPTH"),t.PARALLAX&&h.addFallback(u,"PARALLAX"),t.PARALLAX_RHS&&h.addFallback(u,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&h.addFallback(u++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&h.addFallback(u++,"ENVIRONMENTBRDF"),t.TANGENT&&h.addFallback(u++,"TANGENT"),t.BUMP&&h.addFallback(u++,"BUMP"),u=uo(t,h,this._maxSimultaneousLights,u++),t.SPECULARTERM&&h.addFallback(u++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&h.addFallback(u++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&h.addFallback(u++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&h.addFallback(u++,"LIGHTMAP"),t.NORMAL&&h.addFallback(u++,"NORMAL"),t.AMBIENT&&h.addFallback(u++,"AMBIENT"),t.EMISSIVE&&h.addFallback(u++,"EMISSIVE"),t.VERTEXCOLOR&&h.addFallback(u++,"VERTEXCOLOR"),t.MORPHTARGETS&&h.addFallback(u++,"MORPHTARGETS"),t.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");const d=[Z.PositionKind];t.NORMAL&&d.push(Z.NormalKind),t.TANGENT&&d.push(Z.TangentKind);for(let C=1;C<=6;++C)t["UV"+C]&&d.push(`uv${C===1?"":C}`);t.VERTEXCOLOR&&d.push(Z.ColorKind),Kc(d,e,t,h),pa(d,t),VO(d,e,t),zO(d,e,t);let f="pbr";const p=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],m=["Material","Scene","Mesh"],g={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=u,this._eventInfo.defines=t,this._eventInfo.uniforms=p,this._eventInfo.attributes=d,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=m,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=g,this._callbackPluginEventGeneric(Ko.PrepareEffect,this._eventInfo),Uz.AddUniforms(p),Sa(p),Ji&&(Ji.PrepareUniforms(p,t),Ji.PrepareSamplers(_,t)),Ma({uniformsNames:p,uniformBuffersNames:m,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const v={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,p,m,_,t,d,v));const x=t.toString(),y=l.createEffect(f,{attributes:d,uniformsNames:p,uniformBuffersNames:m,samplers:_,defines:x,fallbacks:h,onCompiled:i,onError:r,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},l);return this._eventInfo.customCode=void 0,y}_prepareDefines(e,t,i=null,r=null,s=!1){var l;const a=this.getScene(),o=a.getEngine();vc(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,N5(a,t);const c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(KO(a,t,this.canRenderToMRT&&!c),hG(a,t,c),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let h=1;h<=6;++h)t["MAINUV"+h]=!1;if(a.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&$e.DiffuseTextureEnabled?(ks(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&$e.AmbientTextureEnabled?(ks(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&$e.OpacityTextureEnabled?(ks(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const h=this._getReflectionTexture();if(h&&$e.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=h.gammaSpace,t.RGBDREFLECTION=h.isRGBD,t.LODINREFLECTIONALPHA=h.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=h.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=h.coordinatesMode===ve.INVCUBIC_MODE,t.REFLECTIONMAP_3D=h.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!h.invertZ:h.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,h.coordinatesMode){case ve.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case ve.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case ve.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case ve.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case ve.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case ve.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case ve.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case ve.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case ve.CUBIC_MODE:case ve.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!h.boundingBoxSize;break}h.coordinatesMode!==ve.SKYBOX_MODE&&(h.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):h.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;if(this._lightmapTexture&&$e.LightmapTextureEnabled?(ks(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&$e.EmissiveTextureEnabled?(ks(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,$e.SpecularTextureEnabled){if(this._metallicTexture?(ks(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(ks(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture){const u=this._metallicReflectanceTexture!==null&&this._metallicReflectanceTexture._texture===((l=this._reflectanceTexture)==null?void 0:l._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!u,this._metallicReflectanceTexture?(ks(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!u&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(ks(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?ks(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&$e.BumpTextureEnabled&&!this._disableBumpMap?(ks(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&$e.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=a.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&$e.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===xr.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===xr.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1===0?".":""}`,t.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(Ql(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(Z.NormalKind),t.DEBUGMODE=this._debugMode),$l(a,o,this,t,!!i,r,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),qn(e,t,!0,!0,!0,this._transparencyMode!==xr.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const r={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(Ko.GetDefineNames,this._eventInfo);const s=new q$(this._eventInfo.defineNames),a=this._prepareEffect(e,s,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(vS.effect=a,vS.subMesh=null,this._onEffectCreatedObservable.notifyObservers(vS)),a.isReady()?t&&t(this):a.onCompileObservable.add(()=>{t&&t(this)})}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var u,d,f;const r=this.getScene(),s=i.materialDefines;if(!s)return;const a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e);const o=r.getEngine();this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const c=this._mustRebind(r,a,i,t.visibility);Yl(t,this._activeEffect,this.prePassConfiguration);let l=null;const h=this._uniformBuffer;if(c){if(this.bindViewProjection(a),l=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(r.texturesEnabled){if(this._albedoTexture&&$e.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),ms(this._albedoTexture,h,"albedo")),this._ambientTexture&&$e.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),ms(this._ambientTexture,h,"ambient")),this._opacityTexture&&$e.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ms(this._opacityTexture,h,"opacity")),l&&$e.ReflectionTextureEnabled){if(h.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),h.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const p=l;h.updateVector3("vReflectionPosition",p.boundingBoxPosition),h.updateVector3("vReflectionSize",p.boundingBoxSize)}if(this.realTimeFiltering){const p=l.getSize().width;h.updateFloat2("vReflectionFilteringInfo",p,_t.Log2(p))}if(!s.USEIRRADIANCEMAP){const p=l.sphericalPolynomial;if(s.USESPHERICALFROMREFLECTIONMAP&&p)if(s.SPHERICAL_HARMONICS){const _=p.preScaledHarmonics;h.updateVector3("vSphericalL00",_.l00),h.updateVector3("vSphericalL1_1",_.l1_1),h.updateVector3("vSphericalL10",_.l10),h.updateVector3("vSphericalL11",_.l11),h.updateVector3("vSphericalL2_2",_.l2_2),h.updateVector3("vSphericalL2_1",_.l2_1),h.updateVector3("vSphericalL20",_.l20),h.updateVector3("vSphericalL21",_.l21),h.updateVector3("vSphericalL22",_.l22)}else h.updateFloat3("vSphericalX",p.x.x,p.x.y,p.x.z),h.updateFloat3("vSphericalY",p.y.x,p.y.y,p.y.z),h.updateFloat3("vSphericalZ",p.z.x,p.z.y,p.z.z),h.updateFloat3("vSphericalXX_ZZ",p.xx.x-p.zz.x,p.xx.y-p.zz.y,p.xx.z-p.zz.z),h.updateFloat3("vSphericalYY_ZZ",p.yy.x-p.zz.x,p.yy.y-p.zz.y,p.yy.z-p.zz.z),h.updateFloat3("vSphericalZZ",p.zz.x,p.zz.y,p.zz.z),h.updateFloat3("vSphericalXY",p.xy.x,p.xy.y,p.xy.z),h.updateFloat3("vSphericalYZ",p.yz.x,p.yz.y,p.yz.z),h.updateFloat3("vSphericalZX",p.zx.x,p.zx.y,p.zx.z)}h.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&$e.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ms(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&$e.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ms(this._lightmapTexture,h,"lightmap")),$e.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),ms(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),ms(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),ms(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&s.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),ms(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),ms(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&$e.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),ms(this._bumpTexture,h,"bump"),r._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),s.METALLICWORKFLOW){wr.Color3[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,wr.Color3[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness,h.updateColor4("vReflectivityColor",wr.Color3[0],1);const p=((u=this.subSurface)==null?void 0:u._indexOfRefraction)??1.5,_=1,m=Math.pow((p-_)/(p+_),2);this._metallicReflectanceColor.scaleToRef(m*this._metallicF0Factor,wr.Color3[0]);const g=this._metallicF0Factor;h.updateColor4("vMetallicReflectanceFactors",wr.Color3[0],g)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",$e.EmissiveTextureEnabled?this._emissiveColor:Me.BlackReadOnly),h.updateColor3("vReflectionColor",this._reflectionColor),!s.SS_REFRACTION&&((d=this.subSurface)!=null&&d._linkRefractionWithTransparency)?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*r.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),r.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}r.texturesEnabled&&(this._albedoTexture&&$e.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&$e.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&$e.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),l&&$e.ReflectionTextureEnabled&&(s.LODBASEDMICROSFURACE?h.setTexture("reflectionSampler",l):(h.setTexture("reflectionSampler",l._lodTextureMid||l),h.setTexture("reflectionSamplerLow",l._lodTextureLow||l),h.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),s.USEIRRADIANCEMAP&&h.setTexture("irradianceSampler",l.irradianceTexture)),s.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&$e.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&$e.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),$e.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&s.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&$e.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),fa(this._activeEffect,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(c||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&gc(r,t,this._activeEffect,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==pt.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||s.PREPASS)&&this.bindView(a),Oo(r,t,this._activeEffect,!0),s.NUM_MORPH_INFLUENCERS&&d1(t,this._activeEffect),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((f=t.bakedVertexAnimationManager)==null||f.bind(a,s.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),Ha(s,this._activeEffect,r)),this._afterBind(t,this._activeEffect,i),h.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e)}setPrePassRenderer(){var t;if(!((t=this.subSurface)!=null&&t.isScatteringEnabled))return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){var i,r,s,a,o,c,l,h,u,d,f,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)==null||i.dispose(),(r=this._ambientTexture)==null||r.dispose(),(s=this._opacityTexture)==null||s.dispose(),(a=this._reflectionTexture)==null||a.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(c=this._metallicTexture)==null||c.dispose(),(l=this._reflectivityTexture)==null||l.dispose(),(h=this._bumpTexture)==null||h.dispose(),(u=this._lightmapTexture)==null||u.dispose(),(d=this._metallicReflectanceTexture)==null||d.dispose(),(f=this._reflectanceTexture)==null||f.dispose(),(p=this._microSurfaceTexture)==null||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}xr.PBRMATERIAL_OPAQUE=Ye.MATERIAL_OPAQUE;xr.PBRMATERIAL_ALPHATEST=Ye.MATERIAL_ALPHATEST;xr.PBRMATERIAL_ALPHABLEND=Ye.MATERIAL_ALPHABLEND;xr.PBRMATERIAL_ALPHATESTANDBLEND=Ye.MATERIAL_ALPHATESTANDBLEND;xr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;xr.LIGHTFALLOFF_PHYSICAL=0;xr.LIGHTFALLOFF_GLTF=1;xr.LIGHTFALLOFF_STANDARD=2;B([xJ()],xr.prototype,"_imageProcessingConfiguration",void 0);B([ze("_markAllSubMeshesAsMiscDirty")],xr.prototype,"debugMode",void 0);class Nt extends xr{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===xr.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=xr.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=xr.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===xr.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=xr.LIGHTFALLOFF_GLTF:this._lightFalloff=xr.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=Nt.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Me.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Me(0,0,0),this.albedoColor=new Me(1,1,1),this.reflectivityColor=new Me(1,1,1),this.reflectionColor=new Me(1,1,1),this.emissiveColor=new Me(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=A9(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const r=Qe.Clone(()=>new Nt(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const r=Qe.Parse(()=>new Nt(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ye._ParsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}Nt.PBRMATERIAL_OPAQUE=xr.PBRMATERIAL_OPAQUE;Nt.PBRMATERIAL_ALPHATEST=xr.PBRMATERIAL_ALPHATEST;Nt.PBRMATERIAL_ALPHABLEND=xr.PBRMATERIAL_ALPHABLEND;Nt.PBRMATERIAL_ALPHATESTANDBLEND=xr.PBRMATERIAL_ALPHATESTANDBLEND;Nt.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=xr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"directIntensity",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"emissiveIntensity",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"environmentIntensity",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"specularIntensity",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"disableBumpMap",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"albedoTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"ambientTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"ambientTextureStrength",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesAndMiscDirty")],Nt.prototype,"opacityTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"reflectionTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"emissiveTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"reflectivityTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"metallicTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"metallic",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"roughness",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"metallicF0Factor",void 0);B([or(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"metallicReflectanceColor",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"metallicReflectanceTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"reflectanceTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"microSurfaceTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"bumpTexture",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty",null)],Nt.prototype,"lightmapTexture",void 0);B([or("ambient"),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"ambientColor",void 0);B([or("albedo"),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"albedoColor",void 0);B([or("reflectivity"),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"reflectivityColor",void 0);B([or("reflection"),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"reflectionColor",void 0);B([or("emissive"),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"emissiveColor",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"microSurface",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useLightmapAsShadowmap",void 0);B([K(),ze("_markAllSubMeshesAsTexturesAndMiscDirty")],Nt.prototype,"useAlphaFromAlbedoTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesAndMiscDirty")],Nt.prototype,"forceAlphaTest",void 0);B([K(),ze("_markAllSubMeshesAsTexturesAndMiscDirty")],Nt.prototype,"alphaCutOff",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useSpecularOverAlpha",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useRoughnessFromMetallicTextureGreen",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useMetallnessFromMetallicTextureBlue",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useAmbientInGrayScale",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);B([K()],Nt.prototype,"usePhysicalLightFalloff",null);B([K()],Nt.prototype,"useGLTFLightFalloff",null);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useRadianceOverAlpha",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useObjectSpaceNormalMap",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useParallax",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useParallaxOcclusion",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"parallaxScaleBias",void 0);B([K(),ze("_markAllSubMeshesAsLightsDirty")],Nt.prototype,"disableLighting",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"forceIrradianceInFragment",void 0);B([K(),ze("_markAllSubMeshesAsLightsDirty")],Nt.prototype,"maxSimultaneousLights",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"invertNormalMapX",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"invertNormalMapY",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"twoSidedLighting",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useAlphaFresnel",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useLinearAlphaFresnel",void 0);B([ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"environmentBRDFTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"forceNormalForward",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"enableSpecularAntiAliasing",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useHorizonOcclusion",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Nt.prototype,"useRadianceOcclusion",void 0);B([K(),ze("_markAllSubMeshesAsMiscDirty")],Nt.prototype,"unlit",void 0);B([K(),ze("_markAllSubMeshesAsMiscDirty")],Nt.prototype,"applyDecalMapAfterDetailMap",void 0);xe("BABYLON.PBRMaterial",Nt);const H9e=542327876,vde=131072,xde=512,yde=4,Ade=64,Cde=131072;function GG(n){return n.charCodeAt(0)+(n.charCodeAt(1)<<8)+(n.charCodeAt(2)<<16)+(n.charCodeAt(3)<<24)}function G9e(n){return String.fromCharCode(n&255,n>>8&255,n>>16&255,n>>24&255)}const bde=GG("DXT1"),Ede=GG("DXT3"),Tde=GG("DXT5"),xY=GG("DX10"),Sde=113,Mde=116,Rde=2,Ide=10,K9e=88,yY=31,W9e=0,j9e=1,Pde=2,wde=3,AY=4,Dde=7,CY=20,Ode=21,X9e=22,Y9e=23,Q9e=24,$9e=25,Z9e=26,q9e=28,J9e=32;class fs{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,yY),i=new Int32Array(e.buffer,e.byteOffset,yY+4);let r=1;t[Pde]&vde&&(r=Math.max(1,t[Dde]));const s=t[Ode],a=s===xY?i[J9e]:0;let o=0;switch(s){case Sde:o=2;break;case Mde:o=1;break;case xY:if(a===Ide){o=2;break}if(a===Rde){o=1;break}}return{width:t[AY],height:t[wde],mipmapCount:r,isFourCC:(t[CY]&yde)===yde,isRGB:(t[CY]&Ade)===Ade,isLuminance:(t[CY]&Cde)===Cde,isCube:(t[q9e]&xde)===xde,isCompressed:s===bde||s===Ede||s===Tde,dxgiFormat:a,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,a){const o=new Float32Array(r),c=new Uint16Array(s,i);let l=0;for(let h=0;h>8)}static _GetRGBArrayBuffer(e,t,i,r,s,a,o,c){const l=new Uint8Array(r),h=new Uint8Array(s,i);let u=0;for(let d=0;d0?r.sphericalPolynomial=q6.ConvertCubeMapToSphericalPolynomial({size:d[AY],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}}fs.StoreLODInAlphaChannel=!1;yt.prototype.createPrefilteredCubeTexture=function(n,e,t,i,r=null,s=null,a,o=null,c=!0){const l=h=>{if(!h){r&&r(null);return}const u=h.texture;if(c?h.info.sphericalPolynomial&&(u._sphericalPolynomial=h.info.sphericalPolynomial):u._sphericalPolynomial=new J0,u._source=mi.CubePrefiltered,this.getCaps().textureLOD){r&&r(u);return}const d=3,f=this._gl,p=h.width;if(!p)return;const _=[];for(let m=0;m1)&&t.generateMipMaps,s._unpackFlipY(a.isCompressed),fs.UploadDDSLevels(s,t,h,a,o,6,-1,l),!a.isFourCC&&a.mipmapCount===1?s.generateMipMapsForCubemap(t):c=a.mipmapCount-1}else{const l=e;a=fs.GetDDSInfo(l),t.width=a.width,t.height=a.height,i&&(a.sphericalPolynomial=new J0),o=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(a.isCompressed),fs.UploadDDSLevels(s,t,l,a,o,6),!a.isFourCC&&a.mipmapCount===1?s.generateMipMapsForCubemap(t,!1):c=a.mipmapCount-1}s._setCubeMapTextureParams(t,o,c),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:a,data:e,texture:t})}loadData(e,t,i){const r=fs.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&r.width>>r.mipmapCount-1===1;i(r.width,r.height,s,r.isFourCC,()=>{fs.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}}De._TextureLoaders.push(new X2e);class Y2e{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;const a=FG(e);if(a){t.width=a.width,t.height=a.width;try{kG(t,a),Eee(t,e,a).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},o=>{s==null||s("Can not upload environment levels",o)})}catch(o){s==null||s("Can not upload environment file",o)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}De._TextureLoaders.push(new Y2e);class Bc{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Bc.IsValid(e)){this.isInvalid=!0,de.Error("texture missing KTX identifier");return}const i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),a=r.getUint32(0,!0)===67305985;if(this.glType=r.getUint32(1*i,a),this.glTypeSize=r.getUint32(2*i,a),this.glFormat=r.getUint32(3*i,a),this.glInternalFormat=r.getUint32(4*i,a),this.glBaseInternalFormat=r.getUint32(5*i,a),this.pixelWidth=r.getUint32(6*i,a),this.pixelHeight=r.getUint32(7*i,a),this.pixelDepth=r.getUint32(8*i,a),this.numberOfArrayElements=r.getUint32(9*i,a),this.numberOfFaces=r.getUint32(10*i,a),this.numberOfMipmapLevels=r.getUint32(11*i,a),this.bytesOfKeyValueData=r.getUint32(12*i,a),this.glType!==0){de.Error("only compressed formats currently supported"),this.isInvalid=!0;return}else this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels);if(this.pixelHeight===0||this.pixelDepth!==0){de.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){de.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){de.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=Bc.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case Bc.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break;case Bc.TEX_2D:case Bc.COMPRESSED_3D:case Bc.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=Bc.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight;const a=t?this.numberOfMipmapLevels:1;for(let o=0;o=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===49&&t[6]===49&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}}Bc.HEADER_LEN=12+13*4;Bc.COMPRESSED_2D=0;Bc.COMPRESSED_3D=1;Bc.TEX_2D=2;Bc.TEX_3D=3;class Q2e{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map(t=>({workerPromise:Promise.resolve(t),idle:!0}))}dispose(){for(const e of this._workerInfos)e.workerPromise.then(t=>{t.terminate()});this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then(i=>{t(i,()=>{const r=this._pendingActions.shift();r?this._execute(e,r):e.idle=!0})})}}class k5 extends Q2e{constructor(e,t,i=k5.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(a=>{a.terminate()});const s=this._workerInfos.indexOf(e);s!==-1&&this._workerInfos.splice(s,1)},this._options.idleTimeElapsedBeforeRelease))})})}}k5.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};var J$;(function(n){n[n.ETC1S=0]="ETC1S",n[n.UASTC4x4=1]="UASTC4x4"})(J$||(J$={}));var a8;(function(n){n[n.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",n[n.BC7_RGBA=1]="BC7_RGBA",n[n.BC3_RGBA=2]="BC3_RGBA",n[n.BC1_RGB=3]="BC1_RGB",n[n.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",n[n.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",n[n.ETC2_RGBA=6]="ETC2_RGBA",n[n.ETC1_RGB=7]="ETC1_RGB",n[n.RGBA32=8]="RGBA32",n[n.R8=9]="R8",n[n.RG8=10]="RG8"})(a8||(a8={}));var Wz;(function(n){n[n.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",n[n.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",n[n.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",n[n.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",n[n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",n[n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",n[n.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",n[n.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",n[n.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",n[n.RGBA8Format=32856]="RGBA8Format",n[n.R8Format=33321]="R8Format",n[n.RG8Format=33323]="RG8Format"})(Wz||(Wz={}));function jz(n,e){const t=(e==null?void 0:e.jsDecoderModule)||KTX2DECODER;n&&(n.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmModuleURL=n.wasmUASTCToASTC),n.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmModuleURL=n.wasmUASTCToBC7),n.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=n.wasmUASTCToRGBA_UNORM),n.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=n.wasmUASTCToRGBA_SRGB),n.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=n.wasmUASTCToR8_UNORM),n.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=n.wasmUASTCToRG8_UNORM),n.jsMSCTranscoder&&(t.MSCTranscoder.JSModuleURL=n.jsMSCTranscoder),n.wasmMSCTranscoder&&(t.MSCTranscoder.WasmModuleURL=n.wasmMSCTranscoder),n.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmModuleURL=n.wasmZSTDDecoder)),e&&(e.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmBinary=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmBinary=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(t.MSCTranscoder.JSModule=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(t.MSCTranscoder.WasmBinary=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmBinary=e.wasmZSTDDecoder))}function eLe(n){typeof n>"u"&&typeof KTX2DECODER<"u"&&(n=KTX2DECODER);let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{const i=t.data.urls;i&&(i.jsDecoderModule&&typeof n>"u"&&(importScripts(i.jsDecoderModule),n=KTX2DECODER),jz(i)),t.data.wasmBinaries&&jz(void 0,{...t.data.wasmBinaries,jsDecoderModule:n}),e=new n.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{n.KTX2Decoder.DefaultDecoderOptions=t.data.options;break}case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(i=>{const r=[];for(let s=0;s{postMessage({action:"decoded",success:!1,msg:i})});break}}}function tLe(n,e,t){return new Promise((i,r)=>{const s=o=>{n.removeEventListener("error",s),n.removeEventListener("message",a),r(o)},a=o=>{o.data.action==="init"&&(n.removeEventListener("error",s),n.removeEventListener("message",a),i(n))};n.addEventListener("error",s),n.addEventListener("message",a),n.postMessage({action:"init",urls:t,wasmBinaries:e})})}class $2e{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;const e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[a8.BC1_RGB,a8.BC3_RGBA],yes:{transcodeFormat:a8.RGBA32,engineFormat:Wz.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class bs{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(bs._WorkerPoolPromise||bs._DecoderModulePromise)return;const t={jsDecoderModule:Ee.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:Ee.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:Ee.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:Ee.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:Ee.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:Ee.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:Ee.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:Ee.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:Ee.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:Ee.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&typeof Worker=="function"&&typeof URL<"u"?bs._WorkerPoolPromise=new Promise(i=>{const r=`${jz}(${eLe})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new k5(e,()=>tLe(new Worker(s),void 0,t)))}):typeof bs._KTX2DecoderModule>"u"?bs._DecoderModulePromise=Ee.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(bs._KTX2DecoderModule=KTX2DECODER,bs._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,bs._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,jz(t,bs._KTX2DecoderModule),new bs._KTX2DecoderModule.KTX2Decoder)):(bs._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,bs._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,bs._DecoderModulePromise=Promise.resolve(new bs._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=bs.DefaultNumWorkers){var i;if(this._engine=e,typeof t=="object"&&t.workerPool)bs._WorkerPoolPromise=Promise.resolve(t.workerPool);else{typeof t=="object"?bs._KTX2DecoderModule=(i=t==null?void 0:t.binariesAndModulesContainer)==null?void 0:i.jsDecoderModule:typeof KTX2DECODER<"u"&&(bs._KTX2DecoderModule=KTX2DECODER);const r=typeof t=="number"?t:t.numWorkers??bs.DefaultNumWorkers;bs._Initialize(r)}}_uploadAsync(e,t,i){const r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(bs._WorkerPoolPromise)return bs._WorkerPoolPromise.then(a=>new Promise((o,c)=>{a.push((l,h)=>{const u=p=>{l.removeEventListener("error",u),l.removeEventListener("message",d),c(p),h()},d=p=>{if(p.data.action==="decoded"){if(l.removeEventListener("error",u),l.removeEventListener("message",d),!p.data.success)c({message:p.data.msg});else try{this._createTexture(p.data.decodedData,t,i),o()}catch(_){c({message:_})}h()}};l.addEventListener("error",u),l.addEventListener("message",d),l.postMessage({action:"setDefaultDecoderOptions",options:bs.DefaultDecoderOptions._getKTX2DecoderOptions()});const f=new Uint8Array(e.byteLength);f.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),l.postMessage({action:"decode",data:f,caps:s,options:i},[f.buffer])})}));if(bs._DecoderModulePromise)return bs._DecoderModulePromise.then(a=>(bs.DefaultDecoderOptions.isDirty&&(bs._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=bs.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((o,c)=>{a.decode(e,r).then(l=>{this._createTexture(l,t),o()}).catch(l=>{c({message:l})})})));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let s=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,s=!1;break}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let a=0;a=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===50&&t[6]===48&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}}bs.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null};bs.DefaultNumWorkers=bs.GetDefaultNumWorkers();bs.DefaultDecoderOptions=new $2e;function iLe(n){switch(n){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}class Z2e{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||t==="image/ktx"||t==="image/ktx2"}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const s=t.getEngine(),a=new Bc(e,6),o=a.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(t,t.generateMipMaps),t.width=a.pixelWidth,t.height=a.pixelHeight,s._setCubeMapTextureParams(t,o,a.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(Bc.IsValid(e)){t._invertVScale=!t.invertY;const s=new Bc(e,1),a=iLe(s.glInternalFormat);a?(t.format=a,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,()=>{s.uploadLevels(t,t.generateMipMaps)},s.isInvalid)}else bs.IsValid(e)?new bs(t.getEngine())._uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},a=>{de.Warn(`Failed to load KTX2 texture data: ${a.message}`),i(0,0,!1,!1,()=>{},!0)}):(de.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}De._TextureLoaders.unshift(new Z2e);class Y8 extends El{constructor(e,t,i){super(e,P.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=we.Identity(),this._referencedPosition=new P,this._trackingState=Cy.NOT_TRACKING,this.onXRCameraInitializedObservable=new Ae,this.onBeforeCameraTeleport=new Ae,this.onAfterCameraTeleport=new Ae,this.onTrackingStateChanged=new Ae,this.compensateOnFirstFrame=!0,this._rotate180=new we(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new we,this.cameraRigMode=Rt.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add(()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame,this._xrSessionManager.onWorldScaleFactorChangedObservable.add(()=>{this._xrSessionManager.currentFrame&&this._updateDepthNearFar()})}),this._xrSessionManager.onXRFrameObservable.add(()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()},void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y*this._xrSessionManager.worldScalingFactor:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new bl(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new bl(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){if(!e||e===this)return;e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,we.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){const t=ie.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),we.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateDepthNearFar(){const e=(this.maxZ||1e4)*this._xrSessionManager.worldScalingFactor,t={depthFar:e,depthNear:this.minZ};this._xrSessionManager.updateRenderState(t),this._cache.minZ=this.minZ,this._cache.maxZ=e}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(Cy.NOT_TRACKING);return}const t=e.emulatedPosition?Cy.TRACKING_LOST:Cy.TRACKING;if(this._setTrackingState(t),(this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ)&&this._updateDepthNearFar(),e.transform){const i=e.transform.orientation;if(e.transform.orientation.x===void 0)return;const r=e.transform.position;this._referencedPosition.set(r.x,r.y,r.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(i.x,i.y,i.z,i.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach((i,r)=>{var h;const s=this.rigCameras[r];!s.isLeftCamera&&!s.isRightCamera&&(i.eye==="right"?s._isRightCamera=!0:i.eye==="left"&&(s._isLeftCamera=!0));const a=this.getScene().customRenderTargets;for(let u=0;ue;){const t=this.rigCameras.pop();t&&t.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=ie.Matrix[0],t=ie.Matrix[1],i=ie.Matrix[2];ce.ComposeToRef(Y8._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),ce.ComposeToRef(Y8._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const r=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(r)}}}Y8._ScaleReadOnly=P.One();class KG{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new Ae,this.onStateChangedObservable=new Ae,this.state=to.NOT_IN_XR,this.sessionManager=new c9(e),this.camera=new Y8("webxr",e,this.sessionManager),this.featuresManager=new vn(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){const t=new KG(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(i=>{throw t._setState(to.NOT_IN_XR),t.dispose(),i})}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),(e=this._spectatorCamera)==null||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),r={}){var s,a,o;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(to.ENTERING_XR),t!=="viewer"&&t!=="local"&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),e==="immersive-ar"&&t!=="unbounded"&&de.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);const c={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(pr.LAYERS)){const l=await i.initializeXRLayerAsync(this.sessionManager.session);c.baseLayer=l}return this.sessionManager.updateRenderState(c),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!((a=(s=this._nonVRCamera)==null?void 0:s.inputs)!=null&&a.attachedToElement),(o=this._nonVRCamera)==null||o.detachControl(),this._scene.activeCamera=this.camera,e!=="immersive-ar"?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce(()=>{this.state!==to.EXITING_XR&&this._setState(to.EXITING_XR),this.camera.rigCameras.forEach(l=>{l.outputRenderTarget=null}),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),e!=="immersive-ar"&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(to.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(to.IN_XR)}),this.sessionManager}catch(c){throw de.Log(c),de.Log(c.message),this._setState(to.NOT_IN_XR),c}}exitXRAsync(){return this.state!==to.IN_XR?Promise.resolve():(this._setState(to.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const i=1/(e!=null&&e.fps?e.fps:1e3)*1e3,r=e!=null&&e.preferredCameraIndex?e==null?void 0:e.preferredCameraIndex:0,s=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[r].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[r].absoluteRotation))};if(this._spectatorMode){if(r>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const a=()=>{this.state===to.IN_XR?(this._spectatorCamera=new h4("webxr-spectator",P.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new we,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(s),this._scene.onAfterRenderCameraObservable.add(o=>{o===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===to.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=null)};this.onStateChangedObservable.add(a),a()}else this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class Yh{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new Ae,this.onButtonStateChangedObservable=new Ae}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return this._axesIndices.length!==0}isButton(){return this._buttonIndex!==-1}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const r=e.buttons[this._buttonIndex];if(!r)return;this._currentValue!==r.value&&(this.changes.value={current:r.value,previous:this._currentValue},t=!0,this._currentValue=r.value),this._touched!==r.touched&&(this.changes.touched={current:r.touched,previous:this._touched},t=!0,this._touched=r.touched),this._pressed!==r.pressed&&(this.changes.pressed={current:r.pressed,previous:this._pressed},t=!0,this._pressed=r.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}Yh.BUTTON_TYPE="button";Yh.SQUEEZE_TYPE="squeeze";Yh.THUMBSTICK_TYPE="thumbstick";Yh.TOUCHPAD_TYPE="touchpad";Yh.TRIGGER_TYPE="trigger";class J6{constructor(e,t,i,r,s=!1,a){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=a,this._initComponent=o=>{if(!o)return;const c=this.layout.components[o],l=c.type,h=c.gamepadIndices.button,u=[];c.gamepadIndices.xAxis!==void 0&&c.gamepadIndices.yAxis!==void 0&&u.push(c.gamepadIndices.xAxis,c.gamepadIndices.yAxis),this.components[o]=new Yh(o,l,h,u)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new Ae,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach(e=>this.getComponent(e).dispose()),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach(e=>{e.setEnabled(!1)}),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map(t=>this.components[t]).filter(t=>t.type===e)}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?de.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,r)=>{const s=a=>{e?this._getGenericParentMesh(a):this._setRootMesh(a),this._processLoadedModel(a),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const a=this._controllerCache.filter(o=>o.filename===t.filename&&o.path===t.path);if(a[0]){a[0].meshes.forEach(o=>o.setEnabled(!0)),s(a[0].meshes);return}}ai.ImportMesh("",t.path,t.filename,this.scene,a=>{this._controllerCache&&this._controllerCache.push({...t,meshes:a}),s(a)},null,(a,o)=>{de.Log(o),de.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(o)})})}updateFromXRFrame(e){this.getComponentIds().forEach(t=>this.getComponent(t).update(this.gamepadObject)),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren(i=>i.name===t,!1)[0]}_getImmediateChildByName(e,t){return e.getChildren(i=>i.name==t,!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh||!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const r=i?t*.5+.5:t;we.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),P.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new Se(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.parent||(t.isPickable=!1,t.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=we.FromEulerAngles(0,Math.PI,0)}}class Q8 extends J6{constructor(e,t,i){super(e,rLe[i],t,i),this.profileId=Q8.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new Se(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1,t.parent||t.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=we.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}Q8.ProfileId="generic-trigger";const rLe={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class q2e extends J6{constructor(e,t,i,r,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=r,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach(e=>{this._touchDots[e].dispose()})}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=ai.IsPluginForExtensionAvailable(".glb");return e||de.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach(t=>{const i=this.layout.components[t];this._buttonMeshMapping[t]={mainMesh:this._getChildByName(this.rootMesh,i.rootNodeName),states:{}},Object.keys(i.visualResponses).forEach(r=>{const s=i.visualResponses[r];if(s.valueNodeProperty==="transform")this._buttonMeshMapping[t].states[r]={valueMesh:this._getChildByName(this.rootMesh,s.valueNodeName),minMesh:this._getChildByName(this.rootMesh,s.minNodeName),maxMesh:this._getChildByName(this.rootMesh,s.maxNodeName)};else{const a=i.type===Yh.TOUCHPAD_TYPE&&i.touchPointNodeName?i.touchPointNodeName:s.valueNodeName;if(this._buttonMeshMapping[t].states[r]={valueMesh:this._getChildByName(this.rootMesh,a)},i.type===Yh.TOUCHPAD_TYPE&&!this._touchDots[r]){const o=Tl(r+"dot",{diameter:.0015,segments:8},this.scene);o.material=new tt(r+"mat",this.scene),o.material.diffuseColor=Me.Red(),o.parent=this._buttonMeshMapping[t].states[r].valueMesh||null,o.isVisible=!1,this._touchDots[r]=o}}})})}_setRootMesh(e){this.rootMesh=new Se(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;i{const i=this.getComponent(t);if(!i.hasChanges)return;const r=this._buttonMeshMapping[t],s=this.layout.components[t];Object.keys(s.visualResponses).forEach(a=>{const o=s.visualResponses[a];let c=i.value;if(o.componentProperty==="xAxis"?c=i.axes.x:o.componentProperty==="yAxis"&&(c=i.axes.y),o.valueNodeProperty==="transform")this._lerpTransform(r.states[a],c,o.componentProperty!=="button");else{const l=r.states[a].valueMesh;l&&(l.isVisible=i.touched||i.pressed),this._touchDots[a]&&(this._touchDots[a].isVisible=i.touched||i.pressed)}})})}}const bY=[];class So{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const r=[];if(i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id)switch(e.gamepad.id){case(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0):r.push("oculus-touch-v2");break}const s=r.indexOf("windows-mixed-reality");if(s!==-1&&r.splice(s,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),this.UseOnlineRepository){const a=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,o=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return a.call(this,r,e,t).catch(()=>o.call(this,r,e,t))}else return this._LoadProfilesFromAvailableControllers(r,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=Ee.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e)),this._ProfilesList}static ClearControllerCache(){bY.forEach(e=>{e.meshes.forEach(t=>{t.dispose(!1,!0)})}),bY.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(r=>{for(let s=0;s(this._ProfileLoadingPromises[r]||(this._ProfileLoadingPromises[r]=Ee.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${r}/profile.json`,!1).then(s=>JSON.parse(s))),this._ProfileLoadingPromises[r])).then(r=>new q2e(i,t,r,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:bY))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;rnew Q8(e,n.gamepad,n.handedness));So.DefaultFallbacks();let sLe=0;class J2e{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new P,this._disposed=!1,this.onDisposeObservable=new Ae,this.onMeshLoadedObservable=new Ae,this.onMotionControllerInitObservable=new Ae,this._uniqueId=`controller-${sLe++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new di(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new we,this.inputSource.gripSpace&&(this.grip=new di(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new we),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&this.inputSource.targetRayMode==="tracked-pointer"&&So.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(r=>{this.motionController=r,this.onMotionControllerInitObservable.notifyObservers(r),!this._options.doNotLoadControllerMesh&&!this.motionController._doNotLoadControllerMesh&&this.motionController.loadModel().then(s=>{var a;s&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach(o=>o.renderingGroupId=this._options.renderingGroupId)),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&((a=this.motionController)==null||a.dispose())})},()=>{Ee.Warn("Could not find a matching motion controller for the registered input source")})}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;P.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,r){const s=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=s,s){const a=s.transform.position;this.pointer.position.set(a.x,a.y,a.z).scaleInPlace(r.worldScalingFactor);const o=s.transform.orientation;this.pointer.rotationQuaternion.set(o.x,o.y,o.z,o.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(r.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const a=e.getPose(this.inputSource.gripSpace,t);if(a){const o=a.transform.position,c=a.transform.orientation;this.grip.position.set(o.x,o.y,o.z).scaleInPlace(r.worldScalingFactor),this.grip.rotationQuaternion.set(c.x,c.y,c.z,c.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(r.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class ege{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new Ae,this.onControllerRemovedObservable=new Ae,this._onInputSourcesChange=r=>{this._addAndRemoveControllers(r.added,r.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(()=>{this._addAndRemoveControllers([],this.controllers.map(r=>r.inputSource))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(r=>{r.addEventListener("inputsourceschange",this._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(r=>{this.controllers.forEach(s=>{s.updateFromXRFrame(r,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)})}),this._options.customControllersRepositoryURL&&(So.BaseRepositoryUrl=this._options.customControllersRepositoryURL),So.UseOnlineRepository=!this._options.disableOnlineControllerRepository,So.UseOnlineRepository)try{So.UpdateProfilesList().catch(()=>{So.UseOnlineRepository=!1})}catch{So.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map(a=>a.inputSource);for(const a of e)if(i.indexOf(a)===-1){const o=new J2e(this.xrSessionManager.scene,a,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(o),this.onControllerAddedObservable.notifyObservers(o)}const r=[],s=[];this.controllers.forEach(a=>{t.indexOf(a.inputSource)===-1?r.push(a):s.push(a)}),this.controllers=r,s.forEach(a=>{this.onControllerRemovedObservable.notifyObservers(a),a.dispose()})}dispose(){this.controllers.forEach(e=>{e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),So.ClearControllerCache()}}class t1 extends Lo{constructor(e,t){super(e),this._options=t,this._attachController=i=>{if(this._controllers[i.uniqueId])return;const{laserPointer:r,selectionMesh:s}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&i.grip?i.grip:i.pointer);switch(this._controllers[i.uniqueId]={xrController:i,laserPointer:r,selectionMesh:s,meshUnderPointer:null,pick:null,tmpRay:new Fi(new P,new P),disabledByNearInteraction:!1,id:t1._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&i.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=i.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=i.uniqueId),i.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(i);case"gaze":return this._attachGazeMode(i);case"screen":case"transient-pointer":return this._attachScreenRayMode(i)}},this._controllers={},this._tmpVectorForPickCompare=new P,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Me(.9,.9,.9),this.laserPointerDefaultColor=new Me(.7,.7,.7),this.selectionMeshDefaultColor=new Me(.8,.8,.8),this.selectionMeshPickedColor=new Me(.3,.3,1),this._identityMatrix=ce.Identity(),this._screenCoordinatesRef=P.Zero(),this._viewportRef=new bl(0,0,0,0),this._scene=this._xrSessionManager.scene,this._options.lookAndPickMode===void 0&&(this._scene.getEngine()._badDesktopOS||this._scene.getEngine()._badOS)&&(this._options.lookAndPickMode=!0),this._options.lookAndPickMode&&(this._options.enablePointerSelectionOnAllControllers=!0,this.displayLaserPointer=!1)}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController,!0),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)},!0),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Fi(new P,new P),disabledByNearInteraction:!1,id:t1._IdCounter++},this._attachGazeMode()}return!0}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0):!1}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{var c;const i=this._controllers[t];if(this._options.lookAndPickMode&&((c=i.xrController)==null?void 0:c.inputSource.targetRayMode)!=="transient-pointer")return;if(!this._options.enablePointerSelectionOnAllControllers&&t!==this._attachedController||i.disabledByNearInteraction){i.selectionMesh.isVisible=!1,i.laserPointer.isVisible=!1,i.pick=null;return}i.laserPointer.isVisible=this.displayLaserPointer;let r;if(i.xrController)r=this._options.forceGripIfAvailable&&i.xrController.grip?i.xrController.grip.position:i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay,this._options.forceGripIfAvailable);else if(i.webXRCamera)r=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay);else return;if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&r){const l=this._xrSessionManager.scene,h=this._options.xrInput.xrCamera;h&&(h.viewport.toGlobalToRef(l.getEngine().getRenderWidth()/h.rigCameras.length,l.getEngine().getRenderHeight(),this._viewportRef),P.ProjectToRef(r,this._identityMatrix,h.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),typeof this._screenCoordinatesRef.x=="number"&&typeof this._screenCoordinatesRef.y=="number"&&!isNaN(this._screenCoordinatesRef.x)&&!isNaN(this._screenCoordinatesRef.y)&&this._screenCoordinatesRef.x!==1/0&&this._screenCoordinatesRef.y!==1/0&&(l.pointerX=this._screenCoordinatesRef.x,l.pointerY=this._screenCoordinatesRef.y,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let s=null;this._utilityLayerScene&&(s=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const a=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);!s||!s.hit?i.pick=a:!a||!a.hit||s.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,a.isVisible=!1,t.pick.hit)if(this._pickingMoved(s,t.pick))c&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),c=!1,o=0;else if(o>i/10&&(a.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),c=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),a.isVisible=!1;else{const h=1-o/i;a.scaling.set(h,h,h)}else c=!1,o=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}}),this._options.renderingGroupId!==void 0&&(a.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&c&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),a.dispose()})}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),!(!t.pick||this._options.disablePointerUpOnTouchOut&&i)&&(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)})})}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))}),e.inputSource.gamepad){const r=s=>{this._options.overrideButtonId&&(t.selectionComponent=s.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=s.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(a=>{if(a.changes.pressed){const o=a.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),o?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)):o&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick&&(this._attachedController=e.uniqueId)}})};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{const r=a=>{this._xrSessionManager.onXRFrameObservable.addOnce(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&a.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)})},s=a=>{this._xrSessionManager.onXRFrameObservable.addOnce(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&a.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)})};t.eventListeners={selectend:s,selectstart:r},this._xrSessionManager.session.addEventListener("selectstart",r),this._xrSessionManager.session.addEventListener("selectend",s)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(P.Dot(e,t.direction)){const r=t.eventListeners&&t.eventListeners[i];r&&this._xrSessionManager.session.removeEventListener(i,r)}),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const i={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new Ro,i),t.finalPointerUpTriggered=!0})}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const i=Object.keys(this._controllers);i.length?this._attachedController=i[0]:this._attachedController=""}}catch{Ee.Warn("controller already detached.")}})}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Or.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():dc("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const r=new tt("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():o1("gazeTracker",{diameter:.0035*3,thickness:.0025*3,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;const a=new tt("targetMat",t);return a.specularColor=Me.Black(),a.emissiveColor=this.selectionMeshDefaultColor,a.backFaceCulling=!1,s.material=a,this._options.renderingGroupId!==void 0&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var s;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;(s=e.pickedPoint)==null||s.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const i=(this._options.gazeModePointerMovedFactor||1)*.01*t.distance;return this._tmpVectorForPickCompare.length()>i}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}t1._IdCounter=200;t1.Name=pr.POINTER_SELECTION;t1.Version=1;vn.AddWebXRFeature(t1.Name,(n,e)=>()=>new t1(n,e),t1.Version,!0);Xo.prototype._projectOnTrianglesToRef=function(n,e,t,i,r,s){const a=ie.Vector3[0],o=ie.Vector3[1];let c=1/0;for(let l=this.indexStart;l{if(this._controllers[i.uniqueId])return;const{touchCollisionMesh:r,touchCollisionMeshFunction:s,hydrateCollisionMeshFunction:a}=this._generateNewTouchPointMesh(),o=this._generateVisualCue();switch(this._controllers[i.uniqueId]={xrController:i,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:r,touchCollisionMeshFunction:s,hydrateCollisionMeshFunction:a,currentAnimationState:mu.DEHYDRATED,grabRay:new Fi(new P,new P),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:i1._IdCounter++,pickedPointVisualCue:o},this._controllers[i.uniqueId]._worldScaleObserver=this._controllers[i.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add(c=>{if(c.newScaleFactor!==c.previousScaleFactor){this._controllers[i.uniqueId].touchCollisionMesh.dispose(),this._controllers[i.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:l,touchCollisionMeshFunction:h,hydrateCollisionMeshFunction:u}=this._generateNewTouchPointMesh();this._controllers[i.uniqueId].touchCollisionMesh=l,this._controllers[i.uniqueId].touchCollisionMeshFunction=h,this._controllers[i.uniqueId].hydrateCollisionMeshFunction=u,this._controllers[i.uniqueId].pickedPointVisualCue=this._generateVisualCue()}}),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&i.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=i.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=i.uniqueId),i.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(i);case"gaze":return null;case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new Me(.8,.8,.8),this.selectionMeshPickedColor=new Me(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,this._options.nearInteractionControllerMode===void 0&&(this._options.nearInteractionControllerMode=b3.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return super.attach()?(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,!0):!1}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0):!1}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case mu.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===mu.HOVER)break;case mu.HOVER:if(e.touchCollisionMeshFunction(!0),t===mu.TOUCH)break}else switch(e.currentAnimationState){case mu.TOUCH:if(e.touchCollisionMeshFunction(!1),t===mu.HOVER)break;case mu.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===mu.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var s;const r=this._controllers[e];r.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(ie.Vector3[0]),r.grabRay.direction.copyFrom(ie.Vector3[0]),this._options.nearInteractionControllerMode===b3.CENTERED_IN_FRONT&&!((s=r.xrController)!=null&&s.inputSource.hand)&&(r.xrController.getWorldPointerRayToRef(this._tmpRay),r.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),r.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,r.touchCollisionMesh.position.copyFrom(r.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var c;const i=this._controllers[t],r=(c=i.xrController)==null?void 0:c.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!r&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad)){i.pick=null;return}if(i.hoverInteraction=!1,i.nearInteraction=!1,i.xrController){if(r){const l=r.get("index-finger-tip");if(l){const h=e.getJointPose(l,this._xrSessionManager.referenceSpace);if(h&&h.transform){const u=this._scene.useRightHandedSystem?1:-1;ie.Vector3[0].set(h.transform.position.x,h.transform.position.y,h.transform.position.z*u),ie.Quaternion[0].set(h.transform.orientation.x,h.transform.orientation.y,h.transform.orientation.z*u,h.transform.orientation.w*u),this._processTouchPoint(t,ie.Vector3[0],ie.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==b3.DISABLED){let l=i.xrController.pointer;i.xrController.grip&&this._options.nearInteractionControllerMode===b3.CENTERED_ON_CONTROLLER&&(l=i.xrController.grip),this._processTouchPoint(t,l.position,l.rotationQuaternion)}}else return;const s=(l,h)=>{let u=null;return!h||!h.hit?u=l:!l||!l.hit||h.distance{let h=new Ro,u=!1;const d=l&&l.pickedPoint&&l.hit;return l!=null&&l.pickedPoint&&(u=l.pickedPoint.x===0&&l.pickedPoint.y===0&&l.pickedPoint.z===0),d&&!u&&(h=l),h};if(!i.grabInteraction){let l=null,h=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(h=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,f=>this._nearInteractionPredicate(f)));const u=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,f=>this._nearInteractionPredicate(f)),d=s(u,h);if(d&&d.hit&&(l=a(d),l.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let f=null;const p=(r?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(f=this._pickWithSphere(i,p,this._utilityLayerScene,v=>this._nearPickPredicate(v)));const _=this._pickWithSphere(i,p,this._scene,v=>this._nearPickPredicate(v)),m=s(_,f),g=a(m);g.hit&&(l=g,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=l,i.pick&&i.pick.pickedPoint&&i.pick.hit?(i.meshUnderPointer=i.pick.pickedMesh,i.pickedPointVisualCue.position.copyFrom(i.pick.pickedPoint),i.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!0)):(i.meshUnderPointer=null,i.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!1))}let o=mu.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=mu.TOUCH:i.hoverInteraction&&(o=mu.HOVER),this._handleTransitionAnimation(i,o)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Or.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Or.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Tl("nearInteraction",{diameter:.0035*3*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=we.Identity();const i=new tt("targetMat",e);return i.specularColor=Me.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return this._farInteractionFeature?this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e):!0}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{!this._options.enableNearInteractionOnAllControllers&&e.uniqueId!==this._attachedController||!t.xrController||!t.xrController.inputSource.hand&&(!this._options.nearInteractionControllerMode||!t.xrController.inputSource.gamepad)||(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))});const r=s=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),s&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!s&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):s&&!this._options.enableNearInteractionOnAllControllers&&!this._options.disableSwitchOnClick&&(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const s=a=>{t.squeezeComponent=a.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const c=o.changes.pressed.current;r(c)}}):(t.selectionComponent=a.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const c=o.changes.pressed.current;r(c)}}))};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const s=o=>{t.xrController&&o.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0)},a=o=>{t.xrController&&o.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0,t.downTriggered=!1)};t.eventListeners={selectend:a,selectstart:s},this._xrSessionManager.session.addEventListener("selectstart",s),this._xrSessionManager.session.addEventListener("selectend",a)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach(i=>{const r=t.eventListeners&&t.eventListeners[i];r&&this._xrSessionManager.session.removeEventListener(i,r)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{if(!t.downTriggered)return;const i={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new Ro,i)}),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const i=Object.keys(this._controllers);i.length?this._attachedController=i[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Or.DefaultUtilityLayer.utilityLayerScene:this._scene,i=Tl("PickSphere",{diameter:1*e},t);i.isVisible=!1,this._options.motionControllerOrbMaterial?i.material=this._options.motionControllerOrbMaterial:Ss.ParseFromSnippetAsync("8RUNKL#3",t).then(S=>{i.material=S});const r=new NJ;r.setEasingMode(Un.EASINGMODE_EASEINOUT);const s=new P(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),a=this._controllerPickRadius*(4/3),o=new P(a,a,a).scaleInPlace(e),c=this._controllerPickRadius*(7/6),l=new P(c,c,c).scaleInPlace(e),h=this._controllerPickRadius*(4/5),u=new P(h,h,h).scaleInPlace(e),d=this._controllerPickRadius*(3/2),f=new P(d,d,d).scaleInPlace(e),p=[{frame:0,value:s},{frame:10,value:f},{frame:18,value:o}],_=[{frame:0,value:o},{frame:10,value:u},{frame:18,value:s}],m=[{frame:0,value:P.ZeroReadOnly},{frame:12,value:l},{frame:15,value:s}],g=[{frame:0,value:s},{frame:10,value:P.ZeroReadOnly},{frame:15,value:P.ZeroReadOnly}],v=new ke("touch","scaling",60,ke.ANIMATIONTYPE_VECTOR3,ke.ANIMATIONLOOPMODE_CONSTANT),x=new ke("release","scaling",60,ke.ANIMATIONTYPE_VECTOR3,ke.ANIMATIONLOOPMODE_CONSTANT),y=new ke("hydrate","scaling",60,ke.ANIMATIONTYPE_VECTOR3,ke.ANIMATIONLOOPMODE_CONSTANT),C=new ke("dehydrate","scaling",60,ke.ANIMATIONTYPE_VECTOR3,ke.ANIMATIONLOOPMODE_CONSTANT);return v.setEasingFunction(r),x.setEasingFunction(r),y.setEasingFunction(r),C.setEasingFunction(r),v.setKeys(p),x.setKeys(_),y.setKeys(m),C.setKeys(g),{touchCollisionMesh:i,touchCollisionMeshFunction:S=>{const N=S?v:x;t.beginDirectAnimation(i,[N],0,18,!1,1)},hydrateCollisionMeshFunction:S=>{const N=S?y:C;S&&(i.isVisible=!0),t.beginDirectAnimation(i,[N],0,15,!1,1,()=>{S||(i.isVisible=!1)})}}}_pickWithSphere(e,t,i,r){const s=new Ro;if(s.distance=1/0,e.touchCollisionMesh&&e.xrController){const a=e.touchCollisionMesh.position,o=e1.CreateFromCenterAndRadius(a,t);for(let c=0;cd&&(u=0,c.copyFrom(t.center)),u!==-1&&u()=>new i1(n,e),i1.Version,!0);class tge{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class nLe{}class WG{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new Ae,this._onSessionGranted=r=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),typeof window<"u"&&window.location&&window.location.protocol==="http:"&&window.location.hostname!=="localhost")throw Ee.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const r=t.sessionMode||"immersive-vr",s=t.referenceSpaceType||"local-floor";let o=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(typeof SVGSVGElement>"u"?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";o+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const c=document.createElement("style");c.appendChild(document.createTextNode(o)),document.getElementsByTagName("head")[0].appendChild(c);const l=document.createElement("button");l.className="babylonVRicon",l.title=`${r} - ${s}`,this._buttons.push(new tge(l,r,s)),this._buttons[this._buttons.length-1].update=function(h){this.element.style.display=h===null||h===this?"":"none",l.className="babylonVRicon"+(h===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce(()=>{this.dispose()}))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map(s=>e.sessionManager.isSessionSupportedAsync(s.sessionMode));e.onStateChangedObservable.add(s=>{s==to.NOT_IN_XR&&this._updateButtons(null)}),(await Promise.all(i)).forEach((s,a)=>{s?(this.overlay.appendChild(this._buttons[a].element),this._buttons[a].element.onclick=this._enterXRWithButtonIndex.bind(this,a)):Ee.Warn(`Session mode "${this._buttons[a].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){const r=new WG(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(this._helper.state==to.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==to.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,r=i.title;i.title="Error entering XR session : "+r,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach(t=>{t.update(this._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}var E3;(function(n){n[n.INIT=0]="INIT",n[n.STARTED=1]="STARTED",n[n.ENDED=2]="ENDED"})(E3||(E3={}));function qw(n){let e=0;const t=Date.now();n.observableParameters=n.observableParameters??{};const i=n.contextObservable.add(r=>{const s=Date.now();e=s-t;const a={startTime:t,currentTime:s,deltaTime:e,completeRate:e/n.timeout,payload:r};n.onTick&&n.onTick(a),n.breakCondition&&n.breakCondition()&&(n.contextObservable.remove(i),n.onAborted&&n.onAborted(a)),e>=n.timeout&&(n.contextObservable.remove(i),n.onEnded&&n.onEnded(a))},n.observableParameters.mask,n.observableParameters.insertFirst,n.observableParameters.scope);return i}class ige{constructor(e){this.onEachCountObservable=new Ae,this.onTimerAbortedObservable=new Ae,this.onTimerEndedObservable=new Ae,this.onStateChangedObservable=new Ae,this._observer=null,this._breakOnNextTick=!1,this._tick=t=>{const i=Date.now();this._timer=i-this._startTime;const r={startTime:this._startTime,currentTime:i,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:t},s=this._breakOnNextTick||this._breakCondition(r);s||this._timer>=this._timeToEnd?this._stop(r,s):this.onEachCountObservable.notifyObservers(r)},this._setState(E3.INIT),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===E3.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(E3.STARTED)}stop(){this._state===E3.STARTED&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(E3.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class ky extends Lo{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,i=>i.name==="rotationCone");t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new Ze(1,1,1,1),this._tmpRay=new Fi(new P,new P),this._tmpVector=new P,this._tmpQuaternion=new we,this._worldScaleObserver=null,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new Ae,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new Ae,this.onAfterCameraTeleportRotation=new Ae,this._attachController=i=>{if(this._controllers[i.uniqueId]||this._options.forceHandedness&&i.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[i.uniqueId]={xrController:i,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const r=this._controllers[i.uniqueId];if(r.xrController.inputSource.targetRayMode==="tracked-pointer"&&r.xrController.inputSource.gamepad){const s=()=>{if(i.motionController){const a=i.motionController.getComponentOfType(Yh.THUMBSTICK_TYPE)||i.motionController.getComponentOfType(Yh.TOUCHPAD_TYPE);if(!a||this._options.useMainComponentOnly){const o=i.motionController.getMainComponent();if(!o)return;r.teleportationState.mainComponentUsed=!0,r.teleportationComponent=o,r.onButtonChangedObserver=o.onButtonStateChangedObservable.add(()=>{if(!this.teleportationEnabled)return;const c=()=>{r.teleportationState.forward=!0,r.teleportationState.initialHit=!1,this._currentTeleportationControllerId=r.xrController.uniqueId,r.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,r.teleportationState.currentRotation=0;const l=this._options.timeToTeleport||3e3;qw({timeout:l,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!o.pressed,onEnded:()=>{this._currentTeleportationControllerId===r.xrController.uniqueId&&r.teleportationState.forward&&this._teleportForward(i.uniqueId)}})};o.changes.pressed&&(o.changes.pressed.current?this._options.timeToTeleportStart?qw({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{o.pressed&&c()}}):c():(r.teleportationState.forward=!1,this._currentTeleportationControllerId=""))})}else r.teleportationComponent=a,r.onAxisChangedObserver=a.onAxisValueChangedObservable.add(o=>{if(o.y<=.7&&r.teleportationState.backwards&&(r.teleportationState.backwards=!1),o.y>.7&&!r.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!r.teleportationState.backwards){r.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,we.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const c=this._xrSessionManager.scene.pickWithRay(this._tmpRay,l=>this._floorMeshes.indexOf(l)!==-1);c&&c.pickedPoint&&(this._options.xrInput.xrCamera.position.x=c.pickedPoint.x,this._options.xrInput.xrCamera.position.z=c.pickedPoint.z)}if(o.y<-.7&&!this._currentTeleportationControllerId&&!r.teleportationState.rotating&&this.teleportationEnabled&&(r.teleportationState.forward=!0,this._currentTeleportationControllerId=r.xrController.uniqueId,r.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),o.x){if(r.teleportationState.forward)this._currentTeleportationControllerId===r.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{r.teleportationState.currentRotation=Math.atan2(o.x,o.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):r.teleportationState.currentRotation=0);else if(!r.teleportationState.rotating&&Math.abs(o.x)>.7){r.teleportationState.rotating=!0;const c=this.rotationAngle*(o.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(c),we.FromEulerAngles(0,c,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else r.teleportationState.rotating=!1;o.x===0&&o.y===0&&(r.teleportationState.blocked&&(r.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),r.teleportationState.forward&&this._teleportForward(i.uniqueId))})}};i.motionController?s():i.onMotionControllerInitObservable.addOnce(()=>{s()})}else{r.teleportationState.mainComponentUsed=!0;let s=!1;const a=()=>{this._currentTeleportationControllerId=r.xrController.uniqueId,r.teleportationState.forward=!0,r.teleportationState.initialHit=!1,r.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,r.teleportationState.currentRotation=0;const o=this._options.timeToTeleport||3e3;qw({timeout:o,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===r.xrController.uniqueId&&r.teleportationState.forward&&this._teleportForward(i.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add(o=>{o.type===ft.POINTERDOWN?(s=!1,this._options.timeToTeleportStart?qw({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===r.xrController.uniqueId&&a()},breakCondition:()=>s?(s=!1,!0):!1}):a()):o.type===ft.POINTERUP&&(s=!0,r.teleportationState.forward=!1,this._currentTeleportationControllerId="")})}},this._colorArray=Array(24).fill(this._cachedColor4White),this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new Ze(1,0,0,.75),this._setTargetMeshVisibility(!1),this.onBeforeCameraTeleport=t.xrInput.xrCamera.onBeforeCameraTeleport,this.onAfterCameraTeleport=t.xrInput.xrCamera.onAfterCameraTeleport,this.parabolicCheckRadius*=this._xrSessionManager.worldScalingFactor,this._worldScaleObserver=e.onWorldScaleFactorChangedObservable.add(i=>{var r;this.parabolicCheckRadius=this.parabolicCheckRadius/i.previousScaleFactor*i.newScaleFactor,(r=this._options.teleportationTargetMesh)==null||r.scaling.scaleInPlace(i.newScaleFactor/i.previousScaleFactor)})}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return super.attach()?(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0):!1}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0):!1}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);t!==-1&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);t!==-1&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(t===-1){for(let i=0;i{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(h)||this._options.blockAllPickableMeshes&&h.isPickable||this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(h)!==-1)return!0;const u=this._floorMeshes.indexOf(h);return u===-1?!1:this._floorMeshes[u].absolutePosition.ythis._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(f)||this._options.blockAllPickableMeshes&&f.isPickable||this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(f)!==-1?!0:this._floorMeshes.indexOf(f)!==-1),d=u&&u.pickedMesh&&this._floorMeshes.indexOf(u.pickedMesh)!==-1;if(u&&u.pickedMesh&&!d){if(s.teleportationState.mainComponentUsed&&!s.teleportationState.initialHit){s.teleportationState.forward=!1;return}s.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,o),this._showParabolicPath(u);return}else u&&u.pickedPoint&&(s.teleportationState.initialHit=!0,s.teleportationState.blocked=!1,a=!0,this._setTargetMeshPosition(u),this._setTargetMeshVisibility(!0,!1,o),this._showParabolicPath(u))}this._setTargetMeshVisibility(a,!1,o)}else this._setTargetMeshVisibility(!1,!1,!0)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1,!1,!0)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Or.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Z6("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const a=new Id("teleportationPlaneDynamicTexture",512,e,!0);a.hasAlpha=!0;const o=a.getContext(),c=512/2,l=512/2,h=200;o.beginPath(),o.arc(c,l,h,0,2*Math.PI,!1),o.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",o.fill(),o.lineWidth=10,o.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",o.stroke(),o.closePath(),a.update();const u=new tt("teleportationPlaneMaterial",e);u.diffuseTexture=a,t.material=u}const i=o1("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const s=new ke("animationInnerCircle","position.y",30,ke.ANIMATIONTYPE_FLOAT,ke.ANIMATIONLOOPMODE_CYCLE),a=[];a.push({frame:0,value:0}),a.push({frame:30,value:.4}),a.push({frame:60,value:0}),s.setKeys(a);const o=new BJ;o.setEasingMode(Un.EASINGMODE_EASEINOUT),s.setEasingFunction(o),i.animations=[],i.animations.push(s),e.beginAnimation(i,0,60,!0)}const r=dc("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate($n.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const s=new tt("torusConsMat",e);s.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,s.disableLighting?s.emissiveColor=new Me(.3,.3,1):s.diffuseColor=new Me(.3,.3,1),s.alpha=.9,i.material=s,r.material=s,this._teleportationRingMaterial=s}this._options.renderingGroupId!==void 0&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){const s=t*t;this._snapToPositions.forEach(a=>{const o=P.DistanceSquared(a,e);o<=s&&o{r.isVisible=e}),e?this._selectionFeature&&i&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&i&&this._selectionFeature.attach())))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Or.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=Cf.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,a=this._colorArray.fill(s||this._cachedColor4White),o=r.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=Us("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:a},t),this._quadraticBezierCurve.isPickable=!1,this._options.renderingGroupId!==void 0&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(!(!t||!t.teleportationState.forward||!this.teleportationEnabled)&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!(this.snapPointsOnly&&!this._snappedToPoint))){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const i=this._options.xrInput.xrCamera.realWorldHeight;this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=i,we.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}}ky.Name=pr.TELEPORTATION;ky.Version=1;vn.AddWebXRFeature(ky.Name,(n,e)=>()=>new ky(n,e),ky.Version,!0);class aLe{}class jG{constructor(){}static CreateAsync(e,t={}){const i=new jG;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){const r={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&(typeof t.optionalFeatures=="boolean"?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new WG(e,r)}return KG.CreateAsync(e).then(r=>{if(i.baseExperience=r,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new ege(r.sessionManager,r.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const s={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(t1.Name,t.useStablePlugins?"stable":"latest",s),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(ky.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}if(t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(i1.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),t.disableHandTracking||i.baseExperience.featuresManager.enableFeature(ss.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),!t.disableDefaultUI)return i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)}).then(()=>i).catch(r=>(de.Error("Error initializing XR"),de.Error(r),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var oLe=!0;pt.prototype.createDefaultLight=function(n=!1){if(n&&this.lights)for(let e=0;ec.isVisible&&c.isEnabled()),r=i.max.subtract(i.min),s=i.min.add(r.scale(.5));let a,o=r.length()*1.5;if(isFinite(o)||(o=1,s.copyFromFloats(0,0,0)),n){const c=new Rr("default camera",-(Math.PI/2),Math.PI/2,o,s,this);c.lowerRadiusLimit=o*.01,c.wheelPrecision=100/o,a=c}else{const c=new El("default camera",new P(s.x,s.y,-o),this);c.setTarget(s),a=c}a.minZ=o*.01,a.maxZ=o*1e3,a.speed=o*.2,this.activeCamera=a,t&&a.attachControl()}};pt.prototype.createDefaultCameraOrLight=function(n=!1,e=!1,t=!1){this.createDefaultLight(e),this.createDefaultCamera(n,e,t)};pt.prototype.createDefaultSkybox=function(n,e=!1,t=1e3,i=0,r=!0){if(!n)return de.Warn("Can not create default skybox without environment texture."),null;r&&n&&(this.environmentTexture=n);const s=zf("hdrSkyBox",{size:t},this);if(e){const a=new Nt("skyBox",this);a.backFaceCulling=!1,a.reflectionTexture=n.clone(),a.reflectionTexture&&(a.reflectionTexture.coordinatesMode=ve.SKYBOX_MODE),a.microSurface=1-i,a.disableLighting=!0,a.twoSidedLighting=!0,s.material=a}else{const a=new tt("skyBox",this);a.backFaceCulling=!1,a.reflectionTexture=n.clone(),a.reflectionTexture&&(a.reflectionTexture.coordinatesMode=ve.SKYBOX_MODE),a.disableLighting=!0,s.material=a}return s.isPickable=!1,s.infiniteDistance=!0,s.ignoreCameraMaxZ=!0,s};pt.prototype.createDefaultEnvironment=function(n){return s4?new s4(n,this):null};pt.prototype.createDefaultVRExperience=function(n={}){return new eA(this,n)};pt.prototype.createDefaultXRExperienceAsync=function(n={}){return jG.CreateAsync(this,n).then(e=>e)};function Lde(n){for(;n.firstChild;)n.removeChild(n.firstChild);n.srcObject=null,n.src="",n.removeAttribute("src")}class wd extends ve{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new Ae),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e==null?void 0:e.message):de.Error(e==null?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if((e==null?void 0:e.name)==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}else if(!this.video.muted){de.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,this.video.play().catch(t=>{this._processError(t)});return}}this._processError(e)})}constructor(e,t,i,r=!1,s=!1,a=ve.TRILINEAR_SAMPLINGMODE,o={},c,l=5){var u;super(null,i,!r,s),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{this._texture!=null&&this._texture.dispose(),!this._getEngine().needPOTTextures||Ee.IsExponentOfTwo(this.video.videoWidth)&&Ee.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=ve.WRAP_ADDRESSMODE,this.wrapV=ve.WRAP_ADDRESSMODE):(this.wrapU=ve.CLAMP_ADDRESSMODE,this.wrapV=ve.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=this._format??5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(this._texture!=null)if(this._displayingPosterTexture)this._displayingPosterTexture=!1;else return;if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),!this.video.autoplay&&!this._settings.poster&&!this._settings.independentVideoSource){const d=this.video.onplaying,f=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=f,this.video.onplaying=d,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}else this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._reset=()=>{this._texture!=null&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(this._texture==null||this.video.readyState=this.video.HAVE_CURRENT_DATA;this._settings.poster&&(!this._settings.autoPlay||!h)?(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0):h&&this._createInternalTexture()}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:typeof e=="object"?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return Ee.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return typeof e=="string"?(Ee.SetCorsBehavior(e,t),t.src=e):(Ee.SetCorsBehavior(e[0],t),e.forEach(i=>{const r=document.createElement("source");r.src=i,t.appendChild(r)})),this.onDisposeObservable.addOnce(()=>{Lde(t)}),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new wd(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("loadeddata",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),(e=this._externalTexture)==null||e.dispose()}static CreateFromStreamAsync(e,t,i,r=!0){const s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||(s.mozSrcObject!==void 0?s.mozSrcObject=t:typeof s.srcObject=="object"?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise(a=>{const o=()=>{const c=new wd("video",s,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&c.onDisposeObservable.addOnce(()=>{s.remove()}),c.onDisposeObservable.addOnce(()=>{Lde(s)}),a(c),s.removeEventListener("playing",o)};s.addEventListener("playing",o),s.play()})}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){const s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),a=await this.CreateFromStreamAsync(e,s,t,r);return a.onDisposeObservable.addOnce(()=>{s.getTracks().forEach(o=>{o.stop()})}),a}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,s=!0){this.CreateFromWebCamAsync(e,i,r,s).then(function(a){t&&t(a)}).catch(function(a){de.Error(a.name)})}}B([K("settings")],wd.prototype,"_settings",void 0);B([K("src")],wd.prototype,"_currentSrc",void 0);B([K()],wd.prototype,"isVideo",void 0);ve._CreateVideoTexture=(n,e,t,i=!1,r=!1,s=ve.TRILINEAR_SAMPLINGMODE,a={},o,c=5)=>new wd(n,e,t,i,r,s,a,o,c);xe("BABYLON.VideoTexture",wd);class XG extends gh{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new wd((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,ve.TRILINEAR_SAMPLINGMODE,r);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(a=>{var o;((o=a.pickInfo)==null?void 0:o.pickedMesh)===this.mesh&&this._texture.video.play()},ft.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add(()=>{this.onLoadObservable.notifyObservers()}),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}XG.MODE_MONOSCOPIC=gh.MODE_MONOSCOPIC;XG.MODE_TOPBOTTOM=gh.MODE_TOPBOTTOM;XG.MODE_SIDEBYSIDE=gh.MODE_SIDEBYSIDE;class rge{get gpuFrameTimeCounter(){return this.engine.getGPUFrameTimeCounter()}get captureGPUFrameTime(){return this._captureGPUFrameTime}set captureGPUFrameTime(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,this.engine.captureGPUFrameTime(e))}get shaderCompilationTimeCounter(){return this._shaderCompilationTime}get captureShaderCompilationTime(){return this._captureShaderCompilationTime}set captureShaderCompilationTime(e){e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add(()=>{this._shaderCompilationTime.fetchNewFrame(),this._shaderCompilationTime.beginMonitoring()}),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add(()=>{this._shaderCompilationTime.endMonitoring()})):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))}constructor(e){this.engine=e,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new Fa,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}dispose(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null}}class sge{get activeMeshesEvaluationTimeCounter(){return this._activeMeshesEvaluationTime}get captureActiveMeshesEvaluationTime(){return this._captureActiveMeshesEvaluationTime}set captureActiveMeshesEvaluationTime(e){e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add(()=>{Ee.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()}),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add(()=>{Ee.EndPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.endMonitoring(!1)})):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))}get renderTargetsRenderTimeCounter(){return this._renderTargetsRenderTime}get captureRenderTargetsRenderTime(){return this._captureRenderTargetsRenderTime}set captureRenderTargetsRenderTime(e){e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add(()=>{Ee.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()}),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add(()=>{Ee.EndPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.endMonitoring(!1)})):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))}get particlesRenderTimeCounter(){return this._particlesRenderTime}get captureParticlesRenderTime(){return this._captureParticlesRenderTime}set captureParticlesRenderTime(e){e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add(()=>{Ee.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()}),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add(()=>{Ee.EndPerformanceCounter("Particles"),this._particlesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))}get spritesRenderTimeCounter(){return this._spritesRenderTime}get captureSpritesRenderTime(){return this._captureSpritesRenderTime}set captureSpritesRenderTime(e){e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add(()=>{Ee.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()}),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add(()=>{Ee.EndPerformanceCounter("Sprites"),this._spritesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))}get physicsTimeCounter(){return this._physicsTime}get capturePhysicsTime(){return this._capturePhysicsTime}set capturePhysicsTime(e){e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add(()=>{Ee.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()}),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add(()=>{Ee.EndPerformanceCounter("Physics"),this._physicsTime.endMonitoring()})):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))}get animationsTimeCounter(){return this._animationsTime}get captureAnimationsTime(){return this._captureAnimationsTime}set captureAnimationsTime(e){e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add(()=>{this._animationsTime.endMonitoring()}):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))}get frameTimeCounter(){return this._frameTime}get captureFrameTime(){return this._captureFrameTime}set captureFrameTime(e){this._captureFrameTime=e}get interFrameTimeCounter(){return this._interFrameTime}get captureInterFrameTime(){return this._captureInterFrameTime}set captureInterFrameTime(e){this._captureInterFrameTime=e}get renderTimeCounter(){return this._renderTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add(()=>{this._renderTime.beginMonitoring(),Ee.StartPerformanceCounter("Main render")}),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add(()=>{this._renderTime.endMonitoring(!1),Ee.EndPerformanceCounter("Main render")})):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))}get cameraRenderTimeCounter(){return this._cameraRenderTime}get captureCameraRenderTime(){return this._captureCameraRenderTime}set captureCameraRenderTime(e){e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add(t=>{this._cameraRenderTime.beginMonitoring(),Ee.StartPerformanceCounter(`Rendering camera ${t.name}`)}),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add(t=>{this._cameraRenderTime.endMonitoring(!1),Ee.EndPerformanceCounter(`Rendering camera ${t.name}`)})):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))}get drawCallsCounter(){return this.scene.getEngine()._drawCalls}constructor(e){this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new Fa,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new Fa,this._captureFrameTime=!1,this._frameTime=new Fa,this._captureRenderTime=!1,this._renderTime=new Fa,this._captureInterFrameTime=!1,this._interFrameTime=new Fa,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new Fa,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new Fa,this._capturePhysicsTime=!1,this._physicsTime=new Fa,this._captureAnimationsTime=!1,this._animationsTime=new Fa,this._captureCameraRenderTime=!1,this._cameraRenderTime=new Fa,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add(()=>{this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.fetchNewFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.fetchNewFrame(),this._captureFrameTime&&(Ee.StartPerformanceCounter("Scene rendering"),this._frameTime.beginMonitoring()),this._captureInterFrameTime&&this._interFrameTime.endMonitoring(),this._captureParticlesRenderTime&&this._particlesRenderTime.fetchNewFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.fetchNewFrame(),this._captureAnimationsTime&&this._animationsTime.beginMonitoring(),this._captureRenderTime&&this._renderTime.fetchNewFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.fetchNewFrame(),this.scene.getEngine()._drawCalls.fetchNewFrame()}),this._onAfterRenderObserver=e.onAfterRenderObservable.add(()=>{this._captureFrameTime&&(Ee.EndPerformanceCounter("Scene rendering"),this._frameTime.endMonitoring()),this._captureRenderTime&&this._renderTime.endMonitoring(!1),this._captureInterFrameTime&&this._interFrameTime.beginMonitoring(),this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.endFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.endFrame(),this._captureParticlesRenderTime&&this._particlesRenderTime.endFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.endFrame(),this._captureRenderTime&&this._renderTime.endFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.endFrame()})}dispose(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null}}const lLe="glowMapGenerationPixelShader",cLe=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) #include #endif #ifdef DIFFUSE varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; #endif #ifdef OPACITY varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; #endif #ifdef EMISSIVE varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; #endif #ifdef VERTEXALPHA varying vec4 vColor; #endif uniform vec4 glowColor;uniform float glowIntensity; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #include vec4 finalColor=glowColor; #ifdef DIFFUSE vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); #ifdef DIFFUSE_ISLINEAR albedoTexture=toGammaSpace(albedoTexture); #endif #ifdef GLOW finalColor.a*=albedoTexture.a; #endif #ifdef HIGHLIGHT finalColor.a=albedoTexture.a; #endif #endif #ifdef OPACITY vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); #ifdef OPACITYRGB finalColor.a*=getLuminance(opacityMap.rgb); #else finalColor.a*=opacityMap.a; #endif finalColor.a*=opacityIntensity; #endif #ifdef VERTEXALPHA finalColor.a*=vColor.a; #endif #ifdef ALPHATEST if (finalColor.a #include #include #include[0..maxSimultaneousMorphTargets] #include #include uniform mat4 viewProjection;varying vec4 vPosition; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #ifdef DIFFUSE varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; #endif #ifdef OPACITY varying vec2 vUVOpacity;uniform mat4 opacityMatrix; #endif #ifdef EMISSIVE varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; #endif #ifdef VERTEXALPHA attribute vec4 color;varying vec4 vColor; #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #ifdef CUBEMAP vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); #else vPosition=viewProjection*worldPos;gl_Position=vPosition; #endif #ifdef DIFFUSE #ifdef DIFFUSEUV1 vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef DIFFUSEUV2 vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif #ifdef OPACITY #ifdef OPACITYUV1 vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef OPACITYUV2 vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); #endif #endif #ifdef EMISSIVE #ifdef EMISSIVEUV1 vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef EMISSIVEUV2 vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); #endif #endif #ifdef VERTEXALPHA vColor=color; #endif #include }`;Re.ShadersStore[hLe]=uLe;class Vu{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||t===0)&&e.subMeshes)for(let r=0;r{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let s;const a=this._scene.getEngine();if(r.length){for(a.setColorWrite(!1),s=0;s{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e}),this._mainTexture.onAfterUnbindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=e})}}_addCustomEffectDefines(e){}_isReady(e,t,i){var v;const r=this._scene.getEngine(),s=e.getMesh(),a=(v=s._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:v[r.currentRenderPassId];if(a)return a.isReadyForSubMesh(s,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const c=[],l=[Z.PositionKind];let h=!1,u=!1;if(o){const x=o.needAlphaTesting(),y=o.getAlphaTestTexture(),C=y&&y.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);y&&(x||C)&&(c.push("#define DIFFUSE"),s.isVerticesDataPresent(Z.UV2Kind)&&y.coordinatesIndex===1?(c.push("#define DIFFUSEUV2"),u=!0):s.isVerticesDataPresent(Z.UVKind)&&(c.push("#define DIFFUSEUV1"),h=!0),x&&(c.push("#define ALPHATEST"),c.push("#define ALPHATESTVALUE 0.4")),y.gammaSpace||c.push("#define DIFFUSE_ISLINEAR"));const b=o.opacityTexture;b&&(c.push("#define OPACITY"),s.isVerticesDataPresent(Z.UV2Kind)&&b.coordinatesIndex===1?(c.push("#define OPACITYUV2"),u=!0):s.isVerticesDataPresent(Z.UVKind)&&(c.push("#define OPACITYUV1"),h=!0))}i&&(c.push("#define EMISSIVE"),s.isVerticesDataPresent(Z.UV2Kind)&&i.coordinatesIndex===1?(c.push("#define EMISSIVEUV2"),u=!0):s.isVerticesDataPresent(Z.UVKind)&&(c.push("#define EMISSIVEUV1"),h=!0),i.gammaSpace||c.push("#define EMISSIVE_ISLINEAR")),s.useVertexColors&&s.isVerticesDataPresent(Z.ColorKind)&&s.hasVertexAlpha&&o.transparencyMode!==Ye.MATERIAL_OPAQUE&&(l.push(Z.ColorKind),c.push("#define VERTEXALPHA")),h&&(l.push(Z.UVKind),c.push("#define UV1")),u&&(l.push(Z.UV2Kind),c.push("#define UV2"));const d=new Hn;if(s.useBones&&s.computeBonesUsingShaders){l.push(Z.MatricesIndicesKind),l.push(Z.MatricesWeightsKind),s.numBoneInfluencers>4&&(l.push(Z.MatricesIndicesExtraKind),l.push(Z.MatricesWeightsExtraKind)),c.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers);const x=s.skeleton;x&&x.isUsingTextureForMatrices?c.push("#define BONETEXTURE"):c.push("#define BonesPerMesh "+(x?x.bones.length+1:0)),s.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,s)}else c.push("#define NUM_BONE_INFLUENCERS 0");const f=s.morphTargetManager;let p=0;f&&(p=f.numMaxInfluencers||f.numInfluencers,p>0&&(c.push("#define MORPHTARGETS"),c.push("#define NUM_MORPH_INFLUENCERS "+p),f.isUsingTextureForTargets&&c.push("#define MORPHTARGETS_TEXTURE"),Y6(l,s,p))),t&&(c.push("#define INSTANCES"),s_(l),e.getRenderingMesh().hasThinInstances&&c.push("#define THIN_INSTANCES")),d2(o,this._scene,c),this._addCustomEffectDefines(c);const _=e._getDrawWrapper(void 0,!0),m=_.defines,g=c.join(` `);if(m!==g){const x=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];Sa(x),_.setEffect(this._engine.createEffect("glowMapGeneration",l,x,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:p}),g)}return _.effect.isReady()}render(){for(let a=0;av.setMatrix("world",y))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[Z.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return Ee.Instantiate(e.customType).Parse(e,t,i)}}Vu._SceneComponentInitialization=n=>{throw ci("EffectLayerSceneComponent")};B([K()],Vu.prototype,"name",void 0);B([P5()],Vu.prototype,"neutralColor",void 0);B([K()],Vu.prototype,"isEnabled",void 0);B([j_e()],Vu.prototype,"camera",null);B([K()],Vu.prototype,"renderingGroupId",null);B([K()],Vu.prototype,"disableBoundingBoxesFromEffectLayer",void 0);da.AddParser(it.NAME_EFFECTLAYER,(n,e,t,i)=>{if(n.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let r=0;r{this.scene.addEffectLayer(t)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(i=>{this.scene.removeEffectLayer(i),t&&i.dispose()})}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,r=this.scene.effectLayers;for(const s of r){if(!s.hasMesh(e))continue;const a=s._mainTexture;this._engine.currentRenderPassId=a.renderPassId;for(const o of e.subMeshes)if(!s.isReady(o,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const r of i)if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===Rt.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==Rt.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();const s=r._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let e=n._getComponent(it.NAME_EFFECTLAYER);e||(e=new nge(n),n._addComponent(e))};const dLe="glowMapMergePixelShader",fLe=`varying vec2 vUV;uniform sampler2D textureSampler; #ifdef EMISSIVE uniform sampler2D textureSampler2; #endif uniform float offset; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec4 baseColor=texture2D(textureSampler,vUV); #ifdef EMISSIVE baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; #else baseColor.a=abs(offset-baseColor.a); #ifdef STROKE float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; #endif #endif #if LDR baseColor=clamp(baseColor,0.,1.0); #endif gl_FragColor=baseColor; #define CUSTOM_FRAGMENT_MAIN_END }`;Re.ShadersStore[dLe]=fLe;const pLe="glowMapMergeVertexShader",_Le=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[pLe]=_Le;da.prototype.getGlowLayerByName=function(n){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===n&&this.effectLayers[t].getEffectName()===Uc.EffectName)return this.effectLayers[t];return null};class Uc extends Vu{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;const t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}get blurKernelSize(){return this._options.blurKernelSize}set intensity(e){this._intensity=e}get intensity(){return this._intensity}constructor(e,t,i){super(e,t),this._intensity=1,this._includedOnlyMeshes=[],this._excludedMeshes=[],this._meshesUsingTheirOwnMaterials=[],this.neutralColor=new Ze(0,0,0,1),this._options={mainTextureRatio:Uc.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType,generateStencilBuffer:this._options.generateStencilBuffer})}getEffectName(){return Uc.EffectName}_createMergeEffect(){let e=`#define EMISSIVE `;return this._options.ldrMerge&&(e+=`#define LDR `),this._engine.createEffect("glowMapMerge",[Z.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?De.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?De.GetExponentOfTwo(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture1=new es("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=ve.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=ve.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(ve.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const r=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new es("GlowLayerBlurRTT2",{width:r,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=ve.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=ve.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(ve.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const a=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new ao("GlowLayerHBP1",new Be(1,0),a,{width:e,height:t},null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add(o=>{o.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess1=new ao("GlowLayerVBP1",new Be(0,1),a,{width:e,height:t},null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new ao("GlowLayerHBP2",new Be(1,0),a,{width:r,height:s},null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(o=>{o.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new ao("GlowLayerVBP2",new Be(0,1),a,{width:r,height:s},null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add(()=>{const o=this._blurTexture1.renderTarget;if(o){this._scene.postProcessManager.directRender(this._postProcesses1,o,!0);const c=this._blurTexture2.renderTarget;c&&this._scene.postProcessManager.directRender(this._postProcesses2,c,!0),this._engine.unBindFramebuffer(c??o,!0)}}),this._postProcesses.map(o=>{o.autoClear=!1})}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;const s=i.emissiveTexture;return super._isReady(e,t,s)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(Ye.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let r=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(r=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){const s=i.emissiveIntensity??1;r*=s,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*r,i.emissiveColor.g*r,i.emissiveColor.b*r,i.alpha)}else this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){this._excludedMeshes.indexOf(e.uniqueId)===-1&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);t!==-1&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){this._includedOnlyMeshes.indexOf(e.uniqueId)===-1&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);t!==-1&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return super.hasMesh(e)?this._includedOnlyMeshes.length?this._includedOnlyMeshes.indexOf(e.uniqueId)!==-1:this._excludedMeshes.length?this._excludedMeshes.indexOf(e.uniqueId)===-1:!0:!1}_useMeshMaterial(e){return this._meshesUsingTheirOwnMaterials.length==0?!1:this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add(()=>{this._disposeMesh(e)})}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=Qe.Serialize(this);e.customType="BABYLON.GlowLayer";let t;if(e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Uc(e.name,t,e.options),e,t,i);let s;for(s=0;s{l.setFloat2("screenSize",this.width,this.height),l.setVector2("direction",this.direction),l.setFloat("blurWidth",this.kernel)})}}class Gl extends Vu{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new Ae,this.onAfterBlurObservable=new Ae,this._instanceGlowingMeshStencilReference=Gl.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Gl.NeutralColor,this._engine.isStencilEnable||de.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return Gl.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[Z.PositionKind],["offset"],["textureSampler"],this._options.isStroke?`#define STROKE `:void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?De.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?De.GetExponentOfTwo(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new es("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=ve.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=ve.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(ve.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new Zf("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(r=>{r.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new Nde("HighlightLayerHBP",new Be(1,0),this._options.blurHorizontalSize,1,null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(r=>{r.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new Nde("HighlightLayerVBP",new Be(0,1),this._options.blurVerticalSize,1,null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(r=>{r.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new ao("HighlightLayerHBP",new Be(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(r=>{r.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new ao("HighlightLayerVBP",new Be(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);const r=this._blurTexture.renderTarget;r&&(this._scene.postProcessManager.directRender(this._postProcesses,r,!0),this._engine.unBindFramebuffer(r,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(r=>{r.autoClear=!1})}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null;const a=this._meshes[r.uniqueId];return a&&a.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&t===0&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(Ye.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Ye.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return super.shouldRender()?!!this._meshes:!1}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;if(!this._excludedMeshes[e.uniqueId]){const i={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};i.beforeBind=e.onBeforeBindObservable.add(r=>{i.stencilState=r.getEngine().getStencilBuffer(),r.getEngine().setStencilBuffer(!1)}),i.afterRender=e.onAfterRenderObservable.add(r=>{r.getEngine().setStencilBuffer(i.stencilState)}),this._excludedMeshes[e.uniqueId]=i}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!this._meshes||!super.hasMesh(e)?!1:this._meshes[e.uniqueId]!==void 0&&this._meshes[e.uniqueId]!==null}addMesh(e,t,i=!1){if(!this._meshes)return;const r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(s=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[s.uniqueId]?this._defaultStencilReference(s):s.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(s=>{this.isEnabled&&this._defaultStencilReference(s)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const i in this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(Gl.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=Qe.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const r=Qe.Parse(()=>new Gl(e.name,t,e.options),e,t,i);let s;for(s=0;sthis._drawCameraPredicate(t,!0,!0,e.layerMask))}_drawCameraForegroundWithPostProcessing(e){this._draw(t=>this._drawCameraPredicate(t,!1,!0,e.layerMask))}_drawCameraForegroundWithoutPostProcessing(e){this._draw(t=>this._drawCameraPredicate(t,!1,!1,e.layerMask))}_drawRenderTargetPredicate(e,t,i,r,s){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(s)>-1&&(e.layerMask&r)!==0}_drawRenderTargetBackground(e){this._draw(t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw(t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw(t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e))}addFromContainer(e){e.layers&&e.layers.forEach(t=>{this.scene.layers.push(t)})}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach(i=>{const r=this.scene.layers.indexOf(i);r!==-1&&this.scene.layers.splice(r,1),t&&i.dispose()})}}const vLe="layerPixelShader",xLe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec4 baseColor=texture2D(textureSampler,vUV); #ifdef LINEAR baseColor.rgb=toGammaSpace(baseColor.rgb); #endif #ifdef ALPHATEST if (baseColor.a<0.4) discard; #endif gl_FragColor=baseColor*color; #define CUSTOM_FRAGMENT_MAIN_END }`;Re.ShadersStore[vLe]=xLe;const yLe="layerVertexShader",ALe=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[yLe]=ALe;class Bee{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}constructor(e,t,i,r,s){this.name=e,this._applyPostProcess=!0,this.scale=new Be(1,1),this.offset=new Be(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new Ae,this.onBeforeRenderObservable=new Ae,this.onAfterRenderObservable=new Ae,this.texture=t?new ve(t,i,!0):null,this.isBackground=r===void 0?!0:r,this.color=s===void 0?new Ze(1,1,1,1):s,this._scene=i||bt.LastCreatedScene;let a=this._scene._getComponent(it.NAME_LAYER);a||(a=new age(this._scene),this._scene._addComponent(a)),this._scene.layers.push(this);const o=this._scene.getEngine();this._drawWrapper=new Sn(o);const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1);const l=new Z(o,c,Z.PositionKind,!1,!1,2);this._vertexBuffers[Z.PositionKind]=l,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[Z.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){var r;const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(t+=` #define LINEAR`),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[Z.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t));const i=this._drawWrapper.effect;return(i==null?void 0:i.isReady())&&((r=this.texture)==null?void 0:r.isReady())}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();if(!this.isReady())return;const t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(Ye.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(Ye.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[Z.PositionKind];e&&(e.dispose(),this._vertexBuffers[Z.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}}class YG{static AddFlare(e,t,i,r,s){return new YG(e,t,i,r,s)}constructor(e,t,i,r,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Me(1,1,1),this.texture=r?new ve(r,s.getScene(),!0):null,this._system=s;const a=s.scene.getEngine();this._drawWrapper=new Sn(a),this._drawWrapper.effect=a.createEffect("lensFlare",[Z.PositionKind],["color","viewportMatrix"],["textureSampler"],""),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}const CLe="lensFlarePixelShader",bLe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; #define CUSTOM_FRAGMENT_MAIN_END }`;Re.ShadersStore[CLe]=bLe;const ELe="lensFlareVertexShader",TLe=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[ELe]=TLe;class aA{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||bt.LastCreatedScene,aA._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=a=>i.activeCamera&&a.material&&a.isVisible&&a.isEnabled()&&a.isBlocker&&(a.layerMask&i.activeCamera.layerMask)!=0;const r=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[Z.PositionKind]=new Z(r,s,Z.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=P.Project(t,ce.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=P.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=this.viewportBorder*2,e.height+=this.viewportBorder*2,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return t.z>0&&!i||t.z<0&&i?(this._positionX>e.x&&this._positionXe.y&&this._positionYi}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),i=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(i)||!this._isVisible())return!1;let r,s;this._positionXi.x+i.width-this.borderLimit?r=this._positionX-i.x-i.width+this.borderLimit:r=0,this._positionYi.y+i.height-this.borderLimit?s=this._positionY-i.y-i.height+this.borderLimit:s=0;let a=r>s?r:s;a-=this.viewportBorder,a>this.borderLimit&&(a=this.borderLimit);let o=1-_t.Clamp(a/this.borderLimit,0,1);if(o<0)return!1;o>1&&(o=1),this.viewportBorder>0&&(i.x+=this.viewportBorder,i.y+=this.viewportBorder,i.width-=this.viewportBorder*2,i.height-=this.viewportBorder*2,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const c=i.x+i.width/2,l=i.y+i.height/2,h=c-this._positionX,u=l-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let d=0;d{throw ci("LensFlareSystemSceneComponent")};da.AddParser(it.NAME_LENSFLARESYSTEM,(n,e,t,i)=>{if(n.lensFlareSystems!==void 0&&n.lensFlareSystems!==null){t.lensFlareSystems||(t.lensFlareSystems=[]);for(let r=0,s=n.lensFlareSystems.length;r{this.scene.addLensFlareSystem(t)})}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach(i=>{this.scene.removeLensFlareSystem(i),t&&i.dispose()})}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;Ee.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();Ee.EndPerformanceCounter("Lens flares",t.length>0)}}}aA._SceneComponentInitialization=n=>{let e=n._getComponent(it.NAME_LENSFLARESYSTEM);e||(e=new oge(n),n._addComponent(e))};const SLe="bayerDitherFunctions",MLe=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); vec2 P2=floor(0.5*mod(_P,4.0)); return 4.0*bayerDither2(P1)+bayerDither2(P2);} float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); vec2 P2=floor(0.5 *mod(_P,4.0)); vec2 P4=floor(0.25*mod(_P,8.0)); return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} `;Re.IncludesShadersStore[SLe]=MLe;const RLe="shadowMapFragmentExtraDeclaration",ILe=`#if SM_FLOAT==0 #include #endif #if SM_SOFTTRANSPARENTSHADOW==1 #include uniform float softTransparentShadowSM; #endif varying float vDepthMetricSM; #if SM_USEDISTANCE==1 uniform vec3 lightDataSM;varying vec3 vPositionWSM; #endif uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying float zSM; #endif `;Re.IncludesShadersStore[RLe]=ILe;const PLe="shadowMapFragment",wLe=`float depthSM=vDepthMetricSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 #if SM_USEDISTANCE==1 depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #else #ifdef USE_REVERSE_DEPTHBUFFER depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #else depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #endif #ifdef USE_REVERSE_DEPTHBUFFER gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); #else gl_FragDepth=clamp(depthSM,0.0,1.0); #endif #elif SM_USEDISTANCE==1 depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #if SM_ESM==1 depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); #endif #if SM_FLOAT==1 gl_FragColor=vec4(depthSM,1.0,1.0,1.0); #else gl_FragColor=pack(depthSM); #endif return;`;Re.IncludesShadersStore[PLe]=wLe;const DLe="shadowMapPixelShader",OLe=`#include #ifdef ALPHATEXTURE varying vec2 vUV;uniform sampler2D diffuseSampler; #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #include #ifdef ALPHATEXTURE float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; #ifdef ALPHATESTVALUE if (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard; #else if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard; #endif #endif #include }`;Re.ShadersStore[DLe]=OLe;const LLe="sceneVertexDeclaration",NLe=`uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; `;Re.IncludesShadersStore[LLe]=NLe;const BLe="meshVertexDeclaration",FLe=`uniform mat4 world;uniform float visibility; `;Re.IncludesShadersStore[BLe]=FLe;const ULe="shadowMapVertexDeclaration",kLe=`#include #include `;Re.IncludesShadersStore[ULe]=kLe;const VLe="shadowMapUboDeclaration",zLe=`layout(std140,column_major) uniform; #include #include `;Re.IncludesShadersStore[VLe]=zLe;const HLe="shadowMapVertexExtraDeclaration",GLe=`#if SM_NORMALBIAS==1 uniform vec3 lightDataSM; #endif uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; #if SM_USEDISTANCE==1 varying vec3 vPositionWSM; #endif #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying float zSM; #endif `;Re.IncludesShadersStore[HLe]=GLe;const KLe="shadowMapVertexNormalBias",WLe=`#if SM_NORMALBIAS==1 #if SM_DIRECTIONINLIGHTDATA==1 vec3 worldLightDirSM=normalize(-lightDataSM.xyz); #else vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); #endif float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; #endif `;Re.IncludesShadersStore[KLe]=WLe;const jLe="shadowMapVertexMetric",XLe=`#if SM_USEDISTANCE==1 vPositionWSM=worldPos.xyz; #endif #if SM_DEPTHTEXTURE==1 #ifdef IS_NDC_HALF_ZRANGE #define BIASFACTOR 0.5 #else #define BIASFACTOR 1.0 #endif #ifdef USE_REVERSE_DEPTHBUFFER gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; #else gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; #endif #endif #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 zSM=gl_Position.z;gl_Position.z=0.0; #elif SM_USEDISTANCE==0 #ifdef USE_REVERSE_DEPTHBUFFER vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #else vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #endif `;Re.IncludesShadersStore[jLe]=XLe;const YLe="shadowMapVertexShader",QLe=`attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #include #include #include #include[0..maxSimultaneousMorphTargets] #ifdef INSTANCES attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; #endif #include #include<__decl__shadowMapVertex> #ifdef ALPHATEXTURE varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #include #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #ifdef UV1 vec2 uvUpdated=uv; #endif #ifdef NORMAL vec3 normalUpdated=normal; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #ifdef NORMAL mat3 normWorldSM=mat3(finalWorld); #if defined(INSTANCES) && defined(THIN_INSTANCES) vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); #else #ifdef NONUNIFORMSCALING normWorldSM=transposeMat3(inverseMat3(normWorldSM)); #endif vec3 vNormalW=normalize(normWorldSM*normalUpdated); #endif #endif #include gl_Position=viewProjection*worldPos; #include #ifdef ALPHATEXTURE #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif #include }`;Re.ShadersStore[YLe]=QLe;const $Le="depthBoxBlurPixelShader",ZLe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) for (int y=-OFFSET; y<=OFFSET; y++) colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;Re.ShadersStore[$Le]=ZLe;const qLe="shadowMapFragmentSoftTransparentShadow",JLe=`#if SM_SOFTTRANSPARENTSHADOW==1 if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; #endif `;Re.IncludesShadersStore[qLe]=JLe;class si{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return this._depthScale!==void 0?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===si.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===si.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===si.FILTER_PCF||e===si.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===si.FILTER_PCF||e===si.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===si.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(si.FILTER_POISSONSAMPLING);!e&&this.filter!==si.FILTER_POISSONSAMPLING||(this.filter=e?t:si.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===si.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(si.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==si.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:si.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===si.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(si.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==si.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:si.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===si.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(si.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==si.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:si.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===si.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(si.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==si.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:si.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===si.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(si.FILTER_PCF);!e&&this.filter!==si.FILTER_PCF||(this.filter=e?t:si.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===si.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(si.FILTER_PCSS);!e&&this.filter!==si.FILTER_PCSS||(this.filter=e?t:si.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return si.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.indexOf(e)===-1&&this._shadowMap.renderList.push(e),t)for(const i of e.getChildMeshes())this._shadowMap.renderList.indexOf(i)===-1&&this._shadowMap.renderList.push(i);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(i!==-1&&this._shadowMap.renderList.splice(i,1),t)for(const r of e.getChildren())this.removeShadowCaster(r);return this}getLight(){return this._light}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,r,s){this.onBeforeShadowMapRenderObservable=new Ae,this.onAfterShadowMapRenderObservable=new Ae,this.onBeforeShadowMapRenderMeshObservable=new Ae,this.onAfterShadowMapRenderMeshObservable=new Ae,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=si.FILTER_NONE,this._filteringQuality=si.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=P.Zero(),this._viewMatrix=ce.Zero(),this._projectionMatrix=ce.Zero(),this._transformMatrix=ce.Zero(),this._cachedPosition=new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=ce.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=r??null,this._useRedTextureType=!!s;let a=t._shadowGenerators;a||(a=t._shadowGenerators=new Map),a.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),si._SceneComponentInitialization(this._scene);const o=this._scene.getEngine().getCaps();i?o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new es(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new es(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),this._shadowMap===null)return;this._shadowMap.wrapU=ve.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=ve.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(ve.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(r,s,a,o)=>this._renderForShadowMap(r,s,a,o),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var r;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),(r=e._debugPushGroup)==null||r.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)}),this._shadowMap.onBeforeRenderObservable.add(r=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=r,this._filter===si.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{var s,a;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===si.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(s=e._debugPopGroup)==null||s.call(e,1);return}const r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0),(a=e._debugPopGroup)==null||a.call(e,1))});const t=new Ze(0,0,0,0),i=new Ze(1,1,1,1);this._shadowMap.onClearObservable.add(r=>{this._filter===si.FILTER_PCF?r.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?r.clear(t,!0,!0,!1):r.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(r=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=r.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let r=rl.MIN_RENDERINGGROUPS;r{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new ao(this._light.name+"KernelBlurY",new Be(0,1),this.blurKernel,1,null,ve.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===0&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Pt(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,ve.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",t,t),i.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let s;if(r.length)for(s=0;s{r!==i&&!v?(i.getMeshUniformBuffer().bindToEffect(_,"Mesh"),i.transferToEffect(x)):(r.getMeshUniformBuffer().bindToEffect(_,"Mesh"),r.transferToEffect(v?x:g))}),this.forceBackFacesOnly&&a.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(_),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===si.FILTER_NONE||this.filter===si.FILTER_PCSS?this._shadowMap.updateSamplingMode(ve.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(ve.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},r=this.getShadowMap();if(!r){e&&e(this);return}const s=r.renderList;if(!s){e&&e(this);return}const a=[];for(const l of s)a.push(...l.subMeshes);if(a.length===0){e&&e(this);return}let o=0;const c=()=>{var l;if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(a[o],i.useInstances,((l=a[o].getMaterial())==null?void 0:l.needAlphaBlendingForMesh(a[o].getMesh()))??!1);)if(o++,o>=a.length){e&&e(this);return}setTimeout(c,16)}};c()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(this._textureType!==0?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(Z.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Ui.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const r=e.getMaterial(),s=r==null?void 0:r.shadowDepthWrapper;if(this._opacityTexture=null,!r)return!1;const a=[];if(this._prepareShadowDefines(e,t,a,i),s){if(!s.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const o=e._getDrawWrapper(void 0,!0);let c=o.effect,l=o.defines;const h=[Z.PositionKind],u=e.getMesh();this.normalBias&&u.isVerticesDataPresent(Z.NormalKind)&&(h.push(Z.NormalKind),a.push("#define NORMAL"),u.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));const d=r.needAlphaTesting();if((d||r.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=r.opacityTexture:this._opacityTexture=r.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const g=r.alphaCutOff??si.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),d&&a.push(`#define ALPHATESTVALUE ${g}${g%1===0?".":""}`),u.isVerticesDataPresent(Z.UVKind)&&(h.push(Z.UVKind),a.push("#define UV1")),u.isVerticesDataPresent(Z.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(h.push(Z.UV2Kind),a.push("#define UV2"))}const f=new Hn;if(u.useBones&&u.computeBonesUsingShaders&&u.skeleton){h.push(Z.MatricesIndicesKind),h.push(Z.MatricesWeightsKind),u.numBoneInfluencers>4&&(h.push(Z.MatricesIndicesExtraKind),h.push(Z.MatricesWeightsExtraKind));const g=u.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+u.numBoneInfluencers),u.numBoneInfluencers>0&&f.addCPUSkinningFallback(0,u),g.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(g.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");const p=u.morphTargetManager;let _=0;if(p&&(_=p.numMaxInfluencers||p.numInfluencers,_>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+_),p.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Y6(h,u,_))),d2(r,this._scene,a),t&&(a.push("#define INSTANCES"),s_(h),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const g of this.customShaderOptions.defines)a.indexOf(g)===-1&&a.push(g);const m=a.join(` `);if(l!==m){l=m;let g="shadowMap";const v=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],x=["diffuseSampler","boneSampler","morphTargets"],y=["Scene","Mesh"];if(Sa(v),this.customShaderOptions){if(g=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const b of this.customShaderOptions.attributes)h.indexOf(b)===-1&&h.push(b);if(this.customShaderOptions.uniforms)for(const b of this.customShaderOptions.uniforms)v.indexOf(b)===-1&&v.push(b);if(this.customShaderOptions.samplers)for(const b of this.customShaderOptions.samplers)x.indexOf(b)===-1&&x.push(b)}const C=this._scene.getEngine();c=C.createEffect(g,{attributes:h,uniformsNames:v,uniformBuffersNames:y,samplers:x,defines:m,fallbacks:f,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:_}},C),o.setEffect(c,l)}if(!c.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,r=this._light;!i.shadowsEnabled||!r.shadowEnabled||(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===si.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===si.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===si.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===si.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const a=this.getShadowMap();a&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===si.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a.getSize().width,1/a.getSize().width,this.frustumEdgeFalloff,e)):this._filter===si.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a.getSize().width,this._contactHardeningLightSizeUVRatio*a.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/a.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e))}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),P.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(P.Dot(this._lightDirection,P.Up()))===1&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),ce.LookAtLHToRef(t,t.add(this._lightDirection),P.Up(),this._viewMatrix);const i=this.getShadowMap();if(i){const r=i.renderList;r&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,r)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const i of t)this._shadowMap.renderList.push(i)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();t.done!==!0;t=e.next()){const[i,r]=t.value;r===this&&this._light._shadowGenerators.delete(i)}this._light._shadowGenerators.size===0&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){var i;const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=(i=this._camera)==null?void 0:i.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let r=0;r{throw ci("ShadowGeneratorSceneComponent")};const eNe="depthPixelShader",tNe=`#ifdef ALPHATEST varying vec2 vUV;uniform sampler2D diffuseSampler; #endif #include varying float vDepthMetric; #ifdef PACKED #include #endif #ifdef STORE_CAMERASPACE_Z varying vec4 vViewPos; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #include #ifdef ALPHATEST if (texture2D(diffuseSampler,vUV).a<0.4) discard; #endif #ifdef STORE_CAMERASPACE_Z #ifdef PACKED gl_FragColor=pack(vViewPos.z); #else gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); #endif #else #ifdef NONLINEARDEPTH #ifdef PACKED gl_FragColor=pack(gl_FragCoord.z); #else gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); #endif #else #ifdef PACKED gl_FragColor=pack(vDepthMetric); #else gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); #endif #endif #endif }`;Re.ShadersStore[eNe]=tNe;const iNe="pointCloudVertexDeclaration",rNe=`#ifdef POINTSIZE uniform float pointSize; #endif `;Re.IncludesShadersStore[iNe]=rNe;const sNe="depthVertexShader",nNe=`attribute vec3 position; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include uniform mat4 viewProjection;uniform vec2 depthValues; #if defined(ALPHATEST) || defined(NEED_UV) varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #ifdef STORE_CAMERASPACE_Z uniform mat4 view;varying vec4 vViewPos; #endif #include varying float vDepthMetric; #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #include gl_Position=viewProjection*worldPos; #ifdef STORE_CAMERASPACE_Z vViewPos=view*worldPos; #else #ifdef USE_REVERSE_DEPTHBUFFER vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); #else vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); #endif #endif #if defined(ALPHATEST) || defined(BASIC_RENDER) #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif #include } `;Re.ShadersStore[sNe]=nNe;class f4{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,s=ve.TRILINEAR_SAMPLINGMODE,a=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=a,this.isPacked=t===0,this.isPacked?this.clearColor=new Ze(1,1,1,1):this.clearColor=new Ze(a?1e8:1,0,0,1),f4._SceneComponentInitialization(this._scene);const c=e.getEngine();this._camera=i,s!==ve.NEAREST_SAMPLINGMODE&&(t===1&&!c._caps.textureFloatLinearFiltering&&(s=ve.NEAREST_SAMPLINGMODE),t===2&&!c._caps.textureHalfFloatLinearFiltering&&(s=ve.NEAREST_SAMPLINGMODE));const l=this.isPacked||!c._features.supportExtendedTextureFormats?5:6;this._depthMap=new es(o??"DepthRenderer",{width:c.getRenderWidth(),height:c.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,l),this._depthMap.wrapU=ve.CLAMP_ADDRESSMODE,this._depthMap.wrapV=ve.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(u=>{u.clear(this.clearColor,!0,!0,!0)}),this._depthMap.onBeforeBindObservable.add(()=>{var u;(u=c._debugPushGroup)==null||u.call(c,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var u;(u=c._debugPopGroup)==null||u.call(c,1)}),this._depthMap.customIsReadyFunction=(u,d,f)=>{if((f||d===0)&&u.subMeshes)for(let p=0;p{var T;const d=u.getRenderingMesh(),f=u.getEffectiveMesh(),p=this._scene,_=p.getEngine(),m=u.getMaterial();if(f._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!m||f.infiniteDistance||m.disableDepthWrite||u.verticesCount===0||u._renderId===p.getRenderId())return;const g=f._getWorldMatrixDeterminant()<0;let v=d.overrideMaterialSideOrientation??m.sideOrientation;g&&(v=v===0?1:0);const x=v===0;_.setState(m.backFaceCulling,0,!1,x,this.reverseCulling?!m.cullBackFaces:m.cullBackFaces);const y=d._getInstancesRenderList(u._id,!!u.getReplacementMesh());if(y.mustReturn)return;const C=_.getCaps().instancedArrays&&(y.visibleInstances[u._id]!==null&&y.visibleInstances[u._id]!==void 0||d.hasThinInstances),b=this._camera||p.activeCamera;if(this.isReady(u,C)&&b){u._renderId=p.getRenderId();const S=(T=f._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:T[_.currentRenderPassId];let N=u._getDrawWrapper();!N&&S&&(N=S._getDrawWrapper());const D=b.mode===Rt.ORTHOGRAPHIC_CAMERA;if(!N)return;const M=N.effect;_.enableEffect(N),C||d._bind(u,M,m.fillMode),S?S.bindForSubMesh(f.getWorldMatrix(),f,u):(M.setMatrix("viewProjection",p.getTransformMatrix()),M.setMatrix("world",f.getWorldMatrix()),this._storeCameraSpaceZ&&M.setMatrix("view",p.getViewMatrix()));let I,R;if(D?(I=!_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:1,R=_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:1):(I=_.useReverseDepthBuffer&&_.isNDCHalfZRange?b.minZ:_.isNDCHalfZRange?0:b.minZ,R=_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:b.maxZ),M.setFloat2("depthValues",I,I+R),!S){if(m.needAlphaTesting()){const O=m.getAlphaTestTexture();O&&(M.setTexture("diffuseSampler",O),M.setMatrix("diffuseMatrix",O.getTextureMatrix()))}if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){const O=d.skeleton;if(O.isUsingTextureForMatrices){const H=O.getTransformMatrixTexture(d);if(!H)return;M.setTexture("boneSampler",H),M.setFloat("boneTextureWidth",4*(O.bones.length+1))}else M.setMatrices("mBones",O.getTransformMatrices(d))}fa(M,m,p),d1(d,M),d.morphTargetManager&&d.morphTargetManager.isUsingTextureForTargets&&d.morphTargetManager._bind(M),m.pointsCloud&&M.setFloat("pointSize",m.pointSize)}d._processRendering(f,u,M,m.fillMode,y,C,(O,H)=>M.setMatrix("world",H))}};this._depthMap.customRenderFunction=(u,d,f,p)=>{let _;if(p.length)for(_=0;_4&&(l.push(Z.MatricesIndicesExtraKind),l.push(Z.MatricesWeightsExtraKind)),c.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),c.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0));const m=e.getRenderingMesh().skeleton;m!=null&&m.isUsingTextureForMatrices&&c.push("#define BONETEXTURE")}else c.push("#define NUM_BONE_INFLUENCERS 0");const h=r.morphTargetManager;let u=0;h&&(u=h.numMaxInfluencers||h.numInfluencers,u>0&&(c.push("#define MORPHTARGETS"),c.push("#define NUM_MORPH_INFLUENCERS "+u),h.isUsingTextureForTargets&&c.push("#define MORPHTARGETS_TEXTURE"),Y6(l,r,u))),o.pointsCloud&&c.push("#define POINTSIZE"),t&&(c.push("#define INSTANCES"),s_(l),e.getRenderingMesh().hasThinInstances&&c.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&c.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&c.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&c.push("#define PACKED"),d2(o,s,c);const d=e._getDrawWrapper(void 0,!0),f=d.defines,p=c.join(` `);if(f!==p){const m=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];Sa(m),d.setEffect(i.createEffect("depth",l,m,["diffuseSampler","morphTargets","boneSampler"],p,void 0,void 0,void 0,{maxSimultaneousMorphTargets:u}),p)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}f4._SceneComponentInitialization=n=>{throw ci("DepthRendererSceneComponent")};const aNe="minmaxReduxPixelShader",oNe=`varying vec2 vUV;uniform sampler2D textureSampler; #if defined(INITIAL) uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) {ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); #ifdef DEPTH_REDUX float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); #else float maxz=max(max(max(f1,f2),f3),f4); #endif glFragColor=vec4(minz,maxz,0.,0.);} #elif defined(MAIN) uniform vec2 texSize;void main(void) {ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} #elif defined(ONEBEFORELAST) uniform ivec2 texSize;void main(void) {ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} #elif defined(LAST) void main(void) {glFragColor=vec4(0.);if (true) { discard;}} #endif `;Re.ShadersStore[aNe]=oNe;class lge{constructor(e){this.onAfterReductionPerformed=new Ae,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new UD(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;const s=this._camera.getScene(),a=new Pt("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,s.getEngine(),!1,"#define INITIAL"+(t?` #define DEPTH_REDUX`:""),i,void 0,void 0,void 0,7);a.autoClear=!1,a.forceFullscreenViewport=r;let o=this._sourceTexture.getRenderWidth(),c=this._sourceTexture.getRenderHeight();a.onApply=((h,u)=>d=>{d.setTexture("sourceTexture",this._sourceTexture),d.setFloat2("texSize",h,u)})(o,c),this._reductionSteps.push(a);let l=1;for(;o>1||c>1;){o=Math.max(Math.round(o/2),1),c=Math.max(Math.round(c/2),1);const h=new Pt("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:c},null,1,s.getEngine(),!1,"#define "+(o==1&&c==1?"LAST":o==1||c==1?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(h.autoClear=!1,h.forceFullscreenViewport=r,h.onApply=((u,d)=>f=>{u==1||d==1?f.setInt2("texSize",u,d):f.setFloat2("texSize",u,d)})(o,c),this._reductionSteps.push(h),l++,o==1&&c==1){const u=(d,f,p)=>{const _=new Float32Array(4*d*f),m={min:0,max:0};return()=>{s.getEngine()._readTexturePixels(p.inputTexture.texture,d,f,-1,0,_,!1),m.min=_[0],m.max=_[1],this.onAfterReductionPerformed.notifyObservers(m)}};h.onAfterRenderObservable.add(u(o,c,h))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){this._onAfterUnbindObserver||!this._sourceTexture||(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{var t,i;const e=this._camera.getScene().getEngine();(t=e._debugPushGroup)==null||t.call(e,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),(i=e._debugPopGroup)==null||i.call(e,1)}),this._activated=!0)}deactivate(){!this._onAfterUnbindObserver||!this._sourceTexture||(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let t=0;tthis._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let i=0;it&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return ko.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&t.maxZ!==0||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let r=i.min,s=i.max;r>=s&&(r=0,s=1),(r!=this._minDistance||s!=this._maxDistance)&&this.setMinMaxDistance(r,s)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t;return((t=(e=this._depthReducer)==null?void 0:e.depthRenderer)==null?void 0:t.getDepthMap().refreshRate)??-1}set autoCalcDepthBoundsRefreshRate(e){var t;(t=this._depthReducer)!=null&&t.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,a=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,o=t+s*r,c=t+a*r,l=c-o,h=c/o;for(let u=0;u{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===si.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),(t=e._debugPushGroup)==null||t.call(e,`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==si.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),this.cascadeBlendPercentage===0&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const a=this.getShadowMap();if(!a)return;const o=a.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,this.cascadeBlendPercentage===0?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===si.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===si.FILTER_PCSS){for(let c=0;cnew ko(r,s,void 0,a));return e.numCascades!==void 0&&(i.numCascades=e.numCascades),e.debug!==void 0&&(i.debug=e.debug),e.stabilizeCascades!==void 0&&(i.stabilizeCascades=e.stabilizeCascades),e.lambda!==void 0&&(i.lambda=e.lambda),e.cascadeBlendPercentage!==void 0&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),e.depthClamp!==void 0&&(i.depthClamp=e.depthClamp),e.autoCalcDepthBounds!==void 0&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),e.shadowMaxZ!==void 0&&(i.shadowMaxZ=e.shadowMaxZ),e.penumbraDarkness!==void 0&&(i.penumbraDarkness=e.penumbraDarkness),e.freezeShadowCastersBoundingInfo!==void 0&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),e.minDistance!==void 0&&e.maxDistance!==void 0&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}ko._FrustumCornersNDCSpace=[new P(-1,1,-1),new P(1,1,-1),new P(1,-1,-1),new P(-1,-1,-1),new P(-1,1,1),new P(1,1,1),new P(1,-1,1),new P(-1,-1,1)];ko.CLASSNAME="CascadedShadowGenerator";ko.DEFAULT_CASCADES_COUNT=4;ko.MIN_CASCADES_COUNT=2;ko.MAX_CASCADES_COUNT=4;ko._SceneComponentInitialization=n=>{throw ci("ShadowGeneratorSceneComponent")};da.AddParser(it.NAME_SHADOWGENERATOR,(n,e)=>{if(n.shadowGenerators!==void 0&&n.shadowGenerators!==null)for(let t=0,i=n.shadowGenerators.length;t{let e=n._getComponent(it.NAME_SHADOWGENERATOR);e||(e=new hge(n),n._addComponent(e))};Lr.AddNodeConstructor("Light_Type_0",(n,e)=>()=>new G0(n,P.Zero(),e));class G0 extends u4{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const i=this._shadowGenerators.values();for(let r=i.next();r.done!==!0;r=i.next())r.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return Ui.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new P(1,0,0);case 1:return new P(-1,0,0);case 2:return new P(0,-1,0);case 3:return new P(0,1,0);case 4:return new P(0,0,1);case 5:return new P(0,0,-1)}return P.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;const s=this.shadowMinZ!==void 0?this.shadowMinZ:r.minZ,a=this.shadowMaxZ!==void 0?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;ce.PerspectiveFovLHToRef(this.shadowAngle,1,o?a:s,o?s:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}B([K()],G0.prototype,"shadowAngle",null);class Om{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const r=this._renderingCanvas.getBoundingClientRect(),s=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position=s==="fixed"?"fixed":"absolute",this._loadingDiv.style.left=r.left+"px",this._loadingDiv.style.top=r.top+"px",this._loadingDiv.style.width=r.width+"px",this._loadingDiv.style.height=r.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css";const e=`@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);} 100% { -webkit-transform: rotate(360deg);} } @keyframes spin1 { 0% { transform: rotate(0deg);} 100% { transform: rotate(360deg);} }`;this._style.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(this._style);const t=!!window.SVGSVGElement,i=new Image;Om.DefaultLogoUrl?i.src=Om.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const r=document.createElement("div");r.style.width="300px",r.style.gridColumn="1",r.style.gridRow="1",r.style.top="50%",r.style.left="50%",r.style.transform="translate(-50%, -50%)",r.style.position="absolute";const s=new Image;if(Om.DefaultSpinnerUrl?s.src=Om.DefaultSpinnerUrl:s.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!t){const a={w:16,h:18.5},o={w:30,h:30};i.style.width=`${a.w}vh`,i.style.height=`${a.h}vh`,i.style.left=`calc(50% - ${a.w/2}vh)`,i.style.top=`calc(50% - ${a.h/2}vh)`,s.style.width=`${o.w}vh`,s.style.height=`${o.h}vh`,s.style.left=`calc(50% - ${o.w/2}vh)`,s.style.top=`calc(50% - ${o.h/2}vh)`}r.appendChild(s),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){if(!this._loadingDiv)return;const e=()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)};this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",e)}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}Om.DefaultLogoUrl="";Om.DefaultSpinnerUrl="";De.DefaultLoadingScreenFactory=n=>new Om(n);class p2{static ConvertPanoramaToCubemap(e,t,i,r,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";const a=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s),o=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s),c=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s),l=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s),h=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s),u=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s);return{front:a,back:o,left:c,right:l,up:h,down:u,size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,a=!1){const o=new ArrayBuffer(e*e*4*3),c=new Float32Array(o),l=a?Math.max(1,Math.round(r/4/e)):1,h=1/l,u=h*h,d=t[1].subtract(t[0]).scale(h/e),f=t[3].subtract(t[2]).scale(h/e),p=1/e;let _=0;for(let m=0;mMath.PI;)s-=2*Math.PI;let o=s/Math.PI;const c=a/Math.PI;o=o*.5+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(c*r);h<0?h=0:h>=r&&(h=r-1);const u=r-h-1,d=t[u*i*3+l*3+0],f=t[u*i*3+l*3+1],p=t[u*i*3+l*3+2];return{r:d,g:f,b:p}}}p2.FACE_LEFT=[new P(-1,-1,-1),new P(1,-1,-1),new P(-1,1,-1),new P(1,1,-1)];p2.FACE_RIGHT=[new P(1,-1,1),new P(-1,-1,1),new P(1,1,1),new P(-1,1,1)];p2.FACE_FRONT=[new P(1,-1,-1),new P(1,-1,1),new P(1,1,-1),new P(1,1,1)];p2.FACE_BACK=[new P(-1,-1,1),new P(-1,-1,-1),new P(-1,1,1),new P(-1,1,-1)];p2.FACE_DOWN=[new P(1,1,-1),new P(1,1,1),new P(-1,1,-1),new P(-1,1,1)];p2.FACE_UP=[new P(-1,-1,-1),new P(-1,-1,1),new P(1,-1,-1),new P(1,-1,1)];class Xz{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,r,s,a){s>0?(s=this._Ldexp(1,s-136),e[a+0]=t*s,e[a+1]=i*s,e[a+2]=r*s):(e[a+0]=0,e[a+1]=0,e[a+2]=0)}static _ReadStringLine(e,t){let i="",r="";for(let s=t;s32767)throw"HDR Bad header format, unsupported size";return o+=r.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const r=new Uint8Array(e),s=this.RGBE_ReadHeader(r),a=this.RGBE_ReadPixels(r,s);return p2.ConvertPanoramaToCubemap(a,s.width,s.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const r=t.width;let s,a,o,c,l,h=t.dataPosition,u=0,d=0,f=0;const p=new ArrayBuffer(r*4),_=new Uint8Array(p),m=new ArrayBuffer(t.width*t.height*4*3),g=new Float32Array(m);for(;i>0;){if(s=e[h++],a=e[h++],o=e[h++],c=e[h++],s!=2||a!=2||o&128||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|c)!=r)throw"HDR Bad header format, wrong scan line width";for(u=0,f=0;f<4;f++)for(d=(f+1)*r;u128){if(l=s-128,l==0||l>d-u)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)_[u++]=a}else{if(l=s,l==0||l>d-u)throw"HDR Bad Format, bad scanline data (non-run)";if(_[u++]=a,--l>0)for(let v=0;v0;){for(l=0;l #include #include #include uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`;Re.ShadersStore[uNe]=dNe;class Fee{constructor(e,t={}){this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}_createRenderTarget(e){let t=0;this._engine.getCaps().textureHalfFloatRender?t=2:this._engine.getCaps().textureFloatRender&&(t=1);const i=this._engine.createRenderTargetCubeTexture(e,{format:5,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(i.texture,0,0,0),this._engine.updateTextureSamplingMode(3,i.texture,!0),i}_prefilterInternal(e){const t=e.getSize().width,i=_t.ILog2(t)+1,r=this._effectWrapper.effect,s=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();const a=e.getInternalTexture();a&&this._engine.updateTextureSamplingMode(3,a,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);const o=[[new P(0,0,-1),new P(0,-1,0),new P(1,0,0)],[new P(0,0,1),new P(0,-1,0),new P(-1,0,0)],[new P(1,0,0),new P(0,0,1),new P(0,1,0)],[new P(1,0,0),new P(0,0,-1),new P(0,-1,0)],[new P(1,0,0),new P(0,-1,0),new P(0,0,1)],[new P(-1,0,0),new P(0,-1,0),new P(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let h=0;h<6;h++){r.setVector3("up",o[h][0]),r.setVector3("right",o[h][1]),r.setVector3("front",o[h][2]);for(let u=0;u{this._effectRenderer=new QO(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(de.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class K0 extends Er{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(ce.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,s=!0,a=!1,o=!1,c=null,l=null,h=!1){var u;super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=P.Zero(),this.onLoadObservable=new Ae,e&&(this._coordinatesMode=ve.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=ce.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),c&&c()},this._onError=l,this.gammaSpace=a,this._noMipmap=r,this._size=i,this._supersample=h,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Ee.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):(u=this.getScene())!=null&&u.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2);const r=s=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const a=Xz.GetCubeMapTextureData(s,this._size,this._supersample);if(this._generateHarmonics){const h=q6.ConvertCubeMapToSphericalPolynomial(a);this.sphericalPolynomial=h}const o=[];let c=null,l=null;for(let h=0;h<6;h++){i===2?l=new Uint16Array(this._size*this._size*3):i===0&&(c=new Uint8Array(this._size*this._size*3));const u=a[K0._FacesMapping[h]];if(this.gammaSpace||l||c){for(let d=0;d255){const g=255/m;f*=g,p*=g,_*=g}c[d*3+0]=f,c[d*3+1]=p,c[d*3+2]=_}}l?o.push(l):c?o.push(c):o.push(u)}return o};if(e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const s=this._onLoad,a=new Fee(e);this._onLoad=()=>{a.prefilter(this,s)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,r,null,this._onLoad,this._onError)}clone(){const e=new K0(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){this.delayLoadState===4&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&((t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.getActiveTextures().indexOf(this)!==-1))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let r=null;return e.name&&!e.isRenderTarget&&(r=new K0(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),r.name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=P.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}K0._FacesMapping=["right","left","up","down","front","back"];xe("BABYLON.HDRCubeTexture",K0);class G3{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(t===0||e===0)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new Ae,this._onDataLayoutChanged=new Ae,this._animationPropertiesOverride=null,this._scene=i||bt.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=Qe.Clone(()=>new G3(this.name,this.influence,this._scene),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),this.id!=null&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),Qe.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new G3(e.name,e.influence);if(i.setPositions(e.positions),e.id!=null&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let r=0;r0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new ba(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=bt.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const t=this._scene.getEngine().getCaps();this._canUseTextureForTargets=t.canUseGLVertexID&&t.textureFloat&&t.maxVertexTextureImageUnits>0&&t.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){var e;return Of.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!((e=this._scene)!=null&&e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add(t=>{this._syncActiveTargets(t)})),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add(()=>{this._syncActiveTargets(!0)})),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new Of(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),(!this._morphTargetTextureIndices||this._morphTargetTextureIndices.length!==this._targets.length)&&(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const r of this._targets){if(i++,r.influence===0&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=Of.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(r),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=r.influence,this._supportsNormals=this._supportsNormals&&r.hasNormals,this._supportsTangents=this._supportsTangents&&r.hasTangents,this._supportsUVs=this._supportsUVs&&r.hasUVs;const s=r.getPositions();if(s){const a=s.length/3;if(this._vertexCount===0)this._vertexCount=a;else if(this._vertexCount!==a){de.Error("Incompatible target. Targets must all have the same vertices count.");return}}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),(!this._influences||this._influences.length!==t)&&(this._influences=new Float32Array(t));for(let r=0;r0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const i=this._targetStoreTexture.getSize();i.width===this._textureWidth&&i.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const i=this._targets.length,r=new Float32Array(i*this._textureWidth*this._textureHeight*4);let s=0;for(let a=0;a-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new Of(t);i._uniqueId=e.id;for(const r of e.targets)i.addTarget(G3.Parse(r,t));return i}}Of.EnableTextureStorage=!0;Of.MaxActiveMorphTargetsInVertexAttributeMode=8;class Uee{constructor(){this._hasHit=!1,this._hitNormal=P.Zero(),this._hitPoint=P.Zero(),this._triangleIndex=-1}get hitPoint(){return this._hitPoint}get hitNormal(){return this._hitNormal}get hasHit(){return this._hasHit}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormal.set(e.x,e.y,e.z),this._hitPoint.set(t.x,t.y,t.z),this._triangleIndex=i??-1}reset(){this._hasHit=!1,this._hitNormal.setAll(0),this._hitPoint.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0,this.shape=void 0}}class C9 extends Uee{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=P.Zero(),this._rayToWorld=P.Zero()}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormal}get hitPointWorld(){return this._hitPoint}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=P.Distance(this._rayFromWorld,this._hitPoint)}reset(e=P.Zero(),t=P.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}let kee=class uge{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw ci("CannonJSPlugin")}constructor(e,t=uge.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new P(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach(function(e){e.dispose()}),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){const r=this._joints.filter(function(s){return s.connectedImpostor===t&&s.joint===i&&s.mainImpostor===e});r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach(t=>{t.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(t)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach(e=>{typeof this.world.removeBody=="function"?this.world.removeBody(e):this.world.remove(e)}),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,r)}applyForce(e,t,i){const r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t){de.Warn("It was not possible to create a physics body for this object.");return}const i=e.physicsBody;i&&this.removePhysicsBody(e);const r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:r},a=e.getParam("nativeOptions");for(const o in a)Object.prototype.hasOwnProperty.call(a,o)&&(s[o]=a[o]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),typeof this.world.addBody=="function"?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(o){const c=i[o];e.physicsBody[o].set(c.x,c.y,c.z)}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const r=s=>{if(!s.rotationQuaternion)return;const a=s.getPhysicsImpostor();if(a&&a.parent!==e&&s.parent){const c=s.getAbsolutePosition().subtract(s.parent.getAbsolutePosition()),l=s.rotationQuaternion.multiply(this._tmpQuaternion);a.physicsBody&&(this.removePhysicsBody(a),a.physicsBody=null),a.parent=e,a.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(a),new this.BJSCANNON.Vec3(c.x,c.y,c.z),new this.BJSCANNON.Quaternion(l.x,l.y,l.z,l.w)),e.physicsBody.mass+=a.getParam("mass")}s.getChildMeshes(!0).filter(o=>!!o.physicsImpostor).forEach(r)};t.filter(s=>!!s.physicsImpostor).forEach(r)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)===-1&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let r;const s=e.joint.jointData,a={pivotA:s.mainPivot?new this.BJSCANNON.Vec3().set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?new this.BJSCANNON.Vec3().set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?new this.BJSCANNON.Vec3().set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?new this.BJSCANNON.Vec3().set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case as.HingeJoint:case as.Hinge2Joint:r=new this.BJSCANNON.HingeConstraint(t,i,a);break;case as.DistanceJoint:r=new this.BJSCANNON.DistanceConstraint(t,i,s.maxDistance||2);break;case as.SpringJoint:{const o=s;r=new this.BJSCANNON.Spring(t,i,{restLength:o.length,stiffness:o.stiffness,damping:o.damping,localAnchorA:a.pivotA,localAnchorB:a.pivotB});break}case as.LockJoint:r=new this.BJSCANNON.LockConstraint(t,i,a);break;case as.PointToPointJoint:case as.BallAndSocketJoint:default:r=new this.BJSCANNON.PointToPointConstraint(t,a.pivotA,i,a.pivotB,a.maxForce);break}r.collideConnected=!!s.collision,e.joint.physicsJoint=r,e.joint.type!==as.SpringJoint?this.world.addConstraint(r):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){r.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==as.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,s;for(r=0;ri*1e3));d++);this.time+=r;const l=this.time%i/i,h=e,u=this.bodies;for(let d=0;d!==u.length;d++){const f=u[d];f.type!==t.Body.STATIC&&f.sleepState!==t.Body.SLEEPING?(f.position.vsub(f.previousPosition,h),h.scale(l,h),f.position.vadd(h,f.interpolatedPosition)):(f.interpolatedPosition.set(f.position.x,f.position.y,f.position.z),f.interpolatedQuaternion.set(f.quaternion.x,f.quaternion.y,f.quaternion.z,f.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}kee.DefaultPluginFactory=()=>new Yz;class eZ{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=P.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new C9}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach(function(r){r.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach(r=>{r.afterStep(),this._tmpImpostorsArray[r.uniqueId]=r});let i=this.world.contacts;for(;i!==null;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const r=this._tmpImpostorsArray[+i.body1.name],s=this._tmpImpostorsArray[+i.body2.name];if(!r||!s){i=i.next;continue}r.onCollide({body:s.physicsBody,point:null,distance:0,impulse:0,normal:null}),s.onCollide({body:r.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next}}applyImpulse(e,t,i){const r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){de.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){const t={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:e.getParam("mass")!==0,density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},i=[e];(o=>{o.getChildMeshes&&o.getChildMeshes().forEach(function(c){c.physicsImpostor&&i.push(c.physicsImpostor)})})(e.object);const s=o=>Math.max(o,ni),a=new we;i.forEach(o=>{if(!o.object.rotationQuaternion)return;const c=o.object.rotationQuaternion;a.copyFrom(c),o.object.rotationQuaternion.set(0,0,0,1),o.object.computeWorldMatrix(!0);const l=a.toEulerAngles(),h=o.getObjectExtents(),u=57.29577951308232;if(o===e){const d=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(d,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),t.pos.push(d.x),t.pos.push(d.y),t.pos.push(d.z),t.posShape.push(0,0,0),t.rotShape.push(0,0,0)}else{const d=o.object.position.clone();t.posShape.push(d.x),t.posShape.push(d.y),t.posShape.push(d.z),t.rotShape.push(l.x*u,l.y*u,l.z*u)}switch(o.object.rotationQuaternion.copyFrom(a),o.type){case Zt.ParticleImpostor:de.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case Zt.SphereImpostor:{const d=h.x,f=h.y,p=h.z,_=Math.max(s(d),s(f),s(p))/2;t.type.push("sphere"),t.size.push(_),t.size.push(_),t.size.push(_);break}case Zt.CylinderImpostor:{const d=s(h.x)/2,f=s(h.y);t.type.push("cylinder"),t.size.push(d),t.size.push(f),t.size.push(f);break}case Zt.PlaneImpostor:case Zt.BoxImpostor:default:{const d=s(h.x),f=s(h.y),p=s(h.z);t.type.push("box"),t.size.push(d),t.size.push(f),t.size.push(p);break}}o.object.rotationQuaternion=c}),e.physicsBody=this.world.add(t),e.physicsBody.resetQuaternion(a),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const r=e.joint.jointData,s=r.nativeParams||{};let a;const o={body1:t,body2:i,axe1:s.axe1||(r.mainAxis?r.mainAxis.asArray():null),axe2:s.axe2||(r.connectedAxis?r.connectedAxis.asArray():null),pos1:s.pos1||(r.mainPivot?r.mainPivot.asArray():null),pos2:s.pos2||(r.connectedPivot?r.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||r.collision,spring:s.spring,world:this.world};switch(e.joint.type){case as.BallAndSocketJoint:a="jointBall";break;case as.SpringJoint:{de.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const c=r;o.min=c.length||o.min,o.max=Math.max(o.min,o.max)}case as.DistanceJoint:a="jointDistance",o.max=r.maxDistance;break;case as.PrismaticJoint:a="jointPrisme";break;case as.SliderJoint:a="jointSlide";break;case as.WheelJoint:a="jointWheel";break;case as.HingeJoint:default:a="jointHinge";break}o.type=a,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(t){de.Warn(t)}}isSupported(){return this.BJSOIMO!==void 0}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new P(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new P(t.x,t.y,t.z):null}setBodyMass(e,t){const i=t===0;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,i!==void 0&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){i!==void 0?de.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,r){const s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,i===void 0?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=i.halfWidth*2,t.y=i.halfHeight*2,t.z=i.halfDepth*2}dispose(){this.world.clear()}raycast(e,t){return de.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){de.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class Zp{constructor(e=!0,t=Ammo,i=null){if(this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new we,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new P,this._tmpContactNormal=new P,this._tmpVec3=new P,this._tmpMatrix=new ce,typeof t=="function"){de.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}else this.bjsAMMO=t;if(!this.isSupported()){de.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=r=>{r=this.bjsAMMO.wrapPointer(r,this.bjsAMMO.btManifoldPoint);const s=r.getPositionWorldOnA(),a=r.m_normalWorldOnB;this._tmpContactPoint.x=s.x(),this._tmpContactPoint.y=s.y(),this._tmpContactPoint.z=s.z(),this._tmpContactNormal.x=a.x(),this._tmpContactNormal.y=a.y(),this._tmpContactNormal.z=a.z(),this._tmpContactImpulse=r.getAppliedImpulse(),this._tmpContactDistance=r.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new C9,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(t==0)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(i))for(const r of i._onPhysicsCollideCallbacks)for(const s of r.otherImpostors)(i.physicsBody.isActive()||s.physicsBody.isActive())&&this._isImpostorPairInContact(i,s)&&(i.onCollide({body:s.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),s.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===Zt.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let r,s,a,o,c;const l=new Array;for(let d=0;d{this.bjsAMMO.destroy(t)}),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const r=e.joint.jointData;r.mainPivot||(r.mainPivot=new P(0,0,0)),r.connectedPivot||(r.connectedPivot=new P(0,0,0));let s;switch(e.joint.type){case as.DistanceJoint:{const a=r.maxDistance;a&&(r.mainPivot=new P(0,-a/2,0),r.connectedPivot=new P(0,a/2,0)),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z),new this.bjsAMMO.btVector3(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z));break}case as.HingeJoint:{r.mainAxis||(r.mainAxis=new P(0,0,0)),r.connectedAxis||(r.connectedAxis=new P(0,0,0));const a=new this.bjsAMMO.btVector3(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z),o=new this.bjsAMMO.btVector3(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z);s=new this.bjsAMMO.btHingeConstraint(t,i,new this.bjsAMMO.btVector3(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z),new this.bjsAMMO.btVector3(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),a,o);break}case as.BallAndSocketJoint:s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z),new this.bjsAMMO.btVector3(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z));break;default:de.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z),new this.bjsAMMO.btVector3(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z));break}this.world.addConstraint(s,!e.joint.jointData.collision),e.joint.physicsJoint=s}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let a=i.getVerticesData(Z.PositionKind);a||(a=[]);let o;if(t&&t!==i){let l;t.rotationQuaternion?l=t.rotationQuaternion:t.rotation?l=we.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):l=we.Identity(),ce.Compose(P.One(),l,t.position).invertToRef(this._tmpMatrix),o=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else ce.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),o=this._tmpMatrix;const c=s.length/3;for(let l=0;l{r+=this._addMeshVerts(e,t,l)})}return r}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){t.getIndices();let i=t.getVerticesData(Z.PositionKind);i||(i=[]);let r=t.getVerticesData(Z.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);const s=[],a=[];for(let c=0;cd*d),c=(d,f)=>d+f;if(o.reduce(c)===0)t=s.length,i=t/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;const d=e.getParam("path");if(e.getParam("shape")===null)return de.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=d.length,i=t-1,this._tmpAmmoVectorA.setValue(d[0].x,d[0].y,d[0].z),this._tmpAmmoVectorB.setValue(d[t-1].x,d[t-1].y,d[t-1].z)}e.segments=i;let h=e.getParam("fixedPoints");h=h>3?3:h;const u=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,h);return u.get_m_cfg().set_collisions(17),u}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),t==null&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let a=i.getVerticesData(Z.PositionKind);a||(a=[]),i.computeWorldMatrix(!1);const o=s.length/3;for(let c=0;c{r+=this._addHullVerts(e,t,c)})}return r}_createShape(e,t=!1){const i=e.object;let r;const s=e.getObjectExtents();if(!t){const a=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];r=new this.bjsAMMO.btCompoundShape;let o=0;if(a.forEach(c=>{const l=c.getPhysicsImpostor();if(l){if(l.type==Zt.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const h=this._createShape(l),u=c.parent.getWorldMatrix().clone(),d=new P;u.decompose(d),this._tmpAmmoTransform.getOrigin().setValue(c.position.x*d.x,c.position.y*d.y,c.position.z*d.z),this._tmpAmmoQuaternion.setValue(c.rotationQuaternion.x,c.rotationQuaternion.y,c.rotationQuaternion.z,c.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),r.addChildShape(this._tmpAmmoTransform,h),l.dispose(),o++}}),o>0){if(e.type!=Zt.NoImpostor){const c=this._createShape(e,!0);c&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),r.addChildShape(this._tmpAmmoTransform,c))}return r}else this.bjsAMMO.destroy(r),r=null}switch(e.type){case Zt.SphereImpostor:if(_t.WithinEpsilon(s.x,s.y,1e-4)&&_t.WithinEpsilon(s.x,s.z,1e-4))r=new this.bjsAMMO.btSphereShape(s.x/2);else{const a=[new this.bjsAMMO.btVector3(0,0,0)],o=[1];r=new this.bjsAMMO.btMultiSphereShape(a,o,1),r.setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case Zt.CapsuleImpostor:{const a=s.x/2;r=new this.bjsAMMO.btCapsuleShape(a,s.y-a*2)}break;case Zt.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),r=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case Zt.PlaneImpostor:case Zt.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),r=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case Zt.MeshImpostor:if(e.getParam("mass")==0){if(this.onCreateCustomMeshImpostor)r=this.onCreateCustomMeshImpostor(e);else{const a=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(a),this._addMeshVerts(a,i,i)==0?r=new this.bjsAMMO.btCompoundShape:r=new this.bjsAMMO.btBvhTriangleMeshShape(a)}break}case Zt.ConvexHullImpostor:{if(this.onCreateCustomConvexHullImpostor)r=this.onCreateCustomConvexHullImpostor(e);else{const a=new this.bjsAMMO.btConvexHullShape;this._addHullVerts(a,i,i)==0?(e._pluginData.toDispose.push(a),r=new this.bjsAMMO.btCompoundShape):r=a}break}case Zt.NoImpostor:r=new this.bjsAMMO.btSphereShape(s.x/2);break;case Zt.CustomImpostor:r=this._createCustom(e);break;case Zt.SoftbodyImpostor:r=this._createSoftbody(e);break;case Zt.ClothImpostor:r=this._createCloth(e);break;case Zt.RopeImpostor:r=this._createRope(e);break;default:de.Warn("The impostor type is not currently supported by the ammo plugin.");break}return r}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>ni||Math.abs(r.getOrigin().y()-t.y)>ni||Math.abs(r.getOrigin().z()-t.z)>ni||Math.abs(r.getRotation().x()-i.x)>ni||Math.abs(r.getRotation().y()-i.y)>ni||Math.abs(r.getRotation().z()-i.z)>ni||Math.abs(r.getRotation().w()-i.w)>ni)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),e.mass==0){const s=e.physicsBody.getMotionState();s&&s.setWorldTransform(r)}else e.physicsBody.activate()}isSupported(){return this.bjsAMMO!==void 0}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(e.soft?t=e.physicsBody.linearVelocity():t=e.physicsBody.getLinearVelocity(),!t)return null;const i=new P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(e.soft?t=e.physicsBody.angularVelocity():t=e.physicsBody.getAngularVelocity(),!t)return null;const i=new P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(de.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===Zt.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):de.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(de.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=t<0?0:t,t=t>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):de.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(de.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):de.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(de.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):de.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,s=1,a=!1){const o=e.segments,c=Math.round((o-1)*i),l=Math.round((o-1)*r),h=o-1-l,u=c+o*h;e.physicsBody.appendAnchor(u,t.physicsBody,a,s)}appendHook(e,t,i,r=1,s=!1){const a=Math.round(e.segments*i);e.physicsBody.appendAnchor(a,t.physicsBody,s,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){de.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){de.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}Zp._DISABLE_COLLISION_FLAG=4;Zp._KINEMATIC_FLAG=2;Zp._DISABLE_DEACTIVATION_FLAG=4;da.prototype.removeReflectionProbe=function(n){if(!this.reflectionProbes)return-1;const e=this.reflectionProbes.indexOf(n);return e!==-1&&this.reflectionProbes.splice(e,1),e};da.prototype.addReflectionProbe=function(n){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(n)};class eC{constructor(e,t,i,r=!0,s=!1,a=!1){if(this.name=e,this._viewMatrix=ce.Identity(),this._target=P.Zero(),this._add=P.Zero(),this._invertYAxis=!1,this.position=P.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let h=0;h<6;++h)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${h}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(s){const h=this._scene.getEngine().getCaps();h.textureHalfFloatRender?o=2:h.textureFloatRender&&(o=1)}this._renderTargetTexture=new es(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!a,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const c=i.getEngine().useReverseDepthBuffer;this._renderTargetTexture.onBeforeRenderObservable.add(h=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[h]),i.getSceneUniformBuffer().unbindEffect()),h){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1);break}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const u=i.useRightHandedSystem?ce.LookAtRHToRef:ce.LookAtLHToRef,d=i.useRightHandedSystem?ce.PerspectiveFovRH:ce.PerspectiveFovLH;u(this.position,this._target,P.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=d(Math.PI/2,1,c?i.activeCamera.maxZ:i.activeCamera.minZ,c?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position});let l;this._renderTargetTexture.onBeforeBindObservable.add(()=>{var h,u;this._currentSceneUBO=i.getSceneUniformBuffer(),(u=(h=i.getEngine())._debugPushGroup)==null||u.call(h,`reflection probe generation for ${e}`,1),l=this._scene.imageProcessingConfiguration.applyByPostProcess,a&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var h,u;i.imageProcessingConfiguration.applyByPostProcess=l,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),(u=(h=i.getEngine())._debugPopGroup)==null||u.call(h,1)})}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(e!==-1&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const t=this._parentContainer.reflectionProbes.indexOf(this);t>-1&&this._parentContainer.reflectionProbes.splice(t,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const t of this._sceneUBOs)t.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=Qe.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let s=0;sr||new eC(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i),r.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}}B([I5()],eC.prototype,"_attachedMesh",void 0);B([Js()],eC.prototype,"position",void 0);class fNe{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class $G extends fNe{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new Ae,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new Ze(1,1,1,1),this.position=P.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,r,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e0)for(let s=0;s=r.distance)&&(r=o,t))break}return r||new Ro};pt.prototype._internalMultiPickSprites=function(n,e,t){if(!Ro)return null;let i=[];if(!t){if(!this.activeCamera)return null;t=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let r=0;rt.actionManager?t.isPickable&&t.actionManager.hasPointerTriggers:!1}register(){this.scene._pointerMoveStage.registerStep(it.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(it.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(it.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,s){const a=this.scene.pickSprite(t,i,this._spritePredicate,r,s);return a&&(a.ray=e?e.ray:null),a}_pointerMove(e,t,i,r,s){const a=this.scene;return r?a.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,a.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite?(a.setPointerOverSprite(i.pickedSprite),!a.doNotHandleCursors&&s&&(a._pointerOverSprite&&a._pointerOverSprite.actionManager&&a._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=a._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=a.hoverCursor)):a.setPointerOverSprite(null)),i}_pointerDown(e,t,i,r){const s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager)){switch(s._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,pn.CreateNewFromSprite(i.pickedSprite,s,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,pn.CreateNewFromSprite(i.pickedSprite,s,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,pn.CreateNewFromSprite(i.pickedSprite,s,r));break}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,pn.CreateNewFromSprite(i.pickedSprite,s,r))}return i}_pointerUp(e,t,i,r,s){const a=this.scene;if(a.spriteManagers&&a.spriteManagers.length>0){const o=a.pickSprite(e,t,this._spritePredicate,!1,a.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(7,pn.CreateNewFromSprite(o.pickedSprite,a,r)),o.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||o.pickedSprite.actionManager.processTrigger(1,pn.CreateNewFromSprite(o.pickedSprite,a,r)),s&&o.pickedSprite.actionManager.processTrigger(6,pn.CreateNewFromSprite(o.pickedSprite,a,r)))),a._pickedDownSprite&&a._pickedDownSprite.actionManager&&a._pickedDownSprite!==o.pickedSprite&&a._pickedDownSprite.actionManager.processTrigger(16,pn.CreateNewFromSprite(a._pickedDownSprite,a,r)))}return i}}const pNe="imageProcessingCompatibility",_Ne=`#ifdef IMAGEPROCESSINGPOSTPROCESS gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); #endif `;Re.IncludesShadersStore[pNe]=_Ne;const mNe="spritesPixelShader",gNe=`uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS #ifdef PIXEL_PERFECT vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} #endif void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #ifdef PIXEL_PERFECT vec2 uv=uvPixelPerfect(vUV); #else vec2 uv=vUV; #endif vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) {if (color.a<0.95) discard;} color*=vColor; #include gl_FragColor=color; #include #define CUSTOM_FRAGMENT_MAIN_END }`;Re.ShadersStore[mNe]=gNe;const vNe="spritesVertexShader",xNe=`attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; #ifdef FOG vFogDistance=viewPos; #endif #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[vNe]=xNe;class yNe{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,r=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new no(e,this._vertexData,!0,this._vertexBufferSize);const s=this._buffer.createVertexBuffer(Z.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),a=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o=6,c;if(this._useInstancing){const d=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new no(e,d,!1,2),c=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else c=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;const l=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer(Z.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Z.PositionKind]=s,this._vertexBuffers.options=a,this._vertexBuffers.offsets=c,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[Z.ColorKind]=u,this._createEffects()}_createEffects(){var t,i,r,s;(t=this._drawWrapperBase)==null||t.dispose(),(i=this._drawWrapperFog)==null||i.dispose(),(r=this._drawWrapperDepth)==null||r.dispose(),(s=this._drawWrapperFogDepth)==null||s.dispose(),this._drawWrapperBase=new Sn(this._engine),this._drawWrapperFog=new Sn(this._engine),this._drawWrapperDepth=new Sn(this._engine,!1),this._drawWrapperFogDepth=new Sn(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);const e=this._pixelPerfect?`#define PIXEL_PERFECT `:"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[Z.PositionKind,"options","offsets","inverts","cellInfo",Z.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],e),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[Z.PositionKind,"options","offsets","inverts","cellInfo",Z.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],e+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,r,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let a=this._drawWrapperBase,o=this._drawWrapperDepth,c=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&this._scene.fogMode!==0&&(a=this._drawWrapperFog,o=this._drawWrapperFogDepth,c=!0);const l=a.effect;if(!l.isReady())return;const h=this._engine,u=!!(this._scene&&this._scene.useRightHandedSystem),d=this.texture.getBaseSize(),f=Math.min(this._capacity,e.length);let p=0,_=!0;for(let x=0;x>0;t._xOffset=(t.cellIndex-h*l)*this.cellWidth/s.width,t._yOffset=h*this.cellHeight/s.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[c]=t.position.x,this._vertexData[c+1]=t.position.y,this._vertexData[c+2]=t.position.z,this._vertexData[c+3]=t.angle,this._vertexData[c+4]=t.width,this._vertexData[c+5]=t.height,this._useInstancing?c-=2:(this._vertexData[c+6]=i,this._vertexData[c+7]=r),a?this._vertexData[c+8]=t.invertU?0:1:this._vertexData[c+8]=t.invertU?1:0,this._vertexData[c+9]=t.invertV?1:0,this._vertexData[c+10]=t._xOffset,this._vertexData[c+11]=t._yOffset,this._vertexData[c+12]=t._xSize/s.width,this._vertexData[c+13]=t._ySize/s.height,this._vertexData[c+14]=t.color.r,this._vertexData[c+15]=t.color.g,this._vertexData[c+16]=t.color.b,this._vertexData[c+17]=t.color.a}_buildIndexBuffer(){const e=[];let t=0;for(let i=0;i{u.cellRef||(u.cellIndex=0);const f=u.cellIndex;typeof f=="number"&&isFinite(f)&&Math.floor(f)===f&&(u.cellRef=this._spriteMap[u.cellIndex]),u._xOffset=this._cellData[u.cellRef].frame.x/d.width,u._yOffset=this._cellData[u.cellRef].frame.y/d.height,u._xSize=this._cellData[u.cellRef].frame.w,u._ySize=this._cellData[u.cellRef].frame.h},s||(s=bt.LastCreatedScene),s._getComponent(it.NAME_SPRITE)||s._addComponent(new dge(s)),this._fromPacked=c,this._scene=s;const h=this._scene.getEngine();if(this._spriteRenderer=new yNe(h,i,a,s),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else if(r!==void 0)this.cellWidth=r,this.cellHeight=r;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new ve(t,s,!0,!1,o)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(t!==null)try{let i;if(typeof t=="string"?i=JSON.parse(t):i=t,i.frames.length){const s={};for(let a=0;a0);const s=e.substring(0,r-1)+".json",a=()=>{de.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},o=c=>{try{const l=JSON.parse(c),h=Reflect.ownKeys(l.frames);this._spriteMap=h,this._packedAndReady=!0,this._cellData=l.frames}catch{throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};Ee.LoadFile(s,o,void 0,void 0,!1,a)}}_checkTextureAlpha(e,t,i,r,s){if(!e.useAlphaForPicking||!this.texture)return!0;const a=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(a.width*a.height*4),this.texture.readPixels(0,0,this._textureContent));const o=ie.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const c=(o.x-r.x)/(s.x-r.x),l=1-(o.y-r.y)/(s.y-r.y),h=e._xOffset*a.width+c*e._xSize|0,u=e._yOffset*a.height+l*e._ySize|0;return this._textureContent[(h+u*a.width)*4+3]>.5}intersects(e,t,i,r){const s=Math.min(this.capacity,this.sprites.length),a=P.Zero(),o=P.Zero();let c=Number.MAX_VALUE,l=null;const h=ie.Vector3[0],u=ie.Vector3[1],d=t.getViewMatrix();let f=e,p=e;for(let _=0;_g){if(!this._checkTextureAlpha(m,f,g,a,o))continue;if(p=f,c=g,l=m,r)break}}}}if(l){const _=new Ro;d.invertToRef(ie.Matrix[0]),_.hit=!0,_.pickedSprite=l,_.distance=c;const m=ie.Vector3[2];return m.copyFrom(p.direction),m.normalize(),m.scaleInPlace(c),p.origin.addToRef(m,h),_.pickedPoint=P.TransformCoordinates(h,ie.Matrix[0]),_}return null}multiIntersects(e,t,i){const r=Math.min(this.capacity,this.sprites.length),s=P.Zero(),a=P.Zero();let o;const c=[],l=ie.Vector3[0].copyFromFloats(0,0,0),h=ie.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix();for(let d=0;d{const o=new on;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const c=JSON.parse(o.responseText),l=qp.Parse(c,i||bt.LastCreatedScene,r);e&&(l.name=e),s(l)}else a("Unable to load the sprite manager")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return e==="_BLANK"?Promise.resolve(new qp("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((r,s)=>{const a=new on;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),c=JSON.parse(o.spriteManager),l=qp.Parse(c,t||bt.LastCreatedScene,i);l.snippetId=e,r(l)}else s("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}}qp.SnippetUrl="https://snippet.babylonjs.com";qp.CreateFromSnippetAsync=qp.ParseFromSnippetAsync;var ANe=!0;class gD{}gD.LoaderInjectedPhysicsEngine=void 0;let PS={},w3={};const Fde=(n,e,t,i)=>{if(!e.materials)return null;for(let r=0,s=e.materials.length;r{for(const i in e)if(n.name===e[i])return t.push(n.id),!0;return n.parentId!==void 0&&t.indexOf(n.parentId)!==-1?(t.push(n.id),!0):!1},BS=(n,e)=>n+" of "+(e?e.file+" from "+e.name+" version: "+e.version+", exporter version: "+e.exporter_version:"unknown"),fge=(n,e)=>{const t=e;if(e._waitingData.lods){if(e._waitingData.lods.ids&&e._waitingData.lods.ids.length>0){const i=e._waitingData.lods.ids,r=t.isEnabled(!1);if(e._waitingData.lods.distances){const s=e._waitingData.lods.distances;if(s.length>=i.length){const a=s.length>i.length?s[s.length-1]:0;t.setEnabled(!1);for(let o=0;o0&&t.addLODLevel(a,null),r===!0&&t.setEnabled(!0)}else Ee.Warn("Invalid level of detail distances for "+e.name)}}e._waitingData.lods=null}},yV=(n,e,t)=>{if(typeof n!="number"){const r=t.getLastEntryById(n);return r&&e!==void 0&&e!==null?r.instances[parseInt(e)]:r}const i=PS[n];return i&&e!==void 0&&e!==null?i.instances[parseInt(e)]:i},Qz=(n,e)=>typeof n!="number"?e.getLastMaterialById(n,!0):w3[n],Ude=(n,e,t,i,r=!1)=>{const s=new jO(n);let a="importScene has failed JSON parse";try{var o=JSON.parse(e);a="";const c=ai.loggingLevel===ai.DETAILED_LOGGING;let l,h;if(o.environmentTexture!==void 0&&o.environmentTexture!==null){const d=o.isPBR!==void 0?o.isPBR:!0;if(o.environmentTextureType&&o.environmentTextureType==="BABYLON.HDRCubeTexture"){const f=o.environmentTextureSize?o.environmentTextureSize:128,p=new K0((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,n,f,!0,!d,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(p.rotationY=o.environmentTextureRotationY),n.environmentTexture=p}else if(typeof o.environmentTexture=="object"){const f=Bn.Parse(o.environmentTexture,n,t);n.environmentTexture=f}else if(o.environmentTexture.endsWith(".env")){const f=new Bn((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,n,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),n.environmentTexture=f}else{const f=Bn.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,n,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),n.environmentTexture=f}if(o.createDefaultSkybox===!0){const f=n.activeCamera!==void 0&&n.activeCamera!==null?(n.activeCamera.maxZ-n.activeCamera.minZ)/2:1e3,p=o.skyboxBlurLevel||0;n.createDefaultSkybox(n.environmentTexture,d,f,p)}s.environmentTexture=n.environmentTexture}if(o.environmentIntensity!==void 0&&o.environmentIntensity!==null&&(n.environmentIntensity=o.environmentIntensity),o.lights!==void 0&&o.lights!==null)for(l=0,h=o.lights.length;l{s.textures.indexOf(_)==-1&&(s.textures.push(_),_._parentContainer=s)}))}if(o.multiMaterials!==void 0&&o.multiMaterials!==null)for(l=0,h=o.multiMaterials.length;l{s.textures.indexOf(_)==-1&&(s.textures.push(_),_._parentContainer=s)})}if(o.morphTargetManagers!==void 0&&o.morphTargetManagers!==null)for(const d of o.morphTargetManagers){const f=Of.Parse(d,n);s.morphTargetManagers.push(f),f._parentContainer=s}if(o.skeletons!==void 0&&o.skeletons!==null)for(l=0,h=o.skeletons.length;l{p&&(s.geometries.push(p),p._parentContainer=s)})}if(o.transformNodes!==void 0&&o.transformNodes!==null)for(l=0,h=o.transformNodes.length;l{d._waitingSubMaterialsUniqueIds.forEach(f=>{d.subMaterials.push(Qz(f,n))}),d._waitingSubMaterialsUniqueIds=[]}),n.meshes.forEach(d=>{d._waitingMaterialId!==null&&(d.material=Qz(d._waitingMaterialId,n),d._waitingMaterialId=null)}),l=0,h=n.skeletons.length;l{if(f._waitingTransformNodeId){const p=n.getLastEntryById(f._waitingTransformNodeId);p&&f.linkTransformNode(p),f._waitingTransformNodeId=null}}),d._hasWaitingData=null)}for(l=0,h=n.meshes.length;l0){for(let f=0;f0){for(let f=0;f{d._loadedUniqueId=""}),da.Parse(o,n,s,t),l=0,h=n.meshes.length;ln.indexOf("babylon")!==-1,importMesh:(n,e,t,i,r,s,a,o)=>{var h;let c="importMesh has failed JSON parse";try{var l=JSON.parse(t);c="";const u=ai.loggingLevel===ai.DETAILED_LOGGING;n?Array.isArray(n)||(n=[n]):n=null;const d=[],f=new Map,p=[];if(l.transformNodes!==void 0&&l.transformNodes!==null)for(let _=0,m=l.transformNodes.length;_{S===!0||!l.geometries[N]||!Array.isArray(l.geometries[N])||l.geometries[N].forEach(D=>{if(D.id===b.geometryId){switch(N){case"vertexData":Ua.Parse(D,e,i);break}S=!0}})}),S===!1&&de.Warn("Geometry not found for mesh "+b.id)}if(b.materialUniqueId||b.materialId){const S=b.materialUniqueId?g:m;let N=S.indexOf(b.materialUniqueId||b.materialId)!==-1;if(N===!1&&l.multiMaterials!==void 0&&l.multiMaterials!==null){const D=(M,I)=>{S.push(M);const R=Fde(I,l,e,i);R&&R.material&&(w3[R.parsedMaterial.uniqueId||R.parsedMaterial.id]=R.material,c+=` Material `+R.material.toString(u))};for(let M=0,I=l.multiMaterials.length;MD(H,G=>G.uniqueId===H)):R.materials.forEach(H=>D(H,G=>G.id===H)),S.push(R.uniqueId||R.id);const O=Fu.ParseMultiMaterial(R,e);w3[R.uniqueId||R.id]=O,O&&(N=!0,c+=` Multi-Material `+O.toString(u));break}}}if(N===!1){S.push(b.materialUniqueId||b.materialId);const D=Fde(M=>b.materialUniqueId&&M.uniqueId===b.materialUniqueId||M.id===b.materialId,l,e,i);!D||!D.material?de.Warn("Material not found for mesh "+b.id):(w3[D.parsedMaterial.uniqueId||D.parsedMaterial.id]=D.material,c+=` Material `+D.material.toString(u))}}if(b.skeletonId!==null&&b.skeletonId!==void 0&&l.skeletonId!==-1&&l.skeletons!==void 0&&l.skeletons!==null&&!(_.indexOf(b.skeletonId)>-1))for(let N=0,D=l.skeletons.length;N-1&&l.morphTargetManagers!==void 0&&l.morphTargetManagers!==null&&!(v.indexOf(b.morphTargetManagerId)>-1))for(let N=0,D=l.morphTargetManagers.length;N{y._waitingSubMaterialsUniqueIds.forEach(C=>{y.subMaterials.push(Qz(C,e))}),y._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(y=>{y._waitingMaterialId!==null&&(y.material=Qz(y._waitingMaterialId,e),y._waitingMaterialId=null)});for(let y=0,C=e.transformNodes.length;y-1&&p.splice(S,1)}x._waitingParentId=null}x._waitingData.lods&&fge(e,x)}for(const y of p)y.dispose();for(let y=0,C=e.skeletons.length;y{if(T._waitingTransformNodeId){const S=e.getLastEntryById(T._waitingTransformNodeId);S&&T.linkTransformNode(S),T._waitingTransformNodeId=null}}),b._hasWaitingData=null)}for(let y=0,C=e.meshes.length;y{_._loadedUniqueId=""}),!0}catch(u){const d=BS("importMesh",l?l.producer:"Unknown")+c;if(o)o(d,u);else throw de.Log(d),u}finally{c!==null&&ai.loggingLevel!==ai.NO_LOGGING&&de.Log(BS("importMesh",l?l.producer:"Unknown")+(ai.loggingLevel!==ai.MINIMAL_LOGGING?c:"")),w3={}}return!1},load:(n,e,t,i)=>{let r="importScene has failed JSON parse";try{var s=JSON.parse(e);if(r="",s.useDelayedTextureLoading!==void 0&&s.useDelayedTextureLoading!==null&&(n.useDelayedTextureLoading=s.useDelayedTextureLoading&&!ai.ForceFullSceneLoadingForIncremental),s.autoClear!==void 0&&s.autoClear!==null&&(n.autoClear=s.autoClear),s.clearColor!==void 0&&s.clearColor!==null&&(n.clearColor=Ze.FromArray(s.clearColor)),s.ambientColor!==void 0&&s.ambientColor!==null&&(n.ambientColor=Me.FromArray(s.ambientColor)),s.gravity!==void 0&&s.gravity!==null&&(n.gravity=P.FromArray(s.gravity)),s.useRightHandedSystem!==void 0&&(n.useRightHandedSystem=!!s.useRightHandedSystem),s.fogMode&&s.fogMode!==0)switch(n.fogMode=s.fogMode,n.fogColor=Me.FromArray(s.fogColor),n.fogStart=s.fogStart,n.fogEnd=s.fogEnd,n.fogDensity=s.fogDensity,r+=" Fog mode for scene: ",n.fogMode){case 1:r+=`exp `;break;case 2:r+=`exp2 `;break;case 3:r+=`linear `;break}if(s.physicsEnabled){let o;s.physicsEngine==="cannon"||s.physicsEngine===Yz.name?o=new Yz(void 0,void 0,gD.LoaderInjectedPhysicsEngine):s.physicsEngine==="oimo"||s.physicsEngine===eZ.name?o=new eZ(void 0,gD.LoaderInjectedPhysicsEngine):(s.physicsEngine==="ammo"||s.physicsEngine===Zp.name)&&(o=new Zp(void 0,gD.LoaderInjectedPhysicsEngine,void 0)),r=" Physics engine "+(s.physicsEngine?s.physicsEngine:"oimo")+` enabled `;const c=s.physicsGravity?P.FromArray(s.physicsGravity):null;n.enablePhysics(c,o)}return s.metadata!==void 0&&s.metadata!==null&&(n.metadata=s.metadata),s.collisionsEnabled!==void 0&&s.collisionsEnabled!==null&&(n.collisionsEnabled=s.collisionsEnabled),Ude(n,e,t,i,!0)?(s.autoAnimate&&n.beginAnimation(n,s.autoAnimateFrom,s.autoAnimateTo,s.autoAnimateLoop,s.autoAnimateSpeed||1),s.activeCameraID!==void 0&&s.activeCameraID!==null&&n.setActiveCameraById(s.activeCameraID),!0):!1}catch(a){const o=BS("importScene",s?s.producer:"Unknown")+r;if(i)i(o,a);else throw de.Log(o),a}finally{r!==null&&ai.loggingLevel!==ai.NO_LOGGING&&de.Log(BS("importScene",s?s.producer:"Unknown")+(ai.loggingLevel!==ai.MINIMAL_LOGGING?r:""))}return!1},loadAssetContainer:(n,e,t,i)=>Ude(n,e,t,i)});class $D{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,De.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=e.bias===void 0?0:e.bias,this.power=e.power===void 0?1:e.power,this.leftColor=e.leftColor||Me.White(),this.rightColor=e.rightColor||Me.Black(),e.isEnabled===!1&&(this.isEnabled=!1)}clone(){const e=new $D;return ol.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new $D({isEnabled:e.isEnabled,leftColor:Me.FromArray(e.leftColor),rightColor:Me.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}Qe._FresnelParametersParser=$D.Parse;class en{}en.BindSceneUniformBuffer=L5;en.PrepareDefinesForMergedUV=ks;en.BindTextureMatrix=ms;en.GetFogState=oG;en.PrepareDefinesForMisc=Ql;en.PrepareDefinesForCamera=uG;en.PrepareDefinesForFrameBoundValues=$l;en.PrepareDefinesForBones=lG;en.PrepareDefinesForMorphTargets=cG;en.PrepareDefinesForBakedVertexAnimation=UJ;en.PrepareDefinesForAttributes=qn;en.PrepareDefinesForMultiview=N5;en.PrepareDefinesForOIT=hG;en.PrepareDefinesForPrePass=KO;en.PrepareDefinesForLight=GO;en.PrepareDefinesForLights=vc;en.PrepareUniformsAndSamplersForLight=WO;en.PrepareUniformsAndSamplersList=Ma;en.HandleFallbacksForShadows=uo;en.PrepareAttributesForMorphTargetsInfluencers=Y6;en.PrepareAttributesForMorphTargets=VO;en.PrepareAttributesForBakedVertexAnimation=zO;en.PrepareAttributesForBones=Kc;en.PrepareAttributesForInstances=pa;en.PushAttributesForInstances=s_;en.BindLightProperties=Eme;en.BindLight=HO;en.BindLights=gc;en.BindFogParameters=Oo;en.BindBonesParameters=Yl;en.BindMorphTargetParameters=d1;en.BindLogDepth=Ha;class bNe extends kn{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new Ze(0,0,0,1))}}class jc extends xr{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new Me(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}B([K(),ze("_markAllSubMeshesAsLightsDirty")],jc.prototype,"maxSimultaneousLights",void 0);B([K(),ze("_markAllSubMeshesAsLightsDirty")],jc.prototype,"disableLighting",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],jc.prototype,"environmentTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],jc.prototype,"invertNormalMapX",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],jc.prototype,"invertNormalMapY",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],jc.prototype,"normalTexture",void 0);B([or("emissive"),ze("_markAllSubMeshesAsTexturesDirty")],jc.prototype,"emissiveColor",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty")],jc.prototype,"emissiveTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],jc.prototype,"occlusionStrength",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],jc.prototype,"occlusionTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],jc.prototype,"alphaCutOff",void 0);B([K()],jc.prototype,"doubleSided",null);B([$t(),ze("_markAllSubMeshesAsTexturesDirty",null)],jc.prototype,"lightmapTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],jc.prototype,"useLightmapAsShadowmap",void 0);class e_ extends jc{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=Qe.Clone(()=>new e_(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=Qe.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const r=Qe.Parse(()=>new e_(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}B([or(),ze("_markAllSubMeshesAsTexturesDirty","_albedoColor")],e_.prototype,"baseColor",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],e_.prototype,"baseTexture",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],e_.prototype,"metallic",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],e_.prototype,"roughness",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],e_.prototype,"metallicRoughnessTexture",void 0);xe("BABYLON.PBRMetallicRoughnessMaterial",e_);class t_ extends jc{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=Qe.Clone(()=>new t_(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=Qe.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const r=Qe.Parse(()=>new t_(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}B([or("diffuse"),ze("_markAllSubMeshesAsTexturesDirty","_albedoColor")],t_.prototype,"diffuseColor",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],t_.prototype,"diffuseTexture",void 0);B([or("specular"),ze("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],t_.prototype,"specularColor",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty","_microSurface")],t_.prototype,"glossiness",void 0);B([$t(),ze("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],t_.prototype,"specularGlossinessTexture",void 0);xe("BABYLON.PBRSpecularGlossinessMaterial",t_);class K3 extends Er{constructor(e,t,i=null){if(super(t),!!e)if(this._textureMatrix=ce.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const r=this.getScene();r?r.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture():this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;e._features.support3DTextures?t=e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):t=e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=s=>{if(typeof s!="string")return;let a=null,o=null,c;const l=s.split(` `);let h=0,u=0,d=0,f=0,p=0;for(let _=0;_0&&(_+1)%4===0)a[_]=255;else{const m=o[_];a[_]=m/p*255}t.is3D?(t.updateSize(h,h,h),e.updateRawTexture3D(t,a,5,!1)):(t.updateSize(h*h,h),e.updateRawTexture(t,a,5,!1)),t.isReady=!0,this._triggerOnLoad()},r=this.getScene();return r?r._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new K3(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){this.delayLoadState===4&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new K3(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}K3._NoneEmptyLineRegex=/\S+/;xe("BABYLON.ColorGradingTexture",K3);class $8 extends Er{constructor(e,t,i,r=!1,s=!0,a=null,o=null,c=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=ve.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=c,this._noMipmap=r,this.gammaSpace=s,this._onLoad=a,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?a&&(this._texture.isReady?Ee.SetImmediate(()=>a()):this._texture.onLoadedObservable.add(a)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(()=>this._loadTexture(),this._onError)}_loadImage(e,t){const i=this.getScene();if(!i)return;const r=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,this._noMipmap,!1,3);r.generateMipMaps=!this._noMipmap,i.addPendingData(r),r.url=this.url,r.isReady=!1,i.getEngine()._internalTexturesCache.push(r),this._texture=r;const s=document.createElement("canvas");w5(this.url,a=>{this._width=a.width,this._height=a.height,s.width=this._width,s.height=this._height;const o=s.getContext("2d");o.drawImage(a,0,0);const c=o.getImageData(0,0,a.width,a.height);this._buffer=c.data.buffer,s.remove(),e()},(a,o)=>{i.removePendingData(r),t&&t(`${this.getClassName()} could not be loaded`,o)},i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene(),t=()=>{const s=this._getFloat32ArrayFromArrayBuffer(this._buffer),a=p2.ConvertPanoramaToCubemap(s,this._width,this._height,this._size,this._supersample),o=[];for(let c=0;c<6;c++){const l=a[$8._FacesMapping[c]];o.push(l)}return o};if(!e)return;const i=t(),r=this._texture;e.getEngine().updateRawCubeTexture(r,i,r.format,r.type,r.invertY),r.isReady=!0,e.removePendingData(r),r.onLoadedObservable.notifyObservers(r),r.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(e.byteLength*3/4);let r=0;for(let s=0;se.length){de.Error("Unable to load TGA file - Not enough data");return}t+=i.id_length;let r=!1,s=!1,a=!1;switch(i.image_type){case MNe:r=!0;case ENe:s=!0;break;case RNe:r=!0;case TNe:break;case INe:r=!0;case SNe:a=!0;break}let o;const c=i.pixel_size>>3,l=i.width*i.height*c;let h;if(s&&(h=e.subarray(t,t+=i.colormap_length*(i.colormap_size>>3))),r){o=new Uint8Array(l);let y,C,b,T=0;const S=new Uint8Array(c);for(;t>wNe){default:case LNe:u=0,f=1,m=i.width,d=0,p=1,_=i.height;break;case DNe:u=0,f=1,m=i.width,d=i.height-1,p=-1,_=-1;break;case NNe:u=i.width-1,f=-1,m=-1,d=0,p=1,_=i.height;break;case ONe:u=i.width-1,f=-1,m=-1,d=i.height-1,p=-1,_=-1;break}const g="_getImageData"+(a?"Grey":"")+i.pixel_size+"bits",v=pge[g](i,h,o,d,p,_,u,f,m);n.getEngine()._uploadDataToTextureDirectly(n,v)}function BNe(n,e,t,i,r,s,a,o,c){const l=t,h=e,u=n.width,d=n.height;let f,p=0,_,m;const g=new Uint8Array(u*d*4);for(m=i;m!==s;m+=r)for(_=a;_!==c;_+=o,p++)f=l[p],g[(_+u*m)*4+3]=255,g[(_+u*m)*4+2]=h[f*3+0],g[(_+u*m)*4+1]=h[f*3+1],g[(_+u*m)*4+0]=h[f*3+2];return g}function FNe(n,e,t,i,r,s,a,o,c){const l=t,h=n.width,u=n.height;let d,f=0,p,_;const m=new Uint8Array(h*u*4);for(_=i;_!==s;_+=r)for(p=a;p!==c;p+=o,f+=2){d=l[f+0]+(l[f+1]<<8);const g=((d&31744)>>10)*255/31|0,v=((d&992)>>5)*255/31|0,x=(d&31)*255/31|0;m[(p+h*_)*4+0]=g,m[(p+h*_)*4+1]=v,m[(p+h*_)*4+2]=x,m[(p+h*_)*4+3]=d&32768?0:255}return m}function UNe(n,e,t,i,r,s,a,o,c){const l=t,h=n.width,u=n.height;let d=0,f,p;const _=new Uint8Array(h*u*4);for(p=i;p!==s;p+=r)for(f=a;f!==c;f+=o,d+=3)_[(f+h*p)*4+3]=255,_[(f+h*p)*4+2]=l[d+0],_[(f+h*p)*4+1]=l[d+1],_[(f+h*p)*4+0]=l[d+2];return _}function kNe(n,e,t,i,r,s,a,o,c){const l=t,h=n.width,u=n.height;let d=0,f,p;const _=new Uint8Array(h*u*4);for(p=i;p!==s;p+=r)for(f=a;f!==c;f+=o,d+=4)_[(f+h*p)*4+2]=l[d+0],_[(f+h*p)*4+1]=l[d+1],_[(f+h*p)*4+0]=l[d+2],_[(f+h*p)*4+3]=l[d+3];return _}function VNe(n,e,t,i,r,s,a,o,c){const l=t,h=n.width,u=n.height;let d,f=0,p,_;const m=new Uint8Array(h*u*4);for(_=i;_!==s;_+=r)for(p=a;p!==c;p+=o,f++)d=l[f],m[(p+h*_)*4+0]=d,m[(p+h*_)*4+1]=d,m[(p+h*_)*4+2]=d,m[(p+h*_)*4+3]=255;return m}function zNe(n,e,t,i,r,s,a,o,c){const l=t,h=n.width,u=n.height;let d=0,f,p;const _=new Uint8Array(h*u*4);for(p=i;p!==s;p+=r)for(f=a;f!==c;f+=o,d+=2)_[(f+h*p)*4+0]=l[d+0],_[(f+h*p)*4+1]=l[d+0],_[(f+h*p)*4+2]=l[d+0],_[(f+h*p)*4+3]=l[d+1];return _}const pge={GetTGAHeader:b9,UploadContent:Vee,_getImageData8bits:BNe,_getImageData16bits:FNe,_getImageData24bits:UNe,_getImageData32bits:kNe,_getImageDataGrey8bits:VNe,_getImageDataGrey16bits:zNe};class _ge{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=b9(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{Vee(t,r)})}}De._TextureLoaders.push(new _ge);class mge{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=Xz.RGBE_ReadHeader(r),a=Xz.RGBE_ReadPixels(r,s),o=s.width*s.height,c=new Float32Array(o*4);for(let l=0;l{const l=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,l._uploadDataToTextureDirectly(t,c)})}}De._TextureLoaders.push(new mge);function HNe(){const n={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC4:4,cTFBC5:5,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFBGR565:15,cTFRGBA4444:16,cTFFXT1_RGB:17,cTFPVRTC2_4_RGB:18,cTFPVRTC2_4_RGBA:19,cTFETC2_EAC_R11:20,cTFETC2_EAC_RG11:21};let e=null;onmessage=a=>{if(a.data.action==="init"){if(a.data.url)try{importScripts(a.data.url)}catch(o){postMessage({action:"error",error:o})}e||(e=BASIS({wasmBinary:a.data.wasmBinary})),e!==null&&e.then(o=>{BASIS=o,o.initializeBasis(),postMessage({action:"init"})})}else if(a.data.action==="transcode"){const o=a.data.config,c=a.data.imageData,l=new BASIS.BasisFile(c),h=i(l);let u=a.data.ignoreSupportedFormats?null:t(a.data.config,h),d=!1;u===null&&(d=!0,u=h.hasAlpha?n.cTFBC3:n.cTFBC1);let f=!0;l.startTranscoding()||(f=!1);const p=[];for(let _=0;_>2&3],u[x++]=h[v>>4&3],u[x++]=h[v>>6&3]}}return u}}function GNe(n,e,t){return new Promise((i,r)=>{const s=a=>{a.data.action==="init"?(n.removeEventListener("message",s),i(n)):a.data.action==="error"&&r(a.data.error||"error initializing worker")};n.addEventListener("message",s),n.postMessage({action:"init",url:t?Ee.GetBabylonScriptURL(t):void 0,wasmBinary:e},[e])})}class KNe{}class WNe{}var xm;(function(n){n[n.cTFETC1=0]="cTFETC1",n[n.cTFETC2=1]="cTFETC2",n[n.cTFBC1=2]="cTFBC1",n[n.cTFBC3=3]="cTFBC3",n[n.cTFBC4=4]="cTFBC4",n[n.cTFBC5=5]="cTFBC5",n[n.cTFBC7=6]="cTFBC7",n[n.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",n[n.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",n[n.cTFASTC_4x4=10]="cTFASTC_4x4",n[n.cTFATC_RGB=11]="cTFATC_RGB",n[n.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",n[n.cTFRGBA32=13]="cTFRGBA32",n[n.cTFRGB565=14]="cTFRGB565",n[n.cTFBGR565=15]="cTFBGR565",n[n.cTFRGBA4444=16]="cTFRGBA4444",n[n.cTFFXT1_RGB=17]="cTFFXT1_RGB",n[n.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",n[n.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",n[n.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",n[n.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(xm||(xm={}));const n2={JSModuleURL:`${Ee._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${Ee._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},gge=(n,e)=>{let t;switch(n){case xm.cTFETC1:t=36196;break;case xm.cTFBC1:t=33776;break;case xm.cTFBC4:t=33779;break;case xm.cTFASTC_4x4:t=37808;break;case xm.cTFETC2:t=37496;break;case xm.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t};let EY=null,D3=null,jNe=0;const XNe=!1,YNe=()=>(EY||(EY=new Promise((n,e)=>{D3?n(D3):Ee.LoadFileAsync(Ee.GetBabylonScriptURL(n2.WasmModuleURL)).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");const i=URL.createObjectURL(new Blob([`(${HNe})()`],{type:"application/javascript"}));D3=new Worker(i),GNe(D3,t,n2.JSModuleURL).then(n,e)}).catch(e)})),EY),QNe=n=>{D3=n},$z=(n,e)=>{const t=n instanceof ArrayBuffer?new Uint8Array(n):n;return new Promise((i,r)=>{YNe().then(()=>{const s=jNe++,a=c=>{c.data.action==="transcode"&&c.data.id===s&&(D3.removeEventListener("message",a),c.data.success?i(c.data):r("Transcode is not supported on this device"))};D3.addEventListener("message",a);const o=new Uint8Array(t.byteLength);o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),D3.postMessage({action:"transcode",id:s,imageData:o,config:e,ignoreSupportedFormats:XNe},[o.buffer])},s=>{r(s)})})},AV=(n,e)=>{var i,r;let t=(i=e._gl)==null?void 0:i.TEXTURE_2D;n.isCube&&(t=(r=e._gl)==null?void 0:r.TEXTURE_CUBE_MAP),e._bindTextureDirectly(t,n,!0)},Zz=(n,e)=>{const t=n.getEngine();for(let i=0;i{t._releaseTexture(s),AV(n,t)})}else n._invertVScale=!n.invertY,n.width=r.width+3&-4,n.height=r.height+3&-4,n.samplingMode=2,AV(n,t),t._uploadDataToTextureDirectly(n,new Uint16Array(r.transcodedPixels.buffer),i,0,4,!0);else{n.width=r.width,n.height=r.height,n.generateMipMaps=e.fileInfo.images[i].levels.length>1;const s=qG.GetInternalFormatFromBasisFormat(e.format,t);n.format=s,AV(n,t),e.fileInfo.images[i].levels.forEach((a,o)=>{t._uploadCompressedDataToTextureDirectly(n,s,a.width,a.height,a.transcodedPixels,i,o)}),t._features.basisNeedsPOT&&(_t.Log2(n.width)%1!==0||_t.Log2(n.height)%1!==0)&&(Ee.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),n._cachedWrapU=ve.CLAMP_ADDRESSMODE,n._cachedWrapV=ve.CLAMP_ADDRESSMODE)}}},qG={JSModuleURL:n2.JSModuleURL,WasmModuleURL:n2.WasmModuleURL,GetInternalFormatFromBasisFormat:gge,TranscodeAsync:$z,LoadTextureFromTranscodeResult:Zz};Object.defineProperty(qG,"JSModuleURL",{get:function(){return n2.JSModuleURL},set:function(n){n2.JSModuleURL=n}});Object.defineProperty(qG,"WasmModuleURL",{get:function(){return n2.WasmModuleURL},set:function(n){n2.WasmModuleURL=n}});class vge{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;const a=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!a.etc1,s3tc:!!a.s3tc,pvrtc:!!a.pvrtc,etc2:!!a.etc2,astc:!!a.astc,bc7:!!a.bptc}};$z(e,o).then(c=>{const l=c.fileInfo.images[0].levels.length>1&&t.generateMipMaps;Zz(t,c),t.getEngine()._setCubeMapTextureParams(t,l),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(c=>{Ee.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(c)})}loadData(e,t,i){const r=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};$z(e,s).then(a=>{const o=a.fileInfo.images[0].levels[0],c=a.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(o.width,o.height,c,a.format!==-1,()=>{Zz(t,a)})}).catch(a=>{Ee.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),Ee.Warn(`Failed to transcode Basis file: ${a}`),i(0,0,!1,!1,()=>{},!0)})}}De._TextureLoaders.push(new vge);class Sm extends es{get isSupported(){var e;return((e=this._engine)==null?void 0:e.getCaps().drawBuffersExtension)??!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(a))}_initTypes(e,t,i,r,s,a,o,c,l,h){for(let u=0;u{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var t,i;const e=(t=this._renderTarget)==null?void 0:t.textures;if(e){for(let r=e.length-1;r>=0;r--)this._textures[r]._texture=null;(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null}}}class tZ{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Lf{constructor(e,t,i,r){return this.name=e,this.meshes=t,this.scene=r,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??Z.UVKind,this.options.uvsOut=this.options.uvsOut??Z.UVKind,this.options.layout=this.options.layout??Lf.LAYOUT_STRIP,this.options.layout===Lf.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum??8),this.options.updateInputMeshes=this.options.updateInputMeshes??!0,this.options.disposeSources=this.options.disposeSources??!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks??!0,this.options.fillBlanks===!0&&(this.options.customFillColor=this.options.customFillColor??"black"),this.options.frameSize=this.options.frameSize??256,this.options.paddingRatio=this.options.paddingRatio??.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!==0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode??Lf.SUBUV_WRAP,this.options.paddingMode===Lf.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new Ze(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new Be(1,1).divide(t);let r=0;const s=this._expecting,a=this.meshes.length,o=Object.keys(this.sets);for(let d=0;d{this._calculateMeshUVFrames(c,l,t,i,this.options.updateInputMeshes||!1)};for(let d=0;d{r++,m.update(!1);const C=g.getImageData(0,0,h,h),b=this.sets[y];if(b.getContext().putImageData(C,t.x*v.x,t.y*v.y),m.dispose(),b.update(!1),r==s){u(),e();return}},y=o[_]||"_blank";if(!p||p[y]===null)g.fillStyle="rgba(0,0,0,0)",this.options.fillBlanks&&(g.fillStyle=this.options.customFillColor),g.fillRect(0,0,h,h),x();else{const C=p[y],b=new Image;C instanceof Id?b.src=C.getContext().canvas.toDataURL("image/png"):b.src=C.url,Ee.SetCorsBehavior(b.src,b),b.onload=()=>{g.fillStyle="rgba(0,0,0,0)",g.fillRect(0,0,h,h),m.update(!1),g.setTransform(1,0,0,-1,0,0);const T=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let S=0;S<9;S++)g.drawImage(b,0,0,b.width,b.height,l+c*T[S],l+c*T[S+1]-h,c,c);break;case 1:for(let S=0;S{a.dispose&&a.dispose()};for(let a=0;a{try{if(this.meshes.length===0){e();return}let i=0;const r=s=>{if(i++,this.options.map){for(let a=0;a{r(o)})}}catch(i){return t(i)}})}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),s=Object.keys(this.options);try{for(let c=0;c{try{this.setFragment(this._texturePath)}catch{de.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",r=new on;r.open("GET",i),r.addEventListener("load",()=>{if(r.status===200||r.responseText&&r.responseText.length>0)try{this._config=JSON.parse(r.response),this.updateShaderUniforms(),this.updateTextures(),this.setFragment(this._texturePath+"/custom"),this._animate=this._config.animate,this.refreshRate=this._config.refreshrate}catch{t()}else t()},!1),r.addEventListener("error",()=>{t()},!1);try{r.send()}catch{de.Error("CustomProceduralTexture: Error on XHR send request.")}}isReady(){if(!super.isReady())return!1;for(const e in this._textures)if(!this._textures[e].isReady())return!1;return!0}render(e){const t=this.getScene();this._animate&&t&&(this._time+=t.getAnimationRatio()*.03,this.updateShaderUniforms()),super.render(e)}updateTextures(){for(let e=0;e{})}clone(){return Qe.Clone(()=>{const e=this.getScene(),t=this._texture,i=new JG(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===mi.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i},this)}}class qNe extends ve{constructor(e,t,i,r,s,a,o=!0,c=!1,l=ve.TRILINEAR_SAMPLINGMODE,h=0,u){super(null,a,!o,c),this.format=s,this._texture=a.getEngine().createRawTexture3D(e,t,i,r,s,o,c,l,null,h,u),this.is3D=!0}update(e){this._texture&&this._getEngine().updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}}class zee extends es{constructor(e,t,i,r){super(e,t,i,r,!0),this.refractionPlane=new yl(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add(()=>{this.getScene().clipPlane=this.refractionPlane}),this.onAfterRenderObservable.add(()=>{this.getScene().clipPlane=null})}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new zee(this.name,t.width,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.refractionPlane=this.refractionPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i.depth=this.depth,i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e}}class JNe extends Im{get renderTarget(){return this._renderTarget}constructor(e,t,i){super(null),this._renderTarget=null,this._engine=e,this._renderTargetOptions=i,this.resize(t)}resize(e){var t;(t=this._renderTarget)==null||t.dispose(),this._renderTarget=null,this._texture=null,this._size=e,this._engine&&(this._renderTarget=this._engine.createRenderTargetTexture(this._size,this._renderTargetOptions)),this._texture=this.renderTarget.texture}getInternalTexture(){return this._texture}getClassName(){return"ThinRenderTargetTexture"}dispose(e=!1){var t;(t=this._renderTarget)==null||t.dispose(!0),this._renderTarget=null,e||super.dispose()}}class Tn extends Jy{constructor(e,t,i,r,s){super(e,t,i),this._blockType=r,this._blockName=s,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof Tn&&e._blockName===this._blockName?Au.Compatible:Au.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class yge extends zt{constructor(e){super(e,Ce.Vertex),this.registerInput("matricesIndices",se.Vector4),this.registerInput("matricesWeights",se.Vector4),this.registerInput("matricesIndicesExtra",se.Vector4,!0),this.registerInput("matricesWeightsExtra",se.Vector4,!0),this.registerInput("world",se.Matrix),this.registerOutput("output",se.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="matricesIndices"&&t(r));i||(i=new Gi("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="matricesWeights"&&t(r));i||(i=new Gi("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.World&&t(r));i||(i=new Gi("world"),i.setAsSystemValue(Zi.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){Yl(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&lG(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const r=this._outputs[0],s=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 `,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName} * ${i}; `,e.compilationString+=`#else `,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName}; `,e.compilationString+=`#endif `,this}}xe("BABYLON.BonesBlock",yge);class Age extends zt{constructor(e){super(e,Ce.Vertex),this.registerInput("world0",se.Vector4),this.registerInput("world1",se.Vector4),this.registerInput("world2",se.Vector4),this.registerInput("world3",se.Vector4),this.registerInput("world",se.Matrix,!0),this.registerOutput("output",se.Matrix),this.registerOutput("instanceID",se.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=()=>!0){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="world0"&&t(r));i||(i=new Gi("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="world1"&&t(r));i||(i=new Gi("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="world2"&&t(r));i||(i=new Gi("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="world3"&&t(r));i||(i=new Gi("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="world"&&t(r));i||(i=new Gi("world"),i.setAsSystemValue(Zi.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,s){let a=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),a=!0),s&&i.THIN_INSTANCES!==!!(s!=null&&s.getRenderingMesh().hasThinInstances)&&(i.setValue("THIN_INSTANCES",!!(s!=null&&s.getRenderingMesh().hasThinInstances)),a=!0),a&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],r=this._outputs[1],s=this.world0,a=this.world1,o=this.world2,c=this.world3;return e.compilationString+=`#ifdef INSTANCES `,e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${a.associatedVariableName}, ${o.associatedVariableName}, ${c.associatedVariableName}); `,e.compilationString+=`#ifdef THIN_INSTANCES `,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName}; `,e.compilationString+=`#endif `,t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(r,e)+` = float(gl_InstanceID); `:e.compilationString+=this._declareOutput(r,e)+` = 0.0; `,e.compilationString+=`#else `,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName}; `,e.compilationString+=this._declareOutput(r,e)+` = 0.0; `,e.compilationString+=`#endif `,this}}xe("BABYLON.InstancesBlock",Age);class Hee extends zt{constructor(e){super(e,Ce.Vertex),this.registerInput("position",se.Vector3),this.registerInput("normal",se.Vector3),this.registerInput("tangent",se.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(se.Color4|se.Vector4|se.Vector3),this.registerInput("uv",se.Vector2),this.registerOutput("positionOutput",se.Vector3),this.registerOutput("normalOutput",se.Vector3),this.registerOutput("tangentOutput",se.Vector4),this.registerOutput("uvOutput",se.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="position"&&t(r));i||(i=new Gi("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="normal"&&t(r));i||(i=new Gi("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="tangent"&&t(r));i||(i=new Gi("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="uv"&&t(r));i||(i=new Gi("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const r=e.morphTargetManager;r!=null&&r.isUsingTextureForTargets&&(r.numMaxInfluencers||r.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&cG(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(d1(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){const s=this.position,a=this.normal,o=this.tangent,c=this.uv,l=this.positionOutput,h=this.normalOutput,u=this.tangentOutput,d=this.uvOutput,f=e,p=r.NUM_MORPH_INFLUENCERS,_=i.morphTargetManager,m=_&&_.supportsNormals&&r.NORMAL,g=_&&_.supportsTangents&&r.TANGENT,v=_&&_.supportsUVs&&r.UV1;let x="";if(_!=null&&_.isUsingTextureForTargets&&p>0&&(x+=`float vertexID; `),x+=`#ifdef MORPHTARGETS `,_!=null&&_.isUsingTextureForTargets)x+=`for (int i = 0; i < NUM_MORPH_INFLUENCERS; i++) { `,x+=`if (i >= morphTargetCount) break; `,x+=`vertexID = float(gl_VertexID) * morphTargetTextureInfo.x; `,x+=`${l.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${s.associatedVariableName}) * morphTargetInfluences[i]; `,x+=`vertexID += 1.0; `,m&&(x+=`#ifdef MORPHTARGETS_NORMAL `,x+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${a.associatedVariableName}) * morphTargetInfluences[i]; `,x+=`vertexID += 1.0; `,x+=`#endif `),v&&(x+=`#ifdef MORPHTARGETS_UV `,x+=`${d.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${c.associatedVariableName}) * morphTargetInfluences[i]; `,x+=`vertexID += 1.0; `,x+=`#endif `),g&&(x+=`#ifdef MORPHTARGETS_TANGENT `,x+=`${u.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * morphTargetInfluences[i]; `,o.type===se.Vector4?x+=`${u.associatedVariableName}.w = ${o.associatedVariableName}.w; `:x+=`${u.associatedVariableName}.w = 1.; `,x+=`#endif `),x+=`} `;else for(let y=0;y0)for(let y=0;y!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(r=>r.isSystemValue&&r.systemValue===Zi.World&&t(r));i||(i=new Gi("world"),i.setAsSystemValue(Zi.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="normal"&&t(r));i||(i=new Gi("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="tangent"&&r.type===se.Vector4&&t(r));i||(i=new Gi("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var l,h,u,d;const r=this.normal,s=this.tangent;let a=r.isConnected;(l=r.connectInputBlock)!=null&&l.isAttribute&&!e.isVerticesDataPresent((h=r.connectInputBlock)==null?void 0:h.name)&&(a=!1);let o=s.isConnected;(u=s.connectInputBlock)!=null&&u.isAttribute&&!e.isVerticesDataPresent((d=s.connectInputBlock)==null?void 0:d.name)&&(o=!1);const c=a&&o;i.setValue("TBNBLOCK",c,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,r=this.world,s=this.TBN,a=this.row0,o=this.row1,c=this.row2;return e.target===Ce.Fragment&&(e.compilationString+=` // ${this.name} vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz; vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz); vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; mat3 ${s.associatedVariableName} = mat3(${r.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); `,a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]); `),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]); `),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]); `),e.sharedData.blocksWithDefines.push(this)),this}}xe("BABYLON.TBNBlock",tC);class V5 extends zt{constructor(e){super(e,Ce.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",se.Vector4,!1),this.registerInput("worldNormal",se.Vector4,!1),this.registerInput("worldTangent",se.Vector4,!0),this.registerInput("uv",se.Vector2,!1),this.registerInput("normalMapColor",se.Color3,!1),this.registerInput("strength",se.Float,!1),this.registerInput("viewDirection",se.Vector3,!0),this.registerInput("parallaxScale",se.Float,!0),this.registerInput("parallaxHeight",se.Float,!0),this.registerInput("TBN",se.Object,!0,Ce.VertexAndFragment,new Tn("TBN",this,Zs.Input,tC,"TBNBlock")),this.registerInput("world",se.Matrix,!0),this.registerOutput("output",se.Vector4),this.registerOutput("uvOffset",se.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){const r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="uv"&&t(r));i||(i=new Gi("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const i=new Gi("strength");i.value=1,i.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,r=this.worldPosition,s=this.worldNormal,a=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let o=null;this.normalMapColor.connectedPoint&&(o=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const c=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&o||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),l=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",h=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?` #if !defined(NORMALXYSCALE) 1.0/ #endif ${e._emitFloat(this.strength.connectInputBlock.value)}`:` #if !defined(NORMALXYSCALE) 1.0/ #endif ${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const u={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},d={search:/varying mat3 vTBN;/g,replace:""},f={search:/uniform mat4 normalMatrix;/g,replace:""},p=this.TBN;p.isConnected?e.compilationString+=` #ifdef TBNBLOCK mat3 vTBN = ${p.associatedVariableName}; #endif `:a.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz); `,e.compilationString+=`vec3 tbnTangent = normalize(${a.associatedVariableName}.xyz); `,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; `,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); `),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[u,d,f]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:`#define inline vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)`},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const _=!c||!o?this.normalMapColor.associatedVariableName:`texture2D(${o}, ${i.associatedVariableName} + uvOffset).xyz`;return e.compilationString+=this._declareOutput(this.output,e)+` = vec4(0.); `,e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${_}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${_}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${c&&this.useParallaxOcclusion?o:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${c?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:l},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:r.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:c?this.viewDirection.associatedVariableName:"vec3(0.)"},u]}),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX}; `;return e+=`${this._codeVariableName}.invertY = ${this.invertY}; `,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion}; `,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap}; `,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}B([Xt("Invert X axis",Gt.Boolean,"PROPERTIES",{notifiers:{update:!1}})],V5.prototype,"invertX",void 0);B([Xt("Invert Y axis",Gt.Boolean,"PROPERTIES",{notifiers:{update:!1}})],V5.prototype,"invertY",void 0);B([Xt("Use parallax occlusion",Gt.Boolean)],V5.prototype,"useParallaxOcclusion",void 0);B([Xt("Object Space Mode",Gt.Boolean,"PROPERTIES",{notifiers:{update:!1}})],V5.prototype,"useObjectSpaceNormalMap",void 0);xe("BABYLON.PerturbNormalBlock",V5);class bge extends zt{constructor(e){super(e,Ce.Fragment,!0),this.registerInput("value",se.Float,!0),this.registerInput("cutoff",se.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,!(!this.cutoff.isConnected||!this.value.isConnected))return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard; `,this}}xe("BABYLON.DiscardBlock",bge);class Ege extends zt{constructor(e){super(e,Ce.Fragment),this.registerOutput("output",se.Float,Ce.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===Ce.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = gl_FrontFacing ? 1.0 : 0.0; `,this}}xe("BABYLON.FrontFacingBlock",Ege);class Tge extends zt{constructor(e){super(e,Ce.Fragment),this.registerInput("input",se.AutoDetect,!1),this.registerOutput("dx",se.BasedOnInput),this.registerOutput("dy",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t.hasEndpoints&&(e.compilationString+=this._declareOutput(t,e)+` = dFdx(${this.input.associatedVariableName}); `),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName}); `),this}}xe("BABYLON.DerivativeBlock",Tge);class Sge extends zt{constructor(e){super(e,Ce.Fragment),this.registerOutput("xy",se.Vector2,Ce.Fragment),this.registerOutput("xyz",se.Vector3,Ce.Fragment),this.registerOutput("xyzw",se.Vector4,Ce.Fragment),this.registerOutput("x",se.Float,Ce.Fragment),this.registerOutput("y",se.Float,Ce.Fragment),this.registerOutput("z",se.Float,Ce.Fragment),this.registerOutput("w",se.Float,Ce.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";for(const i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name}; `);return t}_buildBlock(e){if(super._buildBlock(e),e.target===Ce.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}xe("BABYLON.FragCoordBlock",Sge);class Mge extends zt{constructor(e){super(e,Ce.Fragment),this.registerOutput("xy",se.Vector2,Ce.Fragment),this.registerOutput("x",se.Float,Ce.Fragment),this.registerOutput("y",se.Float,Ce.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; `);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===Ce.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this}}xe("BABYLON.ScreenSizeBlock",Mge);class Rge extends zt{constructor(e){super(e,Ce.Fragment),this.registerInput("vector",se.AutoDetect),this.registerInput("worldViewProjection",se.Matrix),this.registerOutput("output",se.Vector2),this.registerOutput("x",se.Float),this.registerOutput("y",se.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(se.Color3|se.Vector3|se.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.WorldViewProjection&&t(r));i||(i=new Gi("worldViewProjection"),i.setAsSystemValue(Zi.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const r=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case se.Vector3:e.compilationString+=`vec4 ${s} = ${r} * vec4(${t.associatedVariableName}, 1.0); `;break;case se.Vector4:e.compilationString+=`vec4 ${s} = ${r} * ${t.associatedVariableName}; `;break}return e.compilationString+=`${s}.xy /= ${s}.w;`,e.compilationString+=`${s}.xy = ${s}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${s}.xy; `),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x; `),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y; `),this}}xe("BABYLON.ScreenSpaceBlock",Rge);class Ige extends zt{constructor(e){super(e,Ce.Fragment),this.registerInput("input",se.Vector2),this.registerInput("strength",se.Float),this.registerInput("center",se.Vector2),this.registerInput("offset",se.Vector2),this.registerOutput("output",se.Vector2),this.registerOutput("x",se.Float),this.registerOutput("y",se.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new Gi("center");e.value=new Be(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Gi("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Gi("offset");e.value=new Be(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),a=e._getFreeVariableName("result");return e.compilationString+=` vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; float ${i} = ${this.strength.associatedVariableName} * length(${t}); float ${r} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; vec2 ${a} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${a}; `),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${a}.x; `),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${a}.y; `),this}}xe("BABYLON.TwirlBlock",Ige);class E9 extends zt{constructor(e){super(e,Ce.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",se.Float),this.registerInput("worldPosition",se.Vector3),this.registerInput("worldNormal",se.Vector3),this.registerInput("worldTangent",se.AutoDetect,!0),this.registerOutput("output",se.Vector4),this.registerOutput("xyz",se.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(se.Color3|se.Vector3|se.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];!this.generateInWorldSpace&&!this.worldTangent.isConnected&&de.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const i=this.generateInWorldSpace?"":` vec3 biTangent = cross(normal, tangent); mat3 TBN = mat3(tangent, biTangent, normal); `,r=this.generateInWorldSpace?"":` result = TBN * result; result = result * vec3(0.5) + vec3(0.5); `,s=` vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""} ${this.automaticNormalizationNormal?"normal = normalize(normal);":""} ${i} vec3 worlddX = dFdx(position); vec3 worlddY = dFdy(position); vec3 crossX = cross(normal, worlddX); vec3 crossY = cross(normal, worlddY); float d = abs(dot(crossY, worlddX)); vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); inToNormal.y *= -1.0; vec3 result = normalize((d * normal) - inToNormal); ${r} return vec4(result, 0.); }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",s,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName}); `,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; `),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace}; `,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal}; `,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent}; `,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}B([Xt("Generate in world space instead of tangent space",Gt.Boolean,"PROPERTIES",{notifiers:{update:!0}})],E9.prototype,"generateInWorldSpace",void 0);B([Xt("Force normalization for the worldNormal input",Gt.Boolean,"PROPERTIES",{notifiers:{update:!0}})],E9.prototype,"automaticNormalizationNormal",void 0);B([Xt("Force normalization for the worldTangent input",Gt.Boolean,"PROPERTIES",{notifiers:{update:!0}})],E9.prototype,"automaticNormalizationTangent",void 0);xe("BABYLON.HeightToNormalBlock",E9);class Pge extends zt{constructor(e){super(e,Ce.Fragment,!0),this.registerInput("depth",se.Float,!0),this.registerInput("worldPos",se.Vector4,!0),this.registerInput("viewProjection",se.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName}; `:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=` vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; float v = p.z / p.w; #ifndef IS_NDC_HALF_ZRANGE v = v * 0.5 + 0.5; #endif gl_FragDepth = v; `:de.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}xe("BABYLON.FragDepthBlock",Pge);class wge extends zt{constructor(e){super(e,Ce.Fragment),this.registerInput("worldPosition",se.Vector4,!1),this.registerInput("viewProjection",se.Matrix,!1),this.registerInput("worldNormal",se.AutoDetect,!0),this.registerOutput("depth",se.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(se.Color3|se.Vector3|se.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM","vec3"),e._emitUniformFromString("lightDataSM","vec3"),e._emitUniformFromString("depthValuesSM","vec2"),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName}; `,e.compilationString+=`vec3 vPositionWSM; `,e.compilationString+=`float vDepthMetricSM = 0.0; `,e.compilationString+=`float zSM; `,this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz; `,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos; `,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+=` #if SM_DEPTHTEXTURE == 1 #ifdef IS_NDC_HALF_ZRANGE gl_FragDepth = (clipPos.z / clipPos.w); #else gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5; #endif #endif `,e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.); `,this}}xe("BABYLON.ShadowMapBlock",wge);class Dge extends zt{constructor(e){super(e,Ce.Fragment,!0),this.registerInput("viewDepth",se.Float,!0),this.registerInput("worldPosition",se.AutoDetect,!0),this.registerInput("viewNormal",se.AutoDetect,!0),this.registerInput("reflectivity",se.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(se.Vector3|se.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(se.Vector3|se.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(se.Vector3|se.Vector4|se.Color3|se.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,r=this.viewDepth,s=this.reflectivity;e.sharedData.blocksWithDefines.push(this);const a=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",a),e.compilationString+=`#if defined(PREPASS)\r `,e.compilationString+=`#ifdef PREPASS_DEPTH\r `,r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${r.associatedVariableName}, 0.0, 0.0, 1.0);\r `:e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_POSITION\r `,t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===se.Vector4?t.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_NORMAL\r `,i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===se.Vector4?i.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r `,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${s.associatedVariableName}.rgb, ${s.connectedPoint.type===se.Vector4?s.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#endif\r `,this}}xe("BABYLON.PrePassOutputBlock",Dge);class Oge extends zt{constructor(e){super(e,Ce.VertexAndFragment,!1),this.registerInput("worldPosition",se.Vector4,!1,Ce.Vertex),this.registerInput("view",se.Matrix,!1,Ce.Vertex),this.registerInput("input",se.AutoDetect,!1,Ce.Fragment),this.registerInput("fogColor",se.AutoDetect,!1,Ce.Fragment),this.registerOutput("output",se.Color3,Ce.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(se.Color3|se.Vector3|se.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(se.Color3|se.Vector3|se.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.View&&t(r));i||(i=new Gi("view"),i.setAsSystemValue(Zi.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.FogColor&&t(r));i||(i=new Gi("fogColor",void 0,se.Color3),i.setAsSystemValue(Zi.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const r=e.getScene();i.setValue("FOG",t.fogEnabled&&oG(e,r))}bind(e,t,i){if(!i)return;const r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===Ce.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});const t=e._getFreeVariableName("fog"),i=this.input,r=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+=`#ifdef FOG `,e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters}); `,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${r.associatedVariableName}.rgb; `,e.compilationString+=`#else ${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb; `,e.compilationString+=`#endif `}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz; `}return this}}xe("BABYLON.FogBlock",Oge);class qz extends zt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,de.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Ce.Fragment:Ce.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Ce.Fragment:Ce.Vertex}constructor(e){super(e,Ce.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",se.Vector4,!1,Ce.Vertex),this.registerInput("worldNormal",se.Vector4,!1,Ce.Fragment),this.registerInput("cameraPosition",se.Vector3,!1,Ce.Fragment),this.registerInput("glossiness",se.Float,!0,Ce.Fragment),this.registerInput("glossPower",se.Float,!0,Ce.Fragment),this.registerInput("diffuseColor",se.Color3,!0,Ce.Fragment),this.registerInput("specularColor",se.Color3,!0,Ce.Fragment),this.registerInput("view",se.Matrix,!0),this.registerOutput("diffuseOutput",se.Color3,Ce.Fragment),this.registerOutput("specularOutput",se.Color3,Ce.Fragment),this.registerOutput("shadow",se.Float,Ce.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.CameraPosition&&t(r));i||(i=new Gi("cameraPosition"),i.setAsSystemValue(Zi.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const r=e.getScene();if(!this.light)vc(r,e,i,!0,t.maxSimultaneousLights);else{const s={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};GO(r,e,this.light,this._lightId,i,!0,s),s.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;WO(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,a)}}bind(e,t,i){if(!i)return;const r=i.getScene();this.light?HO(this.light,this._lightId,r,e,!0):gc(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(e.counters.lightCounter!==void 0?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${t.associatedVariableName}; `),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName}; `,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; `),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==Ce.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=`//${this.name}`,i=this.worldPosition;let r=i.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${r}; `,t),e.compilationString+=`${r} = ${i.associatedVariableName}.xyz; `,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):r="v_"+r+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),this._lightId===0&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}); `),e.compilationString+=`lightingInfo info; `,e.compilationString+=`float shadow = 1.; `,e.compilationString+=`float aggShadow = 0.; `,e.compilationString+=`float numLights = 0.; `,e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; `,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.); `,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.); `,e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz; `),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),this._lightId===0&&(e.compilationString+=`aggShadow = aggShadow / numLights; `);const s=this.diffuseOutput,a=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; `,a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""}; `),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = aggShadow; `),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}B([Xt("Generate only fragment code",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:qz._OnGenerateOnlyFragmentCodeChanged}})],qz.prototype,"generateOnlyFragmentCode",void 0);xe("BABYLON.LightBlock",qz);class Hf extends zt{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??bt.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}get samplerName(){return this._samplerName}constructor(e){super(e,Ce.VertexAndFragment),this.registerOutput("source",se.Object,Ce.VertexAndFragment,new Tn("source",this,Zs.Output,Hf,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===Ce.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); `,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; `,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; `,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; `,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; `,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; `,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; `,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; `,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; `,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; `,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; `),e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Ss.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ve.Parse(e.texture,t,i))}}xe("BABYLON.ImageSourceBlock",Hf);class qD extends zt{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)==null?void 0:e.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??bt.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}static _IsPrePassTextureBlock(e){return(e==null?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return qD._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!qD._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const t=this.texture.getScene()??bt.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const t=this.texture.getScene()??bt.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?Ce.Fragment:Ce.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",se.AutoDetect,!1,Ce.VertexAndFragment),this.registerInput("source",se.Object,!0,Ce.VertexAndFragment,new Tn("source",this,Zs.Input,Hf,"ImageSourceBlock")),this.registerInput("layer",se.Float,!0),this.registerInput("lod",se.Float,!0),this.registerOutput("rgba",se.Color4,Ce.Neutral),this.registerOutput("rgb",se.Color3,Ce.Neutral),this.registerOutput("r",se.Float,Ce.Neutral),this.registerOutput("g",se.Float,Ce.Neutral),this.registerOutput("b",se.Float,Ce.Neutral),this.registerOutput("a",se.Float,Ce.Neutral),this.registerOutput("level",se.Float,Ce.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(se.Vector2|se.Vector3|se.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return Ce.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return Ce.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===Ce.Fragment)return Ce.Fragment;if(e.target===Ce.Vertex)return Ce.VertexAndFragment;if(e.target===Ce.Neutral||e.target===Ce.VertexAndFragment){const t=e.ownerBlock;if(t.target===Ce.Fragment)return Ce.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return Ce.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected)if(e.mode===wc.PostProcess){const i=e.getBlockByPredicate(r=>r.name==="uv"&&t(r));i&&i.connectTo(this)}else{const i=e.mode===wc.Particle?"particle_uv":"uv";let r=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name===i&&t(s));r||(r=new Gi("uv"),r.setAsAttribute(i)),r.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&this._mainUVDefineName!==void 0&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix){this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0));return}const r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),i[this._mainUVDefineName]==null&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return this._isSourcePrePass?!0:!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==Ce.Fragment}_injectVertexCode(e){const t=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+=`#ifdef ${this._defineName} `,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0)); `,e.compilationString+=`#elif defined(${this._mainUVDefineName}) `,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; `,e.compilationString+=`#endif `,!!this._outputs.some(i=>i.isConnectedInVertexShader)){this._writeTextureRead(e,!0);for(const i of this._outputs)i.hasEndpoints&&i.name!=="level"&&this._writeOutput(e,i,i.name,!0)}}_getUVW(e){var r,s;let t=e;if(((s=(r=this._texture)==null?void 0:r._texture)==null?void 0:s.is2DArray)??!1){const a=this.layer.isConnected?this.layer.associatedVariableName:"0";t=`vec3(${e}, ${a})`}return t}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){const t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName} `,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix}); `,e.compilationString+=`#elif defined(${this._mainUVDefineName}) `,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix}); `,e.compilationString+=`#endif `}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===Ce.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===Ce.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix}); `;return}this._generateTextureLookup(e)}_generateConversionCode(e,t,i){i!=="a"&&((!this.texture||!this.texture.gammaSpace)&&(e.compilationString+=`#ifdef ${this._linearDefineName} ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); #endif `),e.compilationString+=`#ifdef ${this._gammaDefineName} ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); #endif `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===Ce.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; `,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===Ce.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; `,this._generateConversionCode(e,t,i);return}let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s}; `,this._generateConversionCode(e,t,i)}_buildBlock(e){var i,r,s,a;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===Ce.Vertex||this._fragmentOnly||e.target===Ce.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===Ce.Fragment||this._isMixed&&e.target===Ce.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),(r=(i=this._texture)==null?void 0:i._texture)!=null&&r.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==Ce.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(o=>o.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((a=(s=this._texture)==null?void 0:s._texture)!=null&&a.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e);for(const o of this._outputs)o.hasEndpoints&&o.name!=="level"&&this._writeOutput(e,o,o.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; `,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; `,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; `,this.texture&&(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); `,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; `,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; `,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; `,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; `,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; `,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; `,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; `,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; `,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; `,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; `),e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,!this.hasImageSource&&this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!Ss.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ve.Parse(e.texture,t,i))}}xe("BABYLON.TextureBlock",qD);class Z8 extends zt{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??bt.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Ce.Fragment:Ce.VertexAndFragment)}constructor(e){super(e,Ce.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="position"&&t(r));i||(i=new Gi("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.World&&t(r));i||(i=new Gi("world"),i.setAsSystemValue(Zi.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.View&&t(r));i||(i=new Gi("view"),i.setAsSystemValue(Zi.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const r=this._getTexture();!r||!r.getTextureMatrix||(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,r.coordinatesMode===0,!0),i.setValue(this._defineSkyboxName,r.coordinatesMode===5,!0),i.setValue(this._defineCubicName,r.coordinatesMode===3||r.coordinatesMode===6,!0),i.setValue("INVERTCUBICMAP",r.coordinatesMode===6,!0),i.setValue(this._defineSphericalName,r.coordinatesMode===1,!0),i.setValue(this._definePlanarName,r.coordinatesMode===2,!0),i.setValue(this._defineProjectionName,r.coordinatesMode===4,!0),i.setValue(this._defineEquirectangularName,r.coordinatesMode===7,!0),i.setValue(this._defineEquirectangularFixedName,r.coordinatesMode===8,!0),i.setValue(this._defineMirroredEquirectangularFixedName,r.coordinatesMode===9,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,r){const s=this._getTexture();if(!(!i||!s)&&(e.setMatrix(this._reflectionMatrixName,s.getReflectionTextureMatrix()),s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),s.boundingBoxSize)){const a=s;e.setVector3(this._reflectionPositionName,a.boundingBoxPosition),e.setVector3(this._reflectionSizeName,a.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===Ce.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName}; `),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName} `,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; `,t+=`#endif `),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) `,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0))); `,t+=`#endif `),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName} `,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; `,e._samplerDeclaration+=`#else `,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; `,e._samplerDeclaration+=`#endif `,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,r=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const s=this._reflectionMatrixName,a=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,c=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=` #ifdef ${this._defineMirroredEquirectangularFixedName} vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${a}); #endif #ifdef ${this._defineEquirectangularFixedName} vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${a}); #endif #ifdef ${this._defineEquirectangularName} vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${c}.xyz, ${s}); #endif #ifdef ${this._defineSphericalName} vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s}); #endif #ifdef ${this._definePlanarName} vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${c}.xyz, ${s}); #endif #ifdef ${this._defineCubicName} #ifdef ${this._defineLocalCubicName} vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${c}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); #else vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${c}.xyz, ${s}); #endif #endif #ifdef ${this._defineProjectionName} vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s}); #endif #ifdef ${this._defineSkyboxName} vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${s}); #endif #ifdef ${this._defineExplicitName} vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); #endif `;return r||(h+=`#ifdef ${this._defineOppositeZ} ${this._reflectionVectorName}.z *= -1.0; #endif `),i||(h+=` #ifdef ${this._define3DName} vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName}; #else vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy; #ifdef ${this._defineProjectionName} ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; #endif ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; #endif `),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let r=`${"vec"+(t.length===0?"4":t.length-1)} ${this._reflectionColorName}; #ifdef ${this._define3DName} `;return e?r+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t}; `:r+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t}; `,r+=` #else `,e?r+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t}; `:r+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t}; `,r+=`#endif `,r}writeOutputs(e,t){let i="";if(e.target===Ce.Fragment)for(const r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; `);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"}); `}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null); `;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; `,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Ss.IgnoreTexturesAtLoadTime&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=Bn.Parse(e.texture,t,i):this.texture=ve.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}B([Xt("Generate only fragment code",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Z8._OnGenerateOnlyFragmentCodeChanged}})],Z8.prototype,"generateOnlyFragmentCode",void 0);xe("BABYLON.ReflectionTextureBaseBlock",Z8);class Lge extends Z8{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,de.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,de.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?Ce.Fragment:Ce.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Ce.Fragment:Ce.Vertex}constructor(e){super(e),this.registerInput("position",se.AutoDetect,!1,Ce.Vertex),this.registerInput("worldPosition",se.Vector4,!1,Ce.Vertex),this.registerInput("worldNormal",se.Vector4,!1,Ce.Fragment),this.registerInput("world",se.Matrix,!1,Ce.Vertex),this.registerInput("cameraPosition",se.Vector3,!1,Ce.Fragment),this.registerInput("view",se.Matrix,!1,Ce.Fragment),this.registerOutput("rgb",se.Color3,Ce.Fragment),this.registerOutput("rgba",se.Color4,Ce.Fragment),this.registerOutput("r",se.Float,Ce.Fragment),this.registerOutput("g",se.Float,Ce.Fragment),this.registerOutput("b",se.Float,Ce.Fragment),this.registerOutput("a",se.Float,Ce.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(se.Color3|se.Vector3|se.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=()=>!0){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.CameraPosition&&t(r));i||(i=new Gi("cameraPosition"),i.setAsSystemValue(Zi.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==Ce.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName}); `,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}xe("BABYLON.ReflectionTextureBlock",Lge);class T9 extends zt{constructor(e){super(e,Ce.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",se.AutoDetect,!1,Ce.VertexAndFragment),this.registerOutput("depth",se.Float,Ce.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(se.Vector2|se.Vector3|se.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?Ce.VertexAndFragment:Ce.Fragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===se.Vector3?"3":t.type===se.Vector4?"4":"2"))),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; `,!!this._outputs.some(i=>i.isConnectedInVertexShader)){this._writeTextureRead(e,!0);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===Ce.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); `;return}if(this.uv.ownerBlock.target===Ce.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); `;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); `}_writeOutput(e,t,i,r=!1){if(r){if(e.target===Ce.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; `;return}if(this.uv.ownerBlock.target===Ce.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; `;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; `}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==Ce.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(this._outputs.some(t=>t.isConnectedInFragmentShader)){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}B([Xt("Use non linear depth",Gt.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(n,e)=>{const t=e;let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),n&&n.disableDepthRenderer(),i}}})],T9.prototype,"useNonLinearDepth",void 0);B([Xt("Store Camera space Z",Gt.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(n,e)=>{const t=e;let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),n&&n.disableDepthRenderer(),i}}})],T9.prototype,"storeCameraSpaceZ",void 0);B([Xt("Force 32 bits float",Gt.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:n=>n==null?void 0:n.disableDepthRenderer()}})],T9.prototype,"force32itsFloat",void 0);xe("BABYLON.SceneDepthBlock",T9);class Nge extends zt{constructor(e){super(e,Ce.VertexAndFragment,!0),this.registerInput("worldPosition",se.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return Ce.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const r=e.getScene(),s=!!(t.clipPlane??r.clipPlane),a=!!(t.clipPlane2??r.clipPlane2),o=!!(t.clipPlane3??r.clipPlane3),c=!!(t.clipPlane4??r.clipPlane4),l=!!(t.clipPlane5??r.clipPlane5),h=!!(t.clipPlane6??r.clipPlane6);i.setValue("CLIPPLANE",s,!0),i.setValue("CLIPPLANE2",a,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",c,!0),i.setValue("CLIPPLANE5",l,!0),i.setValue("CLIPPLANE6",h,!0)}bind(e,t,i){if(!i)return;const r=i.getScene();fa(e,t,r)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==Ce.Fragment){const i=this.worldPosition;e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),e._emitUniformFromString("vClipPlane6","vec4");return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}xe("BABYLON.ClipPlanesBlock",Nge);class Bge extends zt{get texture(){return null}set texture(e){}constructor(e,t=Ce.VertexAndFragment){super(e,t,!1),this.registerOutput("position",se.Object,Ce.VertexAndFragment,new Tn("position",this,Zs.Output,Hf,"ImageSourceBlock")),this.registerOutput("depth",se.Object,Ce.VertexAndFragment,new Tn("depth",this,Zs.Output,Hf,"ImageSourceBlock")),this.registerOutput("normal",se.Object,Ce.VertexAndFragment,new Tn("normal",this,Zs.Output,Hf,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==Ce.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){const r=t.getScene().enablePrePassRenderer();if(!r)return;const s=r.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[r.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[r.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[r.getIndex(6)]))}}xe("BABYLON.PrePassTextureBlock",Bge);class Fge extends zt{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==Ce.VertexAndFragment)return t.target;if(e.connectedPoint.target!==Ce.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,Ce.Neutral),this._endpoints=[],this.registerInput("input",se.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some(e=>e.output.isConnectedInFragmentShader)}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const r of this.endpoints)t.indexOf(r)===-1&&(i+=r._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);t!==-1&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}xe("BABYLON.NodeMaterialTeleportInBlock",Fge);class Uge extends zt{constructor(e){super(e,Ce.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",se.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){this._target&e||(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName}; `)}clone(e,t=""){const i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&t.indexOf(this.entryPoint)===-1&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); `),e}serialize(){var t;const e=super.serialize();return e.entryPoint=((t=this.entryPoint)==null?void 0:t.uniqueId)??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}xe("BABYLON.NodeMaterialTeleportOutBlock",Uge);class kge extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("left",se.AutoDetect),this.registerInput("right",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1,!0),this._inputs[0].acceptedConnectionPointTypes.push(se.Float),this._inputs[1].acceptedConnectionPointTypes.push(se.Float)}getClassName(){return"AddBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName}; `,this}}xe("BABYLON.AddBlock",kge);class Vge extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("input",se.AutoDetect),this.registerInput("factor",se.Float),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName}; `,this}}xe("BABYLON.ScaleBlock",Vge);class eK extends zt{constructor(e){super(e,Ce.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)}); `,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; `;return e+=`${this._codeVariableName}.maximum = ${this.maximum}; `,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}B([Xt("Minimum",Gt.Float)],eK.prototype,"minimum",void 0);B([Xt("Maximum",Gt.Float)],eK.prototype,"maximum",void 0);xe("BABYLON.ClampBlock",eK);class zge extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("left",se.AutoDetect),this.registerInput("right",se.AutoDetect),this.registerOutput("output",se.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(se.Float),this._inputs[0].excludedConnectionPointTypes.push(se.Matrix),this._inputs[0].excludedConnectionPointTypes.push(se.Vector2),this._inputs[1].excludedConnectionPointTypes.push(se.Float),this._inputs[1].excludedConnectionPointTypes.push(se.Matrix),this._inputs[1].excludedConnectionPointTypes.push(se.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz); `,this}}xe("BABYLON.CrossBlock",zge);class Hge extends zt{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach(s=>{const a=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),o=e._getGLType(s.type);t=t.replace(a,o),i=i.replace(a,o)}),this._outputs.forEach(s=>{const a=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),o=e._getGLType(s.type);t=t.replace(a,o),i=i.replace(a,o)}),e._emitFunction(i,t,""),this._outputs.forEach(s=>{e.compilationString+=this._declareOutput(s,e)+`; `}),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach((s,a)=>{var o,c;a>0&&(e.compilationString+=", "),this._inputSamplers&&this._inputSamplers.indexOf(s.name)!==-1?e.compilationString+=((c=(o=s.connectedPoint)==null?void 0:o.ownerBlock)==null?void 0:c.samplerName)??s.associatedVariableName:e.compilationString+=s.associatedVariableName,r=!0}),this._outputs.forEach((s,a)=>{(a>0||r)&&(e.compilationString+=", "),e.compilationString+=s.associatedVariableName}),e.compilationString+=`); `,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)}; `,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){var t,i,r;this._options=e,this._code=e.code.join(` `)+` `,this.name=this.name||e.name,this.target=Ce[e.target],(t=e.inParameters)==null||t.forEach((s,a)=>{const o=se[s.type];s.type==="sampler2D"||s.type==="samplerCube"?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(s.name),this.registerInput(s.name,se.Object,!0,Ce.VertexAndFragment,new Tn(s.name,this,Zs.Input,Hf,"ImageSourceBlock"))):this.registerInput(s.name,o),Object.defineProperty(this,s.name,{get:function(){return this._inputs[a]},enumerable:!0,configurable:!0})}),(i=e.outParameters)==null||i.forEach((s,a)=>{this.registerOutput(s.name,se[s.type]),Object.defineProperty(this,s.name,{get:function(){return this._outputs[a]},enumerable:!0,configurable:!0}),s.type==="BasedOnInput"&&(this._outputs[a]._typeConnectionSource=this._findInputByName(s.typeFromInput)[0])}),(r=e.inLinkedConnectionTypes)==null||r.forEach(s=>{this._linkConnectionTypes(this._findInputByName(s.input1)[1],this._findInputByName(s.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.CameraPosition&&t(r));i||(i=new Gi("cameraPosition"),i.setAsSystemValue(Zi.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz); `,this}}xe("BABYLON.ViewDirectionBlock",Wee);class Zge extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("worldNormal",se.Vector4),this.registerInput("viewDirection",se.Vector3),this.registerInput("bias",se.Float),this.registerInput("power",se.Float),this.registerOutput("fresnel",se.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new Wee("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const t=new Gi("bias");t.value=0,t.output.connectTo(this.bias)}if(!this.power.isConnected){const t=new Gi("power");t.value=1,t.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName}); `,this}}xe("BABYLON.FresnelBlock",Zge);class qge extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("left",se.AutoDetect),this.registerInput("right",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); `,this}}xe("BABYLON.MaxBlock",qge);class Jge extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("left",se.AutoDetect),this.registerInput("right",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); `,this}}xe("BABYLON.MinBlock",Jge);class e3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("left",se.AutoDetect),this.registerInput("right",se.AutoDetect),this.registerOutput("output",se.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(se.Float),this._inputs[0].excludedConnectionPointTypes.push(se.Matrix),this._inputs[1].excludedConnectionPointTypes.push(se.Float),this._inputs[1].excludedConnectionPointTypes.push(se.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName}); `,this}}xe("BABYLON.DistanceBlock",e3e);class t3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("value",se.AutoDetect),this.registerOutput("output",se.Float),this._inputs[0].excludedConnectionPointTypes.push(se.Float),this._inputs[0].excludedConnectionPointTypes.push(se.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName}); `,this}}xe("BABYLON.LengthBlock",t3e);class i3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("value",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName}; `,this}}xe("BABYLON.NegateBlock",i3e);class r3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("value",se.AutoDetect),this.registerInput("power",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName}); `,this}}xe("BABYLON.PowBlock",r3e);class s3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("seed",se.AutoDetect),this.registerOutput("output",se.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(se.Vector2|se.Vector3|se.Vector4|se.Color3|se.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy); `,this}}xe("BABYLON.RandomNumberBlock",s3e);class n3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("x",se.Float),this.registerInput("y",se.Float),this.registerOutput("output",se.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName}); `,this}}xe("BABYLON.ArcTan2Block",n3e);class a3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("value",se.AutoDetect),this.registerInput("edge0",se.Float),this.registerInput("edge1",se.Float),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName}); `,this}}xe("BABYLON.SmoothStepBlock",a3e);class o3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("input",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===se.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); `:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName}; `,this}}xe("BABYLON.ReciprocalBlock",o3e);class l3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("value",se.AutoDetect),this.registerInput("reference",se.AutoDetect),this.registerInput("distance",se.Float),this.registerInput("replacement",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(se.Float),this._inputs[0].excludedConnectionPointTypes.push(se.Matrix),this._inputs[1].excludedConnectionPointTypes.push(se.Float),this._inputs[1].excludedConnectionPointTypes.push(se.Matrix),this._inputs[3].excludedConnectionPointTypes.push(se.Float),this._inputs[3].excludedConnectionPointTypes.push(se.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+`; `,e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) { `,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName}; `,e.compilationString+=`} else { `,e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName}; `,e.compilationString+=`} `,this}}xe("BABYLON.ReplaceColorBlock",l3e);class c3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("value",se.AutoDetect),this.registerInput("steps",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(se.Matrix),this._inputs[1].excludedConnectionPointTypes.push(se.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(se.Float)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName}); `,this}}xe("BABYLON.PosterizeBlock",c3e);var Ey;(function(n){n[n.SawTooth=0]="SawTooth",n[n.Square=1]="Square",n[n.Triangle=2]="Triangle"})(Ey||(Ey={}));class h3e extends zt{constructor(e){super(e,Ce.Neutral),this.kind=Ey.SawTooth,this.registerInput("input",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(se.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case Ey.SawTooth:{e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); `;break}case Ey.Square:{e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); `;break}case Ey.Triangle:{e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0; `;break}}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}}xe("BABYLON.WaveBlock",h3e);class YV{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}class u3e extends zt{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,Ce.Neutral),this.colorSteps=[new YV(0,Me.Black()),new YV(1,Me.White())],this.onValueChangedObservable=new Ae,this.registerInput("gradient",se.AutoDetect),this.registerOutput("output",se.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(se.Float|se.Vector2|se.Vector3|se.Vector4|se.Color3|se.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){const t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=this._declareOutput(t,e)+` = vec3(0., 0., 0.); `;return}const i=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)}; `,e.compilationString+=`float ${r}; `;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==se.Float&&(s+=".x");for(let a=1;a!0){if(!this.intensity.isConnected){const i=new Gi("Refraction intensity",Ce.Fragment,se.Float);i.value=1,i.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.View&&t(r));i||(i=new Gi("view"),i.setAsSystemValue(Zi.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){var c,l;super.bind(e,t,i);const r=this._getTexture();if(!r)return;r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),e.setMatrix(this._refractionMatrixName,r.getRefractionTextureMatrix());let s=1;r.isCube||r.depth&&(s=r.depth);const a=((c=this.volumeIndexOfRefraction.connectInputBlock)==null?void 0:c.value)??((l=this.indexOfRefractionConnectionPoint.connectInputBlock)==null?void 0:l.value)??1.5;e.setFloat4(this._vRefractionInfosName,r.level,1/a,s,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,r.getSize().width,r.lodGenerationScale,r.lodGenerationOffset,1/a);const o=r.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,_t.Log2(o)),r.boundingBoxSize){const h=r;e.setVector3("vRefractionPosition",h.boundingBoxPosition),e.setVector3("vRefractionSize",h.boundingBoxSize)}}getCode(e){const t="";return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName} `,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; `,e._samplerDeclaration+=`#else `,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; `,e._samplerDeclaration+=`#endif `,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",` #ifdef ${this._define3DName} #define sampleRefraction(s, c) textureCube(s, c) #else #define sampleRefraction(s, c) texture2D(s, c) #endif `,`//${this.name}`),e._emitFunction("sampleRefractionLod",` #ifdef ${this._define3DName} #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) #else #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) #endif `,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),t}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(this.texture.isCube?e=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}"); `:e=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}"); `,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; `),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency}; `,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY}; `,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth}; `,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=Bn.Parse(e.texture,t,i):this.texture=ve.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}B([Xt("Link refraction to transparency",Gt.Boolean,"ADVANCED",{notifiers:{update:!0}})],p4.prototype,"linkRefractionWithTransparency",void 0);B([Xt("Invert refraction Y",Gt.Boolean,"ADVANCED",{notifiers:{update:!0}})],p4.prototype,"invertRefractionY",void 0);B([Xt("Use thickness as depth",Gt.Boolean,"ADVANCED",{notifiers:{update:!0}})],p4.prototype,"useThicknessAsDepth",void 0);xe("BABYLON.RefractionBlock",p4);class q8 extends zt{constructor(e){super(e,Ce.Fragment),this._isUnique=!0,this.registerInput("thickness",se.Float,!1,Ce.Fragment),this.registerInput("tintColor",se.Color3,!0,Ce.Fragment),this.registerInput("translucencyIntensity",se.Float,!0,Ce.Fragment),this.registerInput("translucencyDiffusionDist",se.Color3,!0,Ce.Fragment),this.registerInput("refraction",se.Object,!0,Ce.Fragment,new Tn("refraction",this,Zs.Input,p4,"RefractionBlock")),this.registerInput("dispersion",se.Float,!0,Ce.Fragment),this.registerOutput("subsurface",se.Object,Ce.Fragment,new Tn("subsurface",this,Zs.Output,q8,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new Gi("SubSurface thickness",Ce.Fragment,se.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,r){var _;let s="";const a=t!=null&&t.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t!=null&&t.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",c=t!=null&&t.translucencyIntensity.isConnected?t==null?void 0:t.translucencyIntensity.associatedVariableName:"1.",l=t!=null&&t.translucencyDiffusionDist.isConnected?t==null?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",h=t!=null&&t.refraction.isConnected?(_=t==null?void 0:t.refraction.connectedPoint)==null?void 0:_.ownerBlock:null,u=h!=null&&h.tintAtDistance.isConnected?h.tintAtDistance.associatedVariableName:"1.",d=h!=null&&h.intensity.isConnected?h.intensity.associatedVariableName:"1.",f=h!=null&&h.view.isConnected?h.view.associatedVariableName:"",p=t!=null&&t.dispersion.isConnected?t==null?void 0:t.dispersion.associatedVariableName:"0.0";return s+=(h==null?void 0:h.getCode(e))??"",s+=`subSurfaceOutParams subSurfaceOut; #ifdef SUBSURFACE vec2 vThicknessParam = vec2(0., ${a}); vec4 vTintColor = vec4(${o}, ${u}); vec3 vSubSurfaceIntensity = vec3(${d}, ${c}, 0.); float dispersion = ${p}; subSurfaceBlock( vSubSurfaceIntensity, vThicknessParam, vTintColor, normalW, specularEnvironmentReflectance, #ifdef SS_THICKNESSANDMASK_TEXTURE vec4(0.), #endif #ifdef REFLECTION #ifdef SS_TRANSLUCENCY ${i==null?void 0:i._reflectionMatrixName}, #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) reflectionOut.irradianceVector, #endif #if defined(REALTIME_FILTERING) ${i==null?void 0:i._cubeSamplerName}, ${i==null?void 0:i._vReflectionFilteringInfoName}, #endif #endif #ifdef USEIRRADIANCEMAP irradianceSampler, #endif #endif #endif #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) surfaceAlbedo, #endif #ifdef SS_REFRACTION ${r}.xyz, viewDirectionW, ${f}, ${(h==null?void 0:h._vRefractionInfosName)??""}, ${(h==null?void 0:h._refractionMatrixName)??""}, ${(h==null?void 0:h._vRefractionMicrosurfaceInfosName)??""}, vLightingIntensity, #ifdef SS_LINKREFRACTIONTOTRANSPARENCY alpha, #endif #ifdef ${(h==null?void 0:h._defineLODRefractionAlpha)??"IGNORE"} NdotVUnclamped, #endif #ifdef ${(h==null?void 0:h._defineLinearSpecularRefraction)??"IGNORE"} roughness, #endif alphaG, #ifdef ${(h==null?void 0:h._define3DName)??"IGNORE"} ${(h==null?void 0:h._cubeSamplerName)??""}, #else ${(h==null?void 0:h._2DSamplerName)??""}, #endif #ifndef LODBASEDMICROSFURACE #ifdef ${(h==null?void 0:h._define3DName)??"IGNORE"} ${(h==null?void 0:h._cubeSamplerName)??""}, ${(h==null?void 0:h._cubeSamplerName)??""}, #else ${(h==null?void 0:h._2DSamplerName)??""}, ${(h==null?void 0:h._2DSamplerName)??""}, #endif #endif #ifdef ANISOTROPIC anisotropicOut, #endif #ifdef REALTIME_FILTERING ${(h==null?void 0:h._vRefractionFilteringInfoName)??""}, #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC vRefractionPosition, vRefractionSize, #endif #ifdef SS_DISPERSION dispersion, #endif #endif #ifdef SS_TRANSLUCENCY ${l}, #endif subSurfaceOut ); #ifdef SS_REFRACTION surfaceAlbedo = subSurfaceOut.surfaceAlbedo; #ifdef SS_LINKREFRACTIONTOTRANSPARENCY alpha = subSurfaceOut.alpha; #endif #endif #else subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; #endif `,s}_buildBlock(e){return e.target===Ce.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}xe("BABYLON.SubSurfaceBlock",q8);const eBe={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class ho extends zt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,de.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Ce.Fragment:Ce.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Ce.Fragment:Ce.Vertex}constructor(e){super(e,Ce.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Me.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",se.Vector4,!1,Ce.Vertex),this.registerInput("worldNormal",se.Vector4,!1,Ce.Fragment),this.registerInput("view",se.Matrix,!1),this.registerInput("cameraPosition",se.Vector3,!1,Ce.Fragment),this.registerInput("perturbedNormal",se.Vector4,!0,Ce.Fragment),this.registerInput("baseColor",se.Color3,!0,Ce.Fragment),this.registerInput("metallic",se.Float,!1,Ce.Fragment),this.registerInput("roughness",se.Float,!1,Ce.Fragment),this.registerInput("ambientOcc",se.Float,!0,Ce.Fragment),this.registerInput("opacity",se.Float,!0,Ce.Fragment),this.registerInput("indexOfRefraction",se.Float,!0,Ce.Fragment),this.registerInput("ambientColor",se.Color3,!0,Ce.Fragment),this.registerInput("reflection",se.Object,!0,Ce.Fragment,new Tn("reflection",this,Zs.Input,rC,"ReflectionBlock")),this.registerInput("clearcoat",se.Object,!0,Ce.Fragment,new Tn("clearcoat",this,Zs.Input,oA,"ClearCoatBlock")),this.registerInput("sheen",se.Object,!0,Ce.Fragment,new Tn("sheen",this,Zs.Input,iC,"SheenBlock")),this.registerInput("subsurface",se.Object,!0,Ce.Fragment,new Tn("subsurface",this,Zs.Input,q8,"SubSurfaceBlock")),this.registerInput("anisotropy",se.Object,!0,Ce.Fragment,new Tn("anisotropy",this,Zs.Input,S9,"AnisotropyBlock")),this.registerInput("iridescence",se.Object,!0,Ce.Fragment,new Tn("iridescence",this,Zs.Input,JD,"IridescenceBlock")),this.registerOutput("ambientClr",se.Color3,Ce.Fragment),this.registerOutput("diffuseDir",se.Color3,Ce.Fragment),this.registerOutput("specularDir",se.Color3,Ce.Fragment),this.registerOutput("clearcoatDir",se.Color3,Ce.Fragment),this.registerOutput("sheenDir",se.Color3,Ce.Fragment),this.registerOutput("diffuseInd",se.Color3,Ce.Fragment),this.registerOutput("specularInd",se.Color3,Ce.Fragment),this.registerOutput("clearcoatInd",se.Color3,Ce.Fragment),this.registerOutput("sheenInd",se.Color3,Ce.Fragment),this.registerOutput("refraction",se.Color3,Ce.Fragment),this.registerOutput("lighting",se.Color3,Ce.Fragment),this.registerOutput("shadow",se.Float,Ce.Fragment),this.registerOutput("alpha",se.Float,Ce.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.CameraPosition&&t(r));i||(i=new Gi("cameraPosition"),i.setAsSystemValue(Zi.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===Zi.View&&t(r));i||(i=new Gi("view"),i.setAsSystemValue(Zi.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===xr.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===xr.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",r.indexOf(".")<0?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const s=e.getScene();if(s.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&$e.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),!!i._areLightsDirty)if(!this.light)vc(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,N5(s,i);else{const o={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};GO(s,e,this.light,this._lightId,i,!0,o),o.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;WO(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,a)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var u;if(!i)return;const r=i.getScene();this.light?HO(this.light,this._lightId,r,e,!0):gc(r,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const s=this._scene.ambientColor;s&&e.setColor3("ambientFromScene",s);const a=r.useRightHandedSystem===(r._mirroredCameraPosition!=null);e.setFloat(this._invertNormalName,a?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=1,c=((u=this.indexOfRefraction.connectInputBlock)==null?void 0:u.value)??1.5,l=Math.pow((c-o)/(c+o),2);this._metallicReflectanceColor.scaleToRef(l*this._metallicF0Factor,wr.Color3[0]);const h=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,wr.Color3[0],h),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var a;const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(e.counters.lightCounter!==void 0?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${t.associatedVariableName}; `);const s=this.reflection.isConnected?(a=this.reflection.connectedPoint)==null?void 0:a.ownerBlock:null;s&&(s.viewConnectionPoint=this.view),e.compilationString+=(s==null?void 0:s.handleVertexSide(e))??"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 `,e._injectAtEnd+=`vClipSpacePosition = gl_Position; `,e._injectAtEnd+=`#endif `),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName}; `,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; `),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e=`albedoOpacityOutParams albedoOpacityOut; `;const t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+=`albedoOpacityBlock( vec4(${t}, 1.), #ifdef ALBEDO vec4(1.), vec2(1., 1.), #endif #ifdef OPACITY vec4(${i}), vec2(1., 1.), #endif albedoOpacityOut ); vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; float alpha = albedoOpacityOut.alpha; `,e}_getAmbientOcclusionCode(){let e=`ambientOcclusionOutParams aoOut; `;const t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+=`ambientOcclusionBlock( #ifdef AMBIENT vec3(${t}), vec4(0., 1.0, 1.0, 0.), #endif aoOut ); `,e}_getReflectivityCode(e){let t=`reflectivityOutParams reflectivityOut; `;const i="1.";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo; reflectivityBlock( vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.), #ifdef METALLICWORKFLOW surfaceAlbedo, ${this._vMetallicReflectanceFactorsName}, #endif #ifdef REFLECTIVITY vec3(0., 0., ${i}), vec4(1.), #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) aoOut.ambientOcclusionColor, #endif #ifdef MICROSURFACEMAP microSurfaceTexel, <== not handled! #endif reflectivityOut ); float microSurface = reflectivityOut.microSurface; float roughness = reflectivityOut.roughness; #ifdef METALLICWORKFLOW surfaceAlbedo = reflectivityOut.surfaceAlbedo; #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; #endif `,t}_buildBlock(e){var v,x,y,C,b,T,S,N,D,M,I;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=A9(this._scene));const t=this.reflection.isConnected?(v=this.reflection.connectedPoint)==null?void 0:v.ownerBlock:null;if(t&&(t.worldPositionConnectionPoint=this.worldPosition,t.cameraPositionConnectionPoint=this.cameraPosition,t.worldNormalConnectionPoint=this.worldNormal,t.viewConnectionPoint=this.view),e.target!==Ce.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const i=`//${this.name}`,r=this.perturbedNormal;let s=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(s=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${s}; `,i),e.compilationString+=`${s} = ${this.worldPosition.associatedVariableName}.xyz; `,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 `,e.compilationString+=`vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0); `,e.compilationString+=`#endif `):s="v_"+s,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",i),e._emitFunctionFromInclude("importanceSampling",i),e._emitFunctionFromInclude("pbrHelperFunctions",i),e._emitFunctionFromInclude("imageProcessingDeclaration",i),e._emitFunctionFromInclude("imageProcessingFunctions",i),e._emitFunctionFromInclude("shadowsFragmentFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:s+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",i),e._emitFunctionFromInclude("pbrBRDFFunctions",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:s+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",i),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",i),e._emitFunctionFromInclude("pbrBlockReflectivity",i),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",i),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",i),e._emitFunctionFromInclude("pbrBlockAnisotropic",i),e._emitUniformFromString("vLightingIntensity","vec4"),t!=null&&t.generateOnlyFragmentCode&&(e.compilationString+=t.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName}); `,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${s}.xyz); `),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz; `,e.compilationString+=`vec3 normalW = ${r.isConnected?"normalize("+r.associatedVariableName+".xyz)":"geometricNormalW"}; `,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",i,{replaceStrings:[{search:/vPositionW/g,replace:s+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",i),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",i),e.compilationString+=`#ifdef UNLIT vec3 diffuseBase = vec3(1., 1., 1.); #else `,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"}]});const a=this.anisotropy.isConnected?(x=this.anisotropy.connectedPoint)==null?void 0:x.ownerBlock:null;a&&(a.worldPositionConnectionPoint=this.worldPosition,a.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=a.getCode(e,!this.perturbedNormal.isConnected)),t&&t.hasTexture&&(e.compilationString+=t.getCode(e,a?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(t==null?void 0:t._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(t==null?void 0:t._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(t==null?void 0:t._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(t==null?void 0:t._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:(t==null?void 0:t._vReflectionFilteringInfoName)??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",i,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const o=this.sheen.isConnected?(y=this.sheen.connectedPoint)==null?void 0:y.ownerBlock:null;o&&(e.compilationString+=o.getCode(t)),e._emitFunctionFromInclude("pbrBlockSheen",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(t==null?void 0:t._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(t==null?void 0:t._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"}]});const c=this.iridescence.isConnected?(C=this.iridescence.connectedPoint)==null?void 0:C.ownerBlock:null;e.compilationString+=JD.GetCode(c),e._emitFunctionFromInclude("pbrBlockIridescence",i,{replaceStrings:[]});const l=this.clearcoat.isConnected?(b=this.clearcoat.connectedPoint)==null?void 0:b.ownerBlock:null,h=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,u=this.perturbedNormal.isConnected&&((S=((T=this.perturbedNormal.connectedPoint)==null?void 0:T.ownerBlock).worldTangent)==null?void 0:S.isConnected),d=this.anisotropy.isConnected&&((N=this.anisotropy.connectedPoint)==null?void 0:N.ownerBlock).worldTangent.isConnected;let f=u||!this.perturbedNormal.isConnected&&d;e.compilationString+=oA.GetCode(e,l,t,s,h,f,this.worldNormal.associatedVariableName),h&&(f=(l==null?void 0:l.worldTangent.isConnected)??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(t==null?void 0:t._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(t==null?void 0:t._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(t==null?void 0:t._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(t==null?void 0:t._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:f?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"}]});const p=this.subsurface.isConnected?(D=this.subsurface.connectedPoint)==null?void 0:D.ownerBlock:null,_=this.subsurface.isConnected?(I=((M=this.subsurface.connectedPoint)==null?void 0:M.ownerBlock).refraction.connectedPoint)==null?void 0:I.ownerBlock:null;_&&(_.viewConnectionPoint=this.view,_.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=q8.GetCode(e,p,t,s),e._emitFunctionFromInclude("pbrBlockSubSurface",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(t==null?void 0:t._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(t==null?void 0:t._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:(_==null?void 0:_._define3DName)??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:(_==null?void 0:_._defineLODRefractionAlpha)??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:(_==null?void 0:_._defineLinearSpecularRefraction)??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:(_==null?void 0:_._defineOppositeZ)??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",i),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:s+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${s}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",i),e.compilationString+=`#endif `;const m=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let g=xr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();g.indexOf(".")===-1&&(g+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",i,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:m+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:g}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",i,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",i,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",i,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:s},{search:/albedoTexture\.rgb;/g,replace:`vec3(1.); gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); `}]});for(const R of this._outputs)if(R.hasEndpoints){const O=eBe[R.name];if(O){const[H,G]=O;G&&(e.compilationString+=`#if ${G} `),e.compilationString+=`${this._declareOutput(R,e)} = ${H}; `,G&&(e.compilationString+=`#else `,e.compilationString+=`${this._declareOutput(R,e)} = vec3(0.); `,e.compilationString+=`#endif `)}else de.Error(`There's no remapping for the ${R.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff}; `,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest}; `,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff}; `,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending}; `,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha}; `,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha}; `,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing}; `,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering}; `,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality}; `,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation}; `,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion}; `,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion}; `,e+=`${this._codeVariableName}.unlit = ${this.unlit}; `,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward}; `,e+=`${this._codeVariableName}.debugMode = ${this.debugMode}; `,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit}; `,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor}; `,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=e.lightFalloff??0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=e.realTimeFilteringQuality??8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}B([Xt("Direct lights",Gt.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ho.prototype,"directIntensity",void 0);B([Xt("Environment lights",Gt.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ho.prototype,"environmentIntensity",void 0);B([Xt("Specular highlights",Gt.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ho.prototype,"specularIntensity",void 0);B([Xt("Light falloff",Gt.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:xr.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:xr.LIGHTFALLOFF_GLTF},{label:"Standard",value:xr.LIGHTFALLOFF_STANDARD}]})],ho.prototype,"lightFalloff",void 0);B([Xt("Alpha Testing",Gt.Boolean,"OPACITY")],ho.prototype,"useAlphaTest",void 0);B([Xt("Alpha CutOff",Gt.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],ho.prototype,"alphaTestCutoff",void 0);B([Xt("Alpha blending",Gt.Boolean,"OPACITY")],ho.prototype,"useAlphaBlending",void 0);B([Xt("Radiance over alpha",Gt.Boolean,"RENDERING",{notifiers:{update:!0}})],ho.prototype,"useRadianceOverAlpha",void 0);B([Xt("Specular over alpha",Gt.Boolean,"RENDERING",{notifiers:{update:!0}})],ho.prototype,"useSpecularOverAlpha",void 0);B([Xt("Specular anti-aliasing",Gt.Boolean,"RENDERING",{notifiers:{update:!0}})],ho.prototype,"enableSpecularAntiAliasing",void 0);B([Xt("Realtime filtering",Gt.Boolean,"RENDERING",{notifiers:{update:!0}})],ho.prototype,"realTimeFiltering",void 0);B([Xt("Realtime filtering quality",Gt.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],ho.prototype,"realTimeFilteringQuality",void 0);B([Xt("Energy Conservation",Gt.Boolean,"ADVANCED",{notifiers:{update:!0}})],ho.prototype,"useEnergyConservation",void 0);B([Xt("Radiance occlusion",Gt.Boolean,"ADVANCED",{notifiers:{update:!0}})],ho.prototype,"useRadianceOcclusion",void 0);B([Xt("Horizon occlusion",Gt.Boolean,"ADVANCED",{notifiers:{update:!0}})],ho.prototype,"useHorizonOcclusion",void 0);B([Xt("Unlit",Gt.Boolean,"ADVANCED",{notifiers:{update:!0}})],ho.prototype,"unlit",void 0);B([Xt("Force normal forward",Gt.Boolean,"ADVANCED",{notifiers:{update:!0}})],ho.prototype,"forceNormalForward",void 0);B([Xt("Generate only fragment code",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:ho._OnGenerateOnlyFragmentCodeChanged}})],ho.prototype,"generateOnlyFragmentCode",void 0);B([Xt("Debug mode",Gt.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}]})],ho.prototype,"debugMode",void 0);B([Xt("Split position",Gt.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],ho.prototype,"debugLimit",void 0);B([Xt("Output factor",Gt.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],ho.prototype,"debugFactor",void 0);xe("BABYLON.PBRMetallicRoughnessBlock",ho);class x3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("left",se.AutoDetect),this.registerInput("right",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(se.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); `,this}}xe("BABYLON.ModBlock",x3e);class y3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("row0",se.Vector4),this.registerInput("row1",se.Vector4),this.registerInput("row2",se.Vector4),this.registerInput("row3",se.Vector4),this.registerOutput("output",se.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new Gi("row0");e.value=new Ct(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Gi("row1");e.value=new Ct(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Gi("row2");e.value=new Ct(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Gi("row3");e.value=new Ct(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,r=this.row1,s=this.row2,a=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${r.associatedVariableName}, ${s.associatedVariableName}, ${a.associatedVariableName}); `,this}}xe("BABYLON.MatrixBuilder",y3e);var vu;(function(n){n[n.Equal=0]="Equal",n[n.NotEqual=1]="NotEqual",n[n.LessThan=2]="LessThan",n[n.GreaterThan=3]="GreaterThan",n[n.LessOrEqual=4]="LessOrEqual",n[n.GreaterOrEqual=5]="GreaterOrEqual",n[n.Xor=6]="Xor",n[n.Or=7]="Or",n[n.And=8]="And"})(vu||(vu={}));class A3e extends zt{constructor(e){super(e,Ce.Neutral),this.condition=vu.LessThan,this.registerInput("a",se.Float),this.registerInput("b",se.Float),this.registerInput("true",se.AutoDetect,!0),this.registerInput("false",se.AutoDetect,!0),this.registerOutput("output",se.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=se.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case vu.Equal:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${r}; `;break}case vu.NotEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${r}; `;break}case vu.LessThan:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${r}; `;break}case vu.LessOrEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${r}; `;break}case vu.GreaterThan:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${r}; `;break}case vu.GreaterOrEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${r}; `;break}case vu.Xor:{e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${r}; `;break}case vu.Or:{e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${r}; `;break}case vu.And:{e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${r}; `;break}}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${vu[this.condition]}; `}}xe("BABYLON.ConditionalBlock",A3e);class Xee extends zt{constructor(e){super(e,Ce.Neutral),this.octaves=6,this.registerInput("seed",se.AutoDetect),this.registerInput("chaos",se.AutoDetect,!0),this.registerInput("offsetX",se.Float,!0),this.registerInput("offsetY",se.Float,!0),this.registerInput("offsetZ",se.Float,!0),this.registerOutput("output",se.Float),this._inputs[0].acceptedConnectionPointTypes.push(se.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(se.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){var c,l;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;const t=` float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } // Based on Morgan McGuire @morgan3d // https://www.shadertoy.com/view/4dS3Wd float cloudNoise(in vec2 x, in vec2 chaos) { vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); vec2 i = floor(x); vec2 f = fract(x); float n = dot(i, step); vec2 u = f * f * (3.0 - 2.0 * f); return mix( mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), u.y ); } float cloudNoise(in vec3 x, in vec3 chaos) { vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); vec3 i = floor(x); vec3 f = fract(x); float n = dot(i, step); vec3 u = f * f * (3.0 - 2.0 * f); return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); }`,i=` float fbm(in vec2 st, in vec2 chaos) { // Initial values float value = 0.0; float amplitude = .5; float frequency = 0.; // Loop of octaves for (int i = 0; i < OCTAVES; i++) { value += amplitude * cloudNoise(st, chaos); st *= 2.0; amplitude *= 0.5; } return value; } float fbm(in vec3 x, in vec3 chaos) { // Initial values float value = 0.0; float amplitude = 0.5; for (int i = 0; i < OCTAVES; ++i) { value += amplitude * cloudNoise(x, chaos); x = x * 2.0; amplitude *= 0.5; } return value; }`,r=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,r).replace(/OCTAVES/gi,(this.octaves|0).toString()),"// CloudBlockCode FBM");const s=e._getFreeVariableName("st"),a=((c=this.seed.connectedPoint)==null?void 0:c.type)===se.Vector2?"vec2":"vec3";e.compilationString+=`${a} ${s} = ${this.seed.associatedVariableName}; `,this.offsetX.isConnected&&(e.compilationString+=`${s}.x += 0.1 * ${this.offsetX.associatedVariableName}; `),this.offsetY.isConnected&&(e.compilationString+=`${s}.y += 0.1 * ${this.offsetY.associatedVariableName}; `),this.offsetZ.isConnected&&a==="vec3"&&(e.compilationString+=`${s}.z += 0.1 * ${this.offsetZ.associatedVariableName}; `);let o="";return this.chaos.isConnected?o=this.chaos.associatedVariableName:o=((l=this.seed.connectedPoint)==null?void 0:l.type)===se.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${r}(${s}, ${o}); `,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves}; `}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}B([Xt("Octaves",Gt.Int)],Xee.prototype,"octaves",void 0);xe("BABYLON.CloudBlock",Xee);class C3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("seed",se.Vector2),this.registerInput("offset",se.Float),this.registerInput("density",se.Float),this.registerOutput("output",se.Float),this.registerOutput("cells",se.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t=`vec2 voronoiRandom(vec2 seed, float offset){ mat2 m = mat2(15.27, 47.63, 99.41, 89.98); vec2 uv = fract(sin(m * seed) * 46839.32); return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5); } `;e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ vec2 g = floor(seed * density); vec2 f = fract(seed * density); float t = 8.0; vec3 res = vec3(8.0, 0.0, 0.0); for(int y=-1; y<=1; y++) { for(int x=-1; x<=1; x++) { vec2 lattice = vec2(x,y); vec2 randomOffset = voronoiRandom(lattice + g, offset); float d = distance(lattice + randomOffset, f); if(d < res.x) { res = vec3(d, randomOffset.x, randomOffset.y); outValue = res.x; cells = res.y; } } } } `,e._emitFunction("voronoi",t,"// Voronoi");const i=e._getFreeVariableName("tempOutput"),r=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0; `,e.compilationString+=`float ${r} = 0.0; `,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${r}); `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; `),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${r}; `),this}}xe("BABYLON.VoronoiNoiseBlock",C3e);class b3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("input",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==Ce.VertexAndFragment)return t.target;if(e.connectedPoint.target!==Ce.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName}; `,this}}xe("BABYLON.ElbowBlock",b3e);class tK extends zt{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)==null?void 0:e.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??bt.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}get textureY(){var e;return this.sourceY.isConnected?((e=this.sourceY.connectedPoint)==null?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return(e=this.sourceZ)!=null&&e.isConnected?((t=this.sourceY.connectedPoint)==null?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return e!=null&&e.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){var e;return((e=this._getImageSourceBlock(this.sourceY))==null?void 0:e.samplerName)??null}get samplerZName(){var e;return((e=this._getImageSourceBlock(this.sourceZ))==null?void 0:e.samplerName)??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const t=this.texture.getScene()??bt.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const t=this.texture.getScene()??bt.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,Ce.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",se.AutoDetect,!1),this.registerInput("normal",se.AutoDetect,!1),this.registerInput("sharpness",se.Float,!0),this.registerInput("source",se.Object,!0,Ce.VertexAndFragment,new Tn("source",this,Zs.Input,Hf,"ImageSourceBlock")),this.registerInput("sourceY",se.Object,!0,Ce.VertexAndFragment,new Tn("sourceY",this,Zs.Input,Hf,"ImageSourceBlock")),t||this.registerInput("sourceZ",se.Object,!0,Ce.VertexAndFragment,new Tn("sourceZ",this,Zs.Input,Hf,"ImageSourceBlock")),this.registerOutput("rgba",se.Color4,Ce.Neutral),this.registerOutput("rgb",se.Color3,Ce.Neutral),this.registerOutput("r",se.Float,Ce.Neutral),this.registerOutput("g",se.Float,Ce.Neutral),this.registerOutput("b",se.Float,Ce.Neutral),this.registerOutput("a",se.Float,Ce.Neutral),this.registerOutput("level",se.Float,Ce.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(se.Color3|se.Vector3|se.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(se.Color3|se.Vector3|se.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,r=this.samplerZName??t,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",a=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),c=e._getFreeVariableName("z"),l=e._getFreeVariableName("w"),h=e._getFreeVariableName("n"),u=e._getFreeVariableName("uvx"),d=e._getFreeVariableName("uvy"),f=e._getFreeVariableName("uvz");e.compilationString+=` vec3 ${h} = ${this.normal.associatedVariableName}.xyz; vec2 ${u} = ${this.position.associatedVariableName}.yz; vec2 ${d} = ${this.position.associatedVariableName}.zx; vec2 ${f} = ${this.position.associatedVariableName}.xy; `,this.projectAsCube&&(e.compilationString+=` ${u}.xy = ${u}.yx; if (${h}.x >= 0.0) { ${u}.x = -${u}.x; } if (${h}.y < 0.0) { ${d}.y = -${d}.y; } if (${h}.z < 0.0) { ${f}.x = -${f}.x; } `),e.compilationString+=` vec4 ${a} = texture2D(${t}, ${u}); vec4 ${o} = texture2D(${i}, ${d}); vec4 ${c} = texture2D(${r}, ${f}); // blend weights vec3 ${l} = pow(abs(${h}), vec3(${s})); // blend and return vec4 ${this._tempTextureRead} = (${a}*${l}.x + ${o}*${l}.y + ${c}*${l}.z) / (${l}.x + ${l}.y + ${l}.z); `}_generateConversionCode(e,t,i){i!=="a"&&((!this.texture||!this.texture.gammaSpace)&&(e.compilationString+=`#ifdef ${this._linearDefineName} ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); #endif `),e.compilationString+=`#ifdef ${this._gammaDefineName} ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); #endif `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r}; `,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e);for(const i of this._outputs)i.hasEndpoints&&i.name!=="level"&&this._writeOutput(e,i,i.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; `,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; `,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; `,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube}; `,this.texture&&(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); `,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; `,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; `,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; `,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; `,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; `,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; `,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; `,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; `,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; `,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; `),e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,!this.hasImageSource&&this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!Ss.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ve.Parse(e.texture,t,i))}}B([Xt("Project as cube",Gt.Boolean,"ADVANCED",{notifiers:{update:!0}})],tK.prototype,"projectAsCube",void 0);xe("BABYLON.TriPlanarBlock",tK);class E3e extends tK{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",s=e._getFreeVariableName("dpdx"),a=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),c=e._getFreeVariableName("ma"),l=e._getFreeVariableName("mi"),h=e._getFreeVariableName("me"),u=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),f=e._getFreeVariableName("y");e.compilationString+=` // grab coord derivatives for texturing vec3 ${s} = dFdx(${this.position.associatedVariableName}.xyz); vec3 ${a} = dFdy(${this.position.associatedVariableName}.xyz); vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz); // determine major axis (in x; yz are following axis) ivec3 ${c} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) : (${o}.y>${o}.z) ? ivec3(1,2,0) : ivec3(2,0,1) ; // determine minor axis (in x; yz are following axis) ivec3 ${l} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) : (${o}.y<${o}.z) ? ivec3(1,2,0) : ivec3(2,0,1) ; // determine median axis (in x; yz are following axis) ivec3 ${h} = ivec3(3) - ${l} - ${c}; // project+fetch vec4 ${u} = textureGrad( ${t}, vec2( ${this.position.associatedVariableName}[${c}.y], ${this.position.associatedVariableName}[${c}.z]), vec2(${s}[${c}.y],${s}[${c}.z]), vec2(${a}[${c}.y],${a}[${c}.z]) ); vec4 ${d} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${h}.y], ${this.position.associatedVariableName}[${h}.z]), vec2(${s}[${h}.y],${s}[${h}.z]), vec2(${a}[${h}.y],${a}[${h}.z]) ); // blend factors vec2 ${f} = vec2(${o}[${c}.x],${o}[${h}.x]); // make local support ${f} = clamp( (${f}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); // shape transition ${f} = pow( ${f}, vec2(${r}/8.0) ); // blend and return vec4 ${this._tempTextureRead} = (${u}*${f}.x + ${d}*${f}.y) / (${f}.x + ${f}.y); `}}xe("BABYLON.BiPlanarBlock",E3e);class T3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("input",se.Matrix),this.registerOutput("output",se.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName}); `,this}}xe("BABYLON.MatrixDeterminantBlock",T3e);class S3e extends zt{constructor(e){super(e,Ce.Neutral),this.registerInput("input",se.Matrix),this.registerOutput("output",se.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName}); `,this}}xe("BABYLON.MatrixTransposeBlock",S3e);var Es;(function(n){n[n.None=0]="None",n[n.Normal=1]="Normal",n[n.Tangent=2]="Tangent",n[n.VertexColor=3]="VertexColor",n[n.UV1=4]="UV1",n[n.UV2=5]="UV2",n[n.UV3=6]="UV3",n[n.UV4=7]="UV4",n[n.UV5=8]="UV5",n[n.UV6=9]="UV6"})(Es||(Es={}));class Yee extends zt{constructor(e){super(e,Ce.Neutral),this.attributeType=Es.None,this.registerInput("input",se.AutoDetect),this.registerInput("fallback",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(t=>{var r;if(this.attributeType)return;const i=t.ownerBlock;if(i instanceof Gi&&i.isAttribute)switch(i.name){case"color":this.attributeType=Es.VertexColor;break;case"normal":this.attributeType=Es.Normal;break;case"tangent":this.attributeType=Es.Tangent;break;case"uv":this.attributeType=Es.UV1;break;case"uv2":this.attributeType=Es.UV2;break;case"uv3":this.attributeType=Es.UV3;break;case"uv4":this.attributeType=Es.UV4;break;case"uv5":this.attributeType=Es.UV5;break;case"uv6":this.attributeType=Es.UV6;break}else if(i instanceof Hee)switch((r=this.input.connectedPoint)==null?void 0:r.name){case"normalOutput":this.attributeType=Es.Normal;break;case"tangentOutput":this.attributeType=Es.Tangent;break;case"uvOutput":this.attributeType=Es.UV1;break}})}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case Es.VertexColor:t="VERTEXCOLOR_NME";break;case Es.Normal:t="NORMAL";break;case Es.Tangent:t="TANGENT";break;case Es.UV1:t="UV1";break;case Es.UV2:t="UV2";break;case Es.UV3:t="UV3";break;case Es.UV4:t="UV4";break;case Es.UV5:t="UV5";break;case Es.UV6:t="UV6";break}const i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t} `),e.compilationString+=`${i} = ${this.input.associatedVariableName}; `,t&&(e.compilationString+=`#else `,e.compilationString+=`${i} = ${this.fallback.associatedVariableName}; `,e.compilationString+=`#endif `),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??Es.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType}; `,e}}B([Xt("Attribute lookup",Gt.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:Es.None},{label:"Normal",value:Es.Normal},{label:"Tangent",value:Es.Tangent},{label:"Vertex Color",value:Es.VertexColor},{label:"UV1",value:Es.UV1},{label:"UV2",value:Es.UV2},{label:"UV3",value:Es.UV3},{label:"UV4",value:Es.UV4},{label:"UV5",value:Es.UV5},{label:"UV6",value:Es.UV6}]})],Yee.prototype,"attributeType",void 0);xe("BABYLON.MeshAttributeExistsBlock",Yee);var Qs;(function(n){n[n.EaseInSine=0]="EaseInSine",n[n.EaseOutSine=1]="EaseOutSine",n[n.EaseInOutSine=2]="EaseInOutSine",n[n.EaseInQuad=3]="EaseInQuad",n[n.EaseOutQuad=4]="EaseOutQuad",n[n.EaseInOutQuad=5]="EaseInOutQuad",n[n.EaseInCubic=6]="EaseInCubic",n[n.EaseOutCubic=7]="EaseOutCubic",n[n.EaseInOutCubic=8]="EaseInOutCubic",n[n.EaseInQuart=9]="EaseInQuart",n[n.EaseOutQuart=10]="EaseOutQuart",n[n.EaseInOutQuart=11]="EaseInOutQuart",n[n.EaseInQuint=12]="EaseInQuint",n[n.EaseOutQuint=13]="EaseOutQuint",n[n.EaseInOutQuint=14]="EaseInOutQuint",n[n.EaseInExpo=15]="EaseInExpo",n[n.EaseOutExpo=16]="EaseOutExpo",n[n.EaseInOutExpo=17]="EaseInOutExpo",n[n.EaseInCirc=18]="EaseInCirc",n[n.EaseOutCirc=19]="EaseOutCirc",n[n.EaseInOutCirc=20]="EaseInOutCirc",n[n.EaseInBack=21]="EaseInBack",n[n.EaseOutBack=22]="EaseOutBack",n[n.EaseInOutBack=23]="EaseInOutBack",n[n.EaseInElastic=24]="EaseInElastic",n[n.EaseOutElastic=25]="EaseOutElastic",n[n.EaseInOutElastic=26]="EaseInOutElastic"})(Qs||(Qs={}));class M3e extends zt{constructor(e){super(e,Ce.Neutral),this.type=Qs.EaseInOutSine,this.registerInput("input",se.AutoDetect),this.registerOutput("output",se.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(se.Matrix),this._inputs[0].excludedConnectionPointTypes.push(se.Object),this._inputs[0].excludedConnectionPointTypes.push(se.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t){if(t==="float")return this._duplicateEntryDirect(e);const i=parseInt(t.replace("vec",""));let r=` vec${i} ret = vec${i}(0.0); `;for(let s=1;s<=i;s++)r+=this._duplicateEntry(e,s===1?"x":s===2?"y":s===3?"z":"w")+`; `;return r+=`return ret; `,r}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",r="",s="";switch(this.input.type){case se.Float:s="float";break;case se.Vector2:s="vec2";break;case se.Vector3:case se.Color3:s="vec3";break;case se.Vector4:case se.Color4:s="vec4";break}switch(r=Qs[this.type]+"_"+s,this.type){case Qs.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case Qs.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case Qs.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case Qs.EaseInQuad:i="return v * v";break;case Qs.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case Qs.EaseInOutQuad:{i=this._duplicateVector("VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0",s);break}case Qs.EaseInCubic:i="return v * v * v";break;case Qs.EaseOutCubic:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",s);break}case Qs.EaseInOutCubic:{i=this._duplicateVector("VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0",s);break}case Qs.EaseInQuart:i="return v * v * v * v";break;case Qs.EaseOutQuart:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",s);break}case Qs.EaseInOutQuart:{i=this._duplicateVector("VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0",s);break}case Qs.EaseInQuint:i="return v * v * v * v * v";break;case Qs.EaseOutQuint:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",s);break}case Qs.EaseInOutQuint:{i=this._duplicateVector("VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0",s);break}case Qs.EaseInExpo:{i=this._duplicateVector("VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)",s);break}case Qs.EaseOutExpo:{i=this._duplicateVector("VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)",s);break}case Qs.EaseInOutExpo:{i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0",s);break}case Qs.EaseInCirc:{i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",s);break}case Qs.EaseOutCirc:{i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",s);break}case Qs.EaseInOutCirc:{i=this._duplicateVector("VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0",s);break}case Qs.EaseInBack:{i="return 2.70158 * v * v * v - 1.70158 * v * v";break}case Qs.EaseOutBack:{i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",s);break}case Qs.EaseInOutBack:{i=this._duplicateVector("VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0",s);break}case Qs.EaseInElastic:{i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))",s);break}case Qs.EaseOutElastic:{i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0",s);break}case Qs.EaseInOutElastic:{i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0",s);break}}return e._emitFunction(r,`${s} ${r}(${s} v) {${i};} `,""),e.compilationString+=this._declareOutput(t,e)+` = ${r}(${this.input.associatedVariableName}); `,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${Qs[this.type]}; `}}xe("BABYLON.CurveBlock",M3e);class tBe{optimize(e,t){}}class iBe{constructor(){this.mm=new Map}get(e,t){const i=this.mm.get(e);if(i!==void 0)return i.get(t)}set(e,t,i){let r=this.mm.get(e);r===void 0&&this.mm.set(e,r=new Map),r.set(t,i)}}class rBe{get standalone(){var e;return((e=this._options)==null?void 0:e.standalone)??!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){var e;return((e=this._options)==null?void 0:e.doNotInjectCode)??!1}constructor(e,t,i){this._baseMaterial=e,this._scene=t??bt.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new iBe,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add(r=>{var a,o;const s=(a=r.subMesh)==null?void 0:a.getMesh();s&&!this._meshes.has(s)&&this._meshes.set(s,s.onDisposeObservable.add(c=>{const l=this._subMeshToEffect.keys();for(let h=l.next();h.done!==!0;h=l.next()){const u=h.value;(u==null?void 0:u.getMesh())===c&&(this._subMeshToEffect.delete(u),this._deleteDepthWrapperEffect(u))}})),((o=this._subMeshToEffect.get(r.subMesh))==null?void 0:o[0])!==r.effect&&(this._subMeshToEffect.set(r.subMesh,[r.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(r.subMesh))})}_deleteDepthWrapperEffect(e){const t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach(i=>{var r;(r=i.mainDrawWrapper.effect)==null||r.dispose()}),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,t,i){var a;const r=(a=this._subMeshToDepthWrapper.mm.get(e))==null?void 0:a.get(t);if(!r)return null;let s=r.drawWrapper[i];return s||(s=r.drawWrapper[i]=new Sn(this._scene.getEngine()),s.setEffect(r.mainDrawWrapper.effect,r.mainDrawWrapper.defines)),s}isReadyForSubMesh(e,t,i,r,s){var a;return this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,r)?!1:((a=this._makeEffect(e,t,i,s))==null?void 0:a.isReady())??!1}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let t=e.next();t.done!==!0;t=e.next()){const[i,r]=t.value;i.onDisposeObservable.remove(r)}}_makeEffect(e,t,i,r){var p,_;const s=this._scene.getEngine(),a=this._subMeshToEffect.get(e);if(!a)return null;const[o,c]=a;let l=this._subMeshToDepthWrapper.get(e,i);if(!l){const m=new Sn(s);m.defines=((p=e._getDrawWrapper(c))==null?void 0:p.defines)??null,l={drawWrapper:[],mainDrawWrapper:m,depthDefines:"",token:mh()},l.drawWrapper[r]=m,this._subMeshToDepthWrapper.set(e,i,l)}const h=t.join(` `);if(l.mainDrawWrapper.effect&&h===l.depthDefines)return l.mainDrawWrapper.effect;l.depthDefines=h;const u=o.getUniformNames().slice();let d=o.vertexSourceCodeBeforeMigration,f=o.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){const m=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",g=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",v=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",x="#include",y="#include";o.shaderLanguage===Vs.GLSL?d=d.replace(/void\s+?main/g,` ${y} void main`):d=d.replace(/@vertex/g,` ${y} @vertex`),d=d.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,m),d.indexOf("#define SHADOWDEPTH_METRIC")!==-1?d=d.replace(/#define SHADOWDEPTH_METRIC/g,g):d=d.replace(/}\s*$/g,g+` }`),d=d.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const C=f.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||f.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,b=f.indexOf("#define SHADOWDEPTH_FRAGMENT")!==-1;let T="";C?f=f.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,v):T=v+` `,f=f.replace(/void\s+?main/g,bi.IncludesShadersStore.shadowMapFragmentExtraDeclaration+` void main`),b?f=f.replace(/#define SHADOWDEPTH_FRAGMENT/g,x):T+=x+` `,T&&(f=f.replace(/}\s*$/g,T+"}")),u.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}l.mainDrawWrapper.effect=s.createEffect({vertexSource:d,fragmentSource:f,vertexToken:l.token,fragmentToken:l.token},{attributes:o.getAttributesNames(),uniformsNames:u,uniformBuffersNames:o.getUniformBuffersNames(),samplers:o.getSamplers(),defines:h+` `+o.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:o.getIndexParameters(),shaderLanguage:o.shaderLanguage},s);for(let m=0;m0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof P){const t=[];return e.forEach(r=>{t.push(r.flatMap(s=>[s.x,s.y,s.z]))}),t}else{if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach(i=>{t.push(Array.from(i))}),t}}return[]}static OmitZeroLengthPredicate(e,t,i){const r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),r.length===0?null:r}static OmitDuplicatesPredicate(e,t,i,r){const s=[];return jr._SearchInPoints(e,t,r)||s.push([e,t]),jr._SearchInPoints(t,i,r)||s.push([t,i]),jr._SearchInPoints(i,e,r)||s.push([i,e]),s.length===0?null:s}static _SearchInPoints(e,t,i){var r,s,a;for(const o of i)for(let c=0;c{const a=r.getVerticesData(Z.PositionKind),o=r.getIndices();if(a&&o)for(let c=0,l=0;c[t.x,t.y,t.z])}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){if(e.length===0)return 0;let t;typeof e[0]=="number"?t=jr.ToVector3Array(e):t=e;const i=ie.Vector3[0];let r=0;for(let s=0;s{s.length>t?jr.SegmentizeSegmentByCount(s.point1,s.point2,Math.ceil(s.length/t)).forEach(o=>{r.push(o)}):(r.push(s.point1),r.push(s.point2))}),r}static SegmentizeLineBySegmentCount(e,t){const i=typeof e[0]=="number"?jr.ToVector3Array(e):e,r=jr.GetLineLength(i)/t;return jr.SegmentizeLineBySegmentLength(i,r)}static GetLineSegments(e){const t=[];for(let i=0;ir.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){const s=t*i;let a=0,o=0;const c=e.length;for(let h=0;h[s.x,s.y,s.z])}static GetArrowCap(e,t,i,r,s,a=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[r,s,a,o]}}static GetPointsFromText(e,t,i,r,s=0,a=!0){const o=[],c=Aee(e,t,i,r);for(const l of c){for(const h of l.paths){const u=[],d=h.getPoints();for(const f of d)u.push(f.x,f.y,s);o.push(u)}if(a)for(const h of l.holes){const u=[],d=h.getPoints();for(const f of d)u.push(f.x,f.y,s);o.push(u)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(e.length*4);for(let i=0,r=0;i{jr.DisposeEmptyColorsTexture()}),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){const e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?` uniform vec4 grl_aspect_resolution_lineWidth; uniform mat4 grl_projection; `:"",fragment:` uniform vec4 grl_dashOptions; uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; uniform vec3 grl_singleColor; `}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const r=this._scene.activeCamera;if(r){const a=r.getProjectionMatrix();e.updateMatrix("grl_projection",a)}else throw Error("GreasedLinePluginMaterial requires an active camera.");const s=ie.Vector4[0];s.x=this._aspect,s.y=this._resolution.x,s.z=this._resolution.y,s.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",s)}const t=ie.Vector4[0];t.x=jr.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=ie.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=jr.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",this.colorsTexture??Wo.EmptyColorsTexture)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===k0.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return i_.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if(e==="vertex"){const t={CUSTOM_VERTEX_DEFINITIONS:` attribute float grl_widths; attribute vec3 grl_offsets; attribute float grl_colorPointers; varying float grlCounters; varying float grlColorPointer; #ifdef GREASED_LINE_CAMERA_FACING attribute vec4 grl_previousAndSide; attribute vec4 grl_nextAndCounters; vec2 grlFix( vec4 i, float aspect ) { vec2 res = i.xy / i.w; res.x *= aspect; return res; } #else attribute vec3 grl_slopes; attribute float grl_counters; #endif `,CUSTOM_VERTEX_UPDATE_POSITION:` #ifdef GREASED_LINE_CAMERA_FACING vec3 grlPositionOffset = grl_offsets; positionUpdated += grlPositionOffset; #else positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths); #endif `,CUSTOM_VERTEX_MAIN_END:` grlColorPointer = grl_colorPointers; #ifdef GREASED_LINE_CAMERA_FACING float grlAspect = grl_aspect_resolution_lineWidth.x; float grlBaseWidth = grl_aspect_resolution_lineWidth.w; vec3 grlPrevious = grl_previousAndSide.xyz; float grlSide = grl_previousAndSide.w; vec3 grlNext = grl_nextAndCounters.xyz; grlCounters = grl_nextAndCounters.w; mat4 grlMatrix = viewProjection * finalWorld; vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 ); vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 ); vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 ); vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect ); vec2 grlPrevP = grlFix( grlPrevPos, grlAspect ); vec2 grlNextP = grlFix( grlNextPos, grlAspect ); float grlWidth = grlBaseWidth * grl_widths; vec2 grlDir; if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP ); else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP ); else { vec2 grlDir1 = normalize( grlCurrentP - grlPrevP ); vec2 grlDir2 = normalize( grlNextP - grlCurrentP ); grlDir = normalize( grlDir1 + grlDir2 ); } vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. ); #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM grlNormal.xy *= -.5 * grlWidth; #else grlNormal.xy *= .5 * grlWidth; #endif grlNormal *= grl_projection; #ifdef GREASED_LINE_SIZE_ATTENUATION grlNormal.xy *= grlFinalPosition.w; grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy; #endif grlFinalPosition.xy += grlNormal.xy * grlSide; gl_Position = grlFinalPosition; vPositionW = vec3(grlFinalPosition); #else grlCounters = grl_counters; #endif `};return this._cameraFacing&&(t["!gl_Position\\=viewProjection\\*worldPos;"]="//"),t}return e==="fragment"?{CUSTOM_FRAGMENT_DEFINITIONS:` varying float grlCounters; varying float grlColorPointer; uniform sampler2D grl_colors; `,CUSTOM_FRAGMENT_MAIN_END:` float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; float grlUseDash = grl_dashOptions.x; float grlDashArray = grl_dashOptions.y; float grlDashOffset = grl_dashOptions.z; float grlDashRatio = grl_dashOptions.w; gl_FragColor.a *= step(grlCounters, grlVisibility); if( gl_FragColor.a == 0. ) discard; if(grlUseDash == 1.){ gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); if (gl_FragColor.a == 0.) discard; } #ifdef GREASED_LINE_HAS_COLOR if (grlColorMode == ${Su.COLOR_MODE_SET}.) { gl_FragColor.rgb = grl_singleColor; } else if (grlColorMode == ${Su.COLOR_MODE_ADD}.) { gl_FragColor.rgb += grl_singleColor; } else if (grlColorMode == ${Su.COLOR_MODE_MULTIPLY}.) { gl_FragColor.rgb *= grl_singleColor; } #else if (grlUseColors == 1.) { #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); #else vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.); #endif if (grlColorMode == ${Su.COLOR_MODE_SET}.) { gl_FragColor = grlColor; } else if (grlColorMode == ${Su.COLOR_MODE_ADD}.) { gl_FragColor += grlColor; } else if (grlColorMode == ${Su.COLOR_MODE_MULTIPLY}.) { gl_FragColor *= grlColor; } } #endif `}:null}dispose(){var e;(e=this.colorsTexture)==null||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var s,a,o;const r=((s=this._colors)==null?void 0:s.length)??0;if(this._colors=e,e===null||e.length===0){(a=this.colorsTexture)==null||a.dispose();return}if(!(t&&!i))if(this.colorsTexture&&r===e.length&&!i){const c=jr.Color3toRGBAUint8(e);this.colorsTexture.update(c)}else(o=this.colorsTexture)==null||o.dispose(),this.colorsTexture=jr.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){this._color===null&&e!==null||this._color!==null&&e===null?(this._color=e,!t&&this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var s;super.parse(e,t,i);const r=e.greasedLineMaterialOptions;(s=this.colorsTexture)==null||s.dispose(),r.color&&this.setColor(r.color,!0),r.colorDistributionType&&(this.colorsDistributionType=r.colorDistributionType),r.colors&&(this.colors=r.colors),r.colorsSampling&&(this.colorsSampling=r.colorsSampling),r.colorMode&&(this.colorMode=r.colorMode),r.useColors&&(this.useColors=r.useColors),r.visibility&&(this.visibility=r.visibility),r.useDash&&(this.useDash=r.useDash),r.dashCount&&(this.dashCount=r.dashCount),r.dashRatio&&(this.dashRatio=r.dashRatio),r.dashOffset&&(this.dashOffset=r.dashOffset),r.width&&(this.width=r.width),r.sizeAttenuation&&(this.sizeAttenuation=r.sizeAttenuation),r.resolution&&(this.resolution=r.resolution),this.colors?this.colorsTexture=jr.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):jr.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var i;const t=e;(i=t.colorsTexture)==null||i.dispose(),this._colors&&(t.colorsTexture=jr.CreateColorsTexture(`${t._material.name}-colors-texture`,this._colors,t.colorsSampling,this._scene)),t.setColor(this.color,!0),t.colorsDistributionType=this.colorsDistributionType,t.colorsSampling=this.colorsSampling,t.colorMode=this.colorMode,t.useColors=this.useColors,t.visibility=this.visibility,t.useDash=this.useDash,t.dashCount=this.dashCount,t.dashRatio=this.dashRatio,t.dashOffset=this.dashOffset,t.width=this.width,t.sizeAttenuation=this.sizeAttenuation,t.resolution=this.resolution,t.markAllDefinesAsDirty()}}i_.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial";xe(`BABYLON.${i_.GREASED_LINE_MATERIAL_NAME}`,i_);const uBe="greasedLinePixelShader",dBe=`precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}} `;Re.ShadersStore[uBe]=dBe;const fBe="greasedLineVertexShader",pBe=`precision highp float; #include attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer; #ifdef GREASED_LINE_CAMERA_FACING attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} #else attribute vec3 grl_slopes;attribute float grl_counters; #endif void main() { #include grlColorPointer=grl_colorPointers; #ifdef GREASED_LINE_CAMERA_FACING float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=viewProjection*finalWorld ;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );} vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM grlNormal.xy*=-.5*grlWidth; #else grlNormal.xy*=.5*grlWidth; #endif grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition; #else grlCounters=grl_counters;vec4 grlFinalPosition=worldViewProjection*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition; #endif } `;Re.ShadersStore[fBe]=pBe;class Qee extends kn{constructor(e,t,i){const r=[`COLOR_DISTRIBUTION_TYPE_LINE ${k0.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${k0.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${Su.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${Su.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${Su.COLOR_MODE_MULTIPLY}.`],s=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&r.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(r.push("GREASED_LINE_CAMERA_FACING"),s.push("grl_previousAndSide","grl_nextAndCounters")):(s.push("grl_slopes"),s.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:s,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:r}),this._color=Me.White(),this._colorsDistributionType=k0.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:Wo.DEFAULT_COLOR};const a=t.getEngine();this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.dashCount=i.dashCount??1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?Wo.DEFAULT_WIDTH_ATTENUATED:Wo.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??Me.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??k0.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??$s.NEAREST_NEAREST,this.colorMode=i.colorMode??Su.COLOR_MODE_SET,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new Be(a.getRenderWidth(),a.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=jr.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),a.onDisposeObservable.add(()=>{jr.DisposeEmptyColorsTexture()})}dispose(){var e;(e=this._colorsTexture)==null||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new Be(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var s,a,o;const r=((s=this._colors)==null?void 0:s.length)??0;if(this._colors=e,e===null||e.length===0){(a=this._colorsTexture)==null||a.dispose();return}if(!(t&&!i))if(this._colorsTexture&&r===e.length&&!i){const c=jr.Color3toRGBAUint8(e);this._colorsTexture.update(c)}else(o=this._colorsTexture)==null||o.dispose(),this.colorsTexture=jr.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}get colorsTexture(){return this._colorsTexture??null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",jr.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",jr.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",jr.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??Wo.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var s;const r=e.greasedLineMaterialOptions;(s=this._colorsTexture)==null||s.dispose(),r.color&&(this.color=r.color),r.colorDistributionType&&(this.colorsDistributionType=r.colorDistributionType),r.colorsSampling&&(this.colorsSampling=r.colorsSampling),r.colorMode&&(this.colorMode=r.colorMode),r.useColors&&(this.useColors=r.useColors),r.visibility&&(this.visibility=r.visibility),r.useDash&&(this.useDash=r.useDash),r.dashCount&&(this.dashCount=r.dashCount),r.dashRatio&&(this.dashRatio=r.dashRatio),r.dashOffset&&(this.dashOffset=r.dashOffset),r.width&&(this.width=r.width),r.sizeAttenuation&&(this.sizeAttenuation=r.sizeAttenuation),r.resolution&&(this.resolution=r.resolution),r.colors?this.colorsTexture=jr.CreateColorsTexture(`${this.name}-colors-texture`,r.colors,this.colorsSampling,this.getScene()):this.colorsTexture=jr.PrepareEmptyColorsTexture(t),this._cameraFacing=r.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const _Be=`#if defined(DBG_ENABLED) attribute float dbg_initialPass; varying vec3 dbg_vBarycentric; flat varying vec3 dbg_vVertexWorldPos; flat varying float dbg_vPass; #endif`,mBe=`#if defined(DBG_ENABLED) float dbg_vertexIndex = mod(float(gl_VertexID), 3.); if (dbg_vertexIndex == 0.0) { dbg_vBarycentric = vec3(1.,0.,0.); } else if (dbg_vertexIndex == 1.0) { dbg_vBarycentric = vec3(0.,1.,0.); } else { dbg_vBarycentric = vec3(0.,0.,1.); } dbg_vVertexWorldPos = vPositionW; dbg_vPass = dbg_initialPass; #endif`,gBe=`#if defined(DBG_ENABLED) uniform vec3 dbg_shadedDiffuseColor; uniform vec4 dbg_shadedSpecularColorPower; uniform vec3 dbg_thicknessRadiusScale; #if DBG_MODE == 2 || DBG_MODE == 3 uniform vec3 dbg_vertexColor; #endif #if DBG_MODE == 1 uniform vec3 dbg_wireframeTrianglesColor; #elif DBG_MODE == 3 uniform vec3 dbg_wireframeVerticesColor; #elif DBG_MODE == 4 || DBG_MODE == 5 uniform vec3 dbg_uvPrimaryColor; uniform vec3 dbg_uvSecondaryColor; #elif DBG_MODE == 7 uniform vec3 dbg_materialColor; #endif #endif`,vBe=`#if defined(DBG_ENABLED) varying vec3 dbg_vBarycentric; flat varying vec3 dbg_vVertexWorldPos; flat varying float dbg_vPass; #if !defined(DBG_MULTIPLY) vec3 dbg_applyShading(vec3 color) { vec3 N = vNormalW.xyz; vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); vec3 H = normalize(L + L); float LdotN = clamp(dot(L,N), 0., 1.); float HdotN = clamp(dot(H,N), 0., 1.); float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); color *= (LdotN / PI); color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); return color; } #endif #if DBG_MODE == 1 || DBG_MODE == 3 float dbg_edgeFactor() { vec3 d = fwidth(dbg_vBarycentric); vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); return min(min(a3.x, a3.y), a3.z); } #endif #if DBG_MODE == 2 || DBG_MODE == 3 float dbg_cornerFactor() { vec3 worldPos = vPositionW; float dist = length(worldPos - dbg_vVertexWorldPos); float camDist = length(worldPos - vEyePosition.xyz); float d = sqrt(camDist) * .001; return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); } #endif #if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) float dbg_checkerboardFactor(vec2 uv) { vec2 f = fract(uv * dbg_thicknessRadiusScale.z); f -= .5; return (f.x * f.y) > 0. ? 1. : 0.; } #endif #endif`,xBe=`#if defined(DBG_ENABLED) vec3 dbg_color = vec3(1.); #if DBG_MODE == 1 dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); #elif DBG_MODE == 2 || DBG_MODE == 3 float dbg_cornerFactor = dbg_cornerFactor(); if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); #if DBG_MODE == 3 dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); #endif #elif DBG_MODE == 4 && defined(UV1) dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); #elif DBG_MODE == 5 && defined(UV2) dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); #elif DBG_MODE == 6 && defined(VERTEXCOLOR) dbg_color = vColor.rgb; #elif DBG_MODE == 7 dbg_color = dbg_materialColor; #endif #if defined(DBG_MULTIPLY) gl_FragColor *= vec4(dbg_color, 1.); #else #if DBG_MODE != 6 gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); #else gl_FragColor = vec4(dbg_color, 1.); #endif #endif #endif`,P3e=[new Me(.98,.26,.38),new Me(.47,.75,.3),new Me(0,.26,.77),new Me(.97,.6,.76),new Me(.19,.63,.78),new Me(.98,.8,.6),new Me(.65,.43,.15),new Me(.15,.47,.22),new Me(.67,.71,.86),new Me(.09,.46,.56),new Me(.8,.98,.02),new Me(.39,.29,.13),new Me(.53,.63,.06),new Me(.95,.96,.41),new Me(1,.72,.94),new Me(.63,.08,.31),new Me(.66,.96,.95),new Me(.22,.14,.19),new Me(.14,.65,.59),new Me(.93,1,.68),new Me(.93,.14,.44),new Me(.47,.86,.67),new Me(.85,.07,.78),new Me(.53,.64,.98),new Me(.43,.37,.56),new Me(.71,.65,.25),new Me(.66,.19,.01),new Me(.94,.53,.12),new Me(.41,.44,.44),new Me(.24,.71,.96),new Me(.57,.28,.56),new Me(.44,.98,.42)];var Vy;(function(n){n[n.NONE=0]="NONE",n[n.TRIANGLES=1]="TRIANGLES",n[n.VERTICES=2]="VERTICES",n[n.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",n[n.UV0=4]="UV0",n[n.UV1=5]="UV1",n[n.VERTEXCOLORS=6]="VERTEXCOLORS",n[n.MATERIALIDS=7]="MATERIALIDS"})(Vy||(Vy={}));class yBe extends Kr{constructor(){super(...arguments),this.DBG_MODE=Vy.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class Po extends Wc{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){const i=new yBe;i.DBG_MODE=t.mode??i.DBG_MODE,i.DBG_MULTIPLY=t.multiply??i.DBG_MULTIPLY,super(e,"MeshDebug",200,i,!0,!0),this._mode=i.DBG_MODE,this._multiply=i.DBG_MULTIPLY,this.shadedDiffuseColor=t.shadedDiffuseColor??new Me(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new Me(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new Me(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new Me(.8,.8,.8),this.vertexColor=t.vertexColor??new Me(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new Me(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new Me(.5,.5,.5),this._materialColor=Po.MaterialColors[Po._PluginCount++%Po.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&this._material.getScene().getEngine().webGLVersion==1){de.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){(this._mode==Vy.VERTICES||this._mode==Vy.TRIANGLES||this._mode==Vy.TRIANGLES_VERTICES)&&!i.isVerticesDataPresent("dbg_initialPass")&&de.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:gBe}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return e==="vertex"?{CUSTOM_VERTEX_DEFINITIONS:_Be,CUSTOM_VERTEX_MAIN_END:mBe}:{CUSTOM_FRAGMENT_DEFINITIONS:vBe,CUSTOM_FRAGMENT_MAIN_END:xBe}}static Reset(){this._PluginCount=0,this.MaterialColors=P3e}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(e.getTotalIndices()==0)return i;if(t){const h=e.getVerticesDataKinds(),u=e.getIndices(),d={};for(const f of h)d[f]=e.getVerticesData(f);i=function(){e.setIndices(u);for(const f of h){const p=e.getVertexBuffer(f).getStrideSize();e.setVerticesData(f,d[f],void 0,p)}e.removeVerticesData("dbg_initialPass")}}let r=Array.from(e.getIndices());const s=[];for(let h=0;h #include #include varying vec4 vColor;varying vec2 vPosition;void main () { #include float A=-dot(vPosition,vPosition);if (A<-4.0) discard;float B=exp(A)*vColor.a; #include vec3 color=vColor.rgb; #ifdef FOG #include #endif gl_FragColor=vec4(color,B);} `;Re.ShadersStore[ABe]=CBe;const bBe="gaussianSplattingVertexDeclaration",EBe=`uniform mat4 world;uniform mat4 view;uniform mat4 projection; `;Re.IncludesShadersStore[bBe]=EBe;const TBe="gaussianSplattingUboDeclaration",SBe=`#include #include `;Re.IncludesShadersStore[TBe]=SBe;const MBe="gaussianSplattingVertexShader",RBe=`#include<__decl__gaussianSplattingVertex> #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif #include #include #include attribute vec2 position;attribute float splatIndex;uniform vec2 viewport;uniform vec2 dataTextureSize;uniform vec2 focal;uniform sampler2D covariancesATexture;uniform sampler2D covariancesBTexture;uniform sampler2D centersTexture;uniform sampler2D colorsTexture;varying vec4 vColor;varying vec2 vPosition; #if !defined(WEBGL2) && !defined(WEBGPU) && !defined(NATIVE) mat3 transpose(mat3 matrix) {return mat3(matrix[0][0],matrix[1][0],matrix[2][0], matrix[0][1],matrix[1][1],matrix[2][1], matrix[0][2],matrix[1][2],matrix[2][2]);} #endif vec2 getDataUV(float index,vec2 textureSize) {float y=floor(index/textureSize.x);float x=index-y*textureSize.x;return vec2((x+0.5)/textureSize.x,(y+0.5)/textureSize.y);} void main () {vec2 splatUV=getDataUV(splatIndex,dataTextureSize);vec3 center=texture2D(centersTexture,splatUV).xyz;vec4 color=texture2D(colorsTexture,splatUV);vec3 covA=texture2D(covariancesATexture,splatUV).xyz;vec3 covB=texture2D(covariancesBTexture,splatUV).xyz;vec4 worldPos=world*vec4(center,1.0);mat4 modelView=view*world;vec4 camspace=view*worldPos;vec4 pos2d=projection*camspace;float bounds=1.2*pos2d.w;if (pos2d.z<-pos2d.w || pos2d.x<-bounds || pos2d.x>bounds || pos2d.y<-bounds || pos2d.y>bounds) {gl_Position=vec4(0.0,0.0,2.0,1.0);return;} mat3 Vrk=mat3( covA.x,covA.y,covA.z, covA.y,covB.x,covB.y, covA.z,covB.y,covB.z );mat3 J=mat3( focal.x/camspace.z,0.,-(focal.x*camspace.x)/(camspace.z*camspace.z), 0.,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z), 0.,0.,0. );mat3 invy=mat3(1,0,0,0,-1,0,0,0,1);mat3 T=invy*transpose(mat3(modelView))*J;mat3 cov2d=transpose(T)*Vrk*T;float mid=(cov2d[0][0]+cov2d[1][1])/2.0;float radius=length(vec2((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));float lambda1=mid+radius,lambda2=mid-radius;if (lambda2<0.0) return;vec2 diagonalVector=normalize(vec2(cov2d[0][1],lambda1-cov2d[0][0]));vec2 majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;vec2 minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);vColor=color;vPosition=position;vec2 vCenter=vec2(pos2d);gl_Position=vec4( vCenter + (position.x*majorAxis*1./viewport + position.y*minorAxis*1./viewport)*pos2d.w,pos2d.zw); #include #include #include } `;Re.ShadersStore[MBe]=RBe;class IBe extends Kr{constructor(){super(),this.FOG=!1,this.THIN_INSTANCES=!0,this.LOGARITHMICDEPTH=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.rebuild()}}class e5 extends Rn{constructor(e,t){super(e,t),this.backFaceCulling=!1}get hasRenderTargetTextures(){return!1}needAlphaTesting(){return!1}needAlphaBlending(){return!0}isReadyForSubMesh(e,t){const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===!0)return!0;t.materialDefines||(t.materialDefines=new IBe);const s=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(Ql(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,a),$l(s,o,this,a,!0,null,!0),qn(e,a,!1,!1),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();const c=[Z.PositionKind,"splatIndex"];pa(c,a);const l=["world","view","projection","vFogInfos","vFogColor","logarithmicDepthConstant","viewport","dataTextureSize","focal"],h=["covariancesATexture","covariancesBTexture","centersTexture","colorsTexture"],u=["Scene","Mesh"];Ma({uniformsNames:l,uniformBuffersNames:u,samplers:h,defines:a}),Sa(l);const d=a.toString(),f=s.getEngine().createEffect("gaussianSplatting",{attributes:c,uniformsNames:l,uniformBuffersNames:u,samplers:h,defines:d,onCompiled:this.onCompiled,onError:this.onError},o);t.setEffect(f,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=s.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!0,!0)}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const a=i.effect;if(!a)return;if(this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._mustRebind(r,a,i,t.visibility)){this.bindView(a),this.bindViewProjection(a);const c=r.getEngine(),l=this.getScene().activeCamera,h=c.getRenderWidth(),u=c.getRenderHeight();this._activeEffect.setFloat2("viewport",h,u);let d=1e3;l&&(l.fovMode==Rt.FOVMODE_VERTICAL_FIXED?d=u/2/Math.tan(l.fov/2):d=h/2/Math.tan(l.fov/2)),this._activeEffect.setFloat2("focal",d,d);const f=t;if(f.covariancesATexture){const p=f.covariancesATexture.getSize();a.setFloat2("dataTextureSize",p.width,p.height),a.setTexture("covariancesATexture",f.covariancesATexture),a.setTexture("covariancesBTexture",f.covariancesBTexture),a.setTexture("centersTexture",f.centersTexture),a.setTexture("colorsTexture",f.colorsTexture)}fa(a,this,r)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);Oo(r,t,a),this.useLogarithmicDepth&&Ha(s,a,r),this._afterBind(t,this._activeEffect,i)}clone(e){return Qe.Clone(()=>new e5(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return Qe.Parse(()=>new e5(e.name,t),e,t,i)}}xe("BABYLON.GaussianSplattingMaterial",e5);Object.defineProperty(tt.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new z5(this)}return this._decalMap},enumerable:!0,configurable:!0});Object.defineProperty(xr.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new z5(this)}return this._decalMap},enumerable:!0,configurable:!0});Object.defineProperty(di.prototype,"decalMap",{get:function(){return this._decalMap},set:function(n){this._decalMap=n},enumerable:!0,configurable:!0});class _f{constructor(e,t){this.radius=e,this.theta=t,this.radius=e,this.theta=t}getClassName(){return"Polar"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t}add(e){const t=new _f(0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t){return this.radius+=e,this.theta+=t,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t}subtract(e){const t=new _f(0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i){return i.radius=this.radius-e,i.theta=this.theta-t,i}subtractFromFloats(e,t){const i=new _f(0,0);return this.subtractFromFloatsToRef(e,t,i),i}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t}multiply(e){const t=new _f(0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t}divide(e){const t=new _f(0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new _f(this.radius,this.theta)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this}copyFromFloats(e,t){return this.radius=e,this.theta=t,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t}scale(e){const t=new _f(0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t){return this.radius=e,this.theta=t,this}setAll(e){return this.set(e,e),this}toVector2ToRef(e){const t=this.radius*Math.cos(this.theta),i=this.radius*Math.sin(this.theta);return e.set(t,i),e}toVector2(){const e=new Be(0,0);return this.toVector2ToRef(e)}static FromVector2ToRef(e,t){const i=Math.sign(e.y)*Math.acos(e.x/e.length());return t.radius=e.length(),t.theta=i,t}static FromVector2(e){const t=new _f(0,0);return _f.FromVector2ToRef(e,t),t}static FromArray(e){return new _f(e[0],e[1])}}class mf{constructor(e,t,i){this.radius=e,this.theta=t,this.phi=i,this.radius=e,this.theta=t,this.phi=i}getClassName(){return"Spherical"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta,this.phi]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t.phi=this.phi+e.phi,t}add(e){const t=new mf(0,0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t,i){return this.radius+=e,this.theta+=t,this.phi+=i,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t.phi=this.phi-e.phi,t}subtract(e){const t=new mf(0,0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i,r){return r.radius=this.radius-e,r.theta=this.theta-t,r.phi=this.phi-i,r}subtractFromFloats(e,t,i){const r=new mf(0,0,0);return this.subtractFromFloatsToRef(e,t,i,r),r}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t.phi=this.phi*e.phi,t}multiply(e){const t=new mf(0,0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t.phi=this.phi/e.phi,t}divide(e){const t=new mf(0,0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new mf(this.radius,this.theta,this.phi)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this.phi=e.phi,this}copyFromFloats(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t.phi=this.phi*e,t}scale(e){const t=new mf(0,0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}setAll(e){return this.set(e,e,e),this}toVector3ToRef(e){const t=this.radius*Math.sin(this.theta)*Math.cos(this.phi),i=this.radius*Math.cos(this.theta),r=this.radius*Math.sin(this.theta)*Math.sin(this.phi);return e.set(t,i,r),e}toVector3(){const e=new P(0,0,0);return this.toVector3ToRef(e)}static FromVector3ToRef(e,t){return t.radius=e.length(),t.theta=Math.acos(e.y/t.radius),t.phi=Math.atan2(e.z,e.x),t}static FromVector3(e){const t=new mf(0,0,0);return mf.FromVector3ToRef(e,t),t}static FromArray(e){return new mf(e[0],e[1],e[2])}}class w3e{constructor(e,t=2,i=3,r=1,s=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=r,this._height=s,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=this._numSamples*2&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,r=0;for(;e>0;)i/=t,r+=i*(e%t),e=~~(e/t);return r}}function D3e(n,e){return`{X: ${n.x.toFixed(e)} Y: ${n.y.toFixed(e)}}`}function O3e(n,e){return`{X: ${n._x.toFixed(e)} Y: ${n._y.toFixed(e)} Z: ${n._z.toFixed(e)}}`}function L3e(n,e){return`{X: ${n.x.toFixed(e)} Y: ${n.y.toFixed(e)} Z: ${n.z.toFixed(e)} W: ${n.w.toFixed(e)}}`}function iZ(n,e,t,i,r){let s=null,a=null,o=null;try{s=new n.Decoder,a=new n.DecoderBuffer,a.Init(e,e.byteLength);let c;const l=s.GetEncodedGeometryType(a);switch(l){case n.TRIANGULAR_MESH:{const d=new n.Mesh;if(c=s.DecodeBufferToMesh(a,d),!c.ok()||d.ptr===0)throw new Error(c.error_msg());const p=d.num_faces()*3,_=p*4,m=n._malloc(_);try{s.GetTrianglesUInt32Array(d,_,m);const g=new Uint32Array(p);g.set(new Uint32Array(n.HEAPF32.buffer,m,p)),i(g)}finally{n._free(m)}o=d;break}case n.POINT_CLOUD:{const d=new n.PointCloud;if(c=s.DecodeBufferToPointCloud(a,d),!c.ok()||!d.ptr)throw new Error(c.error_msg());o=d;break}default:throw new Error(`Invalid geometry type ${l}`)}const h=o.num_points(),u=(d,f,p,_)=>{const m=_.data_type(),g=_.num_components(),v=_.normalized(),x=_.byte_stride(),y=_.byte_offset(),b={[n.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:n.HEAPF32},[n.DT_INT8]:{typedArrayConstructor:Int8Array,heap:n.HEAP8},[n.DT_INT16]:{typedArrayConstructor:Int16Array,heap:n.HEAP16},[n.DT_INT32]:{typedArrayConstructor:Int32Array,heap:n.HEAP32},[n.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:n.HEAPU8},[n.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:n.HEAPU16},[n.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:n.HEAPU32}}[m];if(!b)throw new Error(`Invalid data type ${m}`);const T=h*g,S=T*b.typedArrayConstructor.BYTES_PER_ELEMENT,N=n._malloc(S);try{d.GetAttributeDataArrayForAllPoints(f,_,m,S,N);const D=new b.typedArrayConstructor(b.heap.buffer,N,T);r(p,D.slice(),g,y,x,v)}finally{n._free(N)}};if(t)for(const d in t){const f=t[d],p=s.GetAttributeByUniqueId(o,f);u(s,o,d,p)}else{const d={position:n.POSITION,normal:n.NORMAL,color:n.COLOR,uv:n.TEX_COORD};for(const f in d){const p=s.GetAttributeId(o,d[f]);if(p!==-1){const _=s.GetAttribute(o,p);u(s,o,f,_)}}}return h}finally{o&&n.destroy(o),a&&n.destroy(a),s&&n.destroy(s)}}function PBe(){let n;onmessage=e=>{const t=e.data;switch(t.id){case"init":{const i=t.decoder;i.url&&importScripts(i.url),n=DracoDecoderModule({wasmBinary:i.wasmBinary}),postMessage({id:"initDone"});break}case"decodeMesh":{if(!n)throw new Error("Draco decoder module is not available");n.then(i=>{const r=iZ(i,t.dataView,t.attributes,s=>{postMessage({id:"indices",data:s},[s.buffer])},(s,a,o,c,l,h)=>{postMessage({id:"attribute",kind:s,data:a,size:o,byteOffset:c,byteStride:l,normalized:h},[a.buffer])});postMessage({id:"decodeMeshDone",totalVertices:r})});break}}}}function wBe(n,e,t){return new Promise((i,r)=>{const s=c=>{n.removeEventListener("error",s),n.removeEventListener("message",a),r(c)},a=c=>{c.data.id==="initDone"&&(n.removeEventListener("error",s),n.removeEventListener("message",a),i(n))};n.addEventListener("error",s),n.addEventListener("message",a);const o=e.slice(0);n.postMessage({id:"init",decoder:{url:t,wasmBinary:o}},[o])})}function DBe(n,e){return new Promise(t=>{(e||DracoDecoderModule)({wasmBinary:n}).then(i=>{t({module:i})})})}class cc{static get DecoderAvailable(){const e=cc.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&typeof WebAssembly=="object"||e.fallbackUrl)}static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static get Default(){return cc._Default||(cc._Default=new cc),cc._Default}constructor(e=cc.DefaultNumWorkers){const t=cc.Configuration.decoder;if(t.workerPool||typeof e=="object"&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||typeof e=="object"&&e.wasmBinary,r=typeof e=="number"?e:e.numWorkers,s=r&&typeof Worker=="function"&&typeof URL=="function",a=s||!s&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&typeof WebAssembly=="object"?{url:a?Ee.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Ee.LoadFileAsync(Ee.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:a?Ee.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};s?this._workerPoolPromise=o.wasmBinaryPromise.then(c=>{const l=`${iZ}(${PBe})()`,h=URL.createObjectURL(new Blob([l],{type:"application/javascript"}));return new k5(r,()=>{const u=new Worker(h);return wBe(u,c,o.url)})}):this._decoderModulePromise=o.wasmBinaryPromise.then(async c=>{if(typeof DracoDecoderModule>"u"&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await Ee.LoadBabylonScriptAsync(o.url)}return await DBe(c,t.jsModule)})}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then(e=>{e.dispose()}),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){if(this._workerPoolPromise){await this._workerPoolPromise;return}if(this._decoderModulePromise){await this._decoderModulePromise;return}}_decodeMeshAsync(e,t,i){const r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),s=(a,o)=>i&&i[a]!==void 0?(o!==i[a]&&de.Warn(`Normalized flag from Draco data (${o}) does not match normalized flag from glTF accessor (${i[a]}). Using flag from glTF accessor.`),i[a]):o;if(this._workerPoolPromise)return this._workerPoolPromise.then(a=>new Promise((o,c)=>{a.push((l,h)=>{let u=null;const d=[],f=m=>{l.removeEventListener("error",f),l.removeEventListener("message",p),c(m),h()},p=m=>{const g=m.data;switch(g.id){case"decodeMeshDone":{l.removeEventListener("error",f),l.removeEventListener("message",p),o({indices:u,attributes:d,totalVertices:g.totalVertices}),h();break}case"indices":{u=g.data;break}case"attribute":{d.push({kind:g.kind,data:g.data,size:g.size,byteOffset:g.byteOffset,byteStride:g.byteStride,normalized:s(g.kind,g.normalized)});break}}};l.addEventListener("error",f),l.addEventListener("message",p);const _=r.slice();l.postMessage({id:"decodeMesh",dataView:_,attributes:t},[_.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(a=>{let o=null;const c=[],l=iZ(a.module,r,t,h=>{o=h},(h,u,d,f,p,_)=>{c.push({kind:h,data:u,size:d,byteOffset:f,byteStride:p,normalized:_})});return{indices:o,attributes:c,totalVertices:l}});throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,r){const s=await this._decodeMeshAsync(i,r),a=new Ua(e,t);s.indices&&a.setIndices(s.indices);for(const o of s.attributes)a.setVerticesBuffer(new Z(t.getEngine(),o.data,o.kind,!1,void 0,o.byteStride,void 0,o.byteOffset,o.size,void 0,o.normalized,!0),s.totalVertices);return a}async _decodeMeshToGeometryForGltfAsync(e,t,i,r,s){const a=await this._decodeMeshAsync(i,r,s),o=new Ua(e,t);a.indices&&o.setIndices(a.indices);for(const c of a.attributes)o.setVerticesBuffer(new Z(t.getEngine(),c.data,c.kind,!1,void 0,c.byteStride,void 0,c.byteOffset,c.size,void 0,c.normalized,!0),a.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this._decodeMeshAsync(e,t),r=new et;i.indices&&(r.indices=i.indices);for(const s of i.attributes){const a=Z.GetFloatData(s.data,s.size,Z.GetDataType(s.data),s.byteOffset,s.byteStride,s.normalized,i.totalVertices);r.set(a,s.kind)}return r}}cc.Configuration={decoder:{wasmUrl:`${Ee._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Ee._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Ee._DefaultCdnUrl}/draco_decoder_gltf.js`}};cc.DefaultNumWorkers=cc.GetDefaultNumWorkers();cc._Default=null;class w0{static get Default(){return w0._Default||(w0._Default=new w0),w0._Default}constructor(){const e=w0.Configuration.decoder;this._decoderModulePromise=Ee.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,s){return this._decoderModulePromise.then(()=>{const a=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(a,t,i,e,r,s),a})}}w0.Configuration={decoder:{url:`${Ee._DefaultCdnUrl}/meshopt_decoder.js`}};w0._Default=null;let CV=0;class eO{constructor(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}clone(){var e,t;return new eO(this.pos.clone(),this.normal.clone(),(e=this.uv)==null?void 0:e.clone(),(t=this.vertColor)==null?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new eO(P.Lerp(this.pos,e.pos,t),P.Lerp(this.normal,e.normal,t),this.uv&&e.uv?Be.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?Ze.Lerp(this.vertColor,e.vertColor,t):void 0)}}class Ty{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const r=i.subtract(e),s=t.subtract(e);if(r.lengthSquared()===0||s.lengthSquared()===0)return null;const a=P.Normalize(P.Cross(r,s));return new Ty(a,P.Dot(a,e))}clone(){return new Ty(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,s){let h=0;const u=[];let d,f;for(d=0;dTy.EPSILON?1:0;h|=p,u.push(p)}switch(h){case 0:(P.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:s.push(e);break;case 3:{const p=[],_=[];for(d=0;d=3&&(m=new t5(p,e.shared),m.plane&&r.push(m)),_.length>=3&&(m=new t5(_,e.shared),m.plane&&s.push(m));break}}}}Ty.EPSILON=1e-5;class t5{constructor(e,t){this.vertices=e,this.shared=t,this.plane=Ty.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map(t=>t.clone());return new t5(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}let df=class QV{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new QV;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map(t=>t.clone()),e}invert(){for(let t=0;tt.clone()),e.copyTransformAttributes(this),e}union(e){const t=new df(this.clone()._polygons),i=new df(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),Vp._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new df(this._polygons),i=new df(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){const t=new df(this.clone()._polygons),i=new df(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),Vp._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new df(this._polygons),i=new df(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){const t=new df(this.clone()._polygons),i=new df(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),Vp._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new df(this._polygons),i=new df(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map(e=>{e.flip()})}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const r=this._polygons,s=[],a=[],o=[];let c=null,l=null;const h=P.Zero(),u=P.Zero(),d=Be.Zero(),f=new Ze(0,0,0,0),p=[0,0,0],_={};let m;for(let v=0,x=r.length;vh.shared.meshId===u.shared.meshId?h.shared.subMeshId-u.shared.subMeshId:h.shared.meshId-u.shared.meshId),this.toVertexData(h=>{o[h.shared.meshId]||(o[h.shared.meshId]={}),o[h.shared.meshId][h.shared.subMeshId]||(o[h.shared.meshId][h.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:h.shared.materialIndex}),c=o[h.shared.meshId][h.shared.subMeshId]},()=>{c.indexStart=Math.min(a,c.indexStart),c.indexEnd=Math.max(a,c.indexEnd),a++}).applyToMesh(r),i){let h=0,u;r.subMeshes=[];for(const d in o){u=-1;for(const f in o[d])c=o[d][f],Xo.CreateFromIndices(c.materialIndex+h,c.indexStart,c.indexEnd-c.indexStart+1,r),u=Math.max(c.materialIndex,u);h+=++u}}return r}toMesh(e,t=null,i,r){const s=this.buildMeshGeometry(e,i,r);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}}const OBe="meshUVSpaceRendererVertexShader",LBe=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; #include #include #include #include[0..maxSimultaneousMorphTargets] #include void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; #if defined(INSTANCES) && defined(THIN_INSTANCES) vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); #else #ifdef NONUNIFORMSCALING normWorldSM=transposeMat3(inverseMat3(normWorldSM)); #endif vNormalW=normalize(normWorldSM*normalUpdated); #endif vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}`;Re.ShadersStore[OBe]=LBe;const NBe="meshUVSpaceRendererPixelShader",BBe=`precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} gl_FragColor=texture2D(textureSampler,vDecalTC);} `;Re.ShadersStore[NBe]=BBe;const FBe="meshUVSpaceRendererMaskerVertexShader",UBe="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";Re.ShadersStore[FBe]=UBe;const kBe="meshUVSpaceRendererMaskerPixelShader",VBe=`varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);} `;Re.ShadersStore[kBe]=VBe;const zBe="meshUVSpaceRendererFinaliserPixelShader",HBe=`precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;} if (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;} if (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;} if (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;} if (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}} `;Re.ShadersStore[zBe]=HBe;const GBe="meshUVSpaceRendererFinaliserVertexShader",KBe=`precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;} `;Re.ShadersStore[GBe]=KBe;class v0{static _GetShader(e){if(!e._meshUVSpaceRendererShader){const t=new kn("meshUVSpaceRendererShader",e,{vertex:"meshUVSpaceRenderer",fragment:"meshUVSpaceRenderer"},{attributes:["position","normal","uv"],uniforms:["world","projMatrix"],samplers:["textureSampler"],needAlphaBlending:!0});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add(()=>{var i;(i=e._meshUVSpaceRendererShader)==null||i.dispose(),e._meshUVSpaceRendererShader=null}),e._meshUVSpaceRendererShader=t}return e._meshUVSpaceRendererShader}static _GetMaskShader(e){if(!e._meshUVSpaceRendererMaskShader){const t=new kn("meshUVSpaceRendererMaskShader",e,{vertex:"meshUVSpaceRendererMasker",fragment:"meshUVSpaceRendererMasker"},{attributes:["position","uv"],uniforms:["worldViewProjection"]});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add(()=>{var i;(i=e._meshUVSpaceRendererMaskShader)==null||i.dispose(),e._meshUVSpaceRendererMaskShader=null}),e._meshUVSpaceRendererMaskShader=t}return e._meshUVSpaceRendererMaskShader}static _IsRenderTargetTexture(e){return e.renderList!==void 0}constructor(e,t,i){this._textureCreatedInternally=!1,this._configureUserCreatedTexture=!0,this._maskTexture=null,this._finalPostProcess=null,this.clearColor=new Ze(0,0,0,0),this._mesh=e,this._scene=t,this._options={width:1024,height:1024,textureType:0,generateMipMaps:!0,optimizeUVAllocation:!0,uvEdgeBlending:!1,...i}}isReady(){var r,s;this.texture||this._createDiffuseRTT();const e=v0._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady(),t=((r=this._maskTexture)==null?void 0:r.isReadyForRendering())??!0,i=((s=this._finalPostProcess)==null?void 0:s.isReady())??!0;return e&&t&&i}renderTexture(e,t,i,r,s=0){if(this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT(),v0._IsRenderTargetTexture(this.texture)){const a=this._createProjectionMatrix(t,i,r,s),o=v0._GetShader(this._scene);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",a),this.texture.render()}}clear(){var e,t,i;if(v0._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const r=this._scene.getEngine();r.bindFramebuffer(this.texture.renderTarget),r.clear(this.clearColor,!0,!0,!0),r.unBindFramebuffer(this.texture.renderTarget)}if((e=this._finalPostProcess)!=null&&e.inputTexture){const r=this._scene.getEngine();r.bindFramebuffer((t=this._finalPostProcess)==null?void 0:t.inputTexture),r.clear(this.clearColor,!0,!0,!0),r.unBindFramebuffer((i=this._finalPostProcess)==null?void 0:i.inputTexture)}}dispose(){var e,t;this._textureCreatedInternally&&(this.texture.dispose(),this._textureCreatedInternally=!1),this._configureUserCreatedTexture=!0,(e=this._maskTexture)==null||e.dispose(),this._maskTexture=null,(t=this._finalPostProcess)==null||t.dispose(),this._finalPostProcess=null}_configureUserCreatedRTT(){this._configureUserCreatedTexture=!1,v0._IsRenderTargetTexture(this.texture)&&(this.texture.setMaterialForRendering(this._mesh,v0._GetShader(this._scene)),this.texture.onClearObservable.add(()=>{}),this.texture.renderList=[this._mesh],this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),this.texture.addPostProcess(this._finalPostProcess)))}_createDiffuseRTT(){this._textureCreatedInternally=!0;const e=this._createRenderTargetTexture(this._options.width,this._options.height);e.setMaterialForRendering(this._mesh,v0._GetShader(this._scene)),this.texture=e,this._configureUserCreatedTexture=!1,this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),e.addPostProcess(this._finalPostProcess))}_createMaskTexture(){this._maskTexture||(this._maskTexture=new es(this._mesh.name+"_maskTexture",{width:this._options.width,height:this._options.height},this._scene,!1,!0,0,!1,2,void 0,void 0,void 0,6),this._maskTexture.clearColor=new Ze(0,0,0,0),this._maskTexture.renderList.push(this._mesh),this._maskTexture.setMaterialForRendering(this._mesh,v0._GetMaskShader(this._scene)),this._maskTexture.refreshRate=es.REFRESHRATE_RENDER_ONCE,this._scene.customRenderTargets.push(this._maskTexture))}_createPostProcess(){this._finalPostProcess||(this._finalPostProcess=new Pt(this._mesh.name+"_fixSeamsPostProcess","meshUVSpaceRendererFinaliser",["textureSize"],["textureSampler","maskTextureSampler"],1,null,1,this._scene.getEngine(),!1,null,this._options.textureType),this._finalPostProcess.onApplyObservable.add(e=>{e.setTexture("maskTextureSampler",this._maskTexture),e.setFloat2("textureSize",this._options.width,this._options.height)}))}_createRenderTargetTexture(e,t){const i=new es(this._mesh.name+"_uvspaceTexture",{width:e,height:t},this._scene,this._options.generateMipMaps,!0,this._options.textureType,!1,this._options.generateMipMaps?3:2,!1,!1,!1,5);return i.renderParticles=!1,i.optimizeUVAllocation=!!this._options.optimizeUVAllocation,i.onClearObservable.addOnce(()=>{this._scene.getEngine().clear(this.clearColor,!0,!0,!0),i.onClearObservable.add(()=>{})}),i.renderList=[this._mesh],i}_createProjectionMatrix(e,t,i,r=0){const s=-Math.atan2(t.z,t.x)-Math.PI/2,a=Math.sqrt(t.x*t.x+t.z*t.z),o=Math.atan2(t.y,a),c=e.add(t.scale(i.z*.5)),l=ce.RotationYawPitchRoll(s,o,r).multiply(ce.Translation(c.x,c.y,c.z)),h=ce.Invert(l),u=ce.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),d=ce.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return h.multiply(u).multiply(d)}}Se._TrailMeshParser=(n,e)=>tO.Parse(n,e);class tO extends Se{constructor(e,t,i,r=1,s=60,a=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=a,this._generator=t,this.diameter=r,this._length=s,this._sectionVectors=[],this._sectionNormalVectors=[];for(let o=0;o<=this._sectionPolygonPointsCount;o++)this._sectionVectors[o]=P.Zero(),this._sectionNormalVectors[o]=P.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new et,t=[],i=[],r=[],s=[];let a=P.Zero();this._generator instanceof di&&this._generator.hasBoundingInfo?a=this._generator.getBoundingInfo().boundingBox.centerWorld:a=this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let c=0;c<=this._sectionPolygonPointsCount;c++){const l=c!==this._sectionPolygonPointsCount?c*o:0;t.push(a.x+Math.cos(l)*this.diameter,a.y+Math.sin(l)*this.diameter,a.z),s.push(c/this._sectionPolygonPointsCount,0)}for(let c=1;c<=this._length;c++){for(let h=0;h<=this._sectionPolygonPointsCount;h++){const u=h!==this._sectionPolygonPointsCount?h*o:0;t.push(a.x+Math.cos(u)*this.diameter,a.y+Math.sin(u)*this.diameter,a.z),s.push(h/this._sectionPolygonPointsCount,c/this._length)}const l=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let h=0;h<=this._sectionPolygonPointsCount;h++)r.push(l+h,l+h+this._sectionPolygonPointsCount,l+h+this._sectionPolygonPointsCount+1),r.push(l+h,l+h+this._sectionPolygonPointsCount+1,l+h+1)}et.ComputeNormals(t,r,i),e.positions=t,e.normals=i,e.indices=r,e.uvs=s,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add(()=>{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(Z.PositionKind),t=this.getVerticesData(Z.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let a=3*(this._sectionPolygonPointsCount+1);a{this._getSimplifier(e).simplify(t,r=>{t.distance!==void 0&&e.mesh.addLODLevel(t.distance,r),r.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()})});else{const t=this._getSimplifier(e),i=(r,s)=>{t.simplify(r,a=>{r.distance!==void 0&&e.mesh.addLODLevel(r.distance,a),a.isVisible=!0,s()})};md.Run(e.settings.length,r=>{i(e.settings[r.index],()=>{r.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){switch(e.simplificationType){case iO.QUADRATIC:default:return new B3e(e.mesh)}}}var iO;(function(n){n[n.QUADRATIC=0]="QUADRATIC"})(iO||(iO={}));class jBe{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class XBe{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new o8,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class o8{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,s,a,o,c,l){return this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[r]*this.data[c]+this.data[t]*this.data[a]*this.data[o]-this.data[i]*this.data[s]*this.data[o]-this.data[e]*this.data[a]*this.data[c]-this.data[t]*this.data[r]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new o8;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new o8(o8.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}}class YBe{constructor(e,t){this.vertexId=e,this.triangleId=t}}class B3e{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=ni}simplify(e,t){this._initDecimatedMesh(),md.Run(this._mesh.subMeshes.length,i=>{this._initWithMesh(i.index,()=>{this._runDecimation(e,i.index,()=>{i.executeNext()})},e.optimizeMesh)},()=>{setTimeout(()=>{t(this._reconstructedMesh)},0)})}_runDecimation(e,t,i){const r=~~(this._triangles.length*e.quality);let s=0;const a=this._triangles.length,o=(c,l)=>{setTimeout(()=>{c%5===0&&this._updateMesh(c===0);for(let d=0;d{const f=~~((this._triangles.length/2+d)%this._triangles.length),p=this._triangles[f];if(p&&!(p.error[3]>h||p.deleted||p.isDirty)){for(let _=0;_<3;++_)if(p.error[_]{b.indexOf(N)===-1&&(N.deletePending=!0,b.push(N))}),b.length%2!==0)continue;v.q=x.q.add(v.q),v.updatePosition(y);const T=this._references.length;s=this._updateTriangles(v,v,m,s),s=this._updateTriangles(v,x,g,s);const S=this._references.length-T;if(S<=v.triangleCount){if(S)for(let N=0;Na-s<=r)},0)};md.Run(this.decimationIterations,c=>{a-s<=r?c.breakLoop():o(c.index,()=>{c.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const r=this._mesh.getVerticesData(Z.PositionKind),s=this._mesh.getIndices(),a=this._mesh.subMeshes[e],o=u=>{if(i){for(let d=0;d{if(!r)return;const d=u+a.verticesStart,f=P.FromArray(r,d*3),p=o(f)||new XBe(f,this._vertices.length);p.originalOffsets.push(d),p.id===this._vertices.length&&this._vertices.push(p),c.push(p.id)},h=a.verticesCount;md.SyncAsyncForLoop(h,this.syncIterations/4>>0,l,()=>{const u=d=>{if(!s)return;const p=(a.indexStart/3+d)*3,_=s[p+0],m=s[p+1],g=s[p+2],v=this._vertices[c[_-a.verticesStart]],x=this._vertices[c[m-a.verticesStart]],y=this._vertices[c[g-a.verticesStart]],C=new jBe([v,x,y]);C.originalOffset=p,this._triangles.push(C)};md.SyncAsyncForLoop(a.indexCount/3,this.syncIterations,u,()=>{this._init(t)})})}_init(e){const t=i=>{const r=this._triangles[i];r.normal=P.Cross(r._vertices[1].position.subtract(r._vertices[0].position),r._vertices[2].position.subtract(r._vertices[0].position)).normalize();for(let s=0;s<3;s++)r._vertices[s].q.addArrayInPlace(o8.DataFromNumbers(r.normal.x,r.normal.y,r.normal.z,-P.Dot(r.normal,r._vertices[0].position)))};md.SyncAsyncForLoop(this._triangles.length,this.syncIterations,t,()=>{const i=r=>{const s=this._triangles[r];for(let a=0;a<3;++a)s.error[a]=this._calculateError(s._vertices[a],s._vertices[(a+1)%3]);s.error[3]=Math.min(s.error[0],s.error[1],s.error[2])};md.SyncAsyncForLoop(this._triangles.length,this.syncIterations,i,()=>{e()})})}_reconstructMesh(e){const t=[];let i;for(i=0;i{a.push(y.position.x),a.push(y.position.y),a.push(y.position.z),h&&h.length&&(o.push(h[C*3]),o.push(h[C*3+1]),o.push(h[C*3+2])),u&&u.length&&(c.push(u[C*2]),c.push(u[C*2+1])),d&&d.length&&(l.push(d[C*4]),l.push(d[C*4+1]),l.push(d[C*4+2]),l.push(d[C*4+3])),++f})}const p=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),m=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const g=this._reconstructedMesh.getIndices(),v=this._mesh.getIndices();for(i=0;i{const C=v[r.originalOffset+y];let b=r._vertices[y].originalOffsets.indexOf(C);b<0&&(b=0),g.push(r._vertices[y].id+b+_)});this._reconstructedMesh.setIndices(g),this._reconstructedMesh.setVerticesData(Z.PositionKind,a),o.length>0&&this._reconstructedMesh.setVerticesData(Z.NormalKind,o),c.length>0&&this._reconstructedMesh.setVerticesData(Z.UVKind,c),l.length>0&&this._reconstructedMesh.setVerticesData(Z.ColorKind,l);const x=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],m.forEach(y=>{Xo.AddToMesh(y.materialIndex,y.verticesStart,y.verticesCount,y.indexStart,y.indexCount,y.getMesh())}),Xo.AddToMesh(x.materialIndex,_,f,p,t.length*3,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new Se(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,r,s){for(let a=0;a.999)return!0;const f=P.Cross(u,d).normalize();if(r[a]=!1,P.Dot(f,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,r){let s=r;for(let a=0;aWn.Parse(n,e);class Wn extends $ee{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(jr.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach(t=>{for(let i=0;i{const r=[],s=[],a=[],o=jr.GetLineLength(i);for(let d=0,f=0;f0&&(o=Wn._CopyV3(c,e),i.push(o[0],o[1],o[2]),i.push(o[0],o[1],o[2]));return Wn._CompareV3(a-1,0,e)?o=Wn._CopyV3(1,e):o=Wn._CopyV3(a-1,e),i.push(o[0],o[1],o[2]),i.push(o[0],o[1],o[2]),{previous:t,next:i,uvs:s,side:r}}_createVertexBuffers(){const e=super._createVertexBuffers(),t=this._scene.getEngine(),i=new no(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));const r=new no(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(r.createVertexBuffer("grl_nextAndCounters",0,4));const s=new no(t,this._widths,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s;const a=new no(t,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(a.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=a,e}}Wn._V_START=new P;Wn._V_END=new P;Wn._V_OFFSET_START=new P;Wn._V_OFFSET_END=new P;Se._GreasedLineRibbonMeshParser=(n,e)=>oa.Parse(n,e);class oa extends $ee{constructor(e,t,i,r){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=r??[],i.points&&this.addPoints(jr.ConvertPoints(i.points),i,!!r)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{const p=oa._ConvertToRibbonPath(d,l.ribbonOptions,this._scene.useRightHandedSystem,r&&r[f]);i=this._preprocess(p,i,l)})}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){var h,u;const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const r=[],s=[],a=e[0];for(let d=0;d2)for(let d=0;d0&&(o[0]+=1,o[1]+=1),s.push(o[1]+(f%2!==0?i:0),o[0],o[2]),c&&s.push(o[0],o[1]+(f%2!==0?i:0),o[2])}else for(let d=0;dp.y&&p.x>p.z?i?oa._RightHandedForwardReadOnlyQuaternion:oa._LeftHandedForwardReadOnlyQuaternion:oa._LeftReadOnlyQuaternion),l=p.normalize()}h=l.multiplyByFloats(o,o,o),s.push(d.add(h)),a.push(d.subtract(h))}r||(s.push(c[c.length-1].add(h)),a.push(c[c.length-1].subtract(h)))}return[s,a]}static _GetDirectionFromPoints(e,t,i){return e.x===t.x&&(!i||(i==null?void 0:i.x)===1)?oa.DIRECTION_YZ:e.y===t.y?oa.DIRECTION_XZ:e.z===t.z?oa.DIRECTION_XY:oa.DIRECTION_XZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),r={},s=[];ol.DeepCopy(this._pathsOptions,s,void 0,void 0,!0),ol.DeepCopy(i,r,["instance"],void 0,!0);const a=new oa(e,this._scene,r,s);return t&&(a.parent=t),a.material=this.material,a}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){const i=e.lineOptions,r=e.name,s=e.pathOptions;return new oa(r,t,i,s)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let a=0;a{a+=u.length/3});const o=k3e(a,e.widths??[],e.widthDistribution),c=t!=null&&t.colors?V3e(a,t.colors,t.colorDistribution,t.color??Wo.DEFAULT_COLOR):void 0,l={points:s,updatable:e.updatable,widths:o,lazy:e.lazy,ribbonOptions:e.ribbonOptions,uvs:e.uvs,colorPointers:e.colorPointers};if(l.ribbonOptions&&l.ribbonOptions.pointsMode===bf.POINTS_MODE_POINTS&&(l.ribbonOptions.width=t.width??l.ribbonOptions.width??Wo.DEFAULT_WIDTH),e.instance)if(r=e.instance,r instanceof oa)r.addPoints(s,l);else{const u=r.widths;if(u){const d=u.slice();for(const f of o)d.push(f);r.widths=d}else r.widths=o;r.addPoints(s)}else if(r=l.ribbonOptions?new oa(n,i,l):new Wn(n,i,l),t){const u={materialType:t.materialType,dashCount:t.dashCount,dashOffset:t.dashOffset,dashRatio:t.dashRatio,resolution:t.resolution,sizeAttenuation:t.sizeAttenuation,useColors:t.useColors,useDash:t.useDash,visibility:t.visibility,width:t.width,color:t.color,colorMode:t.colorMode,colorsSampling:t.colorsSampling,colorDistributionType:t.colorDistributionType,colors:c,cameraFacing:!e.ribbonOptions,colorsTexture:t.colorsTexture};if(t.createAndAssignMaterial){const d=U3e(n,u,i);r.material=d,((h=e.ribbonOptions)==null?void 0:h.facesMode)===i5.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING&&(d.backFaceCulling=!1)}}if(c&&e.instance&&e.instance.greasedLineMaterial){const u=e.instance.greasedLineMaterial.colors;if(u){const d=u.concat(c);e.instance.greasedLineMaterial.setColors(d,r.isLazy())}}return r}function k3e(n,e,t,i=1,r=1){const s=n-e.length/2,a=[];if(s<0)return e.slice(0,n*2);if(s>0){if(e.length%2!=0&&e.push(i),t===Mm.WIDTH_DISTRIBUTION_START_END){const o=Math.floor(e.length/2);for(let h=0,u=0;h0){if(t===M0.COLOR_DISTRIBUTION_START_END){const a=Math.floor(e.length/2);for(let o=0;o=this._thinInstanceDataStorage.instancesCount)return!1;const i=this._thinInstanceDataStorage.matrixData;return e.copyToArray(i,n*16),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[n]=e),t&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0};Se.prototype.thinInstanceSetAttributeAt=function(n,e,t,i=!0){return n===Z.ColorKind&&(n=Z.ColorInstanceKind),!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[n]||e>=this._thinInstanceDataStorage.instancesCount?!1:(this._thinInstanceUpdateBufferSize(n,0),this._userThinInstanceBuffersStorage.data[n].set(t,e*this._userThinInstanceBuffersStorage.strides[n]),i&&this.thinInstanceBufferUpdated(n),!0)};Object.defineProperty(Se.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(n){var i;const e=this._thinInstanceDataStorage.matrixData??((i=this.source)==null?void 0:i._thinInstanceDataStorage.matrixData),t=e?e.length/16:0;n<=t&&(this._thinInstanceDataStorage.instancesCount=n)},enumerable:!0,configurable:!0});Se.prototype._thinInstanceCreateMatrixBuffer=function(n,e,t=!0){n===Z.ColorKind&&(n=Z.ColorInstanceKind);const i=new no(this.getEngine(),e,!t,16,!1,!0);for(let r=0;r<4;r++)this.setVerticesBuffer(i.createVertexBuffer(n+r,r*4,4));return i};Se.prototype.thinInstanceSetBuffer=function(n,e,t=0,i=!0){var r,s,a;t=t||16,n==="matrix"?((r=this._thinInstanceDataStorage.matrixBuffer)==null||r.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=e?e.length:32*t,this._thinInstanceDataStorage.matrixData=e,this._thinInstanceDataStorage.worldMatrices=null,e!==null?(this._thinInstanceDataStorage.instancesCount=e.length/t,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",e,i),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):n==="previousMatrix"?((s=this._thinInstanceDataStorage.previousMatrixBuffer)==null||s.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=e,e!==null&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",e,i))):(n===Z.ColorKind&&(n=Z.ColorInstanceKind),e===null?(a=this._userThinInstanceBuffersStorage)!=null&&a.data[n]&&(this.removeVerticesData(n),delete this._userThinInstanceBuffersStorage.data[n],delete this._userThinInstanceBuffersStorage.strides[n],delete this._userThinInstanceBuffersStorage.sizes[n],delete this._userThinInstanceBuffersStorage.vertexBuffers[n]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[n]=e,this._userThinInstanceBuffersStorage.strides[n]=t,this._userThinInstanceBuffersStorage.sizes[n]=e.length,this._userThinInstanceBuffersStorage.vertexBuffers[n]=new Z(this.getEngine(),e,n,!i,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[n])))};Se.prototype.thinInstanceBufferUpdated=function(n){var e,t,i;n==="matrix"?(e=this._thinInstanceDataStorage.matrixBuffer)==null||e.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):n==="previousMatrix"?(t=this._thinInstanceDataStorage.previousMatrixBuffer)==null||t.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(n===Z.ColorKind&&(n=Z.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[n]&&this._userThinInstanceBuffersStorage.vertexBuffers[n].updateDirectly(this._userThinInstanceBuffersStorage.data[n],0))};Se.prototype.thinInstancePartialBufferUpdate=function(n,e,t){var i;n==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(e,t):(n===Z.ColorKind&&(n=Z.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[n]&&this._userThinInstanceBuffersStorage.vertexBuffers[n].updateDirectly(e,t))};Se.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const n=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let e=0;ee.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){var t;return this.isConnected?(t=this._connectedPoint)!=null&&t._storedFunction?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=fe.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new Ae,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===ym.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==fe.AutoDetect)return e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1?ym.Compatible:ym.TypeIncompatible;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return ym.TypeIncompatible;let r=i,s=t;return this.direction===r5.Input&&(r=t,s=i),r.isAnAncestorOf(s)?ym.HierarchyIssue:ym.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return t===-1?this:(this._endpoints.splice(t,1),e._connectedPoint=null,this)}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t0){if(!this._outputs.some(i=>i.hasEndpoints)&&!this.isDebug)return!1;this.outputs.forEach(i=>i._resetCounters())}this._buildId=e.buildId;for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.notConnectedNonOptionalInputs.push(i);continue}const r=i.connectedPoint.ownerBlock;r&&r!==this&&r.build(e)}this._customBuildStep(e),e.verbose&&de.Log(`Building ${this.name} [${this.getClassName()}]`);const t=gr.Now;this._buildBlock(e),this._buildExecutionTime=gr.Now-t;for(const i of this._outputs)for(const r of i.endpoints){const s=r.ownerBlock;s&&s.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){const t=this._inputs.filter(i=>i.name===e);return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter(i=>i.name===e);return t.length?t[0]:null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(r=>{const s=this.inputs.find(a=>a.name===r.name);if(s&&(r.displayName&&(s.displayName=r.displayName),r.isExposedOnFrame&&(s.isExposedOnFrame=r.isExposedOnFrame,s.exposedPortPosition=r.exposedPortPosition),r.value!==void 0&&r.value!==null))if(r.valueType==="number")s.value=r.value;else{const a=gn(r.valueType);a&&(s.value=a.FromArray(r.value))}}),i&&i.forEach((r,s)=>{r.displayName&&(this.outputs[s].displayName=r.displayName),r.isExposedOnFrame&&(this.outputs[s].isExposedOnFrame=r.isExposedOnFrame,this.outputs[s].exposedPortPosition=r.exposedPortPosition)})}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame}; `}_dumpCodeForOutputConnections(e){let t="";if(e.indexOf(this)!==-1)return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); `}return t}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,e.indexOf(this._codeVariableName)!==-1){let a=0;do a++,this._codeVariableName=i+a;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let r=` // ${this.getClassName()} `;this.comments&&(r+=`// ${this.comments} `);const s=this.getClassName();if(s==="GeometryInputBlock"){const o=this.type;r+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${o}); `}else r+=`var ${this._codeVariableName} = new BABYLON.${s}("${this.name}"); `;r+=this._dumpPropertiesCode();for(const a of this.inputs){if(!a.isConnected)continue;const c=a.connectedPoint.ownerBlock;t.indexOf(c)===-1&&(r+=c._dumpCode(e,t))}for(const a of this.outputs)if(a.hasEndpoints)for(const o of a.endpoints){const c=o.ownerBlock;c&&t.indexOf(c)===-1&&(r+=c._dumpCode(e,t))}return r}clone(){const e=this.serialize(),t=gn(e.customType);if(t){const i=new t;return i._deserialize(e),i}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this.onBuildObservable.clear()}}B([K("comment")],vi.prototype,"comments",void 0);class Zee extends vi{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",fe.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}xe("BABYLON.GeometryOutputBlock",Zee);var Nr;(function(n){n[n.None=0]="None",n[n.Positions=1]="Positions",n[n.Normals=2]="Normals",n[n.Tangents=3]="Tangents",n[n.UV=4]="UV",n[n.UV2=5]="UV2",n[n.UV3=6]="UV3",n[n.UV4=7]="UV4",n[n.UV5=8]="UV5",n[n.UV6=9]="UV6",n[n.Colors=10]="Colors",n[n.VertexID=11]="VertexID",n[n.FaceID=12]="FaceID",n[n.GeometryID=13]="GeometryID",n[n.CollectionID=14]="CollectionID",n[n.LoopID=15]="LoopID",n[n.InstanceID=16]="InstanceID"})(Nr||(Nr={}));class z3e{constructor(){this._rotationMatrix=new ce,this._scalingMatrix=new ce,this._positionMatrix=new ce,this._scalingRotationMatrix=new ce,this._transformMatrix=new ce,this._tempVector3=new P,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;const i=this.executionContext.getExecutionIndex();switch(e){case Nr.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():!this.geometryContext||!this.geometryContext.positions?P.Zero():P.FromArray(this.geometryContext.positions,i*3);case Nr.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():!this.geometryContext||!this.geometryContext.normals?P.Zero():P.FromArray(this.geometryContext.normals,i*3);case Nr.Colors:return!this.geometryContext||!this.geometryContext.colors?Ct.Zero():Ct.FromArray(this.geometryContext.colors,i*4);case Nr.Tangents:return!this.geometryContext||!this.geometryContext.tangents?Ct.Zero():Ct.FromArray(this.geometryContext.tangents,i*4);case Nr.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():!this.geometryContext||!this.geometryContext.uvs?Be.Zero():Be.FromArray(this.geometryContext.uvs,i*2);case Nr.UV2:return!this.geometryContext||!this.geometryContext.uvs2?Be.Zero():Be.FromArray(this.geometryContext.uvs2,i*2);case Nr.UV3:return!this.geometryContext||!this.geometryContext.uvs3?Be.Zero():Be.FromArray(this.geometryContext.uvs3,i*2);case Nr.UV4:return!this.geometryContext||!this.geometryContext.uvs4?Be.Zero():Be.FromArray(this.geometryContext.uvs4,i*2);case Nr.UV5:return!this.geometryContext||!this.geometryContext.uvs5?Be.Zero():Be.FromArray(this.geometryContext.uvs5,i*2);case Nr.UV6:return!this.geometryContext||!this.geometryContext.uvs6?Be.Zero():Be.FromArray(this.geometryContext.uvs6,i*2);case Nr.VertexID:return i;case Nr.FaceID:return this.executionContext.getExecutionFaceIndex();case Nr.LoopID:return this.executionContext.getExecutionLoopIndex();case Nr.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case Nr.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case Nr.CollectionID:return!this.geometryContext||!this.geometryContext.metadata?0:this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case fe.Vector2:return new Be(i,i);case fe.Vector3:return new P(i,i,i);case fe.Vector4:return new Ct(i,i,i,i)}return null}adaptInput(e,t,i){var s;if(!e.isConnected)return e.value||i;const r=e.getConnectedValue(this);if(((s=e._connectedPoint)==null?void 0:s.type)===t)return r;switch(t){case fe.Vector2:return new Be(r,r);case fe.Vector3:return new P(r,r,r);case fe.Vector4:return new Ct(r,r,r,r)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. `;for(const t of this.noContextualData)e+=`Contextual input ${Nr[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block). `;if(e)throw`Build of NodeGeometry failed: `+e}_instantiate(e,t,i,r,s){ce.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),ce.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),ce.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let a=0;at.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${Nr[this._contextualSource]}; `;const t=[];let i="";switch(this.type){case fe.Float:case fe.Int:i=`${this.value}`;break;case fe.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case fe.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case fe.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break}return t.push(`${e}.value = ${i}`),(this.type===fe.Float||this.type===fe.Int)&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(`; `)}serialize(){const e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,this._storedValue!==null&&!this.isContextual&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const t=gn(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}xe("BABYLON.GeometryInputBlock",Ta);class iK extends vi{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",fe.Float,!0,1),this.registerInput("width",fe.Float,!0,0),this.registerInput("height",fe.Float,!0,0),this.registerInput("depth",fe.Float,!0,0),this.registerInput("subdivisions",fe.Int,!0,1),this.registerInput("subdivisionsX",fe.Int,!0,0),this.registerInput("subdivisionsY",fe.Int,!0,0),this.registerInput("subdivisionsZ",fe.Int,!0,0),this.registerOutput("geometry",fe.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){const e=new Ta("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new Ta("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Ta("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new Ta("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=r=>{t.size=this.size.getConnectedValue(r),t.width=this.width.getConnectedValue(r),t.height=this.height.getConnectedValue(r),t.depth=this.depth.getConnectedValue(r);const s=this.subdivisions.getConnectedValue(r),a=this.subdivisionsX.getConnectedValue(r),o=this.subdivisionsY.getConnectedValue(r),c=this.subdivisionsZ.getConnectedValue(r);return s&&(t.segments=s),a&&(t.widthSegments=a),o&&(t.heightSegments=o),c&&(t.depthSegments=c),m2e(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],iK.prototype,"evaluateContext",void 0);xe("BABYLON.BoxBlock",iK);class Hh{_getGlobalNodeGeometryEditor(){if(typeof NODEGEOMETRYEDITOR<"u")return NODEGEOMETRYEDITOR;if(typeof BABYLON<"u"&&typeof BABYLON.NodeGeometryEditor<"u")return BABYLON}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=Hh._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new Ae,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e)if(!t)t=i;else return Ee.Warn("More than one block was found with the name `"+e+"`"),t;return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise(t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),typeof this.BJSNODEGEOMETRYEDITOR>"u"){const i=e&&e.editorURL?e.editorURL:Hh.EditorURL;Ee.LoadBabylonScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e==null?void 0:e.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(e==null?void 0:e.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const r=gr.Now;this._initializeBlock(this.outputBlock,i);const s=new z3e;s.buildId=this._buildId,s.verbose=e,this.outputBlock.build(s),t&&(this._buildId=Hh._BuildIdGenerator++),this._buildExecutionTime=gr.Now-r,s.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=s.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new Se(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),this._vertexData?(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e):!1}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1&&this.attachedBlocks.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const s=r.ownerBlock;s!==e&&this._initializeBlock(s,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();const i={};for(const r of e.blocks){const s=gn(r.customType);if(s){const a=new s;a._deserialize(r),i[r.id]=a,this.attachedBlocks.push(a)}}for(const r of this.attachedBlocks)if(r.isTeleportOut){const s=r,a=s._tempEntryPointUniqueId;if(a){const o=i[a];o&&o.attachToEndpoint(s)}}for(let r=0;ro.targetConnectionName)&&!t||this._restoreConnections(a,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const r=e.locations||e.editorData.locations;for(const a of r)i[a.blockId]&&(a.blockId=i[a.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);const s=[];for(const a in i)s[a]=i[a].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(const r of e.outputs)for(const s of t.blocks){const a=i[s.id];if(a){for(const o of s.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===r.name){const c=a.getInputByName(o.inputName);if(!c||c.isConnected)continue;r.connectTo(c,!0),this._restoreConnections(a,t,i);continue}}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); `;for(const s of t)s.isInput&&e.indexOf(s)===-1&&(r+=s._dumpCode(i,e));return this.outputBlock&&(e=[],r+=`// Connections `,r+=this.outputBlock._dumpCodeForOutputConnections(e),r+=`// Output nodes `,r+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; `,r+=`nodeGeometry.build(); `),r}_gatherBlocks(e,t){if(t.indexOf(e)===-1){t.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const s=r.ownerBlock;s!==e&&this._gatherBlocks(s,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new iK("Box");e.autoConfigure();const t=new Zee("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=Qe.Clone(()=>new Hh(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:Qe.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const r of i)t.blocks.push(r.serialize());if(!e)for(const r of this.attachedBlocks)i.indexOf(r)===-1&&t.blocks.push(r.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){const t=new Hh(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=Qe.Parse(()=>new Hh(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return e==="_BLANK"?Promise.resolve(Hh.CreateDefault("blank")):new Promise((r,s)=>{const a=new on;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),c=JSON.parse(o.nodeGeometry);t||(t=Qe.Parse(()=>new Hh(e),c,null)),t.parseSerializedObject(c),t.snippetId=e;try{i||t.build(),r(t)}catch(l){s(l)}}else s("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}}Hh._BuildIdGenerator=0;Hh.EditorURL=`${Ee._DefaultCdnUrl}/v${De.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`;Hh.SnippetUrl="https://snippet.babylonjs.com";B([K()],Hh.prototype,"name",void 0);B([K("comment")],Hh.prototype,"comment",void 0);class rK extends vi{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=ni,this.registerInput("geometry",fe.Geometry),this.registerOutput("output",fe.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(!this.geometry.isConnected)return null;const r=this.geometry.getConnectedValue(i),s=[],a={};for(let c=0;ca[c]),o};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `;return e+=`${this._codeVariableName}.epsilon = ${this.epsilon}; `,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],rK.prototype,"evaluateContext",void 0);B([Xt("Epsilon",Gt.Float,"ADVANCED",{notifiers:{rebuild:!0}})],rK.prototype,"epsilon",void 0);xe("BABYLON.GeometryOptimizeBlock",rK);class qee extends vi{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",fe.Float,!0,1),this.registerInput("width",fe.Float,!0,0),this.registerInput("height",fe.Float,!0,0),this.registerOutput("geometry",fe.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){const e=new Ta("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new Ta("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Ta("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=r=>(t.size=this.size.getConnectedValue(r),t.width=this.width.getConnectedValue(r),t.height=this.height.getConnectedValue(r),fG(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],qee.prototype,"evaluateContext",void 0);xe("BABYLON.PlaneBlock",qee);class Jee extends vi{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",fe.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}const e=et.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=et.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=et.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}B([Xt("Serialize cached data",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Jee.prototype,"serializedCachedData",void 0);xe("BABYLON.MeshBlock",Jee);class ete extends vi{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",fe.Float,!0,1),this.registerInput("radiusX",fe.Float,!0,0),this.registerInput("radiusY",fe.Float,!0,0),this.registerInput("radiusZ",fe.Float,!0,0),this.registerInput("subdivisions",fe.Int,!0,4),this.registerOutput("geometry",fe.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new Ta("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=r=>(t.radius=this.radius.getConnectedValue(r),t.subdivisions=this.subdivisions.getConnectedValue(r),t.radiusX=this.radiusX.getConnectedValue(r),t.radiusY=this.radiusY.getConnectedValue(r),t.radiusZ=this.radiusZ.getConnectedValue(r),pG(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ete.prototype,"evaluateContext",void 0);xe("BABYLON.IcoSphereBlock",ete);class tte extends vi{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",fe.Int,!0,32),this.registerInput("diameter",fe.Float,!0,1),this.registerInput("diameterX",fe.Float,!0,0),this.registerInput("diameterY",fe.Float,!0,0),this.registerInput("diameterZ",fe.Float,!0,0),this.registerInput("arc",fe.Float,!0,1),this.registerInput("slice",fe.Float,!0,1),this.registerOutput("geometry",fe.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Ta("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=r=>(t.segments=this.segments.getConnectedValue(r),t.diameter=this.diameter.getConnectedValue(r),t.diameterX=this.diameterX.getConnectedValue(r),t.diameterY=this.diameterY.getConnectedValue(r),t.diameterZ=this.diameterZ.getConnectedValue(r),t.arc=this.arc.getConnectedValue(r),t.slice=this.slice.getConnectedValue(r),RG(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],tte.prototype,"evaluateContext",void 0);xe("BABYLON.SphereBlock",tte);class ite extends vi{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",fe.Float,!0,1),this.registerInput("height",fe.Float,!0,1),this.registerInput("subdivisions",fe.Int,!0,1),this.registerInput("subdivisionsX",fe.Int,!0,0),this.registerInput("subdivisionsY",fe.Int,!0,0),this.registerOutput("geometry",fe.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){const e=new Ta("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Ta("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=r=>(t.width=this.width.getConnectedValue(r),t.height=this.height.getConnectedValue(r),t.subdivisions=this.subdivisions.getConnectedValue(r),t.subdivisionsX=this.subdivisionsX.getConnectedValue(r),t.subdivisionsY=this.subdivisionsY.getConnectedValue(r),S0(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ite.prototype,"evaluateContext",void 0);xe("BABYLON.GridBlock",ite);class rte extends vi{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",fe.Float,!0,1),this.registerInput("thickness",fe.Float,!0,.5),this.registerInput("tessellation",fe.Int,!0,16),this.registerOutput("geometry",fe.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Ta("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=r=>(t.thickness=this.thickness.getConnectedValue(r),t.diameter=this.diameter.getConnectedValue(r),t.tessellation=this.tessellation.getConnectedValue(r),EG(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],rte.prototype,"evaluateContext",void 0);xe("BABYLON.TorusBlock",rte);class ste extends vi{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",fe.Float,!0,25),this.registerInput("diameter",fe.Float,!0,1),this.registerInput("diameterTop",fe.Float,!0,-1),this.registerInput("diameterBottom",fe.Float,!0,-1),this.registerInput("subdivisions",fe.Int,!0,1),this.registerInput("tessellation",fe.Int,!0,24),this.registerInput("arc",fe.Float,!0,1),this.registerOutput("geometry",fe.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Ta("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new Ta("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=r=>(t.height=this.height.getConnectedValue(r),t.diameter=this.diameter.getConnectedValue(r),t.diameterTop=this.diameterTop.getConnectedValue(r),t.diameterBottom=this.diameterBottom.getConnectedValue(r),t.diameterTop===-1&&(t.diameterTop=t.diameter),t.diameterBottom===-1&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(r),t.subdivisions=this.subdivisions.getConnectedValue(r),t.arc=this.arc.getConnectedValue(r),SG(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ste.prototype,"evaluateContext",void 0);xe("BABYLON.CylinderBlock",ste);class nte extends vi{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",fe.Float,!0,1),this.registerInput("radius",fe.Float,!0,.25),this.registerInput("tessellation",fe.Int,!0,16),this.registerInput("subdivisions",fe.Int,!0,2),this.registerOutput("geometry",fe.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){const e=new Ta("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new Ta("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=r=>(t.height=this.height.getConnectedValue(r),t.radius=this.radius.getConnectedValue(r),t.tessellation=this.tessellation.getConnectedValue(r),t.subdivisions=this.subdivisions.getConnectedValue(r),IG(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],nte.prototype,"evaluateContext",void 0);xe("BABYLON.CapsuleBlock",nte);class ate extends vi{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",fe.Float,!0,.5),this.registerInput("tessellation",fe.Int,!0,64),this.registerInput("arc",fe.Float,!0,1),this.registerOutput("geometry",fe.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new Ta("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=r=>(t.radius=this.radius.getConnectedValue(r),t.tessellation=this.tessellation.getConnectedValue(r),t.arc=this.arc.getConnectedValue(r),PG(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ate.prototype,"evaluateContext",void 0);xe("BABYLON.DiscBlock",ate);class H3e extends vi{constructor(e){super(e),this.registerOutput("geometry",fe.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}xe("BABYLON.NullBlock",H3e);class ote extends vi{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",fe.Geometry),this.registerInput("positions",fe.Vector3),this.registerOutput("output",fe.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}const r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.normals.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.normals||(this._vertexData.normals=[]);const r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.uvs.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}const r=[],s=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{var s;if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.colors.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.colors||(this._vertexData.colors=[]);const r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.tangents.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.tangents||(this._vertexData.tangents=[]);const r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndext.getConnectedValue(s)+i.getConnectedValue(s):e=s=>t.getConnectedValue(s).add(s.adapt(i,t.type));break}case Nc.Subtract:{r?e=s=>t.getConnectedValue(s)-i.getConnectedValue(s):e=s=>t.getConnectedValue(s).subtract(s.adapt(i,t.type));break}case Nc.Multiply:{r?e=s=>t.getConnectedValue(s)*i.getConnectedValue(s):e=s=>t.getConnectedValue(s).multiply(s.adapt(i,t.type));break}case Nc.Divide:{r?e=s=>t.getConnectedValue(s)/i.getConnectedValue(s):e=s=>t.getConnectedValue(s).divide(s.adapt(i,t.type));break}case Nc.Min:{if(r)e=s=>Math.min(t.getConnectedValue(s),i.getConnectedValue(s));else switch(t.type){case fe.Vector2:{e=s=>Be.Minimize(t.getConnectedValue(s),s.adapt(i,t.type));break}case fe.Vector3:{e=s=>P.Minimize(t.getConnectedValue(s),s.adapt(i,t.type));break}case fe.Vector4:{e=s=>Ct.Minimize(t.getConnectedValue(s),s.adapt(i,t.type));break}}break}case Nc.Max:if(r)e=s=>Math.max(t.getConnectedValue(s),i.getConnectedValue(s));else{switch(t.type){case fe.Vector2:{e=s=>Be.Maximize(t.getConnectedValue(s),s.adapt(i,t.type));break}case fe.Vector3:{e=s=>P.Maximize(t.getConnectedValue(s),s.adapt(i,t.type));break}case fe.Vector4:{e=s=>Ct.Maximize(t.getConnectedValue(s),s.adapt(i,t.type));break}}break}}this.output._storedFunction=s=>t.type===fe.Int?e(s)|0:e(s)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${Nc[this.operation]}; `}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}B([Xt("Operation",Gt.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:Nc.Add},{label:"Subtract",value:Nc.Subtract},{label:"Multiply",value:Nc.Multiply},{label:"Divide",value:Nc.Divide},{label:"Max",value:Nc.Max},{label:"Min",value:Nc.Min}]})],ute.prototype,"operation",void 0);xe("BABYLON.MathBlock",ute);class G3e extends vi{constructor(e){super(e),this.registerInput("value",fe.AutoDetect),this.registerInput("fromMin",fe.Float,!0,0),this.registerInput("fromMax",fe.Float,!0,1),this.registerInput("toMin",fe.Float,!0,0),this.registerInput("toMax",fe.Float,!0,1),this.registerOutput("output",fe.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(fe.Vector2),this._inputs[0].excludedConnectionPointTypes.push(fe.Vector3),this._inputs[0].excludedConnectionPointTypes.push(fe.Vector4),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),a=this.toMax.getConnectedValue(e),o=(t-i)/(r-i)*(a-s)+s;return this.output.type===fe.Int?Math.floor(o):o}}}xe("BABYLON.MapRangeBlock",G3e);var Co;(function(n){n[n.Equal=0]="Equal",n[n.NotEqual=1]="NotEqual",n[n.LessThan=2]="LessThan",n[n.GreaterThan=3]="GreaterThan",n[n.LessOrEqual=4]="LessOrEqual",n[n.GreaterOrEqual=5]="GreaterOrEqual",n[n.Xor=6]="Xor",n[n.Or=7]="Or",n[n.And=8]="And"})(Co||(Co={}));class dte extends vi{constructor(e){super(e),this.test=Co.Equal,this.registerInput("left",fe.Float),this.registerInput("right",fe.Float,!0,0),this.registerInput("ifTrue",fe.AutoDetect,!0,1),this.registerInput("ifFalse",fe.AutoDetect,!0,0),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=fe.Float,this._inputs[0].acceptedConnectionPointTypes.push(fe.Int),this._inputs[1].acceptedConnectionPointTypes.push(fe.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t);let s=!1;switch(this.test){case Co.Equal:s=_t.WithinEpsilon(i,r,ni);break;case Co.NotEqual:s=i!==r;break;case Co.LessThan:s=ir;break;case Co.LessOrEqual:s=i<=r;break;case Co.GreaterOrEqual:s=i>=r;break;case Co.Xor:s=!!i&&!r||!i&&!!r;break;case Co.Or:s=!!i||!!r;break;case Co.And:s=!!i&&!!r;break}return s};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${Co[this.test]}; `}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}B([Xt("Test",Gt.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:Co.Equal},{label:"NotEqual",value:Co.NotEqual},{label:"LessThan",value:Co.LessThan},{label:"GreaterThan",value:Co.GreaterThan},{label:"LessOrEqual",value:Co.LessOrEqual},{label:"GreaterOrEqual",value:Co.GreaterOrEqual},{label:"Xor",value:Co.Xor},{label:"Or",value:Co.Or},{label:"And",value:Co.And}]})],dte.prototype,"test",void 0);xe("BABYLON.ConditionBlock",dte);var Tf;(function(n){n[n.None=0]="None",n[n.LoopID=1]="LoopID",n[n.InstanceID=2]="InstanceID"})(Tf||(Tf={}));class fte extends vi{constructor(e){super(e),this._currentLockId=-1,this.lockMode=Tf.None,this.registerInput("min",fe.AutoDetect),this.registerInput("max",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture),this._inputs[1].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[1].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[1].excludedConnectionPointTypes.push(fe.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){const e=new Ta("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new Ta("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case fe.Int:case fe.Float:{e=t=>{const i=this.min.getConnectedValue(t)||0,r=this.max.getConnectedValue(t)||0;return i+Math.random()*(r-i)};break}case fe.Vector2:{e=t=>{const i=this.min.getConnectedValue(t)||Be.Zero(),r=this.max.getConnectedValue(t)||Be.Zero();return new Be(i.x+Math.random()*(r.x-i.x),i.y+Math.random()*(r.y-i.y))};break}case fe.Vector3:{e=t=>{const i=this.min.getConnectedValue(t)||P.Zero(),r=this.max.getConnectedValue(t)||P.Zero();return new P(i.x+Math.random()*(r.x-i.x),i.y+Math.random()*(r.y-i.y),i.z+Math.random()*(r.z-i.z))};break}case fe.Vector4:{e=t=>{const i=this.min.getConnectedValue(t)||Ct.Zero(),r=this.max.getConnectedValue(t)||Ct.Zero();return new Ct(i.x+Math.random()*(r.x-i.x),i.y+Math.random()*(r.y-i.y),i.z+Math.random()*(r.z-i.z),i.w+Math.random()*(r.w-i.w))};break}}this.lockMode===Tf.None||!e?this.output._storedFunction=e:this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case Tf.InstanceID:i=t.getContextualValue(Nr.InstanceID,!0)||0;break;case Tf.LoopID:i=t.getContextualValue(Nr.LoopID,!0)||0;break}return(this._currentLockId!==i||this.lockMode===Tf.None)&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${Tf[this.lockMode]}; `}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}B([Xt("LockMode",Gt.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:Tf.None},{label:"LoopID",value:Tf.LoopID},{label:"InstanceID",value:Tf.InstanceID}]})],fte.prototype,"lockMode",void 0);xe("BABYLON.RandomBlock",fte);class K3e extends vi{constructor(e){super(e),this.registerInput("offset",fe.Vector3,!0,P.Zero()),this.registerInput("scale",fe.Float,!0,1),this.registerInput("octaves",fe.Float,!0,2,0,16),this.registerInput("roughness",fe.Float,!0,.5,0,1),this.registerOutput("output",fe.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return t!==0?-e:e}_noiseGrad(e,t,i,r){const s=e&15,a=s<8?t:i,o=s===12||s==14?t:r,c=s<4?i:o;return this._negateIf(a,s&a)+this._negateIf(c,s&2)}_fade(e){return e*e*e*(e*(e*6-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let r,s,a;return r=s=a=3735928584,a+=i,s+=t,r+=e,a^=s,a-=this._hashBitRotate(s,14),r^=a,r-=this._hashBitRotate(a,11),s^=r,s-=this._hashBitRotate(r,25),a^=s,a-=this._hashBitRotate(s,16),r^=a,r-=this._hashBitRotate(a,4),s^=r,s-=this._hashBitRotate(r,14),a^=s,a-=this._hashBitRotate(s,24),a}_mix(e,t,i,r,s,a,o,c,l,h,u){const d=1-l,f=1-h;return(1-u)*(f*(e*d+t*l)+h*(i*d+r*l))+u*(f*(s*d+a*l)+h*(o*d+c*l))}_perlinNoise(e){const t=(e.x|0)-(e.x<0?1:0),i=(e.y|0)-(e.y<0?1:0),r=(e.z|0)-(e.z<0?1:0),s=e.x-t,a=e.y-i,o=e.z-r,c=this._fade(s),l=this._fade(a),h=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,r),s,a,o),this._noiseGrad(this._hash(t+1,i,r),s-1,a,o),this._noiseGrad(this._hash(t,i+1,r),s,a-1,o),this._noiseGrad(this._hash(t+1,i+1,r),s-1,a-1,o),this._noiseGrad(this._hash(t,i,r+1),s,a,o-1),this._noiseGrad(this._hash(t+1,i,r+1),s-1,a,o-1),this._noiseGrad(this._hash(t,i+1,r+1),s,a-1,o-1),this._noiseGrad(this._hash(t+1,i+1,r+1),s-1,a-1,o-1),c,l,h)}_perlinSigned(e){return this._perlinNoise(e)*.982}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,s){const a=new P(i.x*s+r.x,i.y*s+r.y,i.z*s+r.z);let o=1,c=1,l=0,h=0;e=_t.Clamp(e,0,15);const u=e|0;for(let _=0;_<=u;_++){const m=this._perlin(a.scale(o));h+=m*c,l+=c,c*=_t.Clamp(t,0,1),o*=2}const d=e-Math.floor(e);if(d==0)return h/l;const f=this._perlin(a.scale(o));let p=h+f*c;return h/=l,p/=l+c,(1-d)*h+d*p}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(Nr.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),a=this.scale.getConnectedValue(e);return this.noise(i,r,t,s,a)}}}xe("BABYLON.NoiseBlock",K3e);class pte extends vi{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",fe.Geometry),this.registerInput("geometry1",fe.Geometry,!0),this.registerInput("geometry2",fe.Geometry,!0),this.registerInput("geometry3",fe.Geometry,!0),this.registerInput("geometry4",fe.Geometry,!0),this.registerOutput("output",fe.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{let r=this.geometry0.getConnectedValue(i);const s=[];if(r)r=r.clone();else return null;if(this.geometry1.isConnected){const a=this.geometry1.getConnectedValue(i);a&&s.push(a)}if(this.geometry2.isConnected){const a=this.geometry2.getConnectedValue(i);a&&s.push(a)}if(this.geometry3.isConnected){const a=this.geometry3.getConnectedValue(i);a&&s.push(a)}if(this.geometry4.isConnected){const a=this.geometry4.getConnectedValue(i);a&&s.push(a)}return s.length&&r&&(r=r.merge(s,!0,!1,!0,!0)),r};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],pte.prototype,"evaluateContext",void 0);xe("BABYLON.MergeGeometryBlock",pte);class _te extends vi{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",fe.Geometry,!0),this.registerInput("geometry1",fe.Geometry,!0),this.registerInput("geometry2",fe.Geometry,!0),this.registerInput("geometry3",fe.Geometry,!0),this.registerInput("geometry4",fe.Geometry,!0),this.registerInput("geometry5",fe.Geometry,!0),this.registerInput("geometry6",fe.Geometry,!0),this.registerInput("geometry7",fe.Geometry,!0),this.registerInput("geometry8",fe.Geometry,!0),this.registerInput("geometry9",fe.Geometry,!0),this.registerOutput("output",fe.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){const s=e.getConnectedValue(t);if(!s)return;s.metadata=s.metadata||{},s.metadata.collectionId=i,r.push(s)}}_buildBlock(e){const t=i=>{const r=[];return this._storeGeometry(this.geometry0,i,0,r),this._storeGeometry(this.geometry1,i,1,r),this._storeGeometry(this.geometry2,i,2,r),this._storeGeometry(this.geometry3,i,3,r),this._storeGeometry(this.geometry4,i,4,r),this._storeGeometry(this.geometry5,i,5,r),this._storeGeometry(this.geometry6,i,6,r),this._storeGeometry(this.geometry7,i,7,r),this._storeGeometry(this.geometry8,i,8,r),this._storeGeometry(this.geometry9,i,9,r),r.length?r[Math.round(Math.random()*(r.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],_te.prototype,"evaluateContext",void 0);xe("BABYLON.GeometryCollectionBlock",_te);class W3e extends vi{constructor(e){super(e),this.registerInput("input",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];t._storedFunction=r=>i.getConnectedValue(r)}}xe("BABYLON.GeometryElbowBlock",W3e);class j3e extends vi{constructor(e){super(e),this.registerInput("geometry",fe.Geometry),this.registerOutput("output",fe.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),et.ComputeNormals(t.positions,t.indices,t.normals),t}}}xe("BABYLON.ComputeNormalsBlock",j3e);class X3e extends vi{constructor(e){super(e),this.registerInput("xyzw ",fe.Vector4,!0),this.registerInput("xyz ",fe.Vector3,!0),this.registerInput("xy ",fe.Vector2,!0),this.registerInput("zw ",fe.Vector2,!0),this.registerInput("x ",fe.Float,!0),this.registerInput("y ",fe.Float,!0),this.registerInput("z ",fe.Float,!0),this.registerInput("w ",fe.Float,!0),this.registerOutput("xyzw",fe.Vector4),this.registerOutput("xyz",fe.Vector3),this.registerOutput("xy",fe.Vector2),this.registerOutput("zw",fe.Vector2),this.registerOutput("x",fe.Float),this.registerOutput("y",fe.Float),this.registerOutput("z",fe.Float),this.registerOutput("w",fe.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return e==="xyzw "?"xyzwIn":e==="xyz "?"xyzIn":e==="xy "?"xyIn":e==="zw "?"zwIn":e==="x "?"xIn":e==="y "?"yIn":e==="z "?"zIn":e==="w "?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,r=this.zIn,s=this.wIn,a=this.xyIn,o=this.zwIn,c=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,u=this.xyzOut,d=this.xyOut,f=this.zwOut,p=this.xOut,_=this.yOut,m=this.zOut,g=this.wOut,v=x=>{if(l.isConnected)return l.getConnectedValue(x);let y=0,C=0,b=0,T=0;if(t.isConnected&&(y=t.getConnectedValue(x)),i.isConnected&&(C=i.getConnectedValue(x)),r.isConnected&&(b=r.getConnectedValue(x)),s.isConnected&&(T=s.getConnectedValue(x)),a.isConnected){const S=a.getConnectedValue(x);S&&(y=S.x,C=S.y)}if(o.isConnected){const S=o.getConnectedValue(x);S&&(b=S.x,T=S.y)}if(c.isConnected){const S=c.getConnectedValue(x);S&&(y=S.x,C=S.y,b=S.z)}return new Ct(y,C,b,T)};h._storedFunction=x=>v(x),u._storedFunction=x=>{const y=v(x);return new P(y.x,y.y,y.z)},d._storedFunction=x=>{const y=v(x);return new Be(y.x,y.y)},f._storedFunction=x=>{const y=v(x);return new Be(y.z,y.w)},p._storedFunction=x=>v(x).x,_._storedFunction=x=>v(x).y,m._storedFunction=x=>v(x).z,g._storedFunction=x=>v(x).w}}xe("BABYLON.VectorConverterBlock",X3e);class Y3e extends vi{constructor(e){super(e),this.registerInput("input",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(fe.Float),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),this.output._storedFunction=null,!this.input.isConnected){this.output._storedValue=null;return}this.output._storedFunction=t=>this.input.getConnectedValue(t).normalize()}}xe("BABYLON.NormalizeVectorBlock",Y3e);class mte extends vi{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",fe.Geometry),this.registerInput("id",fe.Int,!0,0),this.registerOutput("output",fe.Geometry),this.id.acceptedConnectionPointTypes.push(fe.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const t=i=>{const r=this.geometry.getConnectedValue(i);if(!r||!r.indices||!r.positions)return r;const s=new fD;return s.materialIndex=this.id.getConnectedValue(i)|0,s.indexStart=0,s.indexCount=r.indices.length,s.verticesStart=0,s.verticesCount=r.positions.length/3,r.materialInfos=[s],r};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mte.prototype,"evaluateContext",void 0);xe("BABYLON.SetMaterialIDBlock",mte);var Mr;(function(n){n[n.Cos=0]="Cos",n[n.Sin=1]="Sin",n[n.Abs=2]="Abs",n[n.Exp=3]="Exp",n[n.Round=4]="Round",n[n.Floor=5]="Floor",n[n.Ceiling=6]="Ceiling",n[n.Sqrt=7]="Sqrt",n[n.Log=8]="Log",n[n.Tan=9]="Tan",n[n.ArcTan=10]="ArcTan",n[n.ArcCos=11]="ArcCos",n[n.ArcSin=12]="ArcSin",n[n.Sign=13]="Sign",n[n.Negate=14]="Negate",n[n.OneMinus=15]="OneMinus",n[n.Reciprocal=16]="Reciprocal",n[n.ToDegrees=17]="ToDegrees",n[n.ToRadians=18]="ToRadians",n[n.Fract=19]="Fract",n[n.Exp2=20]="Exp2"})(Mr||(Mr={}));class gte extends vi{constructor(e){super(e),this.operation=Mr.Cos,this.registerInput("input",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case Mr.Cos:{t=i=>Math.cos(i);break}case Mr.Sin:{t=i=>Math.sin(i);break}case Mr.Abs:{t=i=>Math.abs(i);break}case Mr.Exp:{t=i=>Math.exp(i);break}case Mr.Exp2:{t=i=>Math.pow(2,i);break}case Mr.Round:{t=i=>Math.round(i);break}case Mr.Floor:{t=i=>Math.floor(i);break}case Mr.Ceiling:{t=i=>Math.ceil(i);break}case Mr.Sqrt:{t=i=>Math.sqrt(i);break}case Mr.Log:{t=i=>Math.log(i);break}case Mr.Tan:{t=i=>Math.tan(i);break}case Mr.ArcTan:{t=i=>Math.atan(i);break}case Mr.ArcCos:{t=i=>Math.acos(i);break}case Mr.ArcSin:{t=i=>Math.asin(i);break}case Mr.Sign:{t=i=>Math.sign(i);break}case Mr.Negate:{t=i=>-i;break}case Mr.OneMinus:{t=i=>1-i;break}case Mr.Reciprocal:{t=i=>1/i;break}case Mr.ToRadians:{t=i=>i*Math.PI/180;break}case Mr.ToDegrees:{t=i=>i*180/Math.PI;break}case Mr.Fract:{t=i=>i>=0?i-Math.floor(i):i-Math.ceil(i);break}}if(!t){this.output._storedFunction=null,this.output._storedValue=null;return}switch(this.input.type){case fe.Int:case fe.Float:{this.output._storedFunction=i=>{const r=this.input.getConnectedValue(i);return t(r)};break}case fe.Vector2:{this.output._storedFunction=i=>{const r=this.input.getConnectedValue(i);return new Be(t(r.x),t(r.y))};break}case fe.Vector3:{this.output._storedFunction=i=>{const r=this.input.getConnectedValue(i);return new P(t(r.x),t(r.y),t(r.z))};break}case fe.Vector4:{this.output._storedFunction=i=>{const r=this.input.getConnectedValue(i);return new Ct(t(r.x),t(r.y),t(r.z),t(r.w))};break}}return this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${Mr[this.operation]}; `}}B([Xt("Operation",Gt.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:Mr.Cos},{label:"Sin",value:Mr.Sin},{label:"Abs",value:Mr.Abs},{label:"Exp",value:Mr.Exp},{label:"Exp2",value:Mr.Exp2},{label:"Round",value:Mr.Round},{label:"Floor",value:Mr.Floor},{label:"Ceiling",value:Mr.Ceiling},{label:"Sqrt",value:Mr.Sqrt},{label:"Log",value:Mr.Log},{label:"Tan",value:Mr.Tan},{label:"ArcTan",value:Mr.ArcTan},{label:"ArcCos",value:Mr.ArcCos},{label:"ArcSin",value:Mr.ArcSin},{label:"Sign",value:Mr.Sign},{label:"Negate",value:Mr.Negate},{label:"OneMinus",value:Mr.OneMinus},{label:"Reciprocal",value:Mr.Reciprocal},{label:"ToDegrees",value:Mr.ToDegrees},{label:"ToRadians",value:Mr.ToRadians}]})],gte.prototype,"operation",void 0);xe("BABYLON.GeometryTrigonometryBlock",gte);class vte extends vi{constructor(e){super(e),this._rotationMatrix=new ce,this._scalingMatrix=new ce,this._translationMatrix=new ce,this._scalingRotationMatrix=new ce,this._transformMatrix=new ce,this.evaluateContext=!0,this.registerInput("value",fe.AutoDetect),this.registerInput("matrix",fe.Matrix,!0),this.registerInput("translation",fe.Vector3,!0,P.Zero()),this.registerInput("rotation",fe.Vector3,!0,P.Zero()),this.registerInput("scaling",fe.Vector3,!0,P.One()),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(fe.Float),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const t=i=>{const r=this.value.getConnectedValue(i);if(!r)return null;let s;if(this.matrix.isConnected)s=this.matrix.getConnectedValue(i);else{const a=this.scaling.getConnectedValue(i),o=this.rotation.getConnectedValue(i),c=this.translation.getConnectedValue(i);ce.ScalingToRef(a.x,a.y,a.z,this._scalingMatrix),ce.RotationYawPitchRollToRef(o.y,o.x,o.z,this._rotationMatrix),ce.TranslationToRef(c.x,c.y,c.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),s=this._transformMatrix}switch(this.value.type){case fe.Geometry:{const a=r.clone();return a.transform(s),a}case fe.Vector2:return Be.Transform(r,s);case fe.Vector3:return P.TransformCoordinates(r,s);case fe.Vector4:return Ct.TransformCoordinates(r,s)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vte.prototype,"evaluateContext",void 0);xe("BABYLON.GeometryTransformBlock",vte);class Q3e extends vi{constructor(e){super(e),this.registerInput("angle",fe.Float,!1,0),this.registerOutput("matrix",fe.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Ta("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>ce.RotationX(this.angle.getConnectedValue(t))}}xe("BABYLON.RotationXBlock",Q3e);class $3e extends vi{constructor(e){super(e),this.registerInput("angle",fe.Float,!1,0),this.registerOutput("matrix",fe.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Ta("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>ce.RotationY(this.angle.getConnectedValue(t))}}xe("BABYLON.RotationYBlock",$3e);class Z3e extends vi{constructor(e){super(e),this.registerInput("angle",fe.Float,!1,0),this.registerOutput("matrix",fe.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Ta("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>ce.RotationZ(this.angle.getConnectedValue(t))}}xe("BABYLON.RotationZBlock",Z3e);class q3e extends vi{constructor(e){super(e),this.registerInput("scale",fe.Vector3,!1,P.One()),this.registerOutput("matrix",fe.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new Ta("Scale");e.value=new P(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.scale.getConnectedValue(t);return ce.Scaling(i.x,i.y,i.z)}}}xe("BABYLON.ScalingBlock",q3e);class J3e extends vi{constructor(e){super(e),this.registerInput("source",fe.Vector3,!0,P.Up()),this.registerInput("target",fe.Vector3,!0,P.Left()),this.registerOutput("matrix",fe.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.source.getConnectedValue(t).clone(),r=this.target.getConnectedValue(t).clone(),s=new ce;return i.normalize(),r.normalize(),ce.RotationAlignToRef(i,r,s,!0),s}}}xe("BABYLON.AlignBlock",J3e);class e4e extends vi{constructor(e){super(e),this.registerInput("translation",fe.Vector3,!1,P.Zero()),this.registerOutput("matrix",fe.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new Ta("Translation");e.value=new P(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.translation.getConnectedValue(t);return ce.Translation(i.x,i.y,i.z)}}}xe("BABYLON.TranslationBlock",e4e);class nK extends vi{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",fe.Geometry),this.registerInput("instance",fe.Geometry,!0),this.registerInput("density",fe.Float,!0,1,0,1),this.registerInput("matrix",fe.Matrix,!0),this.registerInput("rotation",fe.Vector3,!0,P.Zero()),this.registerInput("scaling",fe.Vector3,!0,P.One()),this.scaling.acceptedConnectionPointTypes.push(fe.Float),this.registerOutput("output",fe.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),i.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(i),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected){i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this.output._storedValue=null;return}let r=this._vertexData.positions.length/3;const s=[],a=new P,o=[];let c=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexh)continue;a.fromArray(c,this._currentIndex*3);const u=l.clone();if(this.matrix.isConnected){const d=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(u,a,d,s)}else{const d=i.adaptInput(this.scaling,fe.Vector3,P.OneReadOnly),f=this.rotation.getConnectedValue(i)||P.ZeroReadOnly;i._instantiate(u,a,f,d,s)}this._currentLoopIndex++}if(i.restoreGeometryContext(),i.restoreExecutionContext(),i.restoreInstancingContext(),s.length)if(s.length===1)this._vertexData=s[0];else{const l=s.splice(0,1)[0];this._vertexData=l.merge(s,!0,!1,!0,!0)}else return null;return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"}; `;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `,e}serialize(){const e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],nK.prototype,"evaluateContext",void 0);B([Xt("Remove duplicated positions",Gt.Boolean,"ADVANCED",{notifiers:{update:!0}})],nK.prototype,"removeDuplicatedPositions",void 0);xe("BABYLON.InstantiateOnVerticesBlock",nK);class xte extends vi{constructor(e){super(e),this._currentPosition=new P,this._currentUV=new Be,this._vertex0=new P,this._vertex1=new P,this._vertex2=new P,this._tempVector0=new P,this._tempVector1=new P,this._uv0=new Be,this._uv1=new Be,this._uv2=new Be,this.evaluateContext=!0,this.registerInput("geometry",fe.Geometry),this.registerInput("instance",fe.Geometry,!0),this.registerInput("count",fe.Int,!0,256),this.registerInput("matrix",fe.Matrix,!0),this.registerInput("rotation",fe.Vector3,!0,P.Zero()),this.registerInput("scaling",fe.Vector3,!0,P.One()),this.scaling.acceptedConnectionPointTypes.push(fe.Float),this.registerOutput("output",fe.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),P.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),i.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(i),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this.output._storedValue=null;return}let r=null;const s=this.count.getConnectedValue(i),a=this._vertexData.indices.length/3,o=s/a;let c=0;const l=[];let h=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=s);_++){let m=Math.random(),g=Math.random();if(m>g){const b=m;m=g,g=b}const v=m,x=g-m,y=1-v-x;if(this._currentPosition.set(v*this._vertex0.x+x*this._vertex1.x+y*this._vertex2.x,v*this._vertex0.y+x*this._vertex1.y+y*this._vertex2.y,v*this._vertex0.z+x*this._vertex1.z+y*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(v*this._uv0.x+x*this._uv1.x+y*this._uv2.x,v*this._uv0.y+x*this._uv1.y+y*this._uv2.y),r=this.instance.getConnectedValue(i),!r||!r.positions||r.positions.length===0){c-=o;continue}const C=r.clone();if(this.matrix.isConnected){const b=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(C,this._currentPosition,b,l)}else{const b=i.adaptInput(this.scaling,fe.Vector3,P.OneReadOnly),T=this.rotation.getConnectedValue(i)||P.ZeroReadOnly;i._instantiate(C,this._currentPosition,T,b,l)}h++,this._currentLoopIndex++}}if(l.length)if(l.length===1)this._vertexData=l[0];else{const u=l.splice(0,1)[0];this._vertexData=u.merge(l,!0,!1,!0,!0)}return i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xte.prototype,"evaluateContext",void 0);xe("BABYLON.InstantiateOnFacesBlock",xte);class yte extends vi{constructor(e){super(e),this._currentPosition=new P,this._vertex0=new P,this._vertex1=new P,this._vertex2=new P,this.evaluateContext=!0,this.registerInput("geometry",fe.Geometry),this.registerInput("instance",fe.Geometry,!0),this.registerInput("count",fe.Int,!0,256),this.registerInput("matrix",fe.Matrix,!0),this.registerInput("rotation",fe.Vector3,!0,P.Zero()),this.registerInput("scaling",fe.Vector3,!0,P.One()),this.scaling.acceptedConnectionPointTypes.push(fe.Float),this.registerOutput("output",fe.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),i.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(i),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this.output._storedValue=null;return}let r=null;const s=this.count.getConnectedValue(i),a=[],o=W8(this._vertexData.positions,0,this._vertexData.positions.length/3),c=o.minimum,l=o.maximum,h=new P(1,0,0),u=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let d=0;d0&&p++}if(p%2===0){d--;continue}if(r=this.instance.getConnectedValue(i),!r||!r.positions||r.positions.length===0)continue;const _=r.clone();if(this.matrix.isConnected){const m=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(_,this._currentPosition,m,a)}else{const m=i.adaptInput(this.scaling,fe.Vector3,P.OneReadOnly),g=this.rotation.getConnectedValue(i)||P.ZeroReadOnly;i._instantiate(_,this._currentPosition,g,m,a)}this._currentLoopIndex++}if(a.length)if(a.length===1)this._vertexData=a[0];else{const d=a.splice(0,1)[0];this._vertexData=d.merge(a,!0,!1,!0,!0)}return i.restoreGeometryContext(),i.restoreExecutionContext(),i.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],yte.prototype,"evaluateContext",void 0);xe("BABYLON.InstantiateOnVolumeBlock",yte);class aK extends vi{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",fe.Geometry,!0),this.registerInput("count",fe.Int,!0,1),this.registerOutput("output",fe.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],aK.prototype,"evaluateContext",void 0);class t4e extends aK{constructor(e){super(e),this.registerInput("matrix",fe.Matrix,!0),this.registerInput("position",fe.Vector3,!0,P.Zero()),this.registerInput("rotation",fe.Vector3,!0,P.Zero()),this.registerInput("scaling",fe.Vector3,!0,P.One()),this.scaling.acceptedConnectionPointTypes.push(fe.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){const t=i=>{i.pushExecutionContext(this),i.pushInstancingContext(this);const r=this.count.getConnectedValue(i),s=[];for(this._currentIndex=0;this._currentIndex{i.pushExecutionContext(this),i.pushInstancingContext(this);const r=this.count.getConnectedValue(i),s=[],a=ce.Identity(),o=P.Zero(),c=P.Zero(),l=P.Zero();for(this._currentIndex=0;this._currentIndex{i.pushExecutionContext(this),i.pushInstancingContext(this);const r=this.count.getConnectedValue(i),s=[],a=ce.Identity(),o=ce.Identity(),c=ce.Identity(),l=P.Zero(),h=P.Zero(),u=P.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}xe("BABYLON.IntFloatConverterBlock",s4e);class n4e extends vi{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.log=[];const t=i=>{const r=this.input.getConnectedValue(i);if(r==null)return this.log.push(["null",""]),r;switch(this.input.type){case fe.Vector2:this.log.push([D3e(r,4),r.toString()]);break;case fe.Vector3:this.log.push([O3e(r,4),r.toString()]);break;case fe.Vector4:this.log.push([L3e(r,4),r.toString()]);break;default:this.log.push([r.toString(),r.toString()]);break}return r};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}xe("BABYLON.DebugBlock",n4e);class a4e extends vi{constructor(e){super(e),this.registerInput("geometry",fe.Geometry),this.registerOutput("output",fe.Geometry),this.registerOutput("id",fe.Int),this.registerOutput("collectionId",fe.Int),this.registerOutput("verticesCount",fe.Int),this.registerOutput("facesCount",fe.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected){this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,this.output._storedFunction=null;return}this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}xe("BABYLON.GeometryInfoBlock",a4e);var Xp;(function(n){n[n.Spherical=0]="Spherical",n[n.Cylindrical=1]="Cylindrical",n[n.Cubic=2]="Cubic"})(Xp||(Xp={}));class Ate extends vi{constructor(e){super(e),this.mapping=Xp.Spherical,this.registerInput("position",fe.Vector3),this.registerInput("normal",fe.Vector3),this.registerInput("center",fe.Vector3,!0,P.Zero()),this.registerOutput("uv",fe.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected){this.uv._storedFunction=null,this.uv._storedValue=null;return}const e=P.Zero(),t=i=>{const r=this.position.getConnectedValue(i)||P.Zero(),s=this.normal.getConnectedValue(i)||P.Zero(),a=this.center.getConnectedValue(i),o=Be.Zero();switch(this.mapping){case Xp.Spherical:{r.subtractToRef(a,e);const c=e.length();c>0&&(o.x=Math.acos(e.y/c)/Math.PI,(e.x!==0||e.z!==0)&&(o.y=Math.atan2(e.x,e.z)/(Math.PI*2)));break}case Xp.Cylindrical:{r.subtractToRef(a,e);const c=e.length();c>0&&(o.x=Math.atan2(e.x/c,e.z/c)/(Math.PI*2),o.y=(e.y+1)/2);break}case Xp.Cubic:{const c=Math.abs(s.x),l=Math.abs(s.y),h=Math.abs(s.z),u=Math.max(Math.abs(r.x),Math.abs(r.y),Math.abs(r.z));let d=0,f=0;c>=l&&c>=h?(d=r.y/u-a.y,f=r.z/u-a.z):l>=c&&l>=h?(d=r.x/u-a.x,f=r.z/u-a.z):(d=r.x/u-a.x,f=r.y/u-a.y),o.x=(d+1)/2,o.y=(f+1)/2}}return o};this.uv._storedFunction=i=>t(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${Xp[this.mapping]}; `}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}B([Xt("Mapping",Gt.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:Xp.Spherical},{label:"Cylindrical",value:Xp.Cylindrical},{label:"Cubic",value:Xp.Cubic}]})],Ate.prototype,"mapping",void 0);xe("BABYLON.MappingBlock",Ate);class o4e extends vi{constructor(e){super(e),this.registerInput("matrix0",fe.Matrix),this.registerInput("matrix1",fe.Matrix),this.registerOutput("output",fe.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;const t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return!t||!i?null:t.multiply(i)}}}xe("BABYLON.MatrixComposeBlock",o4e);class l4e extends vi{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",fe.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const r of this.endpoints)t.indexOf(r)===-1&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this.endpoints){const i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);t!==-1&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=t=>this.input.getConnectedValue(t)}}xe("BABYLON.TeleportInBlock",l4e);class c4e extends vi{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",fe.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&t.indexOf(this.entryPoint)===-1&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){const e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); `),e}serialize(){var t;const e=super.serialize();return e.entryPoint=((t=this.entryPoint)==null?void 0:t.uniqueId)??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}xe("BABYLON.TeleportOutBlock",c4e);class Cte extends vi{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",fe.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{const r=new Image,s=document.createElement("canvas"),a=s.getContext("2d");r.onload=()=>{s.width=r.width,s.height=r.height,a.drawImage(r,0,0);const c=a.getImageData(0,0,r.width,r.height).data,l=new Float32Array(c.length);for(let h=0;h{this._data=null,i()},r.src=e})}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise((t,i)=>{if(!e.isReady()){e.onLoadObservable.addOnce(()=>this.extractFromTextureAsync(e).then(t).catch(i));return}const r=e.getSize();w2e.GetTextureDataAsync(e,r.width,r.height).then(async s=>{const a=new Float32Array(s.length);for(let o=0;o=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=t=>{const i=this.texture.getConnectedValue(t);if(!i||!i.data)return null;const r=this.coordinates.getConnectedValue(t);if(!r)return null;const s=this.clampCoordinates?Math.max(0,Math.min(r.x,1)):this._repeatClamp(r.x),a=this.clampCoordinates?Math.max(0,Math.min(r.y,1)):this._repeatClamp(r.y),o=Math.floor(s*(i.width-1)),c=Math.floor(a*(i.height-1)),l=o+i.width*c;return Ct.FromArray(i.data,l*4)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{const i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{const i=e(t);return i?i.x:null},this.g._storedFunction=t=>{const i=e(t);return i?i.y:null},this.b._storedFunction=t=>{const i=e(t);return i?i.z:null},this.a._storedFunction=t=>{const i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates}; `}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}B([Xt("Clamp Coordinates",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],bte.prototype,"clampCoordinates",void 0);xe("BABYLON.GeometryTextureFetchBlock",bte);class h4e extends vi{constructor(e){super(e),this.registerInput("geometry",fe.Geometry),this.registerOutput("min",fe.Vector3),this.registerOutput("max",fe.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?W8(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?W8(t.positions,0,t.positions.length/3).maximum:null}}}xe("BABYLON.BoundingBlock",h4e);var Yp;(function(n){n[n.Intersect=0]="Intersect",n[n.Subtract=1]="Subtract",n[n.Union=2]="Union"})(Yp||(Yp={}));class oK extends vi{constructor(e){super(e),this.evaluateContext=!1,this.operation=Yp.Intersect,this.registerInput("geometry0",fe.Geometry),this.registerInput("geometry1",fe.Geometry),this.registerOutput("output",fe.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{const r=this.geometry0.getConnectedValue(i),s=this.geometry1.getConnectedValue(i);if(!r||!s)return null;const a=r.positions.length/3;!r.normals&&s.normals&&(r.normals=new Array(r.positions.length)),!s.normals&&r.normals&&(s.normals=new Array(s.positions.length)),!r.uvs&&s.uvs&&(r.uvs=new Array(a*2)),!s.uvs&&r.uvs&&(s.uvs=new Array(a*2)),!r.colors&&s.colors&&(r.colors=new Array(a*4)),!s.colors&&r.colors&&(s.colors=new Array(a*4));const o=Vp.FromVertexData(r),c=Vp.FromVertexData(s);let l;switch(this.operation){case Yp.Intersect:l=o.intersect(c);break;case Yp.Subtract:l=o.subtract(c);break;case Yp.Union:l=o.union(c);break}return l.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${Yp[this.operation]}; `,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}B([Xt("Evaluate context",Gt.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],oK.prototype,"evaluateContext",void 0);B([Xt("Operation",Gt.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:Yp.Intersect},{label:"Subtract",value:Yp.Subtract},{label:"Union",value:Yp.Union}]})],oK.prototype,"operation",void 0);xe("BABYLON.BooleanGeometryBlock",oK);class u4e extends vi{constructor(e){super(e),this.registerInput("x",fe.AutoDetect),this.registerInput("y",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}getClassName(){return"GeometryArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.x.isConnected||!this.y.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>Math.atan2(t,i);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),r=this.y.getConnectedValue(t);switch(this.x.type){case fe.Int:case fe.Float:return e(i,r);case fe.Vector2:return new Be(e(i.x,r.x),e(i.y,r.y));case fe.Vector3:return new P(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z));case fe.Vector4:return new Ct(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z),e(i.w,r.w))}return 0}}}xe("BABYLON.GeometryArcTan2Block",u4e);class d4e extends vi{constructor(e){super(e),this.registerInput("left",fe.AutoDetect),this.registerInput("right",fe.AutoDetect),this.registerInput("gradient",fe.Float),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}getClassName(){return"GeometryLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i,r)=>(1-t)*i+t*r;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t),s=this.gradient.getConnectedValue(t);switch(this.left.type){case fe.Int:case fe.Float:return e(s,i,r);case fe.Vector2:return new Be(e(s,i.x,r.x),e(s,i.y,r.y));case fe.Vector3:return new P(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z));case fe.Vector4:return new Ct(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z),e(s,i.w,r.w))}return 0},this}}xe("BABYLON.GeometryLerpBlock",d4e);class f4e extends vi{constructor(e){super(e),this.registerInput("left",fe.AutoDetect),this.registerInput("right",fe.AutoDetect),this.registerInput("gradient",fe.Float),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}getClassName(){return"GeometryNLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i,r)=>(1-t)*i+t*r;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t),s=this.gradient.getConnectedValue(t);switch(this.left.type){case fe.Int:case fe.Float:return e(s,i,r);case fe.Vector2:{const a=new Be(e(s,i.x,r.x),e(s,i.y,r.y));return a.normalize(),a}case fe.Vector3:{const a=new P(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z));return a.normalize(),a}case fe.Vector4:{const a=new Ct(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z),e(s,i.w,r.w));return a.normalize(),a}}return 0},this}}xe("BABYLON.GeometryNLerpBlock",f4e);class p4e extends vi{constructor(e){super(e),this.registerInput("value",fe.AutoDetect),this.registerInput("edge",fe.Float),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}getClassName(){return"GeometryStepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>t{const i=this.value.getConnectedValue(t),r=this.edge.getConnectedValue(t);switch(this.value.type){case fe.Int:case fe.Float:return e(i,r);case fe.Vector2:return new Be(e(i.x,r),e(i.y,r));case fe.Vector3:return new P(e(i.x,r),e(i.y,r),e(i.z,r));case fe.Vector4:return new Ct(e(i.x,r),e(i.y,r),e(i.z,r),e(i.w,r))}return 0},this}}xe("BABYLON.GeometryStepBlock",p4e);class _4e extends vi{constructor(e){super(e),this.registerInput("value",fe.AutoDetect),this.registerInput("edge0",fe.Float),this.registerInput("edge1",fe.Float),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}getClassName(){return"GeometrySmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge0.isConnected||!this.edge1.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i,r)=>{const s=Math.max(0,Math.min((t-i)/(r-i),1));return s*s*(3-2*s)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),r=this.edge0.getConnectedValue(t),s=this.edge1.getConnectedValue(t);switch(this.value.type){case fe.Int:case fe.Float:return e(i,r,s);case fe.Vector2:return new Be(e(i.x,r,s),e(i.y,r,s));case fe.Vector3:return new P(e(i.x,r,s),e(i.y,r,s),e(i.z,r,s));case fe.Vector4:return new Ct(e(i.x,r,s),e(i.y,r,s),e(i.z,r,s),e(i.w,r,s))}return 0},this}}xe("BABYLON.GeometrySmoothStepBlock",_4e);class m4e extends vi{constructor(e){super(e),this.registerInput("left",fe.AutoDetect),this.registerInput("right",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}getClassName(){return"GeometryModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>t-Math.floor(t/i)*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t);switch(this.left.type){case fe.Int:case fe.Float:return e(i,r);case fe.Vector2:return new Be(e(i.x,r.x),e(i.y,r.y));case fe.Vector3:return new P(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z));case fe.Vector4:return new Ct(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z),e(i.w,r.w))}return 0},this}}xe("BABYLON.GeometryModBlock",m4e);class g4e extends vi{constructor(e){super(e),this.registerInput("value",fe.AutoDetect),this.registerInput("power",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}getClassName(){return"GeometryPowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.power.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>Math.pow(t,i);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),r=this.power.getConnectedValue(t);switch(this.value.type){case fe.Int:case fe.Float:return e(i,r);case fe.Vector2:return new Be(e(i.x,r),e(i.y,r));case fe.Vector3:return new P(e(i.x,r),e(i.y,r),e(i.z,r));case fe.Vector4:return new Ct(e(i.x,r),e(i.y,r),e(i.z,r),e(i.w,r))}return 0},this}}xe("BABYLON.GeometryPowBlock",g4e);class lK extends vi{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Geometry),this._inputs[0].excludedConnectionPointTypes.push(fe.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=t=>Math.max(this.minimum,Math.min(t,this.maximum));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t);switch(this.value.type){case fe.Int:case fe.Float:return e(i);case fe.Vector2:return new Be(e(i.x),e(i.y));case fe.Vector3:return new P(e(i.x),e(i.y),e(i.z));case fe.Vector4:return new Ct(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; `;return e+=`${this._codeVariableName}.maximum = ${this.maximum}; `,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e){super._deserialize(e),this.minimum=e.minimum,this.maximum=e.maximum}}B([Xt("Minimum",Gt.Float)],lK.prototype,"minimum",void 0);B([Xt("Maximum",Gt.Float)],lK.prototype,"maximum",void 0);xe("BABYLON.GeometryClampBlock",lK);class v4e extends vi{constructor(e){super(e),this.registerInput("left",fe.AutoDetect),this.registerInput("right",fe.AutoDetect),this.registerOutput("output",fe.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(fe.Int),this._inputs[0].excludedConnectionPointTypes.push(fe.Float),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Vector2),this._inputs[1].excludedConnectionPointTypes.push(fe.Int),this._inputs[1].excludedConnectionPointTypes.push(fe.Float),this._inputs[1].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[1].excludedConnectionPointTypes.push(fe.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case fe.Vector3:return P.Cross(t,i);case fe.Vector4:return P.Cross(t.toVector3(),i.toVector3())}return 0},this}}xe("BABYLON.GeometryCrossBlock",v4e);var qi;(function(n){n[n.EaseInSine=0]="EaseInSine",n[n.EaseOutSine=1]="EaseOutSine",n[n.EaseInOutSine=2]="EaseInOutSine",n[n.EaseInQuad=3]="EaseInQuad",n[n.EaseOutQuad=4]="EaseOutQuad",n[n.EaseInOutQuad=5]="EaseInOutQuad",n[n.EaseInCubic=6]="EaseInCubic",n[n.EaseOutCubic=7]="EaseOutCubic",n[n.EaseInOutCubic=8]="EaseInOutCubic",n[n.EaseInQuart=9]="EaseInQuart",n[n.EaseOutQuart=10]="EaseOutQuart",n[n.EaseInOutQuart=11]="EaseInOutQuart",n[n.EaseInQuint=12]="EaseInQuint",n[n.EaseOutQuint=13]="EaseOutQuint",n[n.EaseInOutQuint=14]="EaseInOutQuint",n[n.EaseInExpo=15]="EaseInExpo",n[n.EaseOutExpo=16]="EaseOutExpo",n[n.EaseInOutExpo=17]="EaseInOutExpo",n[n.EaseInCirc=18]="EaseInCirc",n[n.EaseOutCirc=19]="EaseOutCirc",n[n.EaseInOutCirc=20]="EaseInOutCirc",n[n.EaseInBack=21]="EaseInBack",n[n.EaseOutBack=22]="EaseOutBack",n[n.EaseInOutBack=23]="EaseInOutBack",n[n.EaseInElastic=24]="EaseInElastic",n[n.EaseOutElastic=25]="EaseOutElastic",n[n.EaseInOutElastic=26]="EaseInOutElastic"})(qi||(qi={}));class Ete extends vi{constructor(e){super(e),this.type=qi.EaseInOutSine,this.registerInput("input",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[0].excludedConnectionPointTypes.push(fe.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let e;switch(this.type){case qi.EaseInSine:e=t=>1-Math.cos(t*3.1415/2);break;case qi.EaseOutSine:e=t=>Math.sin(t*3.1415/2);break;case qi.EaseInOutSine:e=t=>-(Math.cos(t*3.1415)-1)/2;break;case qi.EaseInQuad:e=t=>t*t;break;case qi.EaseOutQuad:e=t=>(1-t)*(1-t);break;case qi.EaseInOutQuad:{e=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;break}case qi.EaseInCubic:e=t=>t*t*t;break;case qi.EaseOutCubic:{e=t=>1-Math.pow(1-t,3);break}case qi.EaseInOutCubic:{e=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;break}case qi.EaseInQuart:e=t=>t*t*t*t;break;case qi.EaseOutQuart:{e=t=>1-Math.pow(1-t,4);break}case qi.EaseInOutQuart:{e=t=>t<.5?8*t*t*t*t:1-Math.pow(-2*t+2,4)/2;break}case qi.EaseInQuint:e=t=>t*t*t*t*t;break;case qi.EaseOutQuint:{e=t=>1-Math.pow(1-t,5);break}case qi.EaseInOutQuint:{e=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;break}case qi.EaseInExpo:{e=t=>t===0?0:Math.pow(2,10*t-10);break}case qi.EaseOutExpo:{e=t=>t===1?1:1-Math.pow(2,-10*t);break}case qi.EaseInOutExpo:{e=t=>t===0?0:t===1?1:t<.5?Math.pow(2,20*t-10)/2:(2-Math.pow(2,-20*t+10))/2;break}case qi.EaseInCirc:{e=t=>1-Math.sqrt(1-Math.pow(t,2));break}case qi.EaseOutCirc:{e=t=>Math.sqrt(1-Math.pow(t-1,2));break}case qi.EaseInOutCirc:{e=t=>t<.5?(1-Math.sqrt(1-Math.pow(2*t,2)))/2:(Math.sqrt(1-Math.pow(-2*t+2,2))+1)/2;break}case qi.EaseInBack:{e=t=>2.70158*t*t*t-1.70158*t*t;break}case qi.EaseOutBack:{e=t=>2.70158*Math.pow(t-1,3)+1.70158*Math.pow(t-1,2);break}case qi.EaseInOutBack:{e=t=>t<.5?Math.pow(2*t,2)*(3.5949095*2*t-2.5949095)/2:(Math.pow(2*t-2,2)*(3.5949095*(t*2-2)+3.5949095)+2)/2;break}case qi.EaseInElastic:{e=t=>t===0?0:t===1?1:-Math.pow(2,10*t-10)*Math.sin((t*10-10.75)*(2*3.1415/3));break}case qi.EaseOutElastic:{e=t=>t===0?0:t===1?1:Math.pow(2,-10*t)*Math.sin((t*10-.75)*(2*3.1415/3))+1;break}case qi.EaseInOutElastic:{e=t=>t===0?0:t==1?1:t<.5?-(Math.pow(2,20*t-10)*Math.sin((20*t-11.125)*(2*3.1415/4.5)))/2:Math.pow(2,-20*t+10)*Math.sin((20*t-11.125)*(2*3.1415/4.5))/2+1;break}}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case fe.Float:return e(i);case fe.Vector2:return new Be(e(i.x),e(i.y));case fe.Vector3:return new P(e(i.x),e(i.y),e(i.z));case fe.Vector4:return new Ct(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e){super._deserialize(e),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${qi[this.type]}; `}}B([Xt("Type",Gt.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:qi.EaseInSine},{label:"EaseOutSine",value:qi.EaseOutSine},{label:"EaseInOutSine",value:qi.EaseInOutSine},{label:"EaseInQuad",value:qi.EaseInQuad},{label:"EaseOutQuad",value:qi.EaseOutQuad},{label:"EaseInOutQuad",value:qi.EaseInOutQuad},{label:"EaseInCubic",value:qi.EaseInCubic},{label:"EaseOutCubic",value:qi.EaseOutCubic},{label:"EaseInOutCubic",value:qi.EaseInOutCubic},{label:"EaseInQuart",value:qi.EaseInQuart},{label:"EaseOutQuart",value:qi.EaseOutQuart},{label:"EaseInOutQuart",value:qi.EaseInOutQuart},{label:"EaseInQuint",value:qi.EaseInQuint},{label:"EaseOutQuint",value:qi.EaseOutQuint},{label:"EaseInOutQuint",value:qi.EaseInOutQuint},{label:"EaseInExpo",value:qi.EaseInExpo},{label:"EaseOutExpo",value:qi.EaseOutExpo},{label:"EaseInOutExpo",value:qi.EaseInOutExpo},{label:"EaseInCirc",value:qi.EaseInCirc},{label:"EaseOutCirc",value:qi.EaseOutCirc},{label:"EaseInOutCirc",value:qi.EaseInOutCirc},{label:"EaseInBack",value:qi.EaseInBack},{label:"EaseOutBack",value:qi.EaseOutBack},{label:"EaseInOutBack",value:qi.EaseInOutBack},{label:"EaseInElastic",value:qi.EaseInElastic},{label:"EaseOutElastic",value:qi.EaseOutElastic},{label:"EaseInOutElastic",value:qi.EaseInOutElastic}]})],Ete.prototype,"type",void 0);xe("BABYLON.GeometryCurveBlock",Ete);class x4e extends vi{constructor(e){super(e),this.registerInput("color",fe.Vector3),this.registerInput("level",fe.Float,!0,0),this.registerOutput("output",fe.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.color.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),r=Math.min(t.x,t.y,t.z),s=Math.max(t.x,t.y,t.z),a=.5*(r+s);return new P(t.x*(1-i)+a*i,t.y*(1-i)+a*i,t.z*(1-i)+a*i)},this}}xe("BABYLON.GeometryDesaturateBlock",x4e);class y4e extends vi{constructor(e){super(e),this.registerInput("value",fe.AutoDetect),this.registerInput("steps",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[1].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(fe.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.steps.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let r=i;if(this.steps.type===fe.Float)switch(this.value.type){case fe.Vector2:r=new Be(i,i);break;case fe.Vector3:r=new P(i,i,i);break;case fe.Vector4:r=new Ct(i,i,i,i);break}switch(this.value.type){case fe.Vector2:return new Be(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y));case fe.Vector3:return new P(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y),t.z/(1/r.z)*(1/r.z));case fe.Vector4:return new Ct(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y),t.z/(1/r.z)*(1/r.z),t.w/(1/r.w)*(1/r.w));default:return Math.floor(t/(1/i)*(1/i))}},this}}xe("BABYLON.GeometryPosterizeBlock",y4e);class A4e extends vi{constructor(e){super(e),this.registerInput("value",fe.AutoDetect),this.registerInput("reference",fe.AutoDetect),this.registerInput("distance",fe.Float),this.registerInput("replacement",fe.AutoDetect),this.registerOutput("output",fe.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(fe.Float),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[1].excludedConnectionPointTypes.push(fe.Float),this._inputs[1].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[3].excludedConnectionPointTypes.push(fe.Float),this._inputs[3].excludedConnectionPointTypes.push(fe.Matrix)}getClassName(){return"GeometryReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.reference.isConnected||!this.distance.isConnected||!this.replacement.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),r=this.distance.getConnectedValue(e),s=this.replacement.getConnectedValue(e);return t.subtract(i).length(){const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this}}xe("BABYLON.GeometryDistanceBlock",C4e);class b4e extends vi{constructor(e){super(e),this.registerInput("left",fe.AutoDetect),this.registerInput("right",fe.AutoDetect),this.registerOutput("output",fe.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(fe.Float),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix),this._inputs[1].excludedConnectionPointTypes.push(fe.Float),this._inputs[1].excludedConnectionPointTypes.push(fe.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this}}xe("BABYLON.GeometryDotBlock",b4e);class E4e extends vi{constructor(e){super(e),this.registerInput("value",fe.AutoDetect),this.registerOutput("output",fe.Float),this._inputs[0].excludedConnectionPointTypes.push(fe.Float),this._inputs[0].excludedConnectionPointTypes.push(fe.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this}}xe("BABYLON.GeometryLengthBlock",E4e);class T4e extends vi{constructor(e){super(e),this.registerInput("input",fe.Vector2),this.registerInput("angle",fe.Float),this.registerOutput("output",fe.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.angle.isConnected||!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new Be(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this}}xe("BABYLON.GeometryRotate2dBlock",T4e);class j3 extends Se{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}constructor(e,t=null,i=null){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=ce.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null;const r=new et;r.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],r.indices=[0,1,2,0,2,3],r.applyToMesh(this),this.subMeshes=[],new Xo(0,0,4,0,6,this),this.doNotSyncBoundingInfo=!0,this.setEnabled(!1),this._lastProj=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t&&this.loadFileAsync(t)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}render(e,t,i){this.material||(this._material=new e5(this.name+"_material",this._scene),this.material=this._material);const r=this.getScene().getFrameId();if(r!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix);const s=this._lastProj[2]*this._modelViewMatrix.m[2]+this._lastProj[6]*this._modelViewMatrix.m[6]+this._lastProj[10]*this._modelViewMatrix.m[10];Math.abs(s-1)>=.01&&(this._frameIdLastUpdate=r,this._canPostToWorker=!1,this._lastProj=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix},[this._depthMix.buffer]))}return super.render(e,t,i)}static ConvertPLYToSplat(e){const t=new Uint8Array(e),i=new TextDecoder().decode(t.slice(0,1024*10)),r=`end_header `,s=i.indexOf(r);if(s<0||!i)return e;const a=parseInt(/element vertex (\d+)\n/.exec(i)[1]);let o=0;const c={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1},l=[],h=i.slice(0,s).split(` `).filter(m=>m.startsWith("property "));for(const m of h){const[,g,v]=m.split(" ");if(l.push({name:v,type:g,offset:o}),c[g])o+=c[g];else return de.Error(`Unsupported property type: ${g}. Are you sure it's a valid Gaussian Splatting file?`),new ArrayBuffer(0)}const u=3*4+3*4+4+4,d=.28209479177387814,f=new DataView(e,s+r.length),p=new ArrayBuffer(u*a),_=new we;for(let m=0;m{this._loadData(j3.ConvertPLYToSplat(t))})}dispose(e){var t,i,r,s,a,o;(t=this._covariancesATexture)==null||t.dispose(),(i=this._covariancesBTexture)==null||i.dispose(),(r=this._centersTexture)==null||r.dispose(),(s=this._colorsTexture)==null||s.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,(a=this._material)==null||a.dispose(!1,!0),this._material=null,(o=this._worker)==null||o.terminate(),this._worker=null,super.dispose(e)}_loadData(e){var C;if(!e.byteLength)return;const t=new Uint8Array(e),i=new Float32Array(t.buffer),r=3*4+3*4+4+4,s=t.length/r;this._vertexCount=s;const a=this._getTextureSize(s),o=a.x*a.y,c=new Float32Array(3*o),l=new Float32Array(3*o),h=new Float32Array(3*o),u=ie.Matrix[0],d=ie.Matrix[1],f=ie.Quaternion[0],p=new P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),_=new P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let b=0;bnew $s(b,T,S,N,this._scene,!1,!1,2,1),x=b=>{const T=b.length/3,S=new Float32Array(T*4);for(let N=0;N{this._depthMix=b.data.depthMix;const T=new Uint32Array(b.data.depthMix.buffer);for(let S=0;Si&&(de.Error("GaussianSplatting texture size: ("+i+", "+r+"), maxTextureSize: "+i),r=i),new Be(i,r)}}j3._CreateWorker=function(n){let e=0,t,i,r,s;n.onmessage=a=>{if(a.data.positions)t=a.data.positions,e=a.data.vertexCount;else{const o=a.data.view;if(!t||!o)throw new Error("positions or view is not defined!");i=a.data.depthMix,r=new Uint32Array(i.buffer),s=new Float32Array(i.buffer);for(let c=0;c{this.update(r.getEngine().getDeltaTime()*.001*e.timeFactor)})}addAgent(e,t,i){const r=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;r.radius=t.radius,r.height=t.height,r.maxAcceleration=t.maxAcceleration,r.maxSpeed=t.maxSpeed,r.collisionQueryRange=t.collisionQueryRange,r.pathOptimizationRange=t.pathOptimizationRange,r.separationWeight=t.separationWeight,r.updateFlags=7,r.obstacleAvoidanceType=0,r.queryFilterType=0,r.userData=0;const s=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),r);return this.transforms.push(i),this.agents.push(s),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new P(0,0,0)),s}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new P(t.x,t.y,t.z)}getAgentPositionToRef(e,t){const i=this.recastCrowd.getAgentPosition(e);t.set(i.x,i.y,i.z)}getAgentVelocity(e){const t=this.recastCrowd.getAgentVelocity(e);return new P(t.x,t.y,t.z)}getAgentVelocityToRef(e,t){const i=this.recastCrowd.getAgentVelocity(e);t.set(i.x,i.y,i.z)}getAgentNextTargetPath(e){const t=this.recastCrowd.getAgentNextTargetPath(e);return new P(t.x,t.y,t.z)}getAgentNextTargetPathToRef(e,t){const i=this.recastCrowd.getAgentNextTargetPath(e);t.set(i.x,i.y,i.z)}getAgentState(e){return this.recastCrowd.getAgentState(e)}overOffmeshConnection(e){return this.recastCrowd.overOffmeshConnection(e)}agentGoto(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z));const i=this.agents.indexOf(e);i>-1&&(this._agentDestinationArmed[i]=!0,this._agentDestination[i].set(t.x,t.y,t.z))}agentTeleport(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))}updateAgentParameters(e,t){const i=this.recastCrowd.getAgentParameters(e);t.radius!==void 0&&(i.radius=t.radius),t.height!==void 0&&(i.height=t.height),t.maxAcceleration!==void 0&&(i.maxAcceleration=t.maxAcceleration),t.maxSpeed!==void 0&&(i.maxSpeed=t.maxSpeed),t.collisionQueryRange!==void 0&&(i.collisionQueryRange=t.collisionQueryRange),t.pathOptimizationRange!==void 0&&(i.pathOptimizationRange=t.pathOptimizationRange),t.separationWeight!==void 0&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)}removeAgent(e){this.recastCrowd.removeAgent(e);const t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1),this.reachRadii.splice(t,1),this._agentDestinationArmed.splice(t,1),this._agentDestination.splice(t,1))}getAgents(){return this.agents}update(e){if(this.bjsRECASTPlugin.navMesh.update(),e<=ni)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=ni)this.recastCrowd.update(e);else{let r=Math.floor(e/t);i&&r>i&&(r=i),r<1&&(r=1);const s=e/r;for(let a=0;ah&&a.ynew Lc(n,e,t);class Lc{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory=typeof indexedDB<"u"?indexedDB:void 0,this._currentSceneUrl=Lc._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,Lc.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Ee.SetImmediate(()=>{t(!0)})):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if(typeof URL=="function"&&this._currentSceneUrl.indexOf("http")===0){const o=new URL(this._currentSceneUrl);return o.pathname+=".manifest",o.toString()}}catch{}return`${this._currentSceneUrl}.manifest`};let r=!1,s=i();const a=new on;navigator.onLine&&(r=!0,s=s+(s.match(/\?/)==null?"?":"&")+Date.now()),a.open("GET",s),a.addEventListener("load",()=>{if(a.status===200||Lc._ValidateXHRData(a,1))try{const o=JSON.parse(a.response);this._enableSceneOffline=o.enableSceneOffline,this._enableTexturesOffline=o.enableTexturesOffline&&Lc._IsUASupportingBlobStorage,o.version&&!isNaN(parseInt(o.version))&&(this._manifestVersionFound=o.version),e(!0)}catch{t()}else t()},!1),a.addEventListener("error",()=>{if(r){r=!1;const o=i();a.open("GET",o),a.send()}else t()},!1);try{a.send()}catch{de.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(!this._idbFactory||!(this._enableSceneOffline||this._enableTexturesOffline))this._isSupported=!1,t&&t();else if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const r=this._idbFactory.open("babylonjs",1);r.onerror=()=>{i()},r.onblocked=()=>{de.Error("IDB request blocked. Please reload the page."),i()},r.onsuccess=()=>{this._db=r.result,e()},r.onupgradeneeded=s=>{if(this._db=s.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(a){de.Error("Error while creating object stores. Exception: "+a.message),i()}}}}loadImage(e,t){const i=Lc._ReturnFullUrlLocation(e),r=()=>{!this._hasReachedQuota&&this._db!==null?this._saveImageIntoDBAsync(i,t):t.src=e};this._mustUpdateRessources?r():this._loadImageFromDBAsync(i,t,r)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&this._db!==null){let r;const s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let o;r&&typeof URL=="function"?(o=URL.createObjectURL(r.data),t.onerror=()=>{de.Error("Error loading image from blob URL: "+o+" switching back to web url: "+e),t.src=e},t.src=o):i()};const a=s.objectStore("textures").get(e);a.onsuccess=o=>{r=o.target.result},a.onerror=()=>{de.Error("Error loading texture "+e+" from DB."),t.src=e}}else de.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const r=()=>{let s;if(i&&typeof URL=="function")try{s=URL.createObjectURL(i)}catch{s=URL.createObjectURL(i)}s&&(t.src=s)};if(Lc._IsUASupportingBlobStorage){const s=new on;s.open("GET",e),s.responseType="blob",s.addEventListener("load",()=>{if(s.status===200&&this._db){i=s.response;const a=this._db.transaction(["textures"],"readwrite");a.onabort=c=>{try{const h=c.target.error;h&&h.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}r()},a.oncomplete=()=>{r()};const o={textureUrl:e,data:i};try{const c=a.objectStore("textures").put(o);c.onsuccess=()=>{},c.onerror=()=>{r()}}catch(c){c.code===25&&(Lc._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),s.addEventListener("error",()=>{de.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),s.send()}else t.src=e}else de.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){const i=()=>{this._saveVersionIntoDBAsync(e,t)};this._loadVersionFromDBAsync(e,t,i)}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let r;try{const s=this._db.transaction(["versions"]);s.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};const a=s.objectStore("versions").get(e);a.onsuccess=o=>{r=o.target.result},a.onerror=()=>{de.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(s){de.Error("Error while accessing 'versions' object store (READ OP). Exception: "+s.message),t(-1)}}else de.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=a=>{try{const o=a.target.error;o&&o.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const r={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(r);s.onsuccess=()=>{},s.onerror=()=>{de.Error("Error in DB add version request in BABYLON.Database.")}}catch(i){de.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+i.message),t(-1)}else t(-1)}loadFile(e,t,i,r,s){const a=Lc._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(a,t,i,s,r)};this._checkVersionFromDB(a,c=>{c!==-1?this._mustUpdateRessources?this._saveFileAsync(a,t,i,s,r):this._loadFileAsync(a,t,o):r&&r()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let r;e.indexOf(".babylon")!==-1?r="scenes":r="textures";let s;const a=this._db.transaction([r]);a.oncomplete=()=>{s?t(s.data):i()},a.onabort=()=>{i()};const o=a.objectStore(r).get(e);o.onsuccess=c=>{s=c.target.result},o.onerror=()=>{de.Error("Error loading file "+e+" from DB."),i()}}else de.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,s){if(this._isSupported){let a;e.indexOf(".babylon")!==-1?a="scenes":a="textures";const o=new on;let c;o.open("GET",e+(e.match(/\?/)==null?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(o.status===200||o.status<400&&Lc._ValidateXHRData(o,r?6:1))if(c=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){const l=this._db.transaction([a],"readwrite");l.onabort=u=>{try{const d=u.target.error;d&&d.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}t(c)},l.oncomplete=()=>{t(c)};let h;a==="scenes"?h={sceneUrl:e,data:c,version:this._manifestVersionFound}:h={textureUrl:e,data:c};try{const u=l.objectStore(a).put(h);u.onsuccess=()=>{},u.onerror=()=>{de.Error("Error in DB add file request in BABYLON.Database.")}}catch{t(c)}}else t(c);else o.status>=400&&s?s(o):t()},!1),o.addEventListener("error",()=>{de.Error("error on XHR request."),s&&s()},!1),o.send()}else de.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}static _ValidateXHRData(e,t=7){try{if(t&1){if(e.responseText&&e.responseText.length>0)return!0;if(t===1)return!1}if(t&2){const i=b9(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(t===2)return!1}if(t&4){const i=new Uint8Array(e.response,0,3);return i[0]===68&&i[1]===68&&i[2]===83}}catch{}return!1}}Lc._IsUASupportingBlobStorage=!0;Lc.IDBStorageEnabled=!1;Lc._ParseURL=n=>{const e=document.createElement("a");e.href=n;const t=n.substring(0,n.lastIndexOf("#")),i=n.substring(t.lastIndexOf("/")+1,n.length);return n.substring(0,n.indexOf(i,0))};Lc._ReturnFullUrlLocation=n=>n.indexOf("http:/")===-1&&n.indexOf("https:/")===-1&&typeof window<"u"?Lc._ParseURL(window.location.href)+n:n;class Gm{constructor(){this.direction1=new P(0,1,0),this.direction2=new P(0,1,0),this.minEmitBox=new P(-.5,-.5,-.5),this.maxEmitBox=new P(.5,.5,.5)}startDirectionFunction(e,t,i,r){const s=Xr(this.direction1.x,this.direction2.x),a=Xr(this.direction1.y,this.direction2.y),o=Xr(this.direction1.z,this.direction2.z);if(r){t.x=s,t.y=a,t.z=o;return}P.TransformNormalFromFloatsToRef(s,a,o,e,t)}startPositionFunction(e,t,i,r){const s=Xr(this.minEmitBox.x,this.maxEmitBox.x),a=Xr(this.minEmitBox.y,this.maxEmitBox.y),o=Xr(this.minEmitBox.z,this.maxEmitBox.z);if(r){t.x=s,t.y=a,t.z=o;return}P.TransformCoordinatesFromFloatsToRef(s,a,o,e,t)}clone(){const e=new Gm;return ol.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){P.FromArrayToRef(e.direction1,0,this.direction1),P.FromArrayToRef(e.direction2,0,this.direction2),P.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),P.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class M9{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){this._angle!==0?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?ie.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),ie.Vector3[0]).normalize();const s=_t.RandomRange(0,this.directionRandomizer),a=_t.RandomRange(0,this.directionRandomizer),o=_t.RandomRange(0,this.directionRandomizer);t.x=ie.Vector3[0].x+s,t.y=ie.Vector3[0].y+a,t.z=ie.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,r){const s=_t.RandomRange(0,Math.PI*2);let a;this.emitFromSpawnPointOnly?a=1e-4:(a=_t.RandomRange(0,this.heightRange),a=1-a*a);let o=this._radius-_t.RandomRange(0,this._radius*this.radiusRange);o=o*a;const c=o*Math.sin(s),l=o*Math.cos(s),h=a*this._height;if(r){t.x=c,t.y=h,t.z=l;return}P.TransformCoordinatesFromFloatsToRef(c,h,l,e,t)}clone(){const e=new M9(this._radius,this._angle,this.directionRandomizer);return ol.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+=` #define CONEEMITTERSPAWNPOINT`),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=e.radiusRange!==void 0?e.radiusRange:1,this.heightRange=e.radiusRange!==void 0?e.heightRange:1,this.emitFromSpawnPointOnly=e.emitFromSpawnPointOnly!==void 0?e.emitFromSpawnPointOnly:!1}}class H5{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=P.Zero()}startDirectionFunction(e,t,i,r,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),P.TransformNormalToRef(this._tempVector,s,this._tempVector);const a=_t.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);if(o+=_t.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=a,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),r){t.copyFrom(this._tempVector);return}P.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){const s=_t.RandomRange(-this.height/2,this.height/2),a=_t.RandomRange(0,2*Math.PI),o=_t.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),c=Math.sqrt(o)*this.radius,l=c*Math.cos(a),h=c*Math.sin(a);if(r){t.copyFromFloats(l,s,h);return}P.TransformCoordinatesFromFloatsToRef(l,s,h,e,t)}clone(){const e=new H5(this.radius,this.directionRandomizer);return ol.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class R9 extends H5{constructor(e=1,t=1,i=1,r=new P(0,1,0),s=new P(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=s}startDirectionFunction(e,t,i,r){const s=_t.RandomRange(this.direction1.x,this.direction2.x),a=_t.RandomRange(this.direction1.y,this.direction2.y),o=_t.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,a,o);return}P.TransformNormalFromFloatsToRef(s,a,o,e,t)}clone(){const e=new R9(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return ol.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return`#define CYLINDEREMITTER #define DIRECTEDCYLINDEREMITTER`}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class I9{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){const s=i.position.subtract(e.getTranslation()).normalize(),a=_t.RandomRange(0,this.directionRandomizer),o=_t.RandomRange(0,this.directionRandomizer),c=_t.RandomRange(0,this.directionRandomizer);if(s.x+=a,s.y+=o,s.z+=c,s.normalize(),r){t.copyFrom(s);return}P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){const s=this.radius-_t.RandomRange(0,this.radius*this.radiusRange),a=_t.RandomRange(0,1),o=_t.RandomRange(0,2*Math.PI),c=Math.acos(2*a-1),l=s*Math.cos(o)*Math.sin(c),h=s*Math.cos(c),u=s*Math.sin(o)*Math.sin(c);if(r){t.copyFromFloats(l,Math.abs(h),u);return}P.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),u,e,t)}clone(){const e=new I9(this.radius,this.directionRandomizer);return ol.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class P9{constructor(){this.direction1=new P(0,1,0),this.direction2=new P(0,1,0)}startDirectionFunction(e,t,i,r){const s=_t.RandomRange(this.direction1.x,this.direction2.x),a=_t.RandomRange(this.direction1.y,this.direction2.y),o=_t.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,a,o);return}P.TransformNormalFromFloatsToRef(s,a,o,e,t)}startPositionFunction(e,t,i,r){if(r){t.copyFromFloats(0,0,0);return}P.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new P9;return ol.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){P.FromArrayToRef(e.direction1,0,this.direction1),P.FromArrayToRef(e.direction2,0,this.direction2)}}class G5{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){const s=i.position.subtract(e.getTranslation()).normalize(),a=_t.RandomRange(0,this.directionRandomizer),o=_t.RandomRange(0,this.directionRandomizer),c=_t.RandomRange(0,this.directionRandomizer);if(s.x+=a,s.y+=o,s.z+=c,s.normalize(),r){t.copyFrom(s);return}P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){const s=this.radius-_t.RandomRange(0,this.radius*this.radiusRange),a=_t.RandomRange(0,1),o=_t.RandomRange(0,2*Math.PI),c=Math.acos(2*a-1),l=s*Math.cos(o)*Math.sin(c),h=s*Math.cos(c),u=s*Math.sin(o)*Math.sin(c);if(r){t.copyFromFloats(l,h,u);return}P.TransformCoordinatesFromFloatsToRef(l,h,u,e,t)}clone(){const e=new G5(this.radius,this.directionRandomizer);return ol.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class w9 extends G5{constructor(e=1,t=new P(0,1,0),i=new P(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=_t.RandomRange(this.direction1.x,this.direction2.x),r=_t.RandomRange(this.direction1.y,this.direction2.y),s=_t.RandomRange(this.direction1.z,this.direction2.z);P.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){const e=new w9(this.radius,this.direction1,this.direction2);return ol.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return`#define SPHEREEMITTER #define DIRECTEDSPHEREEMITTER`}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class Km{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){const s=ie.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);const a=ie.Vector3[1];s.subtractToRef(i.position,a),a.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);if(r){t.copyFrom(s);return}P.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,r){const s=ie.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),r){t.copyFrom(s);return}P.TransformCoordinatesToRef(s,e,t)}clone(){const e=new Km;return ol.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.particlePositionGenerator=this.particlePositionGenerator,e.particleDestinationGenerator=this.particleDestinationGenerator,e}parse(e){e.particlePositionGenerator&&(this.particlePositionGenerator=e.particlePositionGenerator),e.particleDestinationGenerator&&(this.particleDestinationGenerator=e.particleDestinationGenerator)}}class cK{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(Z.PositionKind),this._normals=e.getVerticesData(Z.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=P.Zero(),this._mesh=null,this.direction1=new P(0,1,0),this.direction2=new P(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals){P.TransformNormalToRef(this._storedNormal,e,t);return}const s=_t.RandomRange(this.direction1.x,this.direction2.x),a=_t.RandomRange(this.direction1.y,this.direction2.y),o=_t.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,a,o);return}P.TransformNormalFromFloatsToRef(s,a,o,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;const s=3*Math.random()*(this._indices.length/3)|0,a=Math.random(),o=Math.random()*(1-a),c=1-a-o,l=this._indices[s],h=this._indices[s+1],u=this._indices[s+2],d=ie.Vector3[0],f=ie.Vector3[1],p=ie.Vector3[2],_=ie.Vector3[3];P.FromArrayToRef(this._positions,l*3,d),P.FromArrayToRef(this._positions,h*3,f),P.FromArrayToRef(this._positions,u*3,p),_.x=a*d.x+o*f.x+c*p.x,_.y=a*d.y+o*f.y+c*p.y,_.z=a*d.z+o*f.z+c*p.z,r?t.copyFromFloats(_.x,_.y,_.z):P.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(P.FromArrayToRef(this._normals,l*3,d),P.FromArrayToRef(this._normals,h*3,f),P.FromArrayToRef(this._normals,u*3,p),this._storedNormal.x=a*d.x+o*f.x+c*p.x,this._storedNormal.y=a*d.y+o*f.y+c*p.y,this._storedNormal.z=a*d.z+o*f.z+c*p.z)}clone(){const e=new cK(this.mesh);return ol.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var t;const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=(t=this.mesh)==null?void 0:t.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){P.FromArrayToRef(e.direction1,0,this.direction1),P.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class M4e{_isUbo(e){return e.addUniform!==void 0}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}const ZBe="gpuUpdateParticlesPixelShader",qBe=`#version 300 es void main() {discard;} `;Re.ShadersStore[ZBe]=qBe;const JBe="gpuUpdateParticlesVertexShader",eFe=`#version 300 es #define PI 3.14159 uniform float currentCount;uniform float timeDelta;uniform float stopFactor; #ifndef LOCAL uniform mat4 emitterWM; #endif uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; #ifndef COLORGRADIENTS uniform vec4 color1;uniform vec4 color2; #endif uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; #ifdef BOXEMITTER uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; #endif #ifdef POINTEMITTER uniform vec3 direction1;uniform vec3 direction2; #endif #ifdef HEMISPHERICEMITTER uniform float radius;uniform float radiusRange;uniform float directionRandomizer; #endif #ifdef SPHEREEMITTER uniform float radius;uniform float radiusRange; #ifdef DIRECTEDSPHEREEMITTER uniform vec3 direction1;uniform vec3 direction2; #else uniform float directionRandomizer; #endif #endif #ifdef CYLINDEREMITTER uniform float radius;uniform float height;uniform float radiusRange; #ifdef DIRECTEDCYLINDEREMITTER uniform vec3 direction1;uniform vec3 direction2; #else uniform float directionRandomizer; #endif #endif #ifdef CONEEMITTER uniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer; #endif in vec3 position; #ifdef CUSTOMEMITTER in vec3 initialPosition; #endif in float age;in float life;in vec4 seed;in vec3 size; #ifndef COLORGRADIENTS in vec4 color; #endif in vec3 direction; #ifndef BILLBOARD in vec3 initialDirection; #endif #ifdef ANGULARSPEEDGRADIENTS in float angle; #else in vec2 angle; #endif #ifdef ANIMATESHEET in float cellIndex; #ifdef ANIMATESHEETRANDOMSTART in float cellStartOffset; #endif #endif #ifdef NOISE in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; #endif out vec3 outPosition; #ifdef CUSTOMEMITTER out vec3 outInitialPosition; #endif out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; #ifndef COLORGRADIENTS out vec4 outColor; #endif out vec3 outDirection; #ifndef BILLBOARD out vec3 outInitialDirection; #endif #ifdef ANGULARSPEEDGRADIENTS out float outAngle; #else out vec2 outAngle; #endif #ifdef ANIMATESHEET out float outCellIndex; #ifdef ANIMATESHEETRANDOMSTART out float outCellStartOffset; #endif #endif #ifdef NOISE out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; #endif #ifdef SIZEGRADIENTS uniform sampler2D sizeGradientSampler; #endif #ifdef ANGULARSPEEDGRADIENTS uniform sampler2D angularSpeedGradientSampler; #endif #ifdef VELOCITYGRADIENTS uniform sampler2D velocityGradientSampler; #endif #ifdef LIMITVELOCITYGRADIENTS uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; #endif #ifdef DRAGGRADIENTS uniform sampler2D dragGradientSampler; #endif #ifdef NOISE uniform vec3 noiseStrength;uniform sampler2D noiseSampler; #endif #ifdef ANIMATESHEET uniform vec4 cellInfos; #endif vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} void main() {float newAge=age+timeDelta; if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; #ifdef SIZEGRADIENTS outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; #else outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; #endif outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; #ifndef COLORGRADIENTS outColor=color1+(color2-color1)*randoms.b; #endif #ifndef ANGULARSPEEDGRADIENTS outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; #else outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; #endif #ifdef POINTEMITTER vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; #elif defined(BOXEMITTER) vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; #elif defined(HEMISPHERICEMITTER) vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; #elif defined(SPHEREEMITTER) vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); #ifdef DIRECTEDSPHEREEMITTER newDirection=normalize(direction1+(direction2-direction1)*randoms3); #else newDirection=normalize(newPosition+directionRandomizer*randoms3); #endif #elif defined(CYLINDEREMITTER) vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); #ifdef DIRECTEDCYLINDEREMITTER newDirection=direction1+(direction2-direction1)*randoms3; #else angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); #endif #elif defined(CONEEMITTER) vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; #ifdef CONEEMITTERSPAWNPOINT float h=0.0001; #else float h=randoms2.y*height.y;h=1.-h*h; #endif float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); } #elif defined(CUSTOMEMITTER) newPosition=initialPosition;outInitialPosition=initialPosition; #else newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); #endif float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; #ifdef LOCAL outPosition=newPosition; #else outPosition=(emitterWM*vec4(newPosition,1.)).xyz; #endif #ifdef CUSTOMEMITTER outDirection=direction; #ifndef BILLBOARD outInitialDirection=direction; #endif #else #ifdef LOCAL vec3 initial=newDirection; #else vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; #endif outDirection=initial*power; #ifndef BILLBOARD outInitialDirection=initial; #endif #endif #ifdef ANIMATESHEET outCellIndex=cellInfos.x; #ifdef ANIMATESHEETRANDOMSTART outCellStartOffset=randoms.a*outLife; #endif #endif #ifdef NOISE outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; #endif } else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; #ifdef VELOCITYGRADIENTS directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; #endif #ifdef DRAGGRADIENTS directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; #endif #if defined(CUSTOMEMITTER) outPosition=position+(direction-position)*ageGradient; outInitialPosition=initialPosition; #else outPosition=position+direction*directionScale; #endif outLife=life;outSeed=seed; #ifndef COLORGRADIENTS outColor=color; #endif #ifdef SIZEGRADIENTS outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; #else outSize=size; #endif #ifndef BILLBOARD outInitialDirection=initialDirection; #endif #ifdef CUSTOMEMITTER outDirection=direction; #else vec3 updatedDirection=direction+gravity*timeDelta; #ifdef LIMITVELOCITYGRADIENTS float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} #endif outDirection=updatedDirection; #ifdef NOISE float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; #endif #endif #ifdef ANGULARSPEEDGRADIENTS float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; #else outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); #endif #ifdef ANIMATESHEET float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; #ifdef ANIMATESHEETRANDOMSTART outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; #else float cellStartOffset=0.; #endif float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} outCellIndex=float(int(cellInfos.x+ratio*dist)); #endif }}`;Re.ShadersStore[JBe]=eFe;class R4e{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e;return((e=this._updateEffect)==null?void 0:e.isReady())??!1}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof Km&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new bi("gpuUpdateParticles",this._updateEffectOptions,this._engine),new M4e(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e, age : f32, size : vec3, life : f32, seed : vec4, direction : vec3, dummy0: f32, #ifdef CUSTOMEMITTER initialPosition : vec3, dummy1: f32, #endif #ifndef COLORGRADIENTS color : vec4, #endif #ifndef BILLBOARD initialDirection : vec3, dummy2: f32, #endif #ifdef NOISE noiseCoordinates1 : vec3, dummy3: f32, noiseCoordinates2 : vec3, dummy4: f32, #endif #ifdef ANGULARSPEEDGRADIENTS angle : f32, #else angle : vec2, #endif #ifdef ANIMATESHEET cellIndex : f32, #ifdef ANIMATESHEETRANDOMSTART cellStartOffset : f32, #endif #endif };struct Particles {particles : array,};struct SimParams {currentCount : f32, timeDelta : f32, stopFactor : f32, randomTextureSize: i32, lifeTime : vec2, emitPower : vec2, #ifndef COLORGRADIENTS color1 : vec4, color2 : vec4, #endif sizeRange : vec2, scaleRange : vec4, angleRange : vec4, gravity : vec3, #ifdef LIMITVELOCITYGRADIENTS limitVelocityDamping : f32, #endif #ifdef ANIMATESHEET cellInfos : vec4, #endif #ifdef NOISE noiseStrength : vec3, #endif #ifndef LOCAL emitterWM : mat4x4, #endif #ifdef BOXEMITTER direction1 : vec3, direction2 : vec3, minEmitBox : vec3, maxEmitBox : vec3, #endif #ifdef CONEEMITTER radius : vec2, coneAngle : f32, height : vec2, directionRandomizer : f32, #endif #ifdef CYLINDEREMITTER radius : f32, height : f32, radiusRange : f32, #ifdef DIRECTEDCYLINDEREMITTER direction1 : vec3, direction2 : vec3, #else directionRandomizer : f32, #endif #endif #ifdef HEMISPHERICEMITTER radius : f32, radiusRange : f32, directionRandomizer : f32, #endif #ifdef POINTEMITTER direction1 : vec3, direction2 : vec3, #endif #ifdef SPHEREEMITTER radius : f32, radiusRange : f32, #ifdef DIRECTEDSPHEREEMITTER direction1 : vec3, direction2 : vec3, #else directionRandomizer : f32, #endif #endif };@binding(0) @group(0) var params : SimParams;@binding(1) @group(0) var particlesIn : Particles;@binding(2) @group(0) var particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d;@binding(4) @group(0) var randomTexture2 : texture_2d; #ifdef SIZEGRADIENTS @binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d; #endif #ifdef ANGULARSPEEDGRADIENTS @binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d; #endif #ifdef VELOCITYGRADIENTS @binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d; #endif #ifdef LIMITVELOCITYGRADIENTS @binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d; #endif #ifdef DRAGGRADIENTS @binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d; #endif #ifdef NOISE @binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d; #endif fn getRandomVec3(offset : f32,vertexID : f32)->vec3 {return textureLoad(randomTexture2,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} fn getRandomVec4(offset : f32,vertexID : f32)->vec4 {return textureLoad(randomTexture,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4=particlesIn.particles[index].seed;let direction : vec3=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3;var newDirection : vec3;let randoms : vec4=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; #ifdef SIZEGRADIENTS sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(0.,0.),0.).r; #else sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; #endif particlesOut.particles[index].size=vec3( sizex, params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); #ifndef COLORGRADIENTS particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; #endif #ifndef ANGULARSPEEDGRADIENTS particlesOut.particles[index].angle=vec2( params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); #else particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; #endif #if defined(POINTEMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=vec3(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; #elif defined(BOXEMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; #elif defined(HEMISPHERICEMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); #elif defined(SPHEREEMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,randY,randZ); #ifdef DIRECTEDSPHEREEMITTER newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); #else newDirection=normalize(newPosition+params.directionRandomizer*randoms3); #endif #elif defined(CYLINDEREMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); #ifdef DIRECTEDCYLINDEREMITTER newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; #else angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); #endif #elif defined(CONEEMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; #ifdef CONEEMITTERSPAWNPOINT let h : f32=0.0001; #else var h : f32=randoms2.y*params.height.y;h=1.-h*h; #endif var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3(randX,randY,randZ); if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } #elif defined(CUSTOMEMITTER) newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; #else newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3(0.5,0.5,0.5)); #endif let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; #ifdef LOCAL particlesOut.particles[index].position=newPosition; #else particlesOut.particles[index].position=(params.emitterWM*vec4(newPosition,1.)).xyz; #endif #ifdef CUSTOMEMITTER particlesOut.particles[index].direction=direction; #ifndef BILLBOARD particlesOut.particles[index].initialDirection=direction; #endif #else #ifdef LOCAL let initial : vec3=newDirection; #else let initial : vec3=(params.emitterWM*vec4(newDirection,0.)).xyz; #endif particlesOut.particles[index].direction=initial*power; #ifndef BILLBOARD particlesOut.particles[index].initialDirection=initial; #endif #endif #ifdef ANIMATESHEET particlesOut.particles[index].cellIndex=params.cellInfos.x; #ifdef ANIMATESHEETRANDOMSTART particlesOut.particles[index].cellStartOffset=randoms.a*outLife; #endif #endif #ifdef NOISE particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; #endif } else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; #ifdef VELOCITYGRADIENTS directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2(ageGradient,0.),0.).r; #endif #ifdef DRAGGRADIENTS directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2(ageGradient,0.),0.).r); #endif let position : vec3=particlesIn.particles[index].position; #if defined(CUSTOMEMITTER) particlesOut.particles[index].position=position+(direction-position)*ageGradient; particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; #else particlesOut.particles[index].position=position+direction*directionScale; #endif particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; #ifndef COLORGRADIENTS particlesOut.particles[index].color=particlesIn.particles[index].color; #endif #ifdef SIZEGRADIENTS particlesOut.particles[index].size=vec3( textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(ageGradient,0.),0.).r, particlesIn.particles[index].size.yz); #else particlesOut.particles[index].size=particlesIn.particles[index].size; #endif #ifndef BILLBOARD particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; #endif #ifdef CUSTOMEMITTER particlesOut.particles[index].direction=direction; #else var updatedDirection : vec3=direction+params.gravity*timeDelta; #ifdef LIMITVELOCITYGRADIENTS let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} #endif particlesOut.particles[index].direction=updatedDirection; #ifdef NOISE let noiseCoordinates1 : vec3=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let force : vec3=vec3(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; #endif #endif #ifdef ANGULARSPEEDGRADIENTS let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; #else let angle : vec2=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2(angle.x+angle.y*timeDelta,angle.y); #endif #ifdef ANIMATESHEET var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; #ifdef ANIMATESHEETRANDOMSTART let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; #else let cellStartOffset : f32=0.; #endif var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); #endif }} `;Re.ShadersStoreWGSL[tFe]=iFe;class I4e{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}contextLost(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e;return((e=this._updateComputeShader)==null?void 0:e.isReady())??!1}createUpdateBuffer(e){var i;const t={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(t.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(t.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(t.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(t.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(t.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(t.noiseTexture={group:1,binding:11}),this._updateComputeShader=new Vm("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:t,defines:e.split(` `)}),(i=this._simParamsComputeShader)==null||i.dispose(),this._simParamsComputeShader=new Ft(this._engine,void 0,void 0,"ComputeShaderParticleSystemUBO"),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new M4e(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){const t=new Vme(this._engine,e.length*4,11,"ComputeShaderParticleSystemBuffer");return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)}preUpdateParticleBuffer(){}updateParticleBuffer(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[e^1]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let t=0;te){i(t[0],t[0],1);return}for(let s=0;s=a.gradient&&e<=o.gradient){const c=(e-a.gradient)/(o.gradient-a.gradient);i(a,o,c);return}}const r=t.length-1;i(t[r],t[r],1)}}class s5{constructor(e){this.particleSystem=e,this.position=P.Zero(),this.direction=P.Zero(),this.color=new Ze(0,0,0,0),this.colorStep=new Ze(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new Be(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Ze(0,0,0,0),this._currentColor2=new Ze(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=s5._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(this._randomCellOffset===void 0&&(this._randomCellOffset=Math.random()*this.lifeTime),t===0?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID;let r;this._initialSpriteCellLoop?r=Nn(e*t%this.lifeTime/this.lifeTime):r=Nn(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+r*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const i=ie.Vector3[0];this.direction.normalizeToRef(i),t.setDirection(i,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,ie.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(ie.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=s5._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new Ct(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}s5._Count=0;const rFe="particlesPixelShader",sFe=`#ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; #include #include #include #include #include #ifdef RAMPGRADIENT varying vec4 remapRanges;uniform sampler2D rampSampler; #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; #ifdef RAMPGRADIENT float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); #endif #ifdef BLENDMULTIPLYMODE float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); #endif #include #include(color,baseColor) #ifdef IMAGEPROCESSINGPOSTPROCESS baseColor.rgb=toLinearSpace(baseColor.rgb); #else #ifdef IMAGEPROCESSING baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); #endif #endif gl_FragColor=baseColor; #define CUSTOM_FRAGMENT_MAIN_END }`;Re.ShadersStore[rFe]=sFe;const nFe="particlesVertexShader",aFe=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; #ifdef ANIMATESHEET attribute float cellIndex; #endif #ifndef BILLBOARD attribute vec3 direction; #endif #ifdef BILLBOARDSTRETCHED attribute vec3 direction; #endif #ifdef RAMPGRADIENT attribute vec4 remapData; #endif attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; #ifdef ANIMATESHEET uniform vec3 particlesInfos; #endif varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; #ifdef RAMPGRADIENT varying vec4 remapRanges; #endif #if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) uniform mat4 invView; #endif #include #include #include #ifdef BILLBOARD uniform vec3 eyePosition; #endif vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} #ifdef BILLBOARDSTRETCHED vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); #ifdef BILLBOARDSTRETCHED_LOCAL vec3 row1=direction; #else vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); #endif mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; #ifdef BILLBOARD vec3 rotatedCorner; #ifdef BILLBOARDY rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; #elif defined(BILLBOARDSTRETCHED) rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; #else rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; #endif #ifdef RAMPGRADIENT remapRanges=remapData; #endif gl_Position=projection*vec4(viewPos,1.0); #else vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); #endif vColor=color; #ifdef ANIMATESHEET float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; #else vUV=offset; #endif #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) vec4 worldPos=vec4(vPositionW,1.0); #endif #include #include #include #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[nFe]=aFe;class Jz extends yo{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t;return((t=this._customWrappers[e])==null?void 0:t.effect)??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Sn(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new Ae),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,s=!1,a=.01){super(e),this._emitterInverseWorldMatrix=ce.Identity(),this._inheritedVelocityOffset=new P,this.onDisposeObservable=new Ae,this.onStoppedObservable=new Ae,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new Ze(0,0,0,0),this._colorDiff=new Ze(0,0,0,0),this._scaledDirection=P.Zero(),this._scaledGravity=P.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=c=>{},this.recycleParticle=c=>{const l=this._particles.pop();l!==c&&l.copyTo(c),this._stockParticles.push(l)},this._createParticle=()=>{let c;return this._stockParticles.length!==0?(c=this._stockParticles.pop(),c._reset()):c=new s5(this),this._prepareParticle(c),c},this._capacity=t,this._epsilon=a,this._isAnimationSheetEnabled=s,!i||i.getClassName()==="Scene"?(this._scene=i||bt.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=ce.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Sn(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new Gm;let o=null;this.updateFunction=c=>{var u;let l=null;this.noiseTexture&&(l=this.noiseTexture.getSize(),(u=this.noiseTexture.getContent())==null||u.then(d=>{o=d}));const h=c===this._particles;for(let d=0;df.lifeTime){const v=f.age-_;p=(f.lifeTime-_)*p/v,f.age=f.lifeTime}const m=f.age/f.lifeTime;this._colorGradients&&this._colorGradients.length>0?Nh.GetCurrentGradient(m,this._colorGradients,(v,x,y)=>{v!==f._currentColorGradient&&(f._currentColor1.copyFrom(f._currentColor2),x.getColorToRef(f._currentColor2),f._currentColorGradient=v),Ze.LerpToRef(f._currentColor1,f._currentColor2,y,f.color)}):(f.colorStep.scaleToRef(p,this._scaledColorStep),f.color.addInPlace(this._scaledColorStep),f.color.a<0&&(f.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&Nh.GetCurrentGradient(m,this._angularSpeedGradients,(v,x,y)=>{v!==f._currentAngularSpeedGradient&&(f._currentAngularSpeed1=f._currentAngularSpeed2,f._currentAngularSpeed2=x.getFactor(),f._currentAngularSpeedGradient=v),f.angularSpeed=_u(f._currentAngularSpeed1,f._currentAngularSpeed2,y)}),f.angle+=f.angularSpeed*p;let g=p;if(this._velocityGradients&&this._velocityGradients.length>0&&Nh.GetCurrentGradient(m,this._velocityGradients,(v,x,y)=>{v!==f._currentVelocityGradient&&(f._currentVelocity1=f._currentVelocity2,f._currentVelocity2=x.getFactor(),f._currentVelocityGradient=v),g*=_u(f._currentVelocity1,f._currentVelocity2,y)}),f.direction.scaleToRef(g,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&Nh.GetCurrentGradient(m,this._limitVelocityGradients,(v,x,y)=>{v!==f._currentLimitVelocityGradient&&(f._currentLimitVelocity1=f._currentLimitVelocity2,f._currentLimitVelocity2=x.getFactor(),f._currentLimitVelocityGradient=v);const C=_u(f._currentLimitVelocity1,f._currentLimitVelocity2,y);f.direction.length()>C&&f.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&Nh.GetCurrentGradient(m,this._dragGradients,(v,x,y)=>{v!==f._currentDragGradient&&(f._currentDrag1=f._currentDrag2,f._currentDrag2=x.getFactor(),f._currentDragGradient=v);const C=_u(f._currentDrag1,f._currentDrag2,y);this._scaledDirection.scaleInPlace(1-C)}),this.isLocal&&f._localPosition?(f._localPosition.addInPlace(this._scaledDirection),P.TransformCoordinatesToRef(f._localPosition,this._emitterWorldMatrix,f.position)):f.position.addInPlace(this._scaledDirection),o&&l&&f._randomNoiseCoordinates1){const v=this._fetchR(f._randomNoiseCoordinates1.x,f._randomNoiseCoordinates1.y,l.width,l.height,o),x=this._fetchR(f._randomNoiseCoordinates1.z,f._randomNoiseCoordinates2.x,l.width,l.height,o),y=this._fetchR(f._randomNoiseCoordinates2.y,f._randomNoiseCoordinates2.z,l.width,l.height,o),C=ie.Vector3[0],b=ie.Vector3[1];C.copyFromFloats((2*v-1)*this.noiseStrength.x,(2*x-1)*this.noiseStrength.y,(2*y-1)*this.noiseStrength.z),C.scaleToRef(p,b),f.direction.addInPlace(b)}if(this.gravity.scaleToRef(p,this._scaledGravity),f.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&Nh.GetCurrentGradient(m,this._sizeGradients,(v,x,y)=>{v!==f._currentSizeGradient&&(f._currentSize1=f._currentSize2,f._currentSize2=x.getFactor(),f._currentSizeGradient=v),f.size=_u(f._currentSize1,f._currentSize2,y)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&Nh.GetCurrentGradient(m,this._colorRemapGradients,(v,x,y)=>{const C=_u(v.factor1,x.factor1,y),b=_u(v.factor2,x.factor2,y);f.remapData.x=C,f.remapData.y=b-C}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&Nh.GetCurrentGradient(m,this._alphaRemapGradients,(v,x,y)=>{const C=_u(v.factor1,x.factor1,y),b=_u(v.factor2,x.factor2,y);f.remapData.z=C,f.remapData.w=b-C})),this._isAnimationSheetEnabled&&f.updateCellIndex(),f._inheritParticleInfoToSubEmitters(),f.age>=f.lifeTime){this._emitFromParticle(f),f._attachedSubEmitters&&(f._attachedSubEmitters.forEach(v=>{v.particleSystem.disposeOnStop=!0,v.particleSystem.stop()}),f._attachedSubEmitters=null),this.recycleParticle(f),h&&d--;continue}}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,r){const s=new Ste(t,i,r);e.push(s),e.sort((a,o)=>a.gradiento.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(this._rawTextureWidth*4),t=wr.Color3[0];for(let i=0;i{Me.LerpToRef(s.color,a.color,o,t),e[i*4]=t.r*255,e[i*4+1]=t.g*255,e[i*4+2]=t.b*255,e[i*4+3]=255})}this._rampGradientsTexture=$s.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new P4e(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const r=new Tte(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort((s,a)=>s.gradienta.gradient?1:0),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)t==null||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,s){e=Math.abs(e)*.5+.5,t=Math.abs(t)*.5+.5;const a=e*i%i|0,o=t*r%r|0,c=(a+o*i)*4;return s[c]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),(!this._isBillboardBased||this.billboardMode===8||this.billboardMode===9)&&(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new no(e,this._vertexData,!0,t);let i=0;const r=this._vertexBuffer.createVertexBuffer(Z.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Z.PositionKind]=r,i+=3;const s=this._vertexBuffer.createVertexBuffer(Z.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Z.ColorKind]=s,i+=4;const a=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=a,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const l=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=l,i+=1}if(!this._isBillboardBased||this.billboardMode===8||this.billboardMode===9){const l=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=l,i+=3}if(this._useRampGradients){const l=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=l,i+=4}let c;if(this._useInstancing){const l=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new no(e,l,!1,2),c=this._spriteBuffer.createVertexBuffer("offset",0,2)}else c=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=c,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));return}const e=[],t=[];let i=0;for(let r=0;r{this.start(0)},e);return}if(this._started=!0,this._stopped=!1,this._actualFrame=0,this._preStart(),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){((t=this.emitter)==null?void 0:t.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);const i=this.noiseTexture;if(i&&i.onGeneratedObservable)i.onGeneratedObservable.addOnce(()=>{setTimeout(()=>{for(let r=0;r0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,r){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===8||this.billboardMode===9)&&(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let a=t._initialDirection;this.isLocal&&(P.TransformNormalToRef(a,this._emitterWorldMatrix,ie.Vector3[0]),a=ie.Vector3[0]),a.x===0&&a.z===0&&(a.x=.001),this._vertexData[s++]=a.x,this._vertexData[s++]=a.y,this._vertexData[s++]=a.z}else{let a=t.direction;this.isLocal&&(P.TransformNormalToRef(a,this._emitterWorldMatrix,ie.Vector3[0]),a=ie.Vector3[0]),a.x===0&&a.z===0&&(a.x=.001),this._vertexData[s++]=a.x,this._vertexData[s++]=a.y,this._vertexData[s++]=a.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(i===0?i=this._epsilon:i===1&&(i=1-this._epsilon),r===0?r=this._epsilon:r===1&&(r=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=r)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const i=this.emitter;this._emitterWorldMatrix=i.getWorldMatrix()}else{const i=this.emitter;this._emitterWorldMatrix=ce.Translation(i.x,i.y,i.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);let t;for(let i=0;i0){const s=Nn(this._actualFrame/this.targetStopDuration);Nh.GetCurrentGradient(s,this._lifeTimeGradients,(a,o)=>{const c=a,l=o,h=c.getFactor(),u=l.getFactor(),d=(s-c.gradient)/(l.gradient-c.gradient);t.lifeTime=_u(h,u,d)})}else t.lifeTime=Xr(this.minLifeTime,this.maxLifeTime);const r=Xr(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),P.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),r===0?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(r),!this._sizeGradients||this._sizeGradients.length===0?t.size=Xr(this.minSize,this.maxSize):(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1),t.scale.copyFromFloats(Xr(this.minScaleX,this.maxScaleX),Xr(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const s=this._actualFrame/this.targetStopDuration;Nh.GetCurrentGradient(s,this._startSizeGradients,(a,o,c)=>{a!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=o.getFactor(),this._currentStartSizeGradient=a);const l=_u(this._currentStartSize1,this._currentStartSize2,c);t.scale.scaleInPlace(l)})}if(!this._angularSpeedGradients||this._angularSpeedGradients.length===0?t.angularSpeed=Xr(this.minAngularSpeed,this.maxAngularSpeed):(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1),t.angle=Xr(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),!this._colorGradients||this._colorGradients.length===0){const s=Xr(0,1);Ze.LerpToRef(this.color1,this.color2,s,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}else t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new Ct(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new P(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new P(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const r=[Z.PositionKind,Z.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const r=["invView","view","projection","textureMask","translationPivot","eyePosition"];return Sa(r),e&&r.push("particlesInfos"),t&&r.push("logarithmicDepthConstant"),i&&(r.push("vFogInfos"),r.push("vFogColor")),r}fillDefines(e,t){if(this._scene&&(d2(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==0&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===yo.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case 2:e.push("#define BILLBOARDY");break;case 8:case 9:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===9&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL");break}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...Jz._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==8&&this.billboardMode!==9,this._useRampGradients)),e.push(...Jz._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(ame(e,this._imageProcessingConfigurationDefines),ome(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t!=null&&t.effect)return t;const i=[];this.fillDefines(i,e);const r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let s=this._drawWrappers[r];s||(s=this._drawWrappers[r]=[]);let a=s[e];a||(a=new Sn(this._engine),a.drawContext&&(a.drawContext.useInstancing=this._useInstancing),s[e]=a);const o=i.join(` `);if(a.defines!==o){const c=[],l=[],h=[];this.fillUniformsAttributesAndSamplerNames(l,c,h),a.setEffect(this._engine.createEffect("particles",c,l,h,o),o)}return a}animate(e=!1){var i;if(!this._started)return;if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:((i=this._scene)==null?void 0:i.getAnimationRatio())||1);let t;if(this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let r=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const s=this._actualFrame/this.targetStopDuration;Nh.GetCurrentGradient(s,this._emitRateGradients,(a,o,c)=>{a!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=o.getFactor(),this._currentEmitRateGradient=a),r=_u(this._currentEmitRate1,this._currentEmitRate2,c)})}t=r*this._scaledUpdateSpeed>>0,this._newPartsExcess+=r*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let r=0;for(let s=0;s=0&&(s.invertToRef(ie.Matrix[0]),i.setMatrix("invView",ie.Matrix[0])),this._vertexArrayObject!==void 0?(o=this._scene)!=null&&o.forceWireframe?r.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(c=this._scene)!=null&&c.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?r.bindBuffers(this._vertexBuffers,(h=this._scene)!=null&&h.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):r.bindBuffers(this._vertexBuffers,(l=this._scene)!=null&&l.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&Ha(a,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case yo.BLENDMODE_ADD:r.setAlphaMode(1);break;case yo.BLENDMODE_ONEONE:r.setAlphaMode(6);break;case yo.BLENDMODE_STANDARD:r.setAlphaMode(2);break;case yo.BLENDMODE_MULTIPLY:r.setAlphaMode(4);break}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?(u=this._scene)!=null&&u.forceWireframe?r.drawElementsType(6,0,10,this._particles.length):r.drawArraysType(7,0,4,this._particles.length):(d=this._scene)!=null&&d.forceWireframe?r.drawElementsType(1,0,this._particles.length*10):r.drawElementsType(0,0,this._particles.length*6),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return this.blendMode===yo.BLENDMODE_MULTIPLYADD?t=this._render(yo.BLENDMODE_MULTIPLY)+this._render(yo.BLENDMODE_ADD):t=this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}_onDispose(e=!1,t=!1){}dispose(e=!0,t=!1,i=!1){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._onDispose(t,i),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){const r=this._scene.particleSystems.indexOf(this);r>-1&&this._scene.particleSystems.splice(r,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}var n5;(function(n){n[n.ATTACHED=0]="ATTACHED",n[n.END=1]="END"})(n5||(n5={}));class Wm{constructor(e){if(this.particleSystem=e,this.type=n5.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=gn("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(!e)e=new P;else if(e instanceof P)e=e.clone();else if(e.getClassName().indexOf("Mesh")!==-1){const i=gn("BABYLON.Mesh");e=new i("",e.getScene()),e.isVisible=!1}const t=new Wm(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw ci("ParseParticle")}static Parse(e,t,i){const r=e.particleSystem,s=new Wm(Wm._ParseParticleSystem(r,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}function w4e(n,e){const t=new P9;return t.direction1=n,t.direction2=e,t}function D4e(n=1,e=1){return new I9(n,e)}function O4e(n=1,e=1){return new G5(n,e)}function L4e(n=1,e=new P(0,1,0),t=new P(0,1,0)){return new w9(n,e,t)}function N4e(n=1,e=1,t=1,i=0){return new H5(n,e,t,i)}function B4e(n=1,e=1,t=1,i=new P(0,1,0),r=new P(0,1,0)){return new R9(n,e,t,i,r)}function F4e(n=1,e=Math.PI/4){return new M9(n,e)}class Wr extends Jz{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||this._subEmitters.length===0)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach(i=>{if(i.type===n5.END){const r=i.clone();e._inheritParticleInfoToSubEmitter(r),r.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(r.particleSystem),r.particleSystem.start()}})}}createPointEmitter(e,t){const i=w4e(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=D4e(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=O4e(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new P(0,1,0),i=new P(0,1,0)){const r=L4e(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){const s=N4e(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new P(0,1,0),s=new P(0,1,0)){const a=B4e(e,t,i,r,s);return this.particleEmitterType=a,a}createConeEmitter(e=1,t=Math.PI/4){const i=F4e(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,r){const s=new Gm;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach(e=>{e instanceof Wr?this._subEmitters.push([new Wm(e)]):e instanceof Wm?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)})}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);e!==-1&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length!=0&&(this.activeSubSystems=[])}_postStop(e){e&&this._stopSubEmitters()}_prepareParticle(e){if(this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(i=>{if(i.type===n5.ATTACHED){const r=i.clone();e._attachedSubEmitters.push(r),r.particleSystem.start()}})}}_onDispose(e=!1,t=!1){var i;if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&((i=this.particles)==null||i.forEach(r=>{if(r._attachedSubEmitters)for(let s=r._attachedSubEmitters.length-1;s>=0;s-=1)r._attachedSubEmitters[s].dispose()})),t&&this.activeSubSystems)for(let r=this.activeSubSystems.length-1;r>=0;r-=1)this.activeSubSystems[r].dispose();if(this._subEmitters&&this._subEmitters.length){for(let r=0;r0?c.shaderOptions.defines.join(` `):"";o=l.createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,d)}const u=new Wr(a,s||e.capacity,t,o,e.isAnimationSheetEnabled);if(u.customShader=c,u._rootUrl=i,e.id&&(u.id=e.id),e.subEmitters){u.subEmitters=[];for(const d of e.subEmitters){const f=[];for(const p of d)f.push(Wm.Parse(p,t,i));u.subEmitters.push(f)}}return Wr._Parse(e,u,t,i),e.textureMask&&(u.textureMask=Ze.FromArray(e.textureMask)),e.worldOffset&&(u.worldOffset=P.FromArray(e.worldOffset)),e.preventAutoStart&&(u.preventAutoStart=e.preventAutoStart),!r&&!u.preventAutoStart&&u.start(),u}serialize(e=!1){const t={};if(Wr._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const r=[];for(const s of i)r.push(s.serialize(e));t.subEmitters.push(r)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const m=t.emitter;e.emitterId=m.id}else{const m=t.emitter;e.emitter=m.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,Qe.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const r=t.getColorGradients();if(r){e.colorGradients=[];for(const m of r){const g={gradient:m.gradient,color1:m.color1.asArray()};m.color2?g.color2=m.color2.asArray():g.color2=m.color1.asArray(),e.colorGradients.push(g)}}const s=t.getRampGradients();if(s){e.rampGradients=[];for(const m of s){const g={gradient:m.gradient,color:m.color.asArray()};e.rampGradients.push(g)}e.useRampGradients=t.useRampGradients}const a=t.getColorRemapGradients();if(a){e.colorRemapGradients=[];for(const m of a){const g={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?g.factor2=m.factor2:g.factor2=m.factor1,e.colorRemapGradients.push(g)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const m of o){const g={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?g.factor2=m.factor2:g.factor2=m.factor1,e.alphaRemapGradients.push(g)}}const c=t.getSizeGradients();if(c){e.sizeGradients=[];for(const m of c){const g={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?g.factor2=m.factor2:g.factor2=m.factor1,e.sizeGradients.push(g)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const m of l){const g={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?g.factor2=m.factor2:g.factor2=m.factor1,e.angularSpeedGradients.push(g)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const m of h){const g={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?g.factor2=m.factor2:g.factor2=m.factor1,e.velocityGradients.push(g)}}const u=t.getDragGradients();if(u){e.dragGradients=[];for(const m of u){const g={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?g.factor2=m.factor2:g.factor2=m.factor1,e.dragGradients.push(g)}}const d=t.getEmitRateGradients();if(d){e.emitRateGradients=[];for(const m of d){const g={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?g.factor2=m.factor2:g.factor2=m.factor1,e.emitRateGradients.push(g)}}const f=t.getStartSizeGradients();if(f){e.startSizeGradients=[];for(const m of f){const g={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?g.factor2=m.factor2:g.factor2=m.factor1,e.startSizeGradients.push(g)}}const p=t.getLifeTimeGradients();if(p){e.lifeTimeGradients=[];for(const m of p){const g={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?g.factor2=m.factor2:g.factor2=m.factor1,e.lifeTimeGradients.push(g)}}const _=t.getLimitVelocityGradients();if(_){e.limitVelocityGradients=[];for(const m of _){const g={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?g.factor2=m.factor2:g.factor2=m.factor1,e.limitVelocityGradients.push(g)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const r={...this._customWrappers};let s=null;const a=this._engine;if(a.createEffectForParticles&&this.customShader!=null){s=this.customShader;const l=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join(` `):"",h=a.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,l);r[0]?r[0].effect=h:this.setCustomEffect(h,0)}const o=this.serialize(i),c=Wr.Parse(o,this._scene||this._engine,this._rootUrl);return c.name=e,c.customShader=s,c._customWrappers=r,t===void 0&&(t=this.emitter),this.noiseTexture&&(c.noiseTexture=this.noiseTexture.clone()),c.emitter=t,this.preventAutoStart||c.start(),c}}Wr.BILLBOARDMODE_Y=2;Wr.BILLBOARDMODE_ALL=7;Wr.BILLBOARDMODE_STRETCHED=8;Wr.BILLBOARDMODE_STRETCHED_LOCAL=9;Wm._ParseParticleSystem=Wr.Parse;const oFe="clipPlaneFragmentDeclaration2",lFe=`#ifdef CLIPPLANE in float fClipDistance; #endif #ifdef CLIPPLANE2 in float fClipDistance2; #endif #ifdef CLIPPLANE3 in float fClipDistance3; #endif #ifdef CLIPPLANE4 in float fClipDistance4; #endif #ifdef CLIPPLANE5 in float fClipDistance5; #endif #ifdef CLIPPLANE6 in float fClipDistance6; #endif `;Re.IncludesShadersStore[oFe]=lFe;const cFe="gpuRenderParticlesPixelShader",hFe=`precision highp float; #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; #include #include #include #include #include #include void main() { #include vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; #ifdef BLENDMULTIPLYMODE float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); #endif #include #include(color,gl_FragColor) #ifdef IMAGEPROCESSINGPOSTPROCESS gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); #else #ifdef IMAGEPROCESSING gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); #endif #endif } `;Re.ShadersStore[cFe]=hFe;const uFe="clipPlaneVertexDeclaration2",dFe=`#ifdef CLIPPLANE uniform vec4 vClipPlane;out float fClipDistance; #endif #ifdef CLIPPLANE2 uniform vec4 vClipPlane2;out float fClipDistance2; #endif #ifdef CLIPPLANE3 uniform vec4 vClipPlane3;out float fClipDistance3; #endif #ifdef CLIPPLANE4 uniform vec4 vClipPlane4;out float fClipDistance4; #endif #ifdef CLIPPLANE5 uniform vec4 vClipPlane5;out float fClipDistance5; #endif #ifdef CLIPPLANE6 uniform vec4 vClipPlane6;out float fClipDistance6; #endif `;Re.IncludesShadersStore[uFe]=dFe;const fFe="gpuRenderParticlesVertexShader",pFe=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; #ifdef LOCAL uniform mat4 emitterWM; #endif attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; #ifndef BILLBOARD attribute vec3 initialDirection; #endif #ifdef BILLBOARDSTRETCHED attribute vec3 direction; #endif attribute float angle; #ifdef ANIMATESHEET attribute float cellIndex; #endif attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; #if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) uniform mat4 invView; #endif #include #include #include #ifdef COLORGRADIENTS uniform sampler2D colorGradientSampler; #else uniform vec4 colorDead;attribute vec4 color; #endif #ifdef ANIMATESHEET uniform vec3 sheetInfos; #endif #ifdef BILLBOARD uniform vec3 eyePosition; #endif vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; #ifdef LOCAL return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; #else return (position+worldOffset)+alignedCorner; #endif } #ifdef BILLBOARDSTRETCHED vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; #ifdef LOCAL return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; #else return (position+worldOffset)+alignedCorner; #endif } #endif void main() { #ifdef ANIMATESHEET float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; #else vUV=uv; #endif float ratio=age/life; #ifdef COLORGRADIENTS vColor=texture2D(colorGradientSampler,vec2(ratio,0)); #else vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); #endif vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; #ifdef BILLBOARD vec4 rotatedCorner;rotatedCorner.w=0.; #ifdef BILLBOARDY rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); #elif defined(BILLBOARDSTRETCHED) rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); #else rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; #ifdef LOCAL vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; #else vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; #endif vPositionW=(invView*viewPosition).xyz; #endif #else vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); #endif gl_Position=projection*viewPosition; #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) vec4 worldPos=vec4(vPositionW,1.0); #endif #include #include #include }`;Re.ShadersStore[fFe]=pFe;class wu extends yo{static get IsSupported(){if(!bt.LastCreatedEngine)return!1;const e=bt.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}createPointEmitter(e,t){const i=w4e(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=D4e(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=O4e(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new P(0,1,0),i=new P(0,1,0)){const r=L4e(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){const s=N4e(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new P(0,1,0),s=new P(0,1,0)){const a=B4e(e,t,i,r,s);return this.particleEmitterType=a,a}createConeEmitter(e=1,t=Math.PI/4){const i=F4e(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,r){const s=new Gm;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==Wr.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(Wr.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(Wr.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t;return((t=this._customWrappers[e])==null?void 0:t.effect)??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Sn(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new Ae),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[this._targetIndex^1]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new Tte(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort((t,i)=>t.gradienti.gradient?1:0),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){var e;for(const t in this._drawWrappers)(e=this._drawWrappers[t].drawContext)==null||e.reset()}_addFactorGradient(e,t,i){const r=new Ste(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort((s,a)=>s.gradienta.gradient?1:0);const r=this;r[t]&&(r[t].dispose(),r[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new Ae,this.onStoppedObservable=new Ae,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,!i||i.getClassName()==="Scene"?(this._scene=i||bt.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=ce.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().supportComputeShaders){if(!gn("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(gn("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!gn("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(gn("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Sn(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new Sn(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),t=t??{},t.randomTextureSize||delete t.randomTextureSize;const a={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},o=t;isFinite(o)&&(a.capacity=o),this._capacity=a.capacity,this._maxActiveParticleCount=a.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new Gm;const c=Math.min(this._engine.getCaps().maxTextureSize,a.randomTextureSize);let l=[];for(let h=0;h0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),c=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new no(t,c,!1,this._attributesStrideSize),this._buffer1=new no(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new no(t,o,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+=` #define BILLBOARD`),this._colorGradientsTexture&&(e+=` #define COLORGRADIENTS`),this._sizeGradientsTexture&&(e+=` #define SIZEGRADIENTS`),this._angularSpeedGradientsTexture&&(e+=` #define ANGULARSPEEDGRADIENTS`),this._velocityGradientsTexture&&(e+=` #define VELOCITYGRADIENTS`),this._limitVelocityGradientsTexture&&(e+=` #define LIMITVELOCITYGRADIENTS`),this._dragGradientsTexture&&(e+=` #define DRAGGRADIENTS`),this.isAnimationSheetEnabled&&(e+=` #define ANIMATESHEET`,this.spriteRandomStartCell&&(e+=` #define ANIMATESHEETRANDOMSTART`)),this.noiseTexture&&(e+=` #define NOISE`),this.isLocal&&(e+=` #define LOCAL`),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e?this._platform.isUpdateBufferReady():(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t!=null&&t.effect)return t;const i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||(r=new Sn(this._engine),r.drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);const s=i.join(` `);if(r.defines!==s){const a=[],o=[],c=[];this.fillUniformsAttributesAndSamplerNames(o,a,c),r.setEffect(this._engine.createEffect("gpuRenderParticles",a,o,c,s),s)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){const s=[Z.PositionKind,"age","life","size","angle"];return e||s.push(Z.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),r&&s.push("direction"),s.push("offset",Z.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const r=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return Sa(r),e&&r.push("sheetInfos"),t&&r.push("logarithmicDepthConstant"),i&&(r.push("vFogInfos"),r.push("vFogColor")),r}fillDefines(e,t=0){if(this._scene&&(d2(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==pt.FOGMODE_NONE&&e.push("#define FOG")),t===Wr.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case Wr.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case Wr.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case Wr.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL");break}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...wu._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===Wr.BILLBOARDMODE_STRETCHED)),e.push(...wu._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(Ji.PrepareUniforms(e,this._imageProcessingConfigurationDefines),Ji.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:((t=this._scene)==null?void 0:t.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const r=new Float32Array(this._rawTextureWidth);for(let s=0;s{r[s]=_t.Lerp(o.factor1,c.factor1,l)})}this[t]=$s.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(this._rawTextureWidth*4),t=wr.Color4[0];for(let i=0;i{Ze.LerpToRef(s.color1,a.color1,o,t),e[i*4]=t.r*255,e[i*4+1]=t.g*255,e[i*4+2]=t.b*255,e[i*4+3]=t.a*255})}this._colorGradientsTexture=$s.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var o,c,l,h;const i=this._getWrapper(e),r=i.effect;this._engine.enableEffect(i);const s=((o=this._scene)==null?void 0:o.getViewMatrix())||ce.IdentityReadOnly;if(r.setMatrix("view",s),r.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),r.setTexture("diffuseSampler",this.particleTexture),r.setVector2("translationPivot",this.translationPivot),r.setVector3("worldOffset",this.worldOffset),this.isLocal&&r.setMatrix("emitterWM",t),this._colorGradientsTexture?r.setTexture("colorGradientSampler",this._colorGradientsTexture):r.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const u=this.particleTexture.getBaseSize();r.setFloat3("sheetInfos",this.spriteCellWidth/u.width,this.spriteCellHeight/u.height,u.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const u=this._scene.activeCamera;r.setVector3("eyePosition",u.globalPosition)}const a=r.defines;if(this._scene&&(fa(r,this,this._scene),this.applyFog&&Oo(this._scene,void 0,r)),a.indexOf("#define BILLBOARDMODE_ALL")>=0){const u=s.clone();u.invert(),r.setMatrix("invView",u)}switch(this.useLogarithmicDepth&&this._scene&&Ha(a,r,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(r),e){case Wr.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case Wr.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case Wr.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case Wr.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4);break}return this._platform.bindDrawBuffers(this._targetIndex,r,(c=this._scene)!=null&&c.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(r),(l=this._scene)!=null&&l.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(h=this._scene)!=null&&h.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const i=this.emitter;e=ie.Matrix[0],ce.TranslationToRef(i.x,i.y,i.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,this._targetIndex===2&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started||!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let a=0;a1){const a=this._accumulatedCount|0;this._accumulatedCount-=a,this._currentActiveCount+=a}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;let i;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{const a=this.emitter;i=ie.Matrix[0],ce.TranslationToRef(a.x,a.y,a.z,i)}const r=this._engine;this.updateInAnimate||this._update(i);let s=0;return!e&&!t&&(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),this.blendMode===Wr.BLENDMODE_MULTIPLYADD?s=this._render(Wr.BLENDMODE_MULTIPLY,i)+this._render(Wr.BLENDMODE_ADD,i):s=this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){const e=()=>{!this._recreateUpdateEffect()||!this._platform.isUpdateBufferReady()?setTimeout(e,10):(this._initialize(!0),this._rebuildingAfterContextLost=!1)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),this._rebuildingAfterContextLost=!0,e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const t in this._drawWrappers)this._drawWrappers[t].dispose();if(this._drawWrappers={},this._scene){const t=this._scene.particleSystems.indexOf(this);t>-1&&this._scene.particleSystems.splice(t,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let t=0;t0?s.shaderOptions.defines.join(` `):"";r[0]=a.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,l,void 0,void 0,void 0,this)}const o=this.serialize(i),c=wu.Parse(o,this._scene||this._engine,this._rootUrl);return c.name=e,c.customShader=s,c._customWrappers=r,t===void 0&&(t=this.emitter),this.noiseTexture&&(c.noiseTexture=this.noiseTexture.clone()),c.emitter=t,c}serialize(e=!1){const t={};return Wr._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,s){const a=e.name;let o,c;t instanceof yt?o=t:(c=t,o=c.getEngine());const l=new wu(a,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const h=e.customShader,u=h.shaderOptions.defines.length>0?h.shaderOptions.defines.join(` `):"",d=o.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,u,void 0,void 0,void 0,l);l.setCustomEffect(d,0),l.customShader=h}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),Wr._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),!r&&!l.preventAutoStart&&l.start(),l}}class a2{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const r=Tl("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;const s=new tt("emitterSphereMaterial",i);s.emissiveColor=e.color,r.material=s;for(const a of this.systems)a.emitter=r;this._emitterNode=r}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={};t.systems=[];for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){const s=new a2,a=this.BaseAssetsUrl+"/textures/";t=t||bt.LastCreatedScene;for(const o of e.systems)s.systems.push(i?wu.Parse(o,t,a,!0,r):Wr.Parse(o,t,a,!0,r));if(e.emitter){const o=e.emitter.options;switch(e.emitter.kind){case"Sphere":s.setEmitterAsSphere({diameter:o.diameter,segments:o.segments,color:Me.FromArray(o.color)},e.emitter.renderingGroupId,t);break}}return s}}a2.BaseAssetsUrl="https://assets.babylonjs.com/particles";class lA{static CreateDefault(e,t=500,i,r=!1){let s;return r?s=new wu("default system",{capacity:t},i):s=new Wr("default system",t,i),s.emitter=e,s.particleTexture=new ve("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new Ze(1,1,1,1),s.color2=new Ze(1,1,1,1),s.colorDead=new Ze(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,r){t||(t=bt.LastCreatedScene);const s={};return t.addPendingData(s),new Promise((a,o)=>{if(i&&!wu.IsSupported)return t.removePendingData(s),o("Particle system with GPU is not supported.");Ee.LoadFile(`${lA.BaseAssetsUrl}/systems/${e}.json`,c=>{t.removePendingData(s);const l=JSON.parse(c.toString());return a(a2.Parse(l,t,i,r))},void 0,void 0,void 0,()=>(t.removePendingData(s),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){const t=new a2;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,s="",a){return new Promise((o,c)=>{const l=new on;l.addEventListener("readystatechange",()=>{if(l.readyState==4)if(l.status==200){const h=JSON.parse(l.responseText);let u;r?u=wu.Parse(h,i,s,!1,a):u=Wr.Parse(h,i,s,!1,a),e&&(u.name=e),o(u)}else c("Unable to load the particle system")}),l.open("GET",t),l.send()})}static ParseFromSnippetAsync(e,t,i=!1,r="",s){if(e==="_BLANK"){const a=this.CreateDefault(null);return a.start(),Promise.resolve(a)}return new Promise((a,o)=>{const c=new on;c.addEventListener("readystatechange",()=>{if(c.readyState==4)if(c.status==200){const l=JSON.parse(JSON.parse(c.responseText).jsonPayload),h=JSON.parse(l.particleSystem);let u;i?u=wu.Parse(h,t,r,!1,s):u=Wr.Parse(h,t,r,!1,s),u.snippetId=e,a(u)}else o("Unable to load the snippet "+e)}),c.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),c.send()})}}lA.BaseAssetsUrl=a2.BaseAssetsUrl;lA.SnippetUrl="https://snippet.babylonjs.com";lA.CreateFromSnippetAsync=lA.ParseFromSnippetAsync;da.AddParser(it.NAME_PARTICLESYSTEM,(n,e,t,i)=>{const r=da.GetIndividualParser(it.NAME_PARTICLESYSTEM);if(r&&n.particleSystems!==void 0&&n.particleSystems!==null)for(let s=0,a=n.particleSystems.length;sn.activeParticleCount?wu.Parse(n,e,t):Wr.Parse(n,e,t));De.prototype.createEffectForParticles=function(n,e=[],t=[],i="",r,s,a,o){let c=[],l=[];const h=[];return o?o.fillUniformsAttributesAndSamplerNames(l,c,h):(c=Wr._GetAttributeNamesOrOptions(),l=Wr._GetEffectCreationOptions()),i.indexOf(" BILLBOARD")===-1&&(i+=` #define BILLBOARD `),o!=null&&o.isAnimationSheetEnabled&&i.indexOf(" ANIMATESHEET")===-1&&(i+=` #define ANIMATESHEET `),t.indexOf("diffuseSampler")===-1&&t.push("diffuseSampler"),this.createEffect({vertex:(o==null?void 0:o.vertexShaderName)??"particles",fragmentElement:n},c,l.concat(e),h.concat(t),i,r,s,a)};Se.prototype.getEmittedParticleSystems=function(){const n=[];for(let e=0;es.sqDistance-r.sqDistance,this._materialSortFunction=(r,s)=>r.materialIndex-s.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||bt.LastCreatedScene,this._camera=t.activeCamera,this._pickable=i?i.isPickable:!1,this._depthSort=i?i.enableDepthSort:!1,this._multimaterialEnabled=i?i.enableMultiMaterial:!1,this._useModelMaterial=i?i.useModelMaterial:!1,this._multimaterialEnabled=this._useModelMaterial?!0:this._multimaterialEnabled,this._expandable=i?i.expandable:!1,this._particlesIntersect=i?i.particleIntersection:!1,this._bSphereOnly=i?i.boundingSphereOnly:!1,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,this._computeBoundingBox=i!=null&&i.computeBoundingBox?i.computeBoundingBox:!1,this._autoFixFaceOrientation=i!=null&&i.autoFixFaceOrientation?i.autoFixFaceOrientation:!1,i&&i.updatable!==void 0?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new Fu(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new k4e}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(this.nbParticles===0&&!this.mesh){const t=U5("",{radius:1,tessellation:3},this._scene);this.addShape(t,1),t.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){const t=new Se(this.name,this._scene);this.mesh=t}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&et.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();const e=new et;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,Z.PositionKind),e.set(this._normals32,Z.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,Z.UVKind),this._colors32.length>0&&e.set(this._colors32,Z.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let t=0;for(let i=0;if?f:r,i=Math.round(f/r),s=0):i=i>f?f:i;const p=[],_=[],m=[],g=[],v=[],x=P.Zero(),y=i;for(;df-i&&(i=f-d),p.length=0,_.length=0,m.length=0,g.length=0,v.length=0;let C=0;for(let j=d*3;j<(d+i)*3;j++){m.push(C);const k=o[j],z=k*3;if(p.push(a[z],a[z+1],a[z+2]),_.push(h[z],h[z+1],h[z+2]),c){const Y=k*2;g.push(c[Y],c[Y+1])}if(l){const Y=k*4;v.push(l[Y],l[Y+1],l[Y+2],l[Y+3])}C++}let b=this.nbParticles;const T=this._posToShape(p),S=this._uvsToShapeUV(g),N=m.slice(),D=v.slice(),M=_.slice();x.copyFromFloats(0,0,0);let I;for(I=0;I65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const G=C.materialIndex!==null?C.materialIndex:0;this.depthSortedParticles.push(new U4e(f,t,s.length,G))}return C}_posToShape(e){const t=[];for(let i=0;i=this.nbParticles||!this._updatable)return[];const r=this.particles,s=this.nbParticles;if(t=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(e!=0||t!=this.nbParticles-1)){const $=this.mesh.getBoundingInfo();$&&(x.copyFrom($.minimum),y.copyFrom($.maximum))}M=this.particles[e]._pos;const Q=M/3|0;R=Q*4,H=Q*2;for(let $=e;$<=t;$++){const V=this.particles[$];this.updateParticle(V);const j=V._model._shape,k=V._model._shapeUV,z=V._rotationMatrix,Y=V.position,J=V.rotation,re=V.scaling,he=V._globalPosition;if(p){const le=this.depthSortedParticles[$];le.idx=V.idx,le.ind=V._ind,le.indicesLength=V._model._indicesLength,le.sqDistance=P.DistanceSquared(V.position,C)}if(!V.alive||V._stillInvisible&&!V.isVisible&&!this._recomputeInvisibles){G=j.length,M+=G*3,R+=G*4,H+=G*2;continue}if(V.isVisible){V._stillInvisible=!1;const le=_[12];if(V.pivot.multiplyToRef(re,le),this.billboard&&(J.x=0,J.y=0),(this._computeParticleRotation||this.billboard)&&V.getRotationMatrix(r),V.parentId!==null){const F=this.getParticleById(V.parentId);if(F){const W=F._rotationMatrix,te=F._globalPosition,oe=Y.x*W[1]+Y.y*W[4]+Y.z*W[7],ne=Y.x*W[0]+Y.y*W[3]+Y.z*W[6],pe=Y.x*W[2]+Y.y*W[5]+Y.z*W[8];if(he.x=te.x+ne,he.y=te.y+oe,he.z=te.z+pe,this._computeParticleRotation||this.billboard){const ye=r.m;z[0]=ye[0]*W[0]+ye[1]*W[3]+ye[2]*W[6],z[1]=ye[0]*W[1]+ye[1]*W[4]+ye[2]*W[7],z[2]=ye[0]*W[2]+ye[1]*W[5]+ye[2]*W[8],z[3]=ye[4]*W[0]+ye[5]*W[3]+ye[6]*W[6],z[4]=ye[4]*W[1]+ye[5]*W[4]+ye[6]*W[7],z[5]=ye[4]*W[2]+ye[5]*W[5]+ye[6]*W[8],z[6]=ye[8]*W[0]+ye[9]*W[3]+ye[10]*W[6],z[7]=ye[8]*W[1]+ye[9]*W[4]+ye[10]*W[7],z[8]=ye[8]*W[2]+ye[9]*W[5]+ye[10]*W[8]}}else V.parentId=null}else if(he.x=Y.x,he.y=Y.y,he.z=Y.z,this._computeParticleRotation||this.billboard){const F=r.m;z[0]=F[0],z[1]=F[1],z[2]=F[2],z[3]=F[4],z[4]=F[5],z[5]=F[6],z[6]=F[8],z[7]=F[9],z[8]=F[10]}const L=_[11];for(V.translateFromPivot?L.setAll(0):L.copyFrom(le),G=0;G0)for(let a=0;a(this._isReady=!0,this._buildMesh(e)))}_buildMesh(e){this.nbParticles===0&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const t=new et;t.set(this._positions32,Z.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,Z.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,Z.ColorKind));const r=new Se(this.name,this._scene);t.applyToMesh(r,this._updatable),this.mesh=r,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let s=e;return s||(s=new tt("point cloud material",this._scene),s.emissiveColor=new Me(i,i,i),s.disableLighting=!0,s.pointsCloud=!0,s.pointSize=this._size),r.material=s,new Promise(a=>a(r))}_addParticle(e,t,i,r){const s=new V4e(e,t,i,r,this);return this.particles.push(s),s}_randomUnitVector(e){e.position=new P(Math.random(),Math.random(),Math.random()),e.color=new Ze(1,1,1,1)}_getColorIndicesForCoord(e,t,i,r){const s=e._groupImageData,a=i*(r*4)+t*4,o=[a,a+1,a+2,a+3],c=o[0],l=o[1],h=o[2],u=o[3],d=s[c],f=s[l],p=s[h],_=s[u];return new Ze(d/255,f/255,p/255,_)}_setPointsColorOrUV(e,t,i,r,s,a,o,c){c=c??0,i&&e.updateFacetData();const h=2*e.getBoundingInfo().boundingSphere.radius;let u=e.getVerticesData(Z.PositionKind);const d=e.getIndices(),f=e.getVerticesData(Z.UVKind+(c?c+1:"")),p=e.getVerticesData(Z.ColorKind),_=P.Zero();e.computeWorldMatrix();const m=e.getWorldMatrix();if(!m.isIdentity()){u=u.slice(0);for(let Mi=0;Mi1&&(Dr=1),hs<0&&(hs=0),hs>1&&(hs=1),Me.HSVtoRGBToRef(Kt,Dr,hs,ur),xi.set(ur.r,ur.g,ur.b,1)):xi=gt.set(Math.random(),Math.random(),Math.random(),1),ti.color=new Ze(xi.x,xi.y,xi.z,xi.w),this._colors.push(xi.x,xi.y,xi.z,xi.w))}}_colorFromTexture(e,t,i){if(e.material===null){de.Warn(e.name+"has no material."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const s=e.material.getActiveTextures();if(s.length===0){de.Warn(e.name+"has no usable texture."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const a=e.clone();a.setEnabled(!1),this._promises.push(new Promise(o=>{Er.WhenAllReady(s,()=>{let c=t._textureNb;c<0&&(c=0),c>s.length-1&&(c=s.length-1);const l=()=>{t._groupImgWidth=s[c].getSize().width,t._groupImgHeight=s[c].getSize().height,this._setPointsColorOrUV(a,t,i,!0,!0,void 0,void 0,s[c].coordinatesIndex),a.dispose(),o()};t._groupImageData=null;const h=s[c].readPixels();h?h.then(u=>{t._groupImageData=u,l()}):l()})}))}_calculateDensity(e,t,i){let r=new Array,s,a,o,c,l,h,u,d,f,p,_,m;const g=P.Zero(),v=P.Zero(),x=P.Zero(),y=P.Zero(),C=P.Zero(),b=P.Zero();let T,S,N,D,M;const I=new Array;let R=0;const O=i.length/3;for(let V=0;V0&&(r=r.map(V=>V+Q));for(let V=0;V<$;V++)r[V]+=1;return r}addPoints(e,t=this._randomUnitVector){const i=new $V(this._groupCounter,t);let r,s=this.nbParticles;for(let a=0;a3)&&(a=Ic.Random);const o=e.getVerticesData(Z.PositionKind),c=e.getIndices();this._groups.push(this._groupCounter);const l=new $V(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,c),a===Ic.Color?l._textureNb=r||0:r=r||new Ze(1,1,1,1),a){case Ic.Color:this._colorFromTexture(e,l,!1);break;case Ic.UV:this._setPointsColorOrUV(e,l,!1,!1,!1);break;case Ic.Random:this._setPointsColorOrUV(e,l,!1);break;case Ic.Stated:this._setPointsColorOrUV(e,l,!1,void 0,void 0,r,s);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,r,s){let a=i||Ic.Random;(isNaN(a)||a<0||a>3)&&(a=Ic.Random);const o=e.getVerticesData(Z.PositionKind),c=e.getIndices();this._groups.push(this._groupCounter);const l=new $V(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,c),a===Ic.Color?l._textureNb=r||0:r=r||new Ze(1,1,1,1),a){case Ic.Color:this._colorFromTexture(e,l,!0);break;case Ic.UV:this._setPointsColorOrUV(e,l,!0,!1,!1);break;case Ic.Random:this._setPointsColorOrUV(e,l,!0);break;case Ic.Stated:this._setPointsColorOrUV(e,l,!0,void 0,void 0,r,s);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){var x,y;if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const r=ie.Matrix[0],s=this.mesh,a=this._colors32,o=this._positions32,c=this._uvs32,l=ie.Vector3,h=l[5].copyFromFloats(1,0,0),u=l[6].copyFromFloats(0,1,0),d=l[7].copyFromFloats(0,0,1),f=l[8].setAll(Number.MAX_VALUE),p=l[9].setAll(-Number.MAX_VALUE);ce.IdentityToRef(r);let _=0;if((x=this.mesh)!=null&&x.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(e!=0||t!=this.nbParticles-1)){const C=(y=this.mesh)==null?void 0:y.getBoundingInfo();C&&(f.copyFrom(C.minimum),p.copyFrom(C.maximum))}_=0;let m=0,g=0,v=0;for(let C=e;C<=t;C++){const b=this.particles[C];_=b.idx,m=3*_,g=4*_,v=2*_,this.updateParticle(b);const T=b._rotationMatrix,S=b.position,N=b._globalPosition;if(this._computeParticleRotation&&b.getRotationMatrix(r),b.parentId!==null){const z=this.particles[b.parentId],Y=z._rotationMatrix,J=z._globalPosition,re=S.x*Y[1]+S.y*Y[4]+S.z*Y[7],he=S.x*Y[0]+S.y*Y[3]+S.z*Y[6],le=S.x*Y[2]+S.y*Y[5]+S.z*Y[8];if(N.x=J.x+he,N.y=J.y+re,N.z=J.z+le,this._computeParticleRotation){const ue=r.m;T[0]=ue[0]*Y[0]+ue[1]*Y[3]+ue[2]*Y[6],T[1]=ue[0]*Y[1]+ue[1]*Y[4]+ue[2]*Y[7],T[2]=ue[0]*Y[2]+ue[1]*Y[5]+ue[2]*Y[8],T[3]=ue[4]*Y[0]+ue[5]*Y[3]+ue[6]*Y[6],T[4]=ue[4]*Y[1]+ue[5]*Y[4]+ue[6]*Y[7],T[5]=ue[4]*Y[2]+ue[5]*Y[5]+ue[6]*Y[8],T[6]=ue[8]*Y[0]+ue[9]*Y[3]+ue[10]*Y[6],T[7]=ue[8]*Y[1]+ue[9]*Y[4]+ue[10]*Y[7],T[8]=ue[8]*Y[2]+ue[9]*Y[5]+ue[10]*Y[8]}}else if(N.x=0,N.y=0,N.z=0,this._computeParticleRotation){const z=r.m;T[0]=z[0],T[1]=z[1],T[2]=z[2],T[3]=z[4],T[4]=z[5],T[5]=z[6],T[6]=z[8],T[7]=z[9],T[8]=z[10]}const M=l[11];b.translateFromPivot?M.setAll(0):M.copyFrom(b.pivot);const I=l[0];I.copyFrom(b.position);const R=I.x-b.pivot.x,O=I.y-b.pivot.y,H=I.z-b.pivot.z;let G=R*T[0]+O*T[3]+H*T[6],Q=R*T[1]+O*T[4]+H*T[7],$=R*T[2]+O*T[5]+H*T[8];G+=M.x,Q+=M.y,$+=M.z;const V=o[m]=N.x+h.x*G+u.x*Q+d.x*$,j=o[m+1]=N.y+h.y*G+u.y*Q+d.y*$,k=o[m+2]=N.z+h.z*G+u.z*Q+d.z*$;if(this._computeBoundingBox&&(f.minimizeInPlaceFromFloats(V,j,k),p.maximizeInPlaceFromFloats(V,j,k)),this._computeParticleColor&&b.color){const z=b.color,Y=this._colors32;Y[g]=z.r,Y[g+1]=z.g,Y[g+2]=z.b,Y[g+3]=z.a}if(this._computeParticleTexture&&b.uv){const z=b.uv,Y=this._uvs32;Y[v]=z.x,Y[v+1]=z.y}}return s&&(i&&(this._computeParticleColor&&s.updateVerticesData(Z.ColorKind,a,!1,!1),this._computeParticleTexture&&s.updateVerticesData(Z.UVKind,c,!1,!1),s.updateVerticesData(Z.PositionKind,o,!1,!1)),this._computeBoundingBox&&(s.hasBoundingInfo?s.getBoundingInfo().reConstruct(f,p,s._worldMatrix):s.buildBoundingInfo(f,p,s._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){var e;(e=this.mesh)==null||e.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null}refreshVisibleSize(){var e;return this._isVisibilityBoxLocked||(e=this.mesh)==null||e.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new P(-t,-t,-t),new P(t,t,t))}get isAlwaysVisible(){return this._alwaysVisible}set isAlwaysVisible(e){this.mesh&&(this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e)}set computeParticleRotation(e){this._computeParticleRotation=e}set computeParticleColor(e){this._computeParticleColor=e}set computeParticleTexture(e){this._computeParticleTexture=e}get computeParticleColor(){return this._computeParticleColor}get computeParticleTexture(){return this._computeParticleTexture}set computeBoundingBox(e){this._computeBoundingBox=e}get computeBoundingBox(){return this._computeBoundingBox}initParticles(){}recycleParticle(e){return e}updateParticle(e){return e}beforeUpdateParticles(e,t,i){}afterUpdateParticles(e,t,i){}}Object.defineProperty(di.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(n){this._physicsImpostor!==n&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=n,n&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0});di.prototype.getPhysicsImpostor=function(){return this.physicsImpostor};di.prototype.applyImpulse=function(n,e){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(n,e),this):this};di.prototype.setPhysicsLinkWith=function(n,e,t,i){return!this.physicsImpostor||!n.physicsImpostor?this:(this.physicsImpostor.createJoint(n.physicsImpostor,as.HingeJoint,{mainPivot:e,connectedPivot:t,nativeParams:i}),this)};class hK{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw ci("")}constructor(e,t=hK.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new P(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){const r=new C9;return this._physicsPlugin.raycast(e,t,r,i),r}}var C0;(function(n){n[n.FREE=0]="FREE",n[n.LIMITED=1]="LIMITED",n[n.LOCKED=2]="LOCKED"})(C0||(C0={}));var zp;(function(n){n[n.LINEAR_X=0]="LINEAR_X",n[n.LINEAR_Y=1]="LINEAR_Y",n[n.LINEAR_Z=2]="LINEAR_Z",n[n.ANGULAR_X=3]="ANGULAR_X",n[n.ANGULAR_Y=4]="ANGULAR_Y",n[n.ANGULAR_Z=5]="ANGULAR_Z",n[n.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"})(zp||(zp={}));var xl;(function(n){n[n.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",n[n.DISTANCE=2]="DISTANCE",n[n.HINGE=3]="HINGE",n[n.SLIDER=4]="SLIDER",n[n.LOCK=5]="LOCK",n[n.PRISMATIC=6]="PRISMATIC",n[n.SIX_DOF=7]="SIX_DOF"})(xl||(xl={}));var ca;(function(n){n[n.SPHERE=0]="SPHERE",n[n.CAPSULE=1]="CAPSULE",n[n.CYLINDER=2]="CYLINDER",n[n.BOX=3]="BOX",n[n.CONVEX_HULL=4]="CONVEX_HULL",n[n.CONTAINER=5]="CONTAINER",n[n.MESH=6]="MESH",n[n.HEIGHTFIELD=7]="HEIGHTFIELD"})(ca||(ca={}));var T3;(function(n){n[n.NONE=0]="NONE",n[n.VELOCITY=1]="VELOCITY",n[n.POSITION=2]="POSITION"})(T3||(T3={}));var vf;(function(n){n.COLLISION_STARTED="COLLISION_STARTED",n.COLLISION_CONTINUED="COLLISION_CONTINUED",n.COLLISION_FINISHED="COLLISION_FINISHED",n.TRIGGER_ENTERED="TRIGGER_ENTERED",n.TRIGGER_EXITED="TRIGGER_EXITED"})(vf||(vf={}));var Wh;(function(n){n[n.STATIC=0]="STATIC",n[n.ANIMATED=1]="ANIMATED",n[n.DYNAMIC=2]="DYNAMIC"})(Wh||(Wh={}));var l8;(function(n){n[n.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",n[n.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",n[n.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"})(l8||(l8={}));class uK{constructor(e,t,i,r){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disablePreStep=!0,this.disableSync=!1,this._isDisposed=!1,this._shape=null,!r)return;const s=r.getPhysicsEngine();if(!s)throw new Error("No Physics Engine available.");if(this._physicsEngine=s,s.getPluginVersion()!=2)throw new Error("Plugin version is incorrect. Expected version 2.");const a=s.getPhysicsPlugin();if(!a)throw new Error("No Physics Plugin available.");this._physicsPlugin=a,e.rotationQuaternion||(e.rotationQuaternion=we.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i,this._motionType=t,this.disableSync=t!=Wh.DYNAMIC;const o=e;o.hasThinInstances?this._physicsPlugin.initBodyInstances(this,t,o):(e.parent&&e.computeWorldMatrix(!0),this._physicsPlugin.initBody(this,t,e.absolutePosition,e.absoluteRotationQuaternion)),this.transformNode=e,e.physicsBody=this,s.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}getClassName(){return"PhysicsBody"}clone(e){const t=new uK(e,this.getMotionType(),this.startAsleep,this.transformNode.getScene());return t.shape=this.shape,t.setMassProperties(this.getMassProperties()),t.setLinearDamping(this.getLinearDamping()),t.setAngularDamping(this.getAngularDamping()),t}updateBodyInstances(){const e=this.transformNode;e.hasThinInstances&&this._physicsPlugin.updateBodyInstances(this,e)}get numInstances(){return this._pluginDataInstances.length}get motionType(){return this._motionType}set shape(e){this._shape=e,e&&this._physicsPlugin.setShape(this,e)}get shape(){return this._shape}setEventMask(e,t){this._physicsPlugin.setEventMask(this,e,t)}getEventMask(e){return this._physicsPlugin.getEventMask(this,e)}setMotionType(e,t){this._physicsPlugin.setMotionType(this,e,t)}getMotionType(e){return this._physicsPlugin.getMotionType(this,e)}computeMassProperties(e){return this._physicsPlugin.computeMassProperties(this,e)}setMassProperties(e,t){this._physicsPlugin.setMassProperties(this,e,t)}getMassProperties(e){return this._physicsPlugin.getMassProperties(this,e)}setLinearDamping(e,t){this._physicsPlugin.setLinearDamping(this,e,t)}getLinearDamping(e){return this._physicsPlugin.getLinearDamping(this,e)}setAngularDamping(e,t){this._physicsPlugin.setAngularDamping(this,e,t)}getAngularDamping(e){return this._physicsPlugin.getAngularDamping(this,e)}setLinearVelocity(e,t){this._physicsPlugin.setLinearVelocity(this,e,t)}getLinearVelocityToRef(e,t){this._physicsPlugin.getLinearVelocityToRef(this,e,t)}getLinearVelocity(e){const t=new P;return this.getLinearVelocityToRef(t,e),t}setAngularVelocity(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)}getAngularVelocityToRef(e,t){this._physicsPlugin.getAngularVelocityToRef(this,e,t)}getAngularVelocity(e){const t=new P;return this.getAngularVelocityToRef(t,e),t}applyImpulse(e,t,i){this._physicsPlugin.applyImpulse(this,e,t,i)}applyForce(e,t,i){this._physicsPlugin.applyForce(this,e,t,i)}getGeometry(){return this._physicsPlugin.getBodyGeometry(this)}getCollisionObservable(){return this._physicsPlugin.getCollisionObservable(this)}getCollisionEndedObservable(){return this._physicsPlugin.getCollisionEndedObservable(this)}setCollisionCallbackEnabled(e){this._collisionCBEnabled=e,this._physicsPlugin.setCollisionCallbackEnabled(this,e)}setCollisionEndedCallbackEnabled(e){this._collisionEndedCBEnabled=e,this._physicsPlugin.setCollisionEndedCallbackEnabled(this,e)}getObjectCenterWorld(e){const t=new P;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){var i;if(((i=this._pluginDataInstances)==null?void 0:i.length)>0){const r=t||0,s=this.transformNode._thinInstanceDataStorage.matrixData;s&&e.set(s[r*16+12],s[r*16+13],s[r*16+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,r){this._physicsPlugin.addConstraint(this,e,t,i,r)}syncWithBone(e,t,i,r,s,a){const o=this.transformNode;if(o.rotationQuaternion)if(s){const h=ie.Quaternion[0];e.getRotationQuaternionToRef(Ci.WORLD,t,h),h.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(Ci.WORLD,t,o.rotationQuaternion);const c=ie.Vector3[0],l=ie.Vector3[1];a||(a=ie.Vector3[2],a.x=0,a.y=1,a.z=0),e.getDirectionToRef(a,t,l),e.getAbsolutePositionToRef(t,c),r==null&&i&&(r=i.length()),r!=null&&(c.x+=l.x*r,c.y+=l.y*r,c.z+=l.z*r),o.setAbsolutePosition(c)}iterateOverAllInstances(e){var t;if(((t=this._pluginDataInstances)==null?void 0:t.length)>0)for(let i=0;i{this.dispose()})}_getObjectBoundingBox(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new yd(new P(-.5,-.5,-.5),new P(.5,.5,.5))}_hasVertices(e){return(e==null?void 0:e.getTotalVertices())>0}_addSizeOptions(){this.transformNode.computeWorldMatrix(!0);const e=this._getObjectBoundingBox(),t=ie.Vector3[0];t.copyFrom(e.extendSize),t.scaleInPlace(2),t.multiplyInPlace(this.transformNode.scaling),t.x=Math.abs(t.x),t.y=Math.abs(t.y),t.z=Math.abs(t.z);const i=ie.Vector3[1];if(i.copyFrom(e.minimum),i.multiplyInPlace(this.transformNode.scaling),!this._options.center){const r=new P;r.copyFrom(e.center),r.multiplyInPlace(this.transformNode.scaling),this._options.center=r}switch(this.type){case ca.SPHERE:!this._options.radius&&_t.WithinEpsilon(t.x,t.y,1e-4)&&_t.WithinEpsilon(t.x,t.z,1e-4)?this._options.radius=t.x/2:this._options.radius||(de.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(t.x,t.y,t.z)/2);break;case ca.CAPSULE:{const r=t.x/2;this._options.radius=this._options.radius??r,this._options.pointA=this._options.pointA??new P(0,i.y+r,0),this._options.pointB=this._options.pointB??new P(0,i.y+t.y-r,0)}break;case ca.CYLINDER:{const r=t.x/2;this._options.radius=this._options.radius??r,this._options.pointA=this._options.pointA??new P(0,i.y,0),this._options.pointB=this._options.pointB??new P(0,i.y+t.y,0)}break;case ca.MESH:case ca.CONVEX_HULL:if(!this._options.mesh&&this._hasVertices(this.transformNode))this._options.mesh=this.transformNode;else if(!this._options.mesh||!this._hasVertices(this._options.mesh))throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).");break;case ca.BOX:this._options.extents=this._options.extents??new P(t.x,t.y,t.z),this._options.rotation=this._options.rotation??we.Identity();break}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class RFe{}class IFe{constructor(e,t,i){this._boxConfigs=new Array,this._joints=new Array,this._bones=new Array,this._initialRotation=new Array,this._initialRotation2=new Array,this._boneNames=[],this._transforms=new Array,this._aggregates=new Array,this._ragdollMode=!1,this._rootBoneName="",this._rootBoneIndex=-1,this._mass=10,this._restitution=0,this.pauseSync=!1,this._defaultJoint=xl.HINGE,this._defaultJointMin=-90,this._defaultJointMax=90,this._skeleton=e,this._scene=e.getScene(),this._rootTransformNode=t,this._config=i,this._boxConfigs=[],this._putBoxesInBoneCenter=!1,this._defaultJoint=xl.HINGE,this._init()}getAggregate(e){return e<0||e>=this._aggregates.length?this._aggregates[this._rootBoneIndex]:this._aggregates[e]}_createColliders(){this._rootTransformNode.computeWorldMatrix(),this._skeleton.computeAbsoluteMatrices(!0),this._skeleton.prepare(!0);const e=this._config;for(let t=0;t{this._syncBonesAndBoxes()}),this._syncBonesToPhysics())}ragdoll(){this._ragdollMode=!0,this._skeleton.bones.forEach(e=>{e.linkTransformNode(null)});for(let e=0;e{e.dispose()})}}class PFe{constructor(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addNodeMeshes(e,t){e.computeWorldMatrix(!0);const i=ie.Matrix[0];if(ce.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,i),e instanceof Se?this._addMesh(e,i):e instanceof Kf&&this._addMesh(e.sourceMesh,i),t){const r=ie.Matrix[1];e.computeWorldMatrix().invertToRef(r);const s=ie.Matrix[2];r.multiplyToRef(i,s),e.getChildMeshes(!1).filter(o=>!o.physicsBody).forEach(o=>{const c=o.computeWorldMatrix(),l=ie.Matrix[3];c.multiplyToRef(s,l),o instanceof Se?this._addMesh(o,l):o instanceof Kf&&this._addMesh(o.sourceMesh,l)})}}_addMesh(e,t){const i=e.getVerticesData(Z.PositionKind)||[],r=i.length/3,s=this._vertices.length;for(let a=0;a0)for(const t of e._pluginDataInstances)this._bodyCollisionObservable.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId),this._bodies.delete(t.hpBodyId[0]);e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId),this._bodies.delete(e._pluginData.hpBodyId[0]))}initBodyInstances(e,t,i){var a;const r=((a=i._thinInstanceDataStorage)==null?void 0:a.instancesCount)??0,s=i._thinInstanceDataStorage.matrixData;s&&(this._createOrUpdateBodyInstances(e,t,s,0,r,!1),e._pluginDataInstances.forEach((o,c)=>{this._bodies.set(o.hpBodyId[0],{body:e,index:c})}))}_createOrUpdateBodyInstances(e,t,i,r,s,a){const o=ie.Quaternion[0],c=ce.Identity();for(let l=r;ls){this._createOrUpdateBodyInstances(e,a,r,s,i,!1);const c=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];for(let l=s;l{this._hknp.HP_Body_SetEventMask(r.hpBodyId,t)},i)}getEventMask(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1]}_fromMassPropertiesTuple(e){return{centerOfMass:P.FromArray(e[0]),mass:e[1],inertia:P.FromArray(e[2]),inertiaOrientation:we.FromArray(e[3])}}_internalUpdateMassProperties(e){const t=this._internalComputeMassProperties(e),i=e.userMassProps;i.centerOfMass&&(t[0]=i.centerOfMass.asArray()),i.mass!=null&&(t[1]=i.mass),i.inertia&&(t[2]=i.inertia.asArray()),i.inertiaOrientation&&(t[3]=i.inertiaOrientation.asArray()),this._hknp.HP_Body_SetMassProperties(e.hpBodyId,t)}_internalSetMotionType(e,t){switch(t){case Wh.STATIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case Wh.ANIMATED:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case Wh.DYNAMIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC);break}}setMotionType(e,t,i){this._applyToBodyOrInstances(e,r=>{this._internalSetMotionType(r,t)},i)}getMotionType(e,t){const i=this._getPluginReference(e,t),r=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(r){case this._hknp.MotionType.STATIC:return Wh.STATIC;case this._hknp.MotionType.KINEMATIC:return Wh.ANIMATED;case this._hknp.MotionType.DYNAMIC:return Wh.DYNAMIC}throw new Error("Unknown motion type: "+r)}setActivationControl(e,t){switch(t){case l8.ALWAYS_ACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_ACTIVE);break;case l8.ALWAYS_INACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_INACTIVE);break;case l8.SIMULATION_CONTROLLED:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.SIMULATION_CONTROLLED);break}}_internalComputeMassProperties(e){const t=this._hknp.HP_Body_GetShape(e.hpBodyId);if(t[0]==this._hknp.Result.RESULT_OK){const i=this._hknp.HP_Shape_BuildMassProperties(t[1]);if(i[0]==this._hknp.Result.RESULT_OK)return i[1]}return[[0,0,0],1,[1,1,1],[0,0,0,1]]}computeMassProperties(e,t){const i=this._getPluginReference(e,t),r=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(r)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,r=>{r.userMassProps=t,this._internalUpdateMassProperties(r)},i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),r=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(r)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetLinearDamping(r.hpBodyId,t)},i)}getLinearDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetLinearDamping(i.hpBodyId)[1]}setAngularDamping(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetAngularDamping(r.hpBodyId,t)},i)}getAngularDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetAngularDamping(i.hpBodyId)[1]}setLinearVelocity(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetLinearVelocity(r.hpBodyId,this._bVecToV3(t))},i)}getLinearVelocityToRef(e,t,i){const r=this._getPluginReference(e,i),s=this._hknp.HP_Body_GetLinearVelocity(r.hpBodyId)[1];this._v3ToBvecRef(s,t)}_applyToBodyOrInstances(e,t,i){var r;if(((r=e._pluginDataInstances)==null?void 0:r.length)>0&&i===void 0)for(let s=0;s{this._hknp.HP_Body_ApplyImpulse(s.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))},r)}applyForce(e,t,i,r){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,r)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetAngularVelocity(r.hpBodyId,this._bVecToV3(t))},i)}getAngularVelocityToRef(e,t,i){const r=this._getPluginReference(e,i),s=this._hknp.HP_Body_GetAngularVelocity(r.hpBodyId)[1];this._v3ToBvecRef(s,t)}setPhysicsBodyTransformation(e,t){const i=e.transformNode;if(e.numInstances>0){const s=i._thinInstanceDataStorage.matrixData;if(!s)return;const a=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),s,0,a,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}setTargetTransform(e,t,i,r){this._applyToBodyOrInstances(e,s=>{this._hknp.HP_Body_SetTargetQTransform(s.hpBodyId,[this._bVecToV3(t),this._bQuatToV4(i)])},r)}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetGravityFactor(r.hpBodyId,t)},i)}getGravityFactor(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetGravityFactor(i.hpBodyId)[1]}disposeBody(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(const t of e._pluginDataInstances)this._hknp.HP_Body_Release(t.hpBodyId),t.hpBodyId=void 0;e._pluginData&&(this._hknp.HP_Body_Release(e._pluginData.hpBodyId),e._pluginData.hpBodyId=void 0)}initShape(e,t,i){switch(t){case ca.SPHERE:{const r=i.radius||1,s=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateSphere(s,r)[1]}break;case ca.BOX:{const r=i.rotation?this._bQuatToV4(i.rotation):[0,0,0,1],s=i.extents?this._bVecToV3(i.extents):[1,1,1],a=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateBox(a,r,s)[1]}break;case ca.CAPSULE:{const r=i.pointA?this._bVecToV3(i.pointA):[0,0,0],s=i.pointB?this._bVecToV3(i.pointB):[0,1,0],a=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCapsule(r,s,a)[1]}break;case ca.CONTAINER:e._pluginData=this._hknp.HP_Shape_CreateContainer()[1];break;case ca.CYLINDER:{const r=i.pointA?this._bVecToV3(i.pointA):[0,0,0],s=i.pointB?this._bVecToV3(i.pointB):[0,1,0],a=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCylinder(r,s,a)[1]}break;case ca.CONVEX_HULL:case ca.MESH:{const r=i.mesh;if(r){const s=!!i.includeChildMeshes,a=t!=ca.CONVEX_HULL,o=new PFe(r,a,r==null?void 0:r.getScene());o.addNodeMeshes(r,s);const c=o.getVertices(this._hknp),l=c.numObjects/3;if(t==ca.CONVEX_HULL)e._pluginData=this._hknp.HP_Shape_CreateConvexHull(c.offset,l)[1];else{const h=o.getTriangles(this._hknp),u=h.numObjects/3;e._pluginData=this._hknp.HP_Shape_CreateMesh(c.offset,l,h.offset,u)[1],o.freeBuffer(this._hknp,h)}o.freeBuffer(this._hknp,c)}else throw new Error("No mesh provided to create physics shape.")}break;case ca.HEIGHTFIELD:if(i.numHeightFieldSamplesX&&i.numHeightFieldSamplesZ&&i.heightFieldSizeX&&i.heightFieldSizeZ&&i.heightFieldData){const r=i.numHeightFieldSamplesX*i.numHeightFieldSamplesZ,s=r*4,a=this._hknp._malloc(s),o=new Float32Array(this._hknp.HEAPU8.buffer,a,r);for(let h=0;h0?e._pluginDataInstances[0]:e._pluginData,i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1],r=this._hknp.HP_Shape_CreateDebugDisplayGeometry(i);if(r[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const s=this._hknp.HP_DebugGeometry_GetInfo(r[1])[1],a=new Float32Array(this._hknp.HEAPU8.buffer,s[0],s[1]*3),o=new Uint32Array(this._hknp.HEAPU8.buffer,s[2],s[3]*3),c=a.slice(0),l=o.slice(0);return this._hknp.HP_DebugGeometry_Release(r[1]),{positions:c,indices:l}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,r,s){const a=e.type,o=e.options;if(!a||!o){de.Warn("No constraint type or options. Constraint is invalid.");return}if(t._pluginDataInstances.length>0&&r===void 0||i._pluginDataInstances.length>0&&s===void 0){de.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");return}e._pluginData=e._pluginData??[];const c=this._hknp.HP_Constraint_Create()[1];e._pluginData.push(c);const l=this._getPluginReference(t,r).hpBodyId,h=this._getPluginReference(i,s).hpBodyId;this._hknp.HP_Constraint_SetParentBody(c,l),this._hknp.HP_Constraint_SetChildBody(c,h),this._constraintToBodyIdPair.set(c[0],[l[0],h[0]]);const u=o.pivotA?this._bVecToV3(o.pivotA):this._bVecToV3(P.Zero()),d=o.axisA??new P(1,0,0),f=this._tmpVec3[0];o.perpAxisA?f.copyFrom(o.perpAxisA):d.getNormalToRef(f),this._hknp.HP_Constraint_SetAnchorInParent(c,u,this._bVecToV3(d),this._bVecToV3(f));const p=o.pivotB?this._bVecToV3(o.pivotB):this._bVecToV3(P.Zero()),_=o.axisB??new P(1,0,0),m=this._tmpVec3[0];if(o.perpAxisB?m.copyFrom(o.perpAxisB):_.getNormalToRef(m),this._hknp.HP_Constraint_SetAnchorInChild(c,p,this._bVecToV3(_),this._bVecToV3(m)),e._initOptions||(e._initOptions={axisA:d.clone(),axisB:_.clone(),perpAxisA:f.clone(),perpAxisB:m.clone(),pivotA:new P(u[0],u[1],u[2]),pivotB:new P(p[0],p[1],p[2])}),a==xl.LOCK)this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(a==xl.DISTANCE){const v=o.maxDistance||0,x=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(c,x,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(c,x,v),this._hknp.HP_Constraint_SetAxisMaxLimit(c,x,v)}else if(a==xl.HINGE)this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(a==xl.PRISMATIC)this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(a==xl.SLIDER)this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(a==xl.BALL_AND_SOCKET)this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(c,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(a==xl.SIX_DOF){const v=e;for(const x of v.limits){const y=this._constraintAxisToNative(x.axis);(x.minLimit??-1)==0&&(x.maxLimit??-1)==0?this._hknp.HP_Constraint_SetAxisMode(c,y,this._hknp.ConstraintAxisLimitMode.LOCKED):(x.minLimit!=null&&(this._hknp.HP_Constraint_SetAxisMode(c,y,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(c,y,x.minLimit)),x.maxLimit!=null&&(this._hknp.HP_Constraint_SetAxisMode(c,y,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(c,y,x.maxLimit))),x.stiffness&&this._hknp.HP_Constraint_SetAxisStiffness(c,y,x.stiffness),x.damping&&this._hknp.HP_Constraint_SetAxisDamping(c,y,x.damping)}}else throw new Error("Unsupported Constraint Type.");const g=!!o.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(c,g),this._hknp.HP_Constraint_SetEnabled(c,!0)}getBodiesUsingConstraint(e){const t=[];for(const i of e._pluginData){const r=this._constraintToBodyIdPair.get(i[0]);if(r){const s=this._bodies.get(r[0]),a=this._bodies.get(r[1]);s&&a&&t.push({parentBody:s.body,parentBodyIndex:s.index,childBody:a.body,childBodyIndex:a.index})}}return t}addConstraint(e,t,i,r,s){this.initConstraint(i,e,t,r,s)}setEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetEnabled(i,t)}getEnabled(e){const t=e._pluginData&&e._pluginData[0];return t?this._hknp.HP_Constraint_GetEnabled(t)[1]:!1}setCollisionsEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetCollisionsEnabled(i,t)}getCollisionsEnabled(e){const t=e._pluginData&&e._pluginData[0];return t?this._hknp.HP_Constraint_GetCollisionsEnabled(t)[1]:!1}setAxisFriction(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisFriction(r,this._constraintAxisToNative(t),i)}getAxisFriction(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisFriction(i,this._constraintAxisToNative(t))[1]:null}setAxisMode(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMode(r,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=e._pluginData&&e._pluginData[0];if(i){const r=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(r)}return null}setAxisMinLimit(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMinLimit(r,this._constraintAxisToNative(t),i)}getAxisMinLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMinLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMaxLimit(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMaxLimit(r,this._constraintAxisToNative(t),i)}getAxisMaxLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMaxLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMotorType(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorType(r,this._constraintAxisToNative(t),this._constraintMotorTypeToNative(i))}getAxisMotorType(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(i,this._constraintAxisToNative(t))[1]):null}setAxisMotorTarget(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorTarget(r,this._constraintAxisToNative(t),i)}getAxisMotorTarget(e,t){return e._pluginData&&e._pluginData[0]?this._hknp.HP_Constraint_GetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t))[1]:null}setAxisMotorMaxForce(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorMaxForce(r,this._constraintAxisToNative(t),i)}getAxisMotorMaxForce(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMotorMaxForce(i,this._constraintAxisToNative(t))[1]:null}disposeConstraint(e){for(const t of e._pluginData)this._hknp.HP_Constraint_SetEnabled(t,!1),this._hknp.HP_Constraint_Release(t);e._pluginData.length=0}_populateHitData(e,t){const i=this._bodies.get(e[0][0]);t.body=i==null?void 0:i.body,t.bodyIndex=i==null?void 0:i.index;const r=this._shapes.get(e[1][0]);t.shape=r;const s=e[3],a=e[4],o=e[5];t.setHitData({x:a[0],y:a[1],z:a[2]},{x:s[0],y:s[1],z:s[2]},o)}raycast(e,t,i,r){const s=(r==null?void 0:r.membership)??-1,a=(r==null?void 0:r.collideWith)??-1;i.reset(e,t);const o=!1,c=[BigInt(0)],l=[this._bVecToV3(e),this._bVecToV3(t),[s,a],o,c];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,l),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[,h]=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1];this._populateHitData(h,i),i.calculateHitDistance()}}pointProximity(e,t){var o,c;const i=((o=e==null?void 0:e.collisionFilter)==null?void 0:o.membership)??-1,r=((c=e==null?void 0:e.collisionFilter)==null?void 0:c.collideWith)??-1;t.reset();const s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],a=[this._bVecToV3(e.position),e.maxDistance,[i,r],e.shouldHitTriggers,s];if(this._hknp.HP_World_PointProximityWithCollector(this.world,this._queryCollector,a),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[l,h]=this._hknp.HP_QueryCollector_GetPointProximityResult(this._queryCollector,0)[1];this._populateHitData(h,t),t.setHitDistance(l)}}shapeProximity(e,t,i){t.reset(),i.reset();const r=e.shape._pluginData,s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],a=[r,this._bVecToV3(e.position),this._bQuatToV4(e.rotation),e.maxDistance,e.shouldHitTriggers,s];if(this._hknp.HP_World_ShapeProximityWithCollector(this.world,this._queryCollector,a),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[o,c,l]=this._hknp.HP_QueryCollector_GetShapeProximityResult(this._queryCollector,0)[1];this._populateHitData(c,t),this._populateHitData(l,i),t.setHitDistance(o),i.setHitDistance(o)}}shapeCast(e,t,i){t.reset(),i.reset();const r=e.shape._pluginData,s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],a=[r,this._bQuatToV4(e.rotation),this._bVecToV3(e.startPosition),this._bVecToV3(e.endPosition),e.shouldHitTriggers,s];if(this._hknp.HP_World_ShapeCastWithCollector(this.world,this._queryCollector,a),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[o,c,l]=this._hknp.HP_QueryCollector_GetShapeCastResult(this._queryCollector,0)[1];this._populateHitData(c,t),this._populateHitData(l,i),t.setHitFraction(o),i.setHitFraction(o)}}getCollisionObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionObservable.get(t);return i||(i=new Ae,this._bodyCollisionObservable.set(t,i)),i}getCollisionEndedObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionEndedObservable.get(t);return i||(i=new Ae,this._bodyCollisionEndedObservable.set(t,i)),i}setCollisionCallbackEnabled(e,t){const i=this._hknp.EventType.COLLISION_STARTED.value|this._hknp.EventType.COLLISION_CONTINUED.value|this._hknp.EventType.COLLISION_FINISHED.value;e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach(r=>{this._hknp.HP_Body_SetEventMask(r.hpBodyId,t?i:0)}):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,t?i:0)}setCollisionEndedCallbackEnabled(e,t){const i=this._getPluginReference(e);let r=this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1];r=t?r|this._hknp.EventType.COLLISION_FINISHED.value:r&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach(s=>{this._hknp.HP_Body_SetEventMask(s.hpBodyId,r)}):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,r)}_notifyTriggers(){let e=this._hknp.HP_World_GetTriggerEvents(this.world)[1];const t=new Hde;for(;e;){Hde.readToRef(this._hknp.HEAPU8.buffer,e,t);const i=this._bodies.get(t.bodyIdA),r=this._bodies.get(t.bodyIdB);if(i&&r){const s={collider:i.body,colliderIndex:i.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(s)}e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new zde,i=Number(this.world);for(;e;){zde.readToRef(this._hknp.HEAPU8.buffer,e,t);const r=this._bodies.get(t.contactOnA.bodyId),s=this._bodies.get(t.contactOnB.bodyId);if(r&&s){const a={collider:r.body,colliderIndex:r.index,collidedAgainst:s.body,collidedAgainstIndex:s.index,type:this._nativeCollisionValueToCollisionType(t.type)};if(a.type===vf.COLLISION_FINISHED)this.onCollisionEndedObservable.notifyObservers(a);else{t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);const o=P.Dot(this._tmpVec3[0],t.contactOnA.normal);a.point=t.contactOnA.position,a.distance=o,a.impulse=t.impulseApplied,a.normal=t.contactOnA.normal,this.onCollisionObservable.notifyObservers(a)}if(this._bodyCollisionObservable.size&&a.type!==vf.COLLISION_FINISHED){const o=this._bodyCollisionObservable.get(t.contactOnA.bodyId),c=this._bodyCollisionObservable.get(t.contactOnB.bodyId);o?o.notifyObservers(a):c&&(a.collider=s.body,a.colliderIndex=s.index,a.collidedAgainst=r.body,a.collidedAgainstIndex=r.index,a.normal=t.contactOnB.normal,c.notifyObservers(a))}else if(this._bodyCollisionEndedObservable.size){const o=this._bodyCollisionEndedObservable.get(t.contactOnA.bodyId),c=this._bodyCollisionEndedObservable.get(t.contactOnB.bodyId);o?o.notifyObservers(a):c&&(a.collider=s.body,a.colliderIndex=s.index,a.collidedAgainst=r.body,a.collidedAgainstIndex=r.index,a.normal=t.contactOnB.normal,c.notifyObservers(a))}}e=this._hknp.HP_World_GetNextCollisionEvent(i,e)}}get numBodies(){return this._hknp.HP_World_GetNumBodies(this.world)[1]}dispose(){this._hknp.HP_QueryCollector_Release(this._queryCollector),this._queryCollector=BigInt(0),this._hknp.HP_World_Release(this.world),this.world=void 0}_v3ToBvecRef(e,t){t.set(e[0],e[1],e[2])}_bVecToV3(e){return[e._x,e._y,e._z]}_bQuatToV4(e){return[e._x,e._y,e._z,e._w]}_constraintMotorTypeToNative(e){switch(e){case T3.POSITION:return this._hknp.ConstraintMotorType.POSITION;case T3.VELOCITY:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE}_nativeToMotorType(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return T3.POSITION;case this._hknp.ConstraintMotorType.VELOCITY:return T3.VELOCITY}return T3.NONE}_materialCombineToNative(e){switch(e){case Bh.GEOMETRIC_MEAN:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case Bh.MINIMUM:return this._hknp.MaterialCombine.MINIMUM;case Bh.MAXIMUM:return this._hknp.MaterialCombine.MAXIMUM;case Bh.ARITHMETIC_MEAN:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case Bh.MULTIPLY:return this._hknp.MaterialCombine.MULTIPLY}}_nativeToMaterialCombine(e){switch(e){case this._hknp.MaterialCombine.GEOMETRIC_MEAN:return Bh.GEOMETRIC_MEAN;case this._hknp.MaterialCombine.MINIMUM:return Bh.MINIMUM;case this._hknp.MaterialCombine.MAXIMUM:return Bh.MAXIMUM;case this._hknp.MaterialCombine.ARITHMETIC_MEAN:return Bh.ARITHMETIC_MEAN;case this._hknp.MaterialCombine.MULTIPLY:return Bh.MULTIPLY;default:return}}_constraintAxisToNative(e){switch(e){case zp.LINEAR_X:return this._hknp.ConstraintAxis.LINEAR_X;case zp.LINEAR_Y:return this._hknp.ConstraintAxis.LINEAR_Y;case zp.LINEAR_Z:return this._hknp.ConstraintAxis.LINEAR_Z;case zp.ANGULAR_X:return this._hknp.ConstraintAxis.ANGULAR_X;case zp.ANGULAR_Y:return this._hknp.ConstraintAxis.ANGULAR_Y;case zp.ANGULAR_Z:return this._hknp.ConstraintAxis.ANGULAR_Z;case zp.LINEAR_DISTANCE:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}}_nativeToLimitMode(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return C0.FREE;case this._hknp.ConstraintAxisLimitMode.LIMITED:return C0.LIMITED;case this._hknp.ConstraintAxisLimitMode.LOCKED:return C0.LOCKED}return C0.FREE}_limitModeToNative(e){switch(e){case C0.FREE:return this._hknp.ConstraintAxisLimitMode.FREE;case C0.LIMITED:return this._hknp.ConstraintAxisLimitMode.LIMITED;case C0.LOCKED:return this._hknp.ConstraintAxisLimitMode.LOCKED}}_nativeCollisionValueToCollisionType(e){switch(e){case this._hknp.EventType.COLLISION_STARTED.value:return vf.COLLISION_STARTED;case this._hknp.EventType.COLLISION_FINISHED.value:return vf.COLLISION_FINISHED;case this._hknp.EventType.COLLISION_CONTINUED.value:return vf.COLLISION_CONTINUED}return vf.COLLISION_STARTED}_nativeTriggerCollisionValueToCollisionType(e){switch(e){case 8:return vf.TRIGGER_ENTERED;case 16:return vf.TRIGGER_EXITED}return vf.TRIGGER_ENTERED}}pt.prototype.getPhysicsEngine=function(){return this._physicsEngine};pt.prototype.enablePhysics=function(n=null,e){if(this._physicsEngine)return!0;let t=this._getComponent(it.NAME_PHYSICSENGINE);t||(t=new DFe(this),this._addComponent(t));try{if(!e||(e==null?void 0:e.getPluginVersion())===1)this._physicsEngine=new kee(n,e);else if((e==null?void 0:e.getPluginVersion())===2)this._physicsEngine=new hK(n,e);else throw new Error("Unsupported Physics plugin version.");return this._physicsTimeAccumulator=0,!0}catch(i){return de.Error(i.message),!1}};pt.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)};pt.prototype.isPhysicsEnabled=function(){return this._physicsEngine!==void 0};pt.prototype.deleteCompoundImpostor=function(n){const e=n.parts[0].mesh;e.physicsImpostor&&(e.physicsImpostor.dispose(),e.physicsImpostor=null)};pt.prototype._advancePhysicsEngineStep=function(n){if(this._physicsEngine){const e=this._physicsEngine.getSubTimeStep();if(e>0)for(this._physicsTimeAccumulator+=n;this._physicsTimeAccumulator>e;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=e;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(n/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class DFe{constructor(e){this.name=it.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new Ae,this.scene.onAfterPhysicsObservable=new Ae,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?this.scene._physicsEngine.getTimeStep()*1e3:1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(Et.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(n){this._physicsBody!==n&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=n,n&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0});Et.prototype.getPhysicsBody=function(){return this.physicsBody};Et.prototype.applyImpulse=function(n,e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(n,e),this};class zy{static GetContactPointToRef(e,t,i,r,s){const a=e.getScene().getPhysicsEngine(),o=a==null?void 0:a.getPluginVersion();if(o===1){const l=new Fi(t,i).intersectsMesh(e);if(l.hit&&l.pickedPoint)return r.copyFrom(l.pickedPoint),!0}else if(o===2)return e.physicsBody.getObjectCenterWorldToRef(r,s),!0;return!1}static HasAppliedForces(e,t){var i,r;return e.getMotionType(t)===Wh.STATIC||(((i=e.getMassProperties(t))==null?void 0:i.mass)??0)===0||((r=e.transformNode)==null?void 0:r.getTotalVertices())===0}static IsInsideCylinder(e,t,i,r){const s=ie.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=r}}class OFe{constructor(e){if(this._hitData={force:new P,contactPoint:new P,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),!this._physicsEngine){de.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.");return}}applyRadialExplosionImpulse(e,t,i,r){if(!this._physicsEngine)return de.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;if(this._physicsEngine.getPluginVersion()===1&&this._physicsEngine.getImpostors().length===0||this._physicsEngine.getPluginVersion()===2&&this._physicsEngine.getBodies().length===0)return null;let s=!1;if(typeof t=="number"){const c=t;t=new c8,t.radius=c,t.strength=i??t.strength,t.falloff=r??t.falloff}else s=!!(t.affectedImpostorsCallback||t.affectedBodiesCallback);const a=new Gde(this._scene,t),o=this._hitData;if(this._physicsEngine.getPluginVersion()===1){const c=Array();this._physicsEngine.getImpostors().forEach(h=>{a.getImpostorHitData(h,e,o)&&(h.applyImpulse(o.force,o.contactPoint),s&&c.push({impostor:h,hitData:this._copyPhysicsHitData(o)}))}),a.triggerAffectedImpostorsCallback(c)}else this._applicationForBodies(a,e,o,s,(c,l)=>{c.applyImpulse(l.force,l.contactPoint,l.instanceIndex)});return a.dispose(!1),a}applyRadialExplosionForce(e,t,i,r){if(!this._physicsEngine)return de.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getPluginVersion()===1&&this._physicsEngine.getImpostors().length===0||this._physicsEngine.getPluginVersion()===2&&this._physicsEngine.getBodies().length===0)return null;let s=!1;if(typeof t=="number"){const c=t;t=new c8,t.radius=c,t.strength=i??t.strength,t.falloff=r??t.falloff}else s=!!(t.affectedImpostorsCallback||t.affectedBodiesCallback);const a=new Gde(this._scene,t),o=this._hitData;if(this._physicsEngine.getPluginVersion()===1){const c=Array();this._physicsEngine.getImpostors().forEach(h=>{a.getImpostorHitData(h,e,o)&&(h.applyForce(o.force,o.contactPoint),s&&c.push({impostor:h,hitData:this._copyPhysicsHitData(o)}))}),a.triggerAffectedImpostorsCallback(c)}else this._applicationForBodies(a,e,o,s,(c,l)=>{c.applyForce(l.force,l.contactPoint,l.instanceIndex)});return a.dispose(!1),a}_applicationForBodies(e,t,i,r,s){const a=Array(),o=this._physicsEngine.getBodies();for(const c of o)c.iterateOverAllInstances((l,h)=>{e.getBodyHitData(l,t,i,h)&&(s(l,i),r&&a.push({body:l,hitData:this._copyPhysicsHitData(i)}))});e.triggerAffectedBodiesCallback(a)}gravitationalField(e,t,i,r){if(!this._physicsEngine)return de.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getPluginVersion()===1&&this._physicsEngine.getImpostors().length===0||this._physicsEngine.getPluginVersion()===2&&this._physicsEngine.getBodies().length===0)return null;if(typeof t=="number"){const a=t;t=new c8,t.radius=a,t.strength=i??t.strength,t.falloff=r??t.falloff}const s=new LFe(this,this._scene,e,t);return s.dispose(!1),s}updraft(e,t,i,r,s){if(!this._physicsEngine)return de.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getPluginVersion()===1&&this._physicsEngine.getImpostors().length===0||this._physicsEngine.getPluginVersion()===2&&this._physicsEngine.getBodies().length===0)return null;if(typeof t=="number"){const o=t;t=new wte,t.radius=o,t.strength=i??t.strength,t.height=r??t.height,t.updraftMode=s??t.updraftMode}const a=new dK(this._scene,e,t);return a.dispose(!1),a}vortex(e,t,i,r){if(!this._physicsEngine)return de.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getPluginVersion()===1&&this._physicsEngine.getImpostors().length===0||this._physicsEngine.getPluginVersion()===2&&this._physicsEngine.getBodies().length===0)return null;if(typeof t=="number"){const a=t;t=new Dte,t.radius=a,t.strength=i??t.strength,t.height=r??t.height}const s=new a5(this._scene,e,t);return s.dispose(!1),s}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class Gde{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options={...new c8,...this._options}}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,r){const s=ie.Vector3[0];s.copyFrom(t).subtractInPlace(i);const a=ie.Vector3[1];if(!zy.GetContactPointToRef(e,i,s,a,r.instanceIndex))return!1;const c=P.Distance(i,a);if(c>this._options.radius)return!1;const l=this._options.falloff===rO.Constant?this._options.strength:this._options.strength*(1-c/this._options.radius);return s.scaleInPlace(l),r.force.copyFrom(s),r.contactPoint.copyFrom(a),r.distanceFromOrigin=c,!0}getBodyHitData(e,t,i,r){if(zy.HasAppliedForces(e,r))return!1;const s=e.transformNode,a=e.getObjectCenterWorld(r);return i.instanceIndex=r,this._getHitData(s,a,t,i)}getImpostorHitData(e,t,i){if(e.mass===0||e.object.getClassName()!=="Mesh"&&e.object.getClassName()!=="InstancedMesh")return!1;const r=e.object;if(!this._intersectsWithSphere(r,t,this._options.radius))return!1;const s=e.getObjectCenter();return this._getHitData(r,s,t,i),!0}triggerAffectedImpostorsCallback(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)}triggerAffectedBodiesCallback(e){this._options.affectedBodiesCallback&&this._options.affectedBodiesCallback(e)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout(()=>{this._dataFetched||this._sphere.dispose()},0))}_prepareSphere(){this._sphere||(this._sphere=Tl("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)}_intersectsWithSphere(e,t,i){return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling.setAll(i*2),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(e,!0)}}class LFe{constructor(e,t,i,r){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=r,this._dataFetched=!1,this._options={...new c8,...this._options},this._tickCallback=()=>this._tick(),this._options.strength=this._options.strength*-1}getData(){return this._dataFetched=!0,{sphere:this._sphere}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout(()=>{this._dataFetched||this._sphere.dispose()},0))}_tick(){var e;if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{const t=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);t&&(this._sphere=(e=t.getData().sphere)==null?void 0:e.clone("radialExplosionEventSphereClone"))}}}class dK{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=P.Zero(),this._originDirection=P.Zero(),this._cylinderPosition=P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new wte,...this._options},this._origin.addToRef(new P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new P(0,this._options.height,0),this._originTop),this._options.updraftMode===o5.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),this._physicsEngine.getPluginVersion()===1&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout(()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)},0))}_getHitData(e,t){let i;this._options.updraftMode===o5.Perpendicular?i=this._originDirection:i=e.subtract(this._originTop);const r=P.Distance(this._origin,e),s=this._options.strength*-1,a=i.multiplyByFloats(s,s,s);t.force.copyFrom(a),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(zy.HasAppliedForces(e))return!1;const r=e.getObjectCenterWorld(i);return zy.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)?(t.instanceIndex=i,this._getHitData(r,t),!0):!1}_getImpostorHitData(e,t){if(e.mass===0)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){const e=dK._HitData;this._physicsEngine.getPluginVersion()===1?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((i,r)=>{this._getBodyHitData(i,e,r)&&i.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=dc("updraftEventCylinder",{height:this._options.height,diameter:this._options.radius*2},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder?(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)):!1}}dK._HitData={force:new P,contactPoint:new P,distanceFromOrigin:0};class a5{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=P.Zero(),this._cylinderPosition=P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new Dte,...this._options},this._origin.addToRef(new P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new P(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),this._physicsEngine.getPluginVersion()===1&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout(()=>{this._dataFetched||this._cylinder.dispose()},0))}_getHitData(e,t,i){const r=a5._OriginOnPlane;r.set(this._origin.x,t.y,this._origin.z);const s=ie.Vector3[0];t.subtractToRef(r,s);const a=ie.Vector3[1];if(!zy.GetContactPointToRef(e,r,s,a,i.instanceIndex))return!1;const l=P.Distance(a,r)/this._options.radius,h=ie.Vector3[2];a.normalizeToRef(h),l>this._options.centripetalForceThreshold&&h.negateInPlace();let u,d,f;if(l>this._options.centripetalForceThreshold)u=h.x*this._options.centripetalForceMultiplier,d=h.y*this._options.updraftForceMultiplier,f=h.z*this._options.centripetalForceMultiplier;else{const _=P.Cross(r,t).normalize();u=(_.x+h.x)*this._options.centrifugalForceMultiplier,d=this._originTop.y*this._options.updraftForceMultiplier,f=(_.z+h.z)*this._options.centrifugalForceMultiplier}const p=ie.Vector3[3];return p.set(u,d,f),p.scaleInPlace(this._options.strength),i.force.copyFrom(p),i.contactPoint.copyFrom(t),i.distanceFromOrigin=l,!0}_getBodyHitData(e,t,i){if(zy.HasAppliedForces(e,i))return!1;const r=e.transformNode,s=e.getObjectCenterWorld(i);return zy.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)?(t.instanceIndex=i,this._getHitData(r,s,t)):!1}_getImpostorHitData(e,t){if(e.mass===0||e.object.getClassName()!=="Mesh"&&e.object.getClassName()!=="InstancedMesh")return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){const e=a5._HitData;this._physicsEngine.getPluginVersion()===1?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((i,r)=>{this._getBodyHitData(i,e,r)&&i.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=dc("vortexEventCylinder",{height:this._options.height,diameter:this._options.radius*2},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}a5._OriginOnPlane=P.Zero();a5._HitData={force:new P,contactPoint:new P,distanceFromOrigin:0};class c8{constructor(){this.radius=5,this.strength=10,this.falloff=rO.Constant,this.sphere={segments:32,diameter:1}}}class wte{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=o5.Center}}class Dte{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}var rO;(function(n){n[n.Constant=0]="Constant",n[n.Linear=1]="Linear"})(rO||(rO={}));var o5;(function(n){n[n.Center=0]="Center",n[n.Perpendicular=1]="Perpendicular"})(o5||(o5={}));class NFe extends Uee{constructor(){super(...arguments),this._hitDistance=0}get hitDistance(){return this._hitDistance}setHitDistance(e){this._hitDistance=e}reset(){super.reset(),this._hitDistance=0}}class BFe extends Uee{constructor(){super(...arguments),this._hitFraction=0}get hitFraction(){return this._hitFraction}setHitFraction(e){this._hitFraction=e}}const FFe="blackAndWhitePixelShader",UFe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;Re.ShadersStore[FFe]=UFe;class D9 extends Pt{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,r,s,a){super(e,"blackAndWhite",["degree"],null,t,i,r,s,a),this.degree=1,this.onApplyObservable.add(o=>{o.setFloat("degree",this.degree)})}static _Parse(e,t,i,r){return Qe.Parse(()=>new D9(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}B([K()],D9.prototype,"degree",void 0);xe("BABYLON.BlackAndWhitePostProcess",D9);class Cr{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let i=0;i{const c=s.attachPostProcess(o);this._indicesForCamera[a].push(c)}),this._cameras[a]||(this._cameras[a]=s)}}_detachCameras(e){const t=Ee.MakeArray(e||this._cameras);if(t)for(let i=0;i{r.detachPostProcess(o)}),this._cameras[s]&&(this._cameras[s]=null),delete this._indicesForCamera[s]}}_enable(e){const t=Ee.MakeArray(e||this._cameras);if(t)for(let i=0;i{r.detachPostProcess(a)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}const kFe="extractHighlightsPixelShader",VFe=`#include varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;Re.ShadersStore[kFe]=VFe;class fK extends Pt{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,r,s,a,o=0,c=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,r,s,a,null,o,void 0,null,c),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add(l=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&l.setTextureFromPostProcess("textureSampler",this._inputPostProcess),l.setFloat("threshold",Math.pow(this.threshold,ZS)),l.setFloat("exposure",this._exposure)})}}B([K()],fK.prototype,"threshold",void 0);xe("BABYLON.ExtractHighlightsPostProcess",fK);const zFe="bloomMergePixelShader",HFe=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } `;Re.ShadersStore[zFe]=HFe;class pK extends Pt{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,s,a,o,c,l,h=0,u=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,a,o,c,l,null,h,void 0,null,!0),this.weight=1,this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(d=>{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("bloomBlur",i),d.setFloat("bloomWeight",this.weight)}),u||this.updateEffect()}}B([K()],pK.prototype,"weight",void 0);xe("BABYLON.BloomMergePostProcess",pK);class aZ extends Cr{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,r,s=0,a=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new fK("highlights",1,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,a),this._blurX=new ao("horizontal blur",new Be(1,0),10,t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,a),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new ao("vertical blur",new Be(0,1),10,t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,a),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new pK("bloomMerge",this._downscale,this._blurY,i,t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,a),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{u.setFloat("chromatic_aberration",this.aberrationAmount),u.setFloat("screen_width",t),u.setFloat("screen_height",i),u.setFloat("radialIntensity",this.radialIntensity),u.setFloat2("direction",this.direction.x,this.direction.y),u.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)})}static _Parse(e,t,i,r){return Qe.Parse(()=>new f1(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}}B([K()],f1.prototype,"aberrationAmount",void 0);B([K()],f1.prototype,"radialIntensity",void 0);B([K()],f1.prototype,"direction",void 0);B([K()],f1.prototype,"centerPosition",void 0);B([K()],f1.prototype,"screenWidth",void 0);B([K()],f1.prototype,"screenHeight",void 0);xe("BABYLON.ChromaticAberrationPostProcess",f1);const WFe="circleOfConfusionPixelShader",jFe=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float depth=texture2D(depthSampler,vUV).r; #define CUSTOM_COC_DEPTH float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; #define CUSTOM_COC_PIXELDISTANCE float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} `;Re.ShadersStore[WFe]=jFe;class sC extends Pt{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,s,a,o,c=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,r,s,a,o,null,c,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add(h=>{if(!this._depthTexture){de.Warn("No depth texture set on CircleOfConfusionPostProcess");return}h.setTexture("depthSampler",this._depthTexture);const d=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);h.setFloat("focusDistance",this.focusDistance),h.setFloat("cocPrecalculation",d);const f=this._depthTexture.activeCamera;h.setFloat2("cameraMinMaxZ",f.minZ,f.maxZ-f.minZ)})}set depthTexture(e){this._depthTexture=e}}B([K()],sC.prototype,"lensSize",void 0);B([K()],sC.prototype,"fStop",void 0);B([K()],sC.prototype,"focusDistance",void 0);B([K()],sC.prototype,"focalLength",void 0);xe("BABYLON.CircleOfConfusionPostProcess",sC);const XFe="colorCorrectionPixelShader",YFe=`uniform sampler2D textureSampler; uniform sampler2D colorTable; varying vec2 vUV;const float SLICE_COUNT=16.0; vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; float slicePixelSize=sliceSize/width; float sliceInnerSize=slicePixelSize*(width-1.0); float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;Re.ShadersStore[XFe]=YFe;class O9 extends Pt{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,s,a,o){super(e,"colorCorrection",null,["colorTable"],i,r,s,a,o);const c=(r==null?void 0:r.getScene())||null;this._colorTableTexture=new ve(t,c,!0,!1,ve.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=ve.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=ve.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=l=>{l.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,r){return Qe.Parse(()=>new O9(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}B([K()],O9.prototype,"colorTableUrl",void 0);xe("BABYLON.ColorCorrectionPostProcess",O9);const QFe="convolutionPixelShader",$Fe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = kernel[0] + kernel[1] + kernel[2] + kernel[3] + kernel[4] + kernel[5] + kernel[6] + kernel[7] + kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;Re.ShadersStore[QFe]=$Fe;class p1 extends Pt{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,s,a,o,c=0){super(e,"convolution",["kernel","screenSize"],null,i,r,s,a,o,null,c),this.kernel=t,this.onApply=l=>{l.setFloat2("screenSize",this.width,this.height),l.setArray("kernel",this.kernel)}}static _Parse(e,t,i,r){return Qe.Parse(()=>new p1(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,r)}}p1.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1];p1.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0];p1.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1];p1.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0];p1.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2];p1.GaussianKernel=[0,1,0,1,1,1,0,1,0];B([K()],p1.prototype,"kernel",void 0);xe("BABYLON.ConvolutionPostProcess",p1);class sO extends ao{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,s,a,o,c=null,l=ve.BILINEAR_SAMPLINGMODE,h,u,d=0,f=!1,p=5){super(e,i,r,s,a,l=2,h,u,d,`#define DOF 1 `,f,p),this.direction=i,this.externalTextureSamplerBinding=!!c,this.onApplyObservable.add(_=>{c!=null&&_.setTextureFromPostProcess("textureSampler",c),_.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)})}}B([K()],sO.prototype,"direction",void 0);xe("BABYLON.DepthOfFieldBlurPostProcess",sO);const ZFe="depthOfFieldMergePixelShader",qFe=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) #else #define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) #endif uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; #if BLUR_LEVEL>0 uniform sampler2D blurStep1; #endif #if BLUR_LEVEL>1 uniform sampler2D blurStep2; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; #if BLUR_LEVEL==0 vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); #endif #if BLUR_LEVEL==1 if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} #endif #if BLUR_LEVEL==2 if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} #endif } `;Re.ShadersStore[ZFe]=qFe;class G4e extends Pt{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,s,a,o,c,l,h=0,u=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,a,o,c,l,null,h,void 0,null,!0),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(d=>{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach((f,p)=>{d.setTextureFromPostProcessOutput("blurStep"+(r.length-p-1),f)})}),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,r,s,a){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+` `),super.updateEffect(e,t,i,r,s,a)}}var Hy;(function(n){n[n.Low=0]="Low",n[n.Medium=1]="Medium",n[n.High=2]="High"})(Hy||(Hy={}));class oZ extends Cr{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=Hy.Low,r=0,s=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];const a=e.getEngine(),o=a.isWebGPU||a.webGLVersion>1?6:5;this._circleOfConfusion=new sC("circleOfConfusion",t,1,null,ve.BILINEAR_SAMPLINGMODE,a,!1,r,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let c=1,l=15;switch(i){case Hy.High:{c=3,l=51;break}case Hy.Medium:{c=2,l=31;break}default:{l=15,c=1;break}}const h=l/Math.pow(2,c-1);let u=1;for(let d=0;dnew _K(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}xe("BABYLON.DisplayPassPostProcess",_K);const tUe="filterPixelShader",iUe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;Re.ShadersStore[tUe]=iUe;class L9 extends Pt{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,s,a,o){super(e,"filter",["kernelMatrix"],null,i,r,s,a,o),this.kernelMatrix=t,this.onApply=c=>{c.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,r){return Qe.Parse(()=>new L9(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}B([qH()],L9.prototype,"kernelMatrix",void 0);xe("BABYLON.FilterPostProcess",L9);const rUe="fxaaPixelShader",sUe=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else #define TEXTUREFUNC(s,c,b) texture2D(s,c,b) #endif uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); #define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); #ifndef MALI if(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) {lumaN=lumaW;} if (!horzSpan) {lumaS=lumaE;} if (horzSpan) {lengthSign=texelSize.y;} float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) {lengthSign=-lengthSign;} float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) {posB.x+=lengthSign*0.5;} if (horzSpan) {posB.y+=lengthSign*0.5;} vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) {lumaNN=lumaSS;} float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*3.0;} if (!doneN) {posN.y-=offNP.y*3.0;} bool doneNP=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*3.0;} if (!doneP) {posP.y+=offNP.y*3.0;} if (doneNP) {if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) {dstN=posM.y-posN.y;} if (!horzSpan) {dstP=posP.y-posM.y;} bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{const h=this.texelSize;l.setFloat2("texelSize",h.x,h.y)})}_getDefines(){const e=this.getEngine();if(!e)return null;const t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?`#define MALI 1 `:null}static _Parse(e,t,i,r){return Qe.Parse(()=>new nC(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}xe("BABYLON.FxaaPostProcess",nC);const oUe="grainPixelShader",lUe=`#include uniform sampler2D textureSampler; uniform float intensity;uniform float animatedSeed;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`;Re.ShadersStore[oUe]=lUe;class aC extends Pt{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,s,a,o=0,c=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,s,a,null,o,void 0,null,c),this.intensity=30,this.animated=!1,this.onApplyObservable.add(l=>{l.setFloat("intensity",this.intensity),l.setFloat("animatedSeed",this.animated?Math.random()+1:1)})}static _Parse(e,t,i,r){return Qe.Parse(()=>new aC(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}B([K()],aC.prototype,"intensity",void 0);B([K()],aC.prototype,"animated",void 0);xe("BABYLON.GrainPostProcess",aC);const cUe="highlightsPixelShader",hUe=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;Re.ShadersStore[cUe]=hUe;class uUe extends Pt{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,r,s,a,o=0){super(e,"highlights",null,null,t,i,r,s,a,null,o)}}const dUe="imageProcessingPixelShader",fUe=`varying vec2 vUV;uniform sampler2D textureSampler; #include #include #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 result=texture2D(textureSampler,vUV); #ifdef IMAGEPROCESSING #ifndef FROMLINEARSPACE result.rgb=toLinearSpace(result.rgb); #endif result=applyImageProcessing(result); #else #ifdef FROMLINEARSPACE result=applyImageProcessing(result); #endif #endif gl_FragColor=result;}`;Re.ShadersStore[dUe]=fUe;class mK extends Pt{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let i=null;const r=this.getEngine(),s=this.getCamera();if(s)i=s.getScene();else if(r&&r.scenes){const a=r.scenes;i=a[a.length-1]}else i=bt.LastCreatedScene;i?this._imageProcessingConfiguration=i.imageProcessingConfiguration:this._imageProcessingConfiguration=new Ji}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,s,a,o=0,c){super(e,"imageProcessing",[],[],t,i,r,s,a,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},c?(c.applyByPostProcess=!0,this._attachImageProcessingConfiguration(c,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=l=>{this.imageProcessingConfiguration.bind(l,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const r in this._defines)this._defines[r]&&(e+=`#define ${r}; `);const t=["textureSampler"],i=["scale"];Ji&&(Ji.PrepareSamplers(t,this._defines),Ji.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}B([K()],mK.prototype,"_fromLinearSpace",void 0);const pUe="mrtFragmentDeclaration",_Ue=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) layout(location=0) out vec4 glFragData[{X}]; #endif `;Re.IncludesShadersStore[pUe]=_Ue;const mUe="geometryPixelShader",gUe=`#extension GL_EXT_draw_buffers : require #if defined(BUMP) || !defined(NORMAL) #extension GL_OES_standard_derivatives : enable #endif precision highp float; #ifdef BUMP varying mat4 vWorldView;varying vec3 vNormalW; #else varying vec3 vNormalV; #endif varying vec4 vViewPos; #if defined(POSITION) || defined(BUMP) varying vec3 vPositionW; #endif #ifdef VELOCITY varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #ifdef NEED_UV varying vec2 vUV; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; #endif #if defined(REFLECTIVITY) #if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; #endif #ifdef ALBEDOTEXTURE varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; #endif #ifdef REFLECTIVITYCOLOR uniform vec3 reflectivityColor; #endif #ifdef ALBEDOCOLOR uniform vec3 albedoColor; #endif #ifdef METALLIC uniform float metallic; #endif #if defined(ROUGHNESS) || defined(GLOSSINESS) uniform float glossiness; #endif #endif #if defined(ALPHATEST) && defined(NEED_UV) uniform sampler2D diffuseSampler; #endif #include #include[RENDER_TARGET_COUNT] #include #include #include void main() { #include #ifdef ALPHATEST if (texture2D(diffuseSampler,vUV).a<0.4) discard; #endif vec3 normalOutput; #ifdef BUMP vec3 normalW=normalize(vNormalW); #include #ifdef NORMAL_WORLDSPACE normalOutput=normalW; #else normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); #endif #else normalOutput=normalize(vNormalV); #endif #ifdef ENCODE_NORMAL normalOutput=normalOutput*0.5+0.5; #endif #ifdef PREPASS #ifdef PREPASS_DEPTH gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); #endif #ifdef PREPASS_NORMAL gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); #endif #else gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); #endif #ifdef POSITION gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); #endif #ifdef VELOCITY vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); #endif #ifdef REFLECTIVITY vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); #ifdef METALLICWORKFLOW float metal=1.0;float roughness=1.0; #ifdef ORMTEXTURE metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; #endif #ifdef METALLIC metal*=metallic; #endif #ifdef ROUGHNESS roughness*=(1.0-glossiness); #endif reflectivity.a-=roughness;vec3 color=vec3(1.0); #ifdef ALBEDOTEXTURE color=texture2D(albedoSampler,vAlbedoUV).rgb; #ifdef GAMMAALBEDO color=toLinearSpace(color); #endif #endif #ifdef ALBEDOCOLOR color*=albedoColor.xyz; #endif reflectivity.rgb=mix(vec3(0.04),color,metal); #else #if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) reflectivity=texture2D(reflectivitySampler,vReflectivityUV); #ifdef GAMMAREFLECTIVITYTEXTURE reflectivity.rgb=toLinearSpace(reflectivity.rgb); #endif #else #ifdef REFLECTIVITYCOLOR reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; #endif #endif #ifdef GLOSSINESSS reflectivity.a*=glossiness; #endif #endif gl_FragData[REFLECTIVITY_INDEX]=reflectivity; #endif } `;Re.ShadersStore[mUe]=gUe;const vUe="geometryVertexDeclaration",xUe="uniform mat4 viewProjection;uniform mat4 view;";Re.IncludesShadersStore[vUe]=xUe;const yUe="geometryUboDeclaration",AUe=`#include `;Re.IncludesShadersStore[yUe]=AUe;const CUe="geometryVertexShader",bUe=`precision highp float; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include<__decl__geometryVertex> #include attribute vec3 position;attribute vec3 normal; #ifdef NEED_UV varying vec2 vUV; #ifdef ALPHATEST uniform mat4 diffuseMatrix; #endif #ifdef BUMP uniform mat4 bumpMatrix;varying vec2 vBumpUV; #endif #ifdef REFLECTIVITY uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; #endif #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #ifdef BUMP varying mat4 vWorldView; #endif #ifdef BUMP varying vec3 vNormalW; #else varying vec3 vNormalV; #endif varying vec4 vViewPos; #if defined(POSITION) || defined(BUMP) varying vec3 vPositionW; #endif #ifdef VELOCITY uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #include #include vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); #ifdef BUMP vWorldView=view*finalWorld;vNormalW=normalUpdated; #else #ifdef NORMAL_WORLDSPACE vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0))); #else vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); #endif #endif vViewPos=view*worldPos; #if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); #if NUM_BONE_INFLUENCERS>0 mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); #else vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #endif #if defined(POSITION) || defined(BUMP) vPositionW=worldPos.xyz/worldPos.w; #endif gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); #include #ifdef NEED_UV #ifdef UV1 #if defined(ALPHATEST) && defined(ALPHATEST_UV1) vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #else vUV=uv; #endif #ifdef BUMP_UV1 vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef REFLECTIVITY_UV1 vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef ALBEDO_UV1 vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); #endif #endif #ifdef UV2 #if defined(ALPHATEST) && defined(ALPHATEST_UV2) vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #else vUV=uv2; #endif #ifdef BUMP_UV2 vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); #endif #ifdef REFLECTIVITY_UV2 vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); #endif #ifdef ALBEDO_UV2 vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); #endif #endif #endif #include } `;Re.ShadersStore[CUe]=bUe;const K4e=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];Sa(K4e);class yr{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(()=>{}))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===yr.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===yr.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===yr.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===yr.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===yr.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case yr.POSITION_TEXTURE_TYPE:return this._positionIndex;case yr.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case yr.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case yr.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case yr.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return typeof this._ratioOrDimensions=="object"?1:this._ratioOrDimensions}constructor(e,t=1,i=15,r){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new Ze(0,0,0,0),this._clearDepthColor=new Ze(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=r||{},yr._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const r=[],s=[Z.PositionKind,Z.NormalKind],a=e.getMesh();if(i){let f=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),f=!0),i.bumpTexture&&$e.BumpTextureEnabled&&(r.push("#define BUMP"),r.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),f=!0),this._enableReflectivity){let p=!1;i.getClassName()==="PBRMetallicRoughnessMaterial"?(i.metallicRoughnessTexture!==null&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),f=!0,p=!0),i.metallic!==null&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),p=!0),i.roughness!==null&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),p=!0),p&&(i.baseTexture!==null&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),f=!0),i.baseColor!==null&&r.push("#define ALBEDOCOLOR"))):i.getClassName()==="PBRSpecularGlossinessMaterial"?(i.specularGlossinessTexture!==null?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),f=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor!==null&&r.push("#define REFLECTIVITYCOLOR"),i.glossiness!==null&&r.push("#define GLOSSINESS")):i.getClassName()==="PBRMaterial"?(i.metallicTexture!==null&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),f=!0,p=!0),i.metallic!==null&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),p=!0),i.roughness!==null&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),p=!0),p?(i.albedoTexture!==null&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),f=!0),i.albedoColor!==null&&r.push("#define ALBEDOCOLOR")):(i.reflectivityTexture!==null?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),f=!0):i.reflectivityColor!==null&&r.push("#define REFLECTIVITYCOLOR"),i.microSurface!==null&&r.push("#define GLOSSINESS"))):i.getClassName()==="StandardMaterial"&&(i.specularTexture!==null&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),f=!0),i.specularColor!==null&&r.push("#define REFLECTIVITYCOLOR"))}f&&(r.push("#define NEED_UV"),a.isVerticesDataPresent(Z.UVKind)&&(s.push(Z.UVKind),r.push("#define UV1")),a.isVerticesDataPresent(Z.UV2Kind)&&(s.push(Z.UV2Kind),r.push("#define UV2")))}this._linkedWithPrePass&&(r.push("#define PREPASS"),this._depthIndex!==-1&&(r.push("#define DEPTH_INDEX "+this._depthIndex),r.push("#define PREPASS_DEPTH")),this._normalIndex!==-1&&(r.push("#define NORMAL_INDEX "+this._normalIndex),r.push("#define PREPASS_NORMAL"))),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(a)===-1&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&r.push("#define ENCODE_NORMAL"),a.useBones&&a.computeBonesUsingShaders&&a.skeleton?(s.push(Z.MatricesIndicesKind),s.push(Z.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(Z.MatricesIndicesExtraKind),s.push(Z.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),r.push("#define BONETEXTURE "+a.skeleton.isUsingTextureForMatrices),r.push("#define BonesPerMesh "+(a.skeleton.bones.length+1))):(r.push("#define NUM_BONE_INFLUENCERS 0"),r.push("#define BONETEXTURE false"),r.push("#define BonesPerMesh 0"));const o=a.morphTargetManager;let c=0;o&&(c=o.numMaxInfluencers||o.numInfluencers,c>0&&(r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+c),o.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),Y6(s,a,c))),t&&(r.push("#define INSTANCES"),s_(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):r.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),d2(i,this._scene,r);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),u=h.defines,d=r.join(` `);return u!==d&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:K4e,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:d,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:c}},l),d),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[],t=[];let i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[yr.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[yr.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[yr.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[yr.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[yr.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,r]=this._assignRenderTargetIndices();let s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);const a=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],c=[];for(const m of r)m?(o.push(m.textureType),c.push(m.textureFormat)):(o.push(s),c.push(5));if(this._normalsAreUnsigned=o[yr.NORMAL_TEXTURE_TYPE]===11||o[yr.NORMAL_TEXTURE_TYPE]===13,this._multiRenderTarget=new Sm("gBuffer",a,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:c,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=ve.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=ve.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const l=[!0],h=[!1],u=[!0];for(let m=1;m{m.bindAttachments(this.useSpecificClearForDepthTexture?f:d),m.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(m.bindAttachments(p),m.clear(this._clearDepthColor,!0,!0,!0)),m.bindAttachments(d)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){const m=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(m)}});const _=m=>{const g=m.getRenderingMesh(),v=m.getEffectiveMesh(),x=this._scene,y=x.getEngine(),C=m.getMaterial();if(!C)return;if(v._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[v.uniqueId]&&(this._previousTransformationMatrices[v.uniqueId]={world:ce.Identity(),viewProjection:x.getTransformMatrix()},g.skeleton)){const N=g.skeleton.getTransformMatrices(g);this._previousBonesTransformationMatrices[g.uniqueId]=this._copyBonesTransformationMatrices(N,new Float32Array(N.length))}const b=g._getInstancesRenderList(m._id,!!m.getReplacementMesh());if(b.mustReturn)return;const T=y.getCaps().instancedArrays&&(b.visibleInstances[m._id]!==null||g.hasThinInstances),S=v.getWorldMatrix();if(this.isReady(m,T)){const N=m._getDrawWrapper();if(!N)return;const D=N.effect;y.enableEffect(N),T||g._bind(m,D,C.fillMode),this._useUbo?(L5(D,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(D.setMatrix("viewProjection",x.getTransformMatrix()),D.setMatrix("view",x.getViewMatrix()));let M;const I=g._instanceDataStorage;if(!I.isFrozen&&(C.backFaceCulling||g.overrideMaterialSideOrientation!==null)){const R=v._getWorldMatrixDeterminant();M=g.overrideMaterialSideOrientation,M===null&&(M=C.sideOrientation),R<0&&(M=M===Ye.ClockWiseSideOrientation?Ye.CounterClockWiseSideOrientation:Ye.ClockWiseSideOrientation)}else M=I.sideOrientation;if(C._preBind(N,M),C.needAlphaTesting()){const R=C.getAlphaTestTexture();R&&(D.setTexture("diffuseSampler",R),D.setMatrix("diffuseMatrix",R.getTextureMatrix()))}if(C.bumpTexture&&x.getEngine().getCaps().standardDerivatives&&$e.BumpTextureEnabled&&(D.setFloat3("vBumpInfos",C.bumpTexture.coordinatesIndex,1/C.bumpTexture.level,C.parallaxScaleBias),D.setMatrix("bumpMatrix",C.bumpTexture.getTextureMatrix()),D.setTexture("bumpSampler",C.bumpTexture),D.setFloat2("vTangentSpaceParams",C.invertNormalMapX?-1:1,C.invertNormalMapY?-1:1)),this._enableReflectivity&&(C.getClassName()==="PBRMetallicRoughnessMaterial"?(C.metallicRoughnessTexture!==null&&(D.setTexture("reflectivitySampler",C.metallicRoughnessTexture),D.setMatrix("reflectivityMatrix",C.metallicRoughnessTexture.getTextureMatrix())),C.metallic!==null&&D.setFloat("metallic",C.metallic),C.roughness!==null&&D.setFloat("glossiness",1-C.roughness),C.baseTexture!==null&&(D.setTexture("albedoSampler",C.baseTexture),D.setMatrix("albedoMatrix",C.baseTexture.getTextureMatrix())),C.baseColor!==null&&D.setColor3("albedoColor",C.baseColor)):C.getClassName()==="PBRSpecularGlossinessMaterial"?(C.specularGlossinessTexture!==null?(D.setTexture("reflectivitySampler",C.specularGlossinessTexture),D.setMatrix("reflectivityMatrix",C.specularGlossinessTexture.getTextureMatrix())):C.specularColor!==null&&D.setColor3("reflectivityColor",C.specularColor),C.glossiness!==null&&D.setFloat("glossiness",C.glossiness)):C.getClassName()==="PBRMaterial"?(C.metallicTexture!==null&&(D.setTexture("reflectivitySampler",C.metallicTexture),D.setMatrix("reflectivityMatrix",C.metallicTexture.getTextureMatrix())),C.metallic!==null&&D.setFloat("metallic",C.metallic),C.roughness!==null&&D.setFloat("glossiness",1-C.roughness),C.roughness!==null||C.metallic!==null||C.metallicTexture!==null?(C.albedoTexture!==null&&(D.setTexture("albedoSampler",C.albedoTexture),D.setMatrix("albedoMatrix",C.albedoTexture.getTextureMatrix())),C.albedoColor!==null&&D.setColor3("albedoColor",C.albedoColor)):(C.reflectivityTexture!==null?(D.setTexture("reflectivitySampler",C.reflectivityTexture),D.setMatrix("reflectivityMatrix",C.reflectivityTexture.getTextureMatrix())):C.reflectivityColor!==null&&D.setColor3("reflectivityColor",C.reflectivityColor),C.microSurface!==null&&D.setFloat("glossiness",C.microSurface))):C.getClassName()==="StandardMaterial"&&(C.specularTexture!==null&&(D.setTexture("reflectivitySampler",C.specularTexture),D.setMatrix("reflectivityMatrix",C.specularTexture.getTextureMatrix())),C.specularColor!==null&&D.setColor3("reflectivityColor",C.specularColor))),fa(D,C,this._scene),g.useBones&&g.computeBonesUsingShaders&&g.skeleton){const R=g.skeleton;if(R.isUsingTextureForMatrices&&D.getUniformIndex("boneTextureWidth")>-1){const O=R.getTransformMatrixTexture(g);D.setTexture("boneSampler",O),D.setFloat("boneTextureWidth",4*(R.bones.length+1))}else D.setMatrices("mBones",g.skeleton.getTransformMatrices(g));this._enableVelocity&&D.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[g.uniqueId])}d1(g,D),g.morphTargetManager&&g.morphTargetManager.isUsingTextureForTargets&&g.morphTargetManager._bind(D),this._enableVelocity&&(D.setMatrix("previousWorld",this._previousTransformationMatrices[v.uniqueId].world),D.setMatrix("previousViewProjection",this._previousTransformationMatrices[v.uniqueId].viewProjection)),T&&g.hasThinInstances&&D.setMatrix("world",S),g._processRendering(v,m,D,C.fillMode,b,T,(R,O)=>{R||D.setMatrix("world",O)})}this._enableVelocity&&(this._previousTransformationMatrices[v.uniqueId].world=S.clone(),this._previousTransformationMatrices[v.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),g.skeleton&&this._copyBonesTransformationMatrices(g.skeleton.getTransformMatrices(g),this._previousBonesTransformationMatrices[v.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(m,g,v)=>{if((v||g===0)&&m.subMeshes)for(let x=0;x{let y;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(x.length){for(e.setColorWrite(!1),y=0;y{throw ci("GeometryBufferRendererSceneComponent")};class EUe{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(pt.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(n){n&&n.isSupported&&(this._geometryBufferRenderer=n)},enumerable:!0,configurable:!0});pt.prototype.enableGeometryBufferRenderer=function(n=1,e=15,t){return this._geometryBufferRenderer?this._geometryBufferRenderer:(this._geometryBufferRenderer=new yr(this,n,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null),this._geometryBufferRenderer)};pt.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class W4e{constructor(e){this.name=it.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(it.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}yr._SceneComponentInitialization=n=>{let e=n._getComponent(it.NAME_GEOMETRYBUFFERRENDERER);e||(e=new W4e(n),n._addComponent(e))};const TUe="motionBlurPixelShader",SUe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; #ifdef OBJECT_BASED uniform sampler2D velocitySampler; #else uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #ifdef GEOMETRY_SUPPORTED #ifdef OBJECT_BASED vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount) break;vec2 offset=vUV+velocity*(hlim+float(i)); #if defined(WEBGPU) result+=texture2DLodEXT(textureSampler,offset,0.0); #else result+=texture2D(textureSampler,offset); #endif } gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; #else vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples) break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); #if defined(WEBGPU) result+=texture2DLodEXT(textureSampler,offset1,0.0); #else result+=texture2D(textureSampler,offset1); #endif } gl_FragColor=result/float(nSamples); #endif #else gl_FragColor=texture2D(textureSampler,vUV); #endif } `;Re.ShadersStore[TUe]=SUe;class _4 extends Pt{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,s,a,o,c=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,s,a,o,`#define GEOMETRY_SUPPORTED #define SAMPLES 64.0 #define OBJECT_BASED`,c,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new EUe)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else if(this._prePassRenderer)t=this._prePassRenderer.excludedSkinnedMesh;else return;t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else if(this._prePassRenderer)t=this._prePassRenderer.excludedSkinnedMesh;else return;const i=t.indexOf(e);i!==-1&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return de.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=ce.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new Be(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(yr.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=ie.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new Be(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const i=this._geometryBufferRenderer.getTextureIndex(yr.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[i])}else if(this._prePassRenderer){const i=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[i])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join(` `))}}static _Parse(e,t,i,r){return Qe.Parse(()=>new _4(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}}B([K()],_4.prototype,"motionStrength",void 0);B([K()],_4.prototype,"motionBlurSamples",null);B([K()],_4.prototype,"isObjectBased",null);xe("BABYLON.MotionBlurPostProcess",_4);const MUe="refractionPixelShader",RUe="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";Re.ShadersStore[MUe]=RUe;class m4 extends Pt{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,s,a,o,c,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,o,c,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add(u=>{this._refTexture=this._refTexture||new ve(t,u.getScene())}),this.onApplyObservable.add(u=>{u.setColor3("baseColor",this.color),u.setFloat("depth",this.depth),u.setFloat("colorLevel",this.colorLevel),u.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return Qe.Parse(()=>new m4(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}B([K()],m4.prototype,"color",void 0);B([K()],m4.prototype,"depth",void 0);B([K()],m4.prototype,"colorLevel",void 0);B([K()],m4.prototype,"refractionTextureUrl",void 0);xe("BABYLON.RefractionPostProcess",m4);const IUe="sharpenPixelShader",PUe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;Re.ShadersStore[IUe]=PUe;class oC extends Pt{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,s,a,o=0,c=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,s,a,null,o,void 0,null,c),this.colorAmount=1,this.edgeAmount=.3,this.onApply=l=>{l.setFloat2("screenSize",this.width,this.height),l.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,r){return Qe.Parse(()=>new oC(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}B([K()],oC.prototype,"colorAmount",void 0);B([K()],oC.prototype,"edgeAmount",void 0);xe("BABYLON.SharpenPostProcess",oC);class m2{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(Ee.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Ee.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Ee.MakeArray(e||this._cameras);if(!i)return;const r=[];let s;for(s=0;s0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const i=this._renderEffects[t].getPostProcesses();if(i)for(const r of i)r.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}B([K()],m2.prototype,"_name",void 0);class j4e{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(pt.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let n=this._getComponent(it.NAME_POSTPROCESSRENDERPIPELINEMANAGER);n||(n=new X4e(this),this._addComponent(n)),this._postProcessRenderPipelineManager=new j4e}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class X4e{constructor(e){this.name=it.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(it.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class Qo extends m2{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new aZ(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen,!0),this.depthOfField=new oZ(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=o.getHardwareScalingLevel(),this._resizeObserver=o.onResizeObservable.add(()=>{this._hardwareScaleLevel=o.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new aZ(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new f1("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,ve.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new Cr(o,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new aC("Grain",1,null,ve.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new Cr(o,this.GrainPostProcessId,()=>this.grain,!0);let c=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add(()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,c?Ee.SetImmediate(()=>{this._buildPipeline()}):this._buildPipeline())}),this._buildPipeline(),c=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const t of this._cameras){const i=this._scene.enableDepthRenderer(t);i.useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add(t=>{this._cameras.indexOf(t.activeCamera)>-1&&(this.depthOfField.depthTexture=t.enableDepthRenderer(t.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const t=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=t.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new mK("imageProcessing",1,null,ve.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new Cr(e,this.ImageProcessingPostProcessId,()=>this.imageProcessing,!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,(!this._cameras||this._cameras.length===0)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new nC("fxaa",1,null,ve.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new Cr(e,this.FxaaPostProcessId,()=>this.fxaa,!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&this._cameras.indexOf(this._scene.activeCamera)===-1)&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add(()=>{this._scene.activeCamera&&this._cameras.indexOf(this._scene.activeCamera)===-1&&(this._scene.autoClear=!0)})),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add(()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)})),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&de.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew Qo(e._name,e._name._hdr,t),e,t,i)}}B([K()],Qo.prototype,"sharpenEnabled",null);B([K()],Qo.prototype,"bloomKernel",null);B([K()],Qo.prototype,"_bloomWeight",void 0);B([K()],Qo.prototype,"_bloomThreshold",void 0);B([K()],Qo.prototype,"_hdr",void 0);B([K()],Qo.prototype,"bloomWeight",null);B([K()],Qo.prototype,"bloomThreshold",null);B([K()],Qo.prototype,"bloomScale",null);B([K()],Qo.prototype,"bloomEnabled",null);B([K()],Qo.prototype,"depthOfFieldEnabled",null);B([K()],Qo.prototype,"depthOfFieldBlurLevel",null);B([K()],Qo.prototype,"fxaaEnabled",null);B([K()],Qo.prototype,"samples",null);B([K()],Qo.prototype,"imageProcessingEnabled",null);B([K()],Qo.prototype,"glowLayerEnabled",null);B([K()],Qo.prototype,"chromaticAberrationEnabled",null);B([K()],Qo.prototype,"grainEnabled",null);xe("BABYLON.DefaultRenderingPipeline",Qo);const wUe="lensHighlightsPixelShader",DUe=`uniform sampler2D textureSampler; uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } else { lum_threshold=0.5+0.44*threshold; } luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); #ifdef PENTAGON blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); #else blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); #endif blurred/=39.0;gl_FragColor=blurred;}`;Re.ShadersStore[wUe]=DUe;const OUe="depthOfFieldPixelShader",LUe=`uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; #define PI 3.14159265 #define TWOPI 6.28318530 #define inverse_focal_length 0.1 vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) {float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} col/=total_weight; if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} return col;} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); float depth=texture2D(depthSampler,distorted_coords).r; float distance=near+(far-near)*depth; vec4 color=texture2D(textureSampler,vUV); float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} `;Re.ShadersStore[OUe]=LUe;class NUe extends m2{constructor(e,t,i,r=1,s){super(i.getEngine(),e),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._pentagonBokehIsEnabled=!1,this._scene=i,this._depthTexture=i.enableDepthRenderer().getDepthMap(),t.grain_texture?this._grainTexture=t.grain_texture:this._createGrainTexture(),this._edgeBlur=t.edge_blur?t.edge_blur:0,this._grainAmount=t.grain_amount?t.grain_amount:0,this._chromaticAberration=t.chromatic_aberration?t.chromatic_aberration:0,this._distortion=t.distortion?t.distortion:0,this._highlightsGain=t.dof_gain!==void 0?t.dof_gain:-1,this._highlightsThreshold=t.dof_threshold?t.dof_threshold:1,this._dofDistance=t.dof_focus_distance!==void 0?t.dof_focus_distance:-1,this._dofAperture=t.dof_aperture?t.dof_aperture:1,this._dofDarken=t.dof_darken?t.dof_darken:0,this._dofPentagon=t.dof_pentagon!==void 0?t.dof_pentagon:!0,this._blurNoise=t.blur_noise!==void 0?t.blur_noise:!0,this._createChromaticAberrationPostProcess(r),this._createHighlightsPostProcess(r),this._createDepthOfFieldPostProcess(r/4),this.addEffect(new Cr(i.getEngine(),this.LensChromaticAberrationEffect,()=>this._chromaticAberrationPostProcess,!0)),this.addEffect(new Cr(i.getEngine(),this.HighlightsEnhancingEffect,()=>this._highlightsPostProcess,!0)),this.addEffect(new Cr(i.getEngine(),this.LensDepthOfFieldEffect,()=>this._depthOfFieldPostProcess,!0)),this._highlightsGain===-1&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),s&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"LensRenderingPipeline"}get scene(){return this._scene}get edgeBlur(){return this._edgeBlur}set edgeBlur(e){this.setEdgeBlur(e)}get grainAmount(){return this._grainAmount}set grainAmount(e){this.setGrainAmount(e)}get chromaticAberration(){return this._chromaticAberration}set chromaticAberration(e){this.setChromaticAberration(e)}get dofAperture(){return this._dofAperture}set dofAperture(e){this.setAperture(e)}get edgeDistortion(){return this._distortion}set edgeDistortion(e){this.setEdgeDistortion(e)}get dofDistortion(){return this._dofDistance}set dofDistortion(e){this.setFocusDistance(e)}get darkenOutOfFocus(){return this._dofDarken}set darkenOutOfFocus(e){this.setDarkenOutOfFocus(e)}get blurNoise(){return this._blurNoise}set blurNoise(e){this._blurNoise=e}get pentagonBokeh(){return this._pentagonBokehIsEnabled}set pentagonBokeh(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()}get highlightsGain(){return this._highlightsGain}set highlightsGain(e){this.setHighlightsGain(e)}get highlightsThreshold(){return this._highlightsThreshold}set highlightsThreshold(e){this.setHighlightsThreshold(e)}setEdgeBlur(e){this._edgeBlur=e}disableEdgeBlur(){this._edgeBlur=0}setGrainAmount(e){this._grainAmount=e}disableGrain(){this._grainAmount=0}setChromaticAberration(e){this._chromaticAberration=e}disableChromaticAberration(){this._chromaticAberration=0}setEdgeDistortion(e){this._distortion=e}disableEdgeDistortion(){this._distortion=0}setFocusDistance(e){this._dofDistance=e}disableDepthOfField(){this._dofDistance=-1}setAperture(e){this._dofAperture=e}setDarkenOutOfFocus(e){this._dofDarken=e}enablePentagonBokeh(){this._highlightsPostProcess.updateEffect(`#define PENTAGON `),this._pentagonBokehIsEnabled=!0}disablePentagonBokeh(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()}enableNoiseBlur(){this._blurNoise=!0}disableNoiseBlur(){this._blurNoise=!1}setHighlightsGain(e){this._highlightsGain=e}setHighlightsThreshold(e){this._highlightsGain===-1&&(this._highlightsGain=1),this._highlightsThreshold=e}disableHighlights(){this._highlightsGain=-1}dispose(e=!1){this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()}_createChromaticAberrationPostProcess(e){this._chromaticAberrationPostProcess=new Pt("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,ve.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=t=>{t.setFloat("chromatic_aberration",this._chromaticAberration),t.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),t.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),t.setFloat("radialIntensity",1),t.setFloat2("direction",17,17),t.setFloat2("centerPosition",.5,.5)}}_createHighlightsPostProcess(e){this._highlightsPostProcess=new Pt("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,ve.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?`#define PENTAGON `:""),this._highlightsPostProcess.externalTextureSamplerBinding=!0,this._highlightsPostProcess.onApply=t=>{t.setFloat("gain",this._highlightsGain),t.setFloat("threshold",this._highlightsThreshold),t.setTextureFromPostProcess("textureSampler",this._chromaticAberrationPostProcess),t.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),t.setFloat("screen_height",this._scene.getEngine().getRenderHeight())}}_createDepthOfFieldPostProcess(e){this._depthOfFieldPostProcess=new Pt("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,ve.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.externalTextureSamplerBinding=!0,this._depthOfFieldPostProcess.onApply=t=>{t.setTexture("depthSampler",this._depthTexture),t.setTexture("grainSampler",this._grainTexture),t.setTextureFromPostProcess("textureSampler",this._highlightsPostProcess),t.setTextureFromPostProcess("highlightsSampler",this._depthOfFieldPostProcess),t.setFloat("grain_amount",this._grainAmount),t.setBool("blur_noise",this._blurNoise),t.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),t.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),t.setFloat("distortion",this._distortion),t.setBool("dof_enabled",this._dofDistance!==-1),t.setFloat("screen_distance",1/(.1-1/this._dofDistance)),t.setFloat("aperture",this._dofAperture),t.setFloat("darken",this._dofDarken),t.setFloat("edge_blur",this._edgeBlur),t.setBool("highlights",this._highlightsGain!==-1),this._scene.activeCamera&&(t.setFloat("near",this._scene.activeCamera.minZ),t.setFloat("far",this._scene.activeCamera.maxZ))}}_createGrainTexture(){const t=new Uint8Array(1048576);for(let r=0;r1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;} float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} #endif #ifdef BLUR uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; #ifndef BLUR_BYPASS uniform sampler2D depthSampler; #ifdef BLUR_LEGACY #define inline float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} #endif #endif void main() {float result=0.0; #ifdef BLUR_BYPASS result=textureLod(textureSampler,vUV,0.0).r; #else #ifdef BLUR_H vec2 step=vec2(1.0/outSize,0.0); #else vec2 step=vec2(0.0,1.0/outSize); #endif #ifdef BLUR_LEGACY result=blur13Bilateral(textureSampler,vUV,step); #else float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess,!0)),this.addEffect(new Cr(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new Cr(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new Cr(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new Cr(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let t=0;t{if(!this._scene.activeCamera)return;const l=a?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,h=a?this._originalColorPostProcess.width:this._originalColorPostProcess.height;c.setFloat("outSize",l>0?l:h),c.setInt("samples",this.bilateralSamples),c.setFloat("soften",this.bilateralSoften),c.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?c.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&c.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(this._bits[0]&1431655765)<<1|(this._bits[0]&2863311530)>>>1>>>0,this._bits[0]=(this._bits[0]&858993459)<<2|(this._bits[0]&3435973836)>>>2>>>0,this._bits[0]=(this._bits[0]&252645135)<<4|(this._bits[0]&4042322160)>>>4>>>0,this._bits[0]=(this._bits[0]&16711935)<<8|(this._bits[0]&4278255360)>>>8>>>0,this._bits[0]*23283064365386963e-26}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=t*2*Math.PI,r=1-e*.85,s=Math.sqrt(1-r*r);return new P(Math.cos(i)*s,Math.sin(i)*s,r)}_generateHemisphere(){const e=this.samples,t=[];let i,r=0;for(;r{if(this._scene.activeCamera){if(s.setArray3("sampleSphere",this._sampleSphere),s.setFloat("randTextureTiles",32),s.setFloat("samplesFactor",1/this.samples),s.setFloat("totalStrength",this.totalStrength),s.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),s.setFloat("radius",this.radius),s.setFloat("maxZ",this.maxZ),s.setFloat("minZAspect",this.minZAspect),s.setFloat("base",this.base),s.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===Rt.PERSPECTIVE_CAMERA)s.setMatrix3x3("depthProjection",co.PERSPECTIVE_DEPTH_PROJECTION),s.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),s.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const a=this._scene.getEngine().getRenderWidth()/2,o=this._scene.getEngine().getRenderHeight()/2,c=this._scene.activeCamera.orthoLeft??-a,l=this._scene.activeCamera.orthoRight??a,h=this._scene.activeCamera.orthoBottom??-o,u=this._scene.activeCamera.orthoTop??o;s.setMatrix3x3("depthProjection",co.ORTHO_DEPTH_PROJECTION),s.setFloat("xViewport",(l-c)*.5),s.setFloat("yViewport",(u-h)*.5)}s.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(s.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),s.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(s.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),s.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),s.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new BUe)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new Pt("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=i=>{const r=this._scene.activeCamera.viewport;i.setVector4("viewport",ie.Vector4[0].copyFromFloats(r.x,r.y,r.width,r.height)),i.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const t=new Uint8Array(65536),i=Be.Zero();for(let s=0;snew co(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}co.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1];co.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1];B([K()],co.prototype,"totalStrength",void 0);B([K()],co.prototype,"maxZ",void 0);B([K()],co.prototype,"minZAspect",void 0);B([K("epsilon")],co.prototype,"_epsilon",void 0);B([K("samples")],co.prototype,"_samples",void 0);B([K("textureSamples")],co.prototype,"_textureSamples",void 0);B([K()],co.prototype,"_forceGeometryBuffer",void 0);B([K()],co.prototype,"_ratio",void 0);B([K()],co.prototype,"_textureType",void 0);B([K()],co.prototype,"radius",void 0);B([K()],co.prototype,"base",void 0);B([K("bypassBlur")],co.prototype,"_bypassBlur",void 0);B([K("expensiveBlur")],co.prototype,"_expensiveBlur",void 0);B([K()],co.prototype,"bilateralSamples",void 0);B([K()],co.prototype,"bilateralSoften",void 0);B([K()],co.prototype,"bilateralTolerance",void 0);xe("BABYLON.SSAO2RenderingPipeline",co);const zUe="ssaoPixelShader",HUe=`uniform sampler2D textureSampler;varying vec2 vUV; #ifdef SSAO uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) {vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} void main() {vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess,!0)),this.addEffect(new Cr(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new Cr(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new Cr(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new Cr(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){super._attachCameras(e,t);for(const i of this._cameras)this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let t=0;t{const i=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*i}),this._blurVPostProcess.onActivateObservable.add(()=>{const i=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*i})}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const i=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271],r=1/16;this._ssaoPostProcess=new Pt("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,`#define SAMPLES 16 #define SSAO`),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=s=>{this._firstUpdate&&(s.setArray3("sampleSphere",i),s.setFloat("samplesFactor",r),s.setFloat("randTextureTiles",4)),s.setFloat("totalStrength",this.totalStrength),s.setFloat("radius",this.radius),s.setFloat("area",this.area),s.setFloat("fallOff",this.fallOff),s.setFloat("base",this.base),s.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),s.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new Pt("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,ve.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=t=>{t.setVector4("viewport",ie.Vector4[0].copyFromFloats(0,0,1,1)),t.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const t=new Uint8Array(1048576);for(let r=0;r0.0) hitCoord-=dir;else hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} /** * Tests the given world position (hitCoord) according to the given reflection vector (dir) * until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). */ ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) {ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{const d=this._geometryBufferRenderer,f=this._prePassRenderer;if(!f&&!d)return;if(d){const g=d.getTextureIndex(yr.POSITION_TEXTURE_TYPE),v=d.getTextureIndex(yr.REFLECTIVITY_TEXTURE_TYPE);u.setTexture("normalSampler",d.getGBuffer().textures[1]),u.setTexture("positionSampler",d.getGBuffer().textures[g]),u.setTexture("reflectivitySampler",d.getGBuffer().textures[v])}else if(f){const g=f.getIndex(1),v=f.getIndex(3),x=f.getIndex(6);u.setTexture("normalSampler",f.getRenderTarget().textures[x]),u.setTexture("positionSampler",f.getRenderTarget().textures[g]),u.setTexture("reflectivitySampler",f.getRenderTarget().textures[v])}const p=t.activeCamera;if(!p)return;const _=p.getViewMatrix(!0),m=p.getProjectionMatrix(!0);u.setMatrix("projection",m),u.setMatrix("view",_),u.setFloat("threshold",this.threshold),u.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),u.setFloat("strength",this.strength),u.setFloat("stepSize",this.step),u.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(this._reflectionSamples>>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join(` `))}static _Parse(e,t,i,r){return Qe.Parse(()=>new Ud(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}B([K()],Ud.prototype,"threshold",void 0);B([K()],Ud.prototype,"strength",void 0);B([K()],Ud.prototype,"reflectionSpecularFalloffExponent",void 0);B([K()],Ud.prototype,"step",void 0);B([K()],Ud.prototype,"roughnessFactor",void 0);B([K()],Ud.prototype,"enableSmoothReflections",null);B([K()],Ud.prototype,"reflectionSamples",null);B([K()],Ud.prototype,"smoothSteps",null);xe("BABYLON.ScreenSpaceReflectionPostProcess",Ud);const jUe="standardPixelShader",XUe=`uniform sampler2D textureSampler;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS #if defined(PASS_POST_PROCESS) void main(void) {vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} #endif #if defined(DOWN_SAMPLE_X4) uniform vec2 dsOffsets[16];void main(void) {vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} #endif #if defined(BRIGHT_PASS) uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) {vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth) accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} #endif #if defined(VLSMERGE) uniform sampler2D originalSampler;void main(void) {gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} #endif #if defined(LUMINANCE) uniform vec2 lumOffsets[4];void main() {float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) {color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); #ifdef WEIGHTED_AVERAGE float GreyValue=dot(color.rgb,weight); #endif #ifdef BRIGHTNESS float GreyValue=max(color.r,max(color.g,color.b)); #endif #ifdef HSL_COMPONENT float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); #endif #ifdef MAGNITUDE float GreyValue=length(color.rgb); #endif maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} #endif #if defined(LUMINANCE_DOWN_SAMPLE) uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; #ifdef FINAL_DOWN_SAMPLER #include #endif void main() {vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) {color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} average/=9.0; #ifdef FINAL_DOWN_SAMPLER gl_FragColor=pack(average); #else gl_FragColor=vec4(average,average,0.0,1.0); #endif } #endif #if defined(HDR) uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() {vec4 color=texture2D(textureAdderSampler,vUV); #ifndef AUTO_EXPOSURE vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; #endif gl_FragColor=color;} #endif #if defined(LENS_FLARE) #define GHOSTS 3 uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) {float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} float noise(in vec2 p) {vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), hash(i+vec2(1.0,0.0)),u.x), mix(hash(i+vec2(0.0,1.0)), hash(i+vec2(1.0,1.0)),u.x),u.y);} float fbm(vec2 p) {float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} vec3 pattern(vec2 uv) {vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} float luminance(vec3 color) {return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) {return vec4( texture2D(tex,texcoord+direction*distortion.r).r, texture2D(tex,texcoord+direction*distortion.g).g, texture2D(tex,texcoord+direction*distortion.b).b, 1.0 );} void main(void) {vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples) break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} gl_FragColor=result/float(nSamples);} #endif `;Re.ShadersStore[jUe]=XUe;class Br extends m2{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join(` `))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer()){de.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");return}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect(`#define VLS #define NB_STEPS `+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect(`#define MOTION_BLUR #define MAX_MOTION_SAMPLES `+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new Ud("HDRPass",t,e,null,ve.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new Cr(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new Pt("HDRPass","standard",[],[],e,null,ve.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.originalPostProcess}),this.addEffect(new Cr(t.getEngine(),"HDRPassPostProcess",()=>this.originalPostProcess,!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new Pt("HDRDepthOfFieldSource","standard",[],[],e,null,ve.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Cr(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new Pt("HDRVLSFinal","standard",[],[],e,null,ve.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Cr(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new Pt("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,ve.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Cr(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new Pt("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,ve.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Cr(t.getEngine(),"HDRPostHDReDepthOfFieldSource",()=>this.hdrFinalPostProcess,!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new nC("fxaa",1,null,ve.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new Cr(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&de.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new Pt("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=r=>{let s=0;const a=this.downSampleX4PostProcess.width,o=this.downSampleX4PostProcess.height;for(let c=-2;c<2;c++)for(let l=-2;l<2;l++)i[s]=(c+.5)*(1/a),i[s+1]=(l+.5)*(1/o),s+=2;r.setArray2("dsOffsets",i)},this.addEffect(new Cr(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new Pt("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=r=>{const s=1/this.brightPassPostProcess.width,a=1/this.brightPassPostProcess.height;i[0]=-.5*s,i[1]=.5*a,i[2]=.5*s,i[3]=.5*a,i[4]=-.5*s,i[5]=-.5*a,i[6]=.5*s,i[7]=-.5*a,r.setArray2("dsOffsets",i),r.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new Cr(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){const s=e.getEngine(),a=new ao("HDRBlurH_"+i,new Be(1,0),this[r],t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new ao("HDRBlurV_"+i,new Be(0,1),this[r],t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);a.onActivateObservable.add(()=>{const c=a.width/s.getRenderWidth();a.kernel=this[r]*c}),o.onActivateObservable.add(()=>{const c=o.height/s.getRenderHeight();o.kernel=this.horizontalBlur?64*c:this[r]*c}),this.addEffect(new Cr(e.getEngine(),"HDRBlurH"+i,()=>a,!0)),this.addEffect(new Cr(e.getEngine(),"HDRBlurV"+i,()=>o,!0)),this.blurHPostProcesses.push(a),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new Pt("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=i=>{i.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),i.setTexture("lensSampler",this.lensTexture),i.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new Cr(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const r=i.getGBuffer();this.volumetricLightPostProcess=new Pt("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define VLS #define NB_STEPS `+this._volumetricLightStepsCount.toFixed(1));const s=Be.Zero();this.volumetricLightPostProcess.onApply=a=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const o=this.sourceLight.getShadowGenerator();a.setTexture("shadowMapSampler",o.getShadowMap()),a.setTexture("positionSampler",r.textures[2]),a.setColor3("sunColor",this.sourceLight.diffuse),a.setVector3("sunDirection",this.sourceLight.getShadowDirection()),a.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),a.setMatrix("shadowViewProjection",o.getTransformMatrix()),a.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),a.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),a.setVector2("depthValues",s)}},this.addEffect(new Cr(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new Pt("HDRVLSMerge","standard",[],["originalSampler"],t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=a=>{a.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new Cr(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,Br.LuminanceSteps);this.luminancePostProcess=new Pt("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const r=[];this.luminancePostProcess.onApply=a=>{const o=1/this.luminancePostProcess.width,c=1/this.luminancePostProcess.height;r[0]=-.5*o,r[1]=.5*c,r[2]=.5*o,r[3]=.5*c,r[4]=-.5*o,r[5]=-.5*c,r[6]=.5*o,r[7]=-.5*c,a.setArray2("lumOffsets",r)},this.addEffect(new Cr(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let a=Br.LuminanceSteps-1;a>=0;a--){i=Math.pow(3,a);let o=`#define LUMINANCE_DOWN_SAMPLE `;a===0&&(o+="#define FINAL_DOWN_SAMPLER");const c=new Pt("HDRLuminanceDownSample"+a,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,o,t);this.luminanceDownSamplePostProcesses.push(c)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((a,o)=>{const c=new Array(18);a.onApply=l=>{if(!s)return;let h=0;for(let u=-1;u<2;u++)for(let d=-1;d<2;d++)c[h]=u/s.width,c[h+1]=d/s.height,h+=2;l.setArray2("dsOffsets",c),l.setFloat("halfDestPixelSize",.5/s.width),o===this.luminanceDownSamplePostProcesses.length-1?s=this.luminancePostProcess:s=a},o===this.luminanceDownSamplePostProcesses.length-1&&(a.onAfterRender=()=>{const l=e.getEngine().readPixels(0,0,1,1),h=new Ct(1/(255*255*255),1/(255*255),1/255,1);l.then(u=>{const d=new Uint8Array(u.buffer);this._hdrCurrentLuminance=(d[0]*h.x+d[1]*h.y+d[2]*h.z+d[3]*h.w)/100})}),this.addEffect(new Cr(e.getEngine(),"HDRLuminanceDownSample"+o,()=>a,!0))})}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new Pt("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join(` `),0);let r=1,s=0,a=0;this.hdrPostProcess.onApply=o=>{if(o.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{const c=(a-s)/1e3;this._hdrCurrentLuminancer-this.hdrIncreaseRate*c?r-=this.hdrIncreaseRate*c:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=_t.Clamp(r,this.hdrMinimumLuminance,1e20),o.setFloat("averageLuminance",r)),a=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new Cr(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new Pt("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new Cr(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new Pt("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new Cr(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));const i=new Be(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=a=>{a.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),a.setTexture("lensColorSampler",this.lensColorTexture),a.setFloat("strength",this.lensFlareStrength),a.setFloat("ghostDispersal",this.lensFlareGhostDispersal),a.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,a.setVector2("resolution",i),a.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const r=ce.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=ce.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=a=>{if(!this._scene.activeCamera)return;a.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),a.setTexture("lensDirtSampler",this.lensFlareDirtTexture),a.setTexture("lensStarSampler",this.lensStarTexture);const o=this._scene.activeCamera.getViewMatrix().getRow(0),c=this._scene.activeCamera.getViewMatrix().getRow(2);let l=P.Dot(o.toVector3(),new P(1,0,0))+P.Dot(c.toVector3(),new P(0,0,1));l*=4;const h=ce.FromValues(Math.cos(l)*.5,-Math.sin(l),0,0,Math.sin(l),Math.cos(l)*.5,0,0,0,0,1,0,0,0,0,1),u=s.multiply(h).multiply(r);a.setMatrix("lensStarMatrix",u),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new Pt("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=i=>{i.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),i.setTexture("depthSampler",this._getDepthTexture()),i.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new Cr(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new _4("HDRMotionBlur",e,t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new Pt("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,ve.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define MOTION_BLUR #define MAX_MOTION_SAMPLES `+this.motionBlurSamples.toFixed(1),0);let i=0,r=ce.Identity();const s=ce.Identity();let a=ce.Identity();const o=Be.Zero();this.motionBlurPostProcess.onApply=c=>{a=e.getProjectionMatrix().multiply(e.getViewMatrix()),a.invertToRef(s),c.setMatrix("inverseViewProjection",s),c.setMatrix("prevViewProjection",r),r=a,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,c.setVector2("screenSize",o),i=e.getEngine().getFps()/60,c.setFloat("motionScale",i),c.setFloat("motionStrength",this.motionStrength),c.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new Cr(e.getEngine(),"HDRMotionBlur",()=>this.motionBlurPostProcess,!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew Br(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&Qe.Parse(()=>r.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),r}}Br.LuminanceSteps=6;B([K()],Br.prototype,"brightThreshold",void 0);B([K()],Br.prototype,"blurWidth",void 0);B([K()],Br.prototype,"horizontalBlur",void 0);B([K()],Br.prototype,"exposure",null);B([$t("lensTexture")],Br.prototype,"lensTexture",void 0);B([K()],Br.prototype,"volumetricLightCoefficient",void 0);B([K()],Br.prototype,"volumetricLightPower",void 0);B([K()],Br.prototype,"volumetricLightBlurScale",void 0);B([K()],Br.prototype,"hdrMinimumLuminance",void 0);B([K()],Br.prototype,"hdrDecreaseRate",void 0);B([K()],Br.prototype,"hdrIncreaseRate",void 0);B([K()],Br.prototype,"hdrAutoExposure",null);B([$t("lensColorTexture")],Br.prototype,"lensColorTexture",void 0);B([K()],Br.prototype,"lensFlareStrength",void 0);B([K()],Br.prototype,"lensFlareGhostDispersal",void 0);B([K()],Br.prototype,"lensFlareHaloWidth",void 0);B([K()],Br.prototype,"lensFlareDistortionStrength",void 0);B([K()],Br.prototype,"lensFlareBlurWidth",void 0);B([$t("lensStarTexture")],Br.prototype,"lensStarTexture",void 0);B([$t("lensFlareDirtTexture")],Br.prototype,"lensFlareDirtTexture",void 0);B([K()],Br.prototype,"depthOfFieldDistance",void 0);B([K()],Br.prototype,"depthOfFieldBlurWidth",void 0);B([K()],Br.prototype,"motionStrength",null);B([K()],Br.prototype,"objectBasedMotionBlur",null);B([K()],Br.prototype,"_ratio",void 0);B([K()],Br.prototype,"BloomEnabled",null);B([K()],Br.prototype,"DepthOfFieldEnabled",null);B([K()],Br.prototype,"LensFlareEnabled",null);B([K()],Br.prototype,"HDREnabled",null);B([K()],Br.prototype,"VLSEnabled",null);B([K()],Br.prototype,"MotionBlurEnabled",null);B([K()],Br.prototype,"fxaaEnabled",null);B([K()],Br.prototype,"screenSpaceReflectionsEnabled",null);B([K()],Br.prototype,"volumetricLightStepsCount",null);B([K()],Br.prototype,"motionBlurSamples",null);B([K()],Br.prototype,"samples",null);xe("BABYLON.StandardRenderingPipeline",Br);class YUe{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}const QUe="screenSpaceRayTrace",$Ue=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } /** param csOrigin Camera-space ray origin,which must be within the view volume and must have z>0.01 and project within the valid screen rectangle param csDirection Unit length camera-space ray direction param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates (**not** [-1,+1] normalized device coordinates). param csZBuffer The camera-space Z buffer param csZBufferSize Dimensions of csZBuffer param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value for clipping rays headed towards the camera param stride Step in horizontal or vertical pixels between samples. This is a float because integer math is slow on GPUs,but should be set to an integer>=1 param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units to conceal banding artifacts,plus the stride ray offset. param maxSteps Maximum number of iterations. Higher gives better images but may be slow param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. 1 is a reasonable value,depending on the scene you may need to set this value to 2 param hitPixel Pixel coordinates of the first intersection with the scene param numIterations number of iterations performed param csHitPoint Camera space location of the ray hit */ #define inline bool traceScreenSpaceRay1( vec3 csOrigin, vec3 csDirection, mat4 projectToPixelMatrix, sampler2D csZBuffer, vec2 csZBufferSize, #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER sampler2D csZBackBuffer, float csZBackSizeFactor, #endif float csZThickness, float nearPlaneZ, float stride, float jitterFraction, float maxSteps, float maxRayTraceDistance, float selfCollisionNumSkip, out vec2 startPixel, out vec2 hitPixel, out vec3 csHitPoint, out float numIterations #ifdef SSRAYTRACE_DEBUG ,out vec3 debugColor #endif ) { #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; #else float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);} if ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));} P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); #endif P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); #else hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); #endif #else #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); #else hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); #endif #endif } pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} #ifdef SSRAYTRACE_ENABLE_REFINEMENT if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || (refinementStepCount<=stride*1.4) && (rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} #endif return hit;} /** texCoord: in the [0,1] range depth: depth in view space (range [znear,zfar]]) */ vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE ndc.z=-projection[2].z-projection[3].z/depth; #else ndc.z=projection[2].z+projection[3].z/depth; #endif ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} `;Re.IncludesShadersStore[QUe]=$Ue;const ZUe="screenSpaceReflection2PixelShader",qUe=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) #define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) #else #define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) #define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) #endif uniform sampler2D textureSampler;varying vec2 vUV; #ifdef SSR_SUPPORTED uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER uniform sampler2D backDepthSampler;uniform float backSizeFactor; #endif #ifdef SSR_USE_ENVIRONMENT_CUBE uniform samplerCube envCubeSampler; #ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; #endif #endif uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; #include #include #include vec3 hash(vec3 a) {a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; #ifdef SSR_ATTENUATE_SCREEN_BORDERS vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); #endif #ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); #endif #ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS attenuation*=1.0-(numIterations/maxSteps); #endif #ifdef SSR_ATTENUATE_BACKFACE_REFLECTION vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; #endif return attenuation;} #endif void main() { #ifdef SSR_SUPPORTED vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0); #ifndef SSR_DISABLE_REFLECTIVITY_TEST if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { #ifdef SSR_USE_BLUR gl_FragColor=vec4(0.); #else gl_FragColor=colorFull; #endif return;} #endif #ifdef SSR_INPUT_IS_GAMMA_SPACE color=toLinearSpace(color); #endif vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; #ifdef SSR_DECODE_NORMAL csNormal=csNormal*2.0-1.0; #endif #ifdef SSR_NORMAL_IS_IN_WORLDSPACE csNormal=(view*vec4(csNormal,0.0)).xyz; #endif float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal); #ifdef SSR_USE_ENVIRONMENT_CUBE vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); #ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); #endif #ifdef SSR_INVERTCUBICMAP wReflectedVector.y*=-1.0; #endif #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE wReflectedVector.z*=-1.0; #endif vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; #ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE envColor=toLinearSpace(envColor); #endif #else vec3 envColor=color; #endif float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; #ifdef SSRAYTRACE_DEBUG vec3 debugColor; #endif #ifdef SSR_ATTENUATE_FACING_CAMERA reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); #endif if (reflectionAttenuation>0.0) { #ifdef SSR_USE_BLUR vec3 jitt=vec3(0.); #else float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; #endif vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); rayHasHit=traceScreenSpaceRay1( csPosition, normalize(csReflectedVector+jitt), projectionPixel, depthSampler, texSize, #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER backDepthSampler, backSizeFactor, #endif thickness, nearPlaneZ, stepSize, jitter, maxSteps, maxDistance, selfCollisionNumSkip, startPixel, hitPixel, hitPoint, numIterations #ifdef SSRAYTRACE_DEBUG ,debugColor #endif );} #ifdef SSRAYTRACE_DEBUG gl_FragColor=vec4(debugColor,1.);return; #endif vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; #ifdef SSR_INPUT_IS_GAMMA_SPACE reflectedColor=toLinearSpace(reflectedColor); #endif reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} #ifndef SSR_BLEND_WITH_FRESNEL SSR*=fresnel; #endif #ifdef SSR_USE_BLUR float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} gl_FragColor=vec4(SSR,blur_radius/255.0); #else #ifdef SSR_BLEND_WITH_FRESNEL vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #else vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #endif vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); #ifdef SSR_OUTPUT_IS_GAMMA_SPACE finalColor=toGammaSpace(finalColor); #endif gl_FragColor=vec4(finalColor,colorFull.a); #endif #else gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); #endif } `;Re.ShadersStore[ZUe]=qUe;const JUe="screenSpaceReflection2BlurPixelShader",eke=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) #else #define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) #endif uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) {vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} void main() {vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} float blurRadius=colorFull.a*255.0; vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} `;Re.ShadersStore[JUe]=eke;const tke="screenSpaceReflection2BlurCombinerPixelShader",ike=`uniform sampler2D textureSampler; uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; #include #ifdef SSR_BLEND_WITH_FRESNEL #include #include uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler; #endif void main() { #ifdef SSRAYTRACE_DEBUG gl_FragColor=texture2D(textureSampler,vUV); #else vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); #ifndef SSR_DISABLE_REFLECTIVITY_TEST if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} #endif #ifdef SSR_INPUT_IS_GAMMA_SPACE color=toLinearSpace(color); #endif #ifdef SSR_BLEND_WITH_FRESNEL vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #else vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #endif vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); #ifdef SSR_OUTPUT_IS_GAMMA_SPACE finalColor=toGammaSpace(finalColor); #endif gl_FragColor=vec4(finalColor,color.a); #endif } `;Re.ShadersStore[tke]=ike;const rke=ce.Compose(new P(.5,.5,.5),we.Identity(),new P(.5,.5,.5)),ske=ce.Compose(new P(.5,.5,1),we.Identity(),new P(.5,.5,0));class Is extends m2{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(e===0&&this._reflectivityThreshold!==0||e!==0&&this._reflectivityThreshold===0?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=e===0&&this._blurDispersionStrength!==0||e!==0&&this._blurDispersionStrength===0;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!1,s=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._forceGeometryBuffer=r,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const a=t.enableGeometryBufferRenderer();a&&(a.enableReflectivity=!0,a.useSpecificClearForDepthTexture=!0)}else{const a=t.enablePrePassRenderer();a&&(a.useSpecificClearForDepthTexture=!0,a.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){var r,s;const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&((r=this._scene.activeCamera)==null?void 0:r._getFirstPostProcess())===this._ssrPostProcess){const a=t.getRenderTarget();a&&a.textures&&(i=a.textures[t.getIndex(4)].getSize())}else(s=this._ssrPostProcess)!=null&&s.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){var t,i,r,s;const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&e.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(e.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&e.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&e.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&e.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&e.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&e.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&e.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&e.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&e.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&e.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&e.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&e.push("#define SSR_USE_BLUR"),this._debug&&e.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&e.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&e.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&e.push("#define SSR_BLEND_WITH_FRESNEL"),this._reflectivityThreshold===0&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(((t=this._geometryBufferRenderer)==null?void 0:t.generateNormalsInWorldSpace)??((i=this._prePassRenderer)==null?void 0:i.generateNormalsInWorldSpace))&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),(r=this._geometryBufferRenderer)!=null&&r.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL"),(s=this._ssrPostProcess)==null||s.updateEffect(e.join(` `))}_buildPipeline(){var t;if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const i=(t=this._cameras)==null?void 0:t[0];i&&(this._depthRendererCamera=i,this._depthRenderer=new f4(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),i.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new Cr(e,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new Cr(e,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new Cr(e,this.SSRCombineRenderEffect,()=>this._blurCombinerPostProcess,!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==r)&&this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;e!==-1&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,r;for(let s=0;s{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const c=t.getTextureIndex(yr.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[c]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const c=i.getIndex(5),l=i.getIndex(3),h=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[h]),e.setTexture("depthSampler",i.getRenderTarget().textures[c]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[l])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const r=this._scene.activeCamera;if(!r)return;const s=r.getViewMatrix(),a=r.getProjectionMatrix();a.invertToRef(ie.Matrix[0]),s.invertToRef(ie.Matrix[1]),e.setMatrix("projection",a),e.setMatrix("view",s),e.setMatrix("invView",ie.Matrix[1]),e.setMatrix("invProjectionMatrix",ie.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",r.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();ce.ScalingToRef(o.width,o.height,1,ie.Matrix[2]),a.multiplyToRef(this._scene.getEngine().isWebGPU?ske:rke,ie.Matrix[3]),ie.Matrix[3].multiplyToRef(ie.Matrix[2],ie.Matrix[4]),e.setMatrix("projectionPixel",ie.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new YUe)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new Pt("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add(s=>{var o;const a=((o=this._blurPostProcessX)==null?void 0:o.inputTexture.width)??this._scene.getEngine().getRenderWidth();s.setFloat2("texelOffsetScale",this._blurDispersionStrength/a,0)}),this._blurPostProcessY=new Pt("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add(s=>{var o;const a=((o=this._blurPostProcessY)==null?void 0:o.inputTexture.height)??this._scene.getEngine().getRenderHeight();s.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/a)});const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let r="";this._debug&&(r+=`#define SSRAYTRACE_DEBUG `),this._inputTextureColorIsInGammaSpace&&(r+=`#define SSR_INPUT_IS_GAMMA_SPACE `),this._generateOutputInGammaSpace&&(r+=`#define SSR_OUTPUT_IS_GAMMA_SPACE `),this.useFresnel&&(r+=`#define SSR_BLEND_WITH_FRESNEL `,t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),this._reflectivityThreshold===0&&(r+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new Pt("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,r,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(s=>{var c;const a=this._geometryBufferRenderer,o=this._prePassRenderer;if(!(!o&&!a)){if(o&&((c=this._scene.activeCamera)==null?void 0:c._getFirstPostProcess())===this._ssrPostProcess){const l=o.getRenderTarget();l&&l.textures&&s.setTexture("mainSampler",l.textures[o.getIndex(4)])}else s.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(a){const l=a.getTextureIndex(yr.REFLECTIVITY_TEXTURE_TYPE);s.setTexture("reflectivitySampler",a.getGBuffer().textures[l]),this.useFresnel&&(s.setTexture("normalSampler",a.getGBuffer().textures[1]),s.setTexture("depthSampler",a.getGBuffer().textures[0]))}else if(o){const l=o.getIndex(3);if(s.setTexture("reflectivitySampler",o.getRenderTarget().textures[l]),this.useFresnel){const h=o.getIndex(5),u=o.getIndex(6);s.setTexture("normalSampler",o.getRenderTarget().textures[u]),s.setTexture("depthSampler",o.getRenderTarget().textures[h])}}if(s.setFloat("strength",this.strength),s.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),s.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const l=this._scene.activeCamera;if(l){const h=l.getProjectionMatrix();h.invertToRef(ie.Matrix[0]),s.setMatrix("projection",h),s.setMatrix("invProjectionMatrix",ie.Matrix[0])}}}})}serialize(){const e=Qe.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return Qe.Parse(()=>new Is(e._name,t,e._ratio),e,t,i)}}B([K()],Is.prototype,"samples",null);B([K()],Is.prototype,"maxDistance",void 0);B([K()],Is.prototype,"step",void 0);B([K()],Is.prototype,"thickness",void 0);B([K()],Is.prototype,"strength",void 0);B([K()],Is.prototype,"reflectionSpecularFalloffExponent",void 0);B([K()],Is.prototype,"maxSteps",void 0);B([K()],Is.prototype,"roughnessFactor",void 0);B([K()],Is.prototype,"selfCollisionNumSkip",void 0);B([K()],Is.prototype,"_reflectivityThreshold",void 0);B([K("_ssrDownsample")],Is.prototype,"_ssrDownsample",void 0);B([K()],Is.prototype,"ssrDownsample",null);B([K("blurDispersionStrength")],Is.prototype,"_blurDispersionStrength",void 0);B([K("blurDownsample")],Is.prototype,"_blurDownsample",void 0);B([K("enableSmoothReflections")],Is.prototype,"_enableSmoothReflections",void 0);B([K("environmentTexture")],Is.prototype,"_environmentTexture",void 0);B([K("environmentTextureIsProbe")],Is.prototype,"_environmentTextureIsProbe",void 0);B([K("attenuateScreenBorders")],Is.prototype,"_attenuateScreenBorders",void 0);B([K("attenuateIntersectionDistance")],Is.prototype,"_attenuateIntersectionDistance",void 0);B([K("attenuateIntersectionIterations")],Is.prototype,"_attenuateIntersectionIterations",void 0);B([K("attenuateFacingCamera")],Is.prototype,"_attenuateFacingCamera",void 0);B([K("attenuateBackfaceReflection")],Is.prototype,"_attenuateBackfaceReflection",void 0);B([K("clipToFrustum")],Is.prototype,"_clipToFrustum",void 0);B([K("useFresnel")],Is.prototype,"_useFresnel",void 0);B([K("enableAutomaticThicknessComputation")],Is.prototype,"_enableAutomaticThicknessComputation",void 0);B([K("backfaceDepthTextureDownsample")],Is.prototype,"_backfaceDepthTextureDownsample",void 0);B([K("backfaceForceDepthWriteTransparentMeshes")],Is.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0);B([K("isEnabled")],Is.prototype,"_isEnabled",void 0);B([K("inputTextureColorIsInGammaSpace")],Is.prototype,"_inputTextureColorIsInGammaSpace",void 0);B([K("generateOutputInGammaSpace")],Is.prototype,"_generateOutputInGammaSpace",void 0);B([K("debug")],Is.prototype,"_debug",void 0);xe("BABYLON.SSRRenderingPipeline",Is);const nke="taaPixelShader",ake=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);} `;Re.ShadersStore[nke]=ake;class g2 extends m2{set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():this._cameras!==null&&(this._firstUpdate=!0,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,r=0){const s=t.getEngine();super(s,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._samples=8,this._msaaSamples=1,this.factor=.05,this.disableOnCameraMove=!0,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._firstUpdate=!0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._hs=new w3e(this.samples),this.isSupported&&(this._createPingPongTextures(s.getRenderWidth(),s.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){var r,s;const i=this._scene.getEngine();(r=this._ping)==null||r.dispose(),(s=this._pong)==null||s.dispose(),this._ping=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._pong=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._hs.setDimensions(e/2,t/2),this._firstUpdate=!0}_updateEffectDefines(){var t;const e=[];(t=this._taaPostProcess)==null||t.updateEffect(e.join(` `))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new Cr(e,this.TAARenderEffect,()=>this._taaPostProcess,!0)),this._createPassPostProcess(),this.addEffect(new Cr(e,this.TAAPassEffect,()=>this._passPostProcess,!0)),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){var e,t;for(let i=0;i{var t,i;const e=this._scene.activeCamera;if(((t=this._taaPostProcess)==null?void 0:t.width)!==this._ping.width||((i=this._taaPostProcess)==null?void 0:i.height)!==this._ping.height){const r=this._scene.getEngine();this._createPingPongTextures(r.getRenderWidth(),r.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===Rt.PERSPECTIVE_CAMERA){const r=e.getProjectionMatrix();r.setRowFromFloats(2,this._hs.x,this._hs.y,r.m[10],r.m[11])}else{const r=e.getProjectionMatrix(!0);r.setRowFromFloats(3,this._hs.x+r.m[12],this._hs.y+r.m[13],r.m[14],r.m[15])}this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=this._pingpong^1,this._hs.next()}),this._taaPostProcess.onApplyObservable.add(e=>{const t=this._scene.activeCamera;e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture),e.setFloat("factor",t!=null&&t.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1})}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new Zf("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=Qe.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return Qe.Parse(()=>new g2(e._name,t,e._ratio),e,t,i)}}B([K("samples")],g2.prototype,"_samples",void 0);B([K("msaaSamples")],g2.prototype,"_msaaSamples",void 0);B([K()],g2.prototype,"factor",void 0);B([K()],g2.prototype,"disableOnCameraMove",void 0);B([K("isEnabled")],g2.prototype,"_isEnabled",void 0);xe("BABYLON.TAARenderingPipeline",g2);const oke="tonemapPixelShader",lke=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; #if defined(HABLE_TONEMAPPING) const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2; #endif float Luminance(vec3 c) {return dot(c,vec3(0.22,0.707,0.071));} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec3 colour=texture2D(textureSampler,vUV).rgb; #if defined(REINHARD_TONEMAPPING) float lum=Luminance(colour.rgb); float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); colour*=scale/lum; #elif defined(HABLE_TONEMAPPING) colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; #elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; #elif defined(PHOTOGRAPHIC_TONEMAPPING) colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); #endif gl_FragColor=vec4(colour.rgb,1.0);}`;Re.ShadersStore[oke]=lke;var Sy;(function(n){n[n.Hable=0]="Hable",n[n.Reinhard=1]="Reinhard",n[n.HejiDawson=2]="HejiDawson",n[n.Photographic=3]="Photographic"})(Sy||(Sy={}));class cke extends Pt{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,r,s=2,a,o=0,c){super(e,"tonemap",["_ExposureAdjustment"],null,1,r,s,a,c,null,o),this._operator=t,this.exposureAdjustment=i;let l="#define ";this._operator===Sy.Hable?l+="HABLE_TONEMAPPING":this._operator===Sy.Reinhard?l+="REINHARD_TONEMAPPING":this._operator===Sy.HejiDawson?l+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":this._operator===Sy.Photographic&&(l+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(l),this.onApply=h=>{h.setFloat("_ExposureAdjustment",this.exposureAdjustment)}}}const hke="volumetricLightScatteringPixelShader",uke=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i #include #include #include[0..maxSimultaneousMorphTargets] #include uniform mat4 viewProjection;uniform vec2 depthValues; #if defined(ALPHATEST) || defined(NEED_UV) varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); #if defined(ALPHATEST) || defined(BASIC_RENDER) #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif } `;Re.ShadersStore[dke]=fke;const pke="volumetricLightScatteringPassPixelShader",_ke=`#if defined(ALPHATEST) || defined(NEED_UV) varying vec2 vUV; #endif #if defined(ALPHATEST) uniform sampler2D diffuseSampler; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #if defined(ALPHATEST) vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) discard; #endif gl_FragColor=vec4(0.0,0.0,0.0,1.0);} `;Re.ShadersStore[pke]=_ke;class zu extends Pt{get useDiffuseColor(){return de.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){de.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,r,s=100,a=ve.BILINEAR_SAMPLINGMODE,o,c,l){super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,a,o,c,"#define NUM_SAMPLES "+s),this._screenCoordinates=Be.Zero(),this.customMeshPosition=P.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,l=(i==null?void 0:i.getScene())??l??this._scene,o=l.getEngine(),this._viewPort=new bl(0,0,1,1).toGlobal(o.getRenderWidth(),o.getRenderHeight()),this.mesh=r??zu.CreateDefaultMesh("VolumetricLightScatteringMesh",l),this._createPass(l,t.passRatio||t),this.onActivate=h=>{this.isSupported||this.dispose(h),this.onActivate=null},this.onApplyObservable.add(h=>{this._updateMeshScreenCoordinates(l),h.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),h.setFloat("exposure",this.exposure),h.setFloat("decay",this.decay),h.setFloat("weight",this.weight),h.setFloat("density",this.density),h.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var u;const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const r=(u=i._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:u[this._scene.getEngine().currentRenderPassId];if(r)return r.isReadyForSubMesh(i,e,t);const s=[],a=[Z.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&s.push("#define ALPHATEST"),i.isVerticesDataPresent(Z.UVKind)&&(a.push(Z.UVKind),s.push("#define UV1")),i.isVerticesDataPresent(Z.UV2Kind)&&(a.push(Z.UV2Kind),s.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(a.push(Z.MatricesIndicesKind),a.push(Z.MatricesWeightsKind),s.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),s.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0"),t&&(s.push("#define INSTANCES"),s_(a),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(void 0,!0),l=c.defines,h=s.join(` `);return l!==h&&c.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],h,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers}),h),c.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);t!==-1&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&this.includedMeshes.indexOf(e)===-1||this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new es("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=ve.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=ve.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const r=this.getCamera();r?r.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const s=c=>{var m;const l=c.getRenderingMesh(),h=c.getEffectiveMesh();if(this._meshExcluded(l))return;h._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const u=c.getMaterial();if(!u)return;const d=l.getScene(),f=d.getEngine();f.setState(u.backFaceCulling,void 0,void 0,void 0,u.cullBackFaces);const p=l._getInstancesRenderList(c._id,!!c.getReplacementMesh());if(p.mustReturn)return;const _=f.getCaps().instancedArrays&&(p.visibleInstances[c._id]!==null||l.hasThinInstances);if(this._isReady(c,_)){const g=(m=h._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:m[f.currentRenderPassId];let v=c._getDrawWrapper();if(l===this.mesh&&!v&&(v=u._getDrawWrapper()),!v)return;const x=v.effect;if(f.enableEffect(v),_||l._bind(c,x,u.fillMode),l===this.mesh)u.bind(h.getWorldMatrix(),l);else if(g)g.bindForSubMesh(h.getWorldMatrix(),h,c);else{if(x.setMatrix("viewProjection",d.getTransformMatrix()),u&&u.needAlphaTesting()){const y=u.getAlphaTestTexture();x.setTexture("diffuseSampler",y),y&&x.setMatrix("diffuseMatrix",y.getTextureMatrix())}l.useBones&&l.computeBonesUsingShaders&&l.skeleton&&x.setMatrices("mBones",l.skeleton.getTransformMatrices(l))}_&&l.hasThinInstances&&x.setMatrix("world",h.getWorldMatrix()),l._processRendering(h,c,x,Ye.TriangleFillMode,p,_,(y,C)=>{y||x.setMatrix("world",C)})}};let a;const o=new Ze(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{a=e.clearColor,e.clearColor=o}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=a}),this._volumetricLightScatteringRTT.customIsReadyFunction=(c,l,h)=>{if((h||l===0)&&c.subMeshes)for(let u=0;u{const d=e.getEngine();let f;if(u.length){for(d.setColorWrite(!1),f=0;f_._alphaIndex>m._alphaIndex?1:_._alphaIndexm._distanceToCamera?-1:0),d.setAlphaMode(2),f=0;f{h.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),h.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const u=this._geometryBufferRenderer.getGBuffer().textures[1];h.setTexture("normalSampler",u)}):de.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=bt.LastCreatedEngine;return e?e.getCaps().drawBuffersExtension:!1}static _Parse(e,t,i,r){return Qe.Parse(()=>new W5(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}B([K()],W5.prototype,"ridge",void 0);B([K()],W5.prototype,"valley",void 0);xe("BABYLON.ScreenSpaceCurvaturePostProcess",W5);const vke="boundingBoxRendererFragmentDeclaration",xke=`uniform vec4 color; `;Re.IncludesShadersStore[vke]=xke;const yke="boundingBoxRendererUboDeclaration",Ake=`#ifdef WEBGL2 uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif #else layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; #endif `;Re.IncludesShadersStore[yke]=Ake;const Cke="boundingBoxRendererPixelShader",bke=`#include<__decl__boundingBoxRendererFragment> #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END }`;Re.ShadersStore[Cke]=bke;const Eke="boundingBoxRendererVertexDeclaration",Tke=`uniform mat4 world;uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif `;Re.IncludesShadersStore[Eke]=Tke;const Ske="boundingBoxRendererVertexShader",Mke=`attribute vec3 position; #include<__decl__boundingBoxRendererVertex> #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec4 worldPos=world*vec4(position,1.0); #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} #else gl_Position=viewProjection*worldPos; #endif #define CUSTOM_VERTEX_MAIN_END } `;Re.ShadersStore[Ske]=Mke;Object.defineProperty(pt.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(n){this._forceShowBoundingBoxes=n,n&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});pt.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new Y4e(this)),this._boundingBoxRenderer};Object.defineProperty(di.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(n){this._showBoundingBox=n,n&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class Y4e{constructor(e){this.name=it.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Me(1,1,1),this.backColor=new Me(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new Ae,this.onAfterBoxRenderingObservable=new Ae,this.onResourcesReadyObservable=new Ae,this.enabled=!0,this.renderList=new ba(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new Ft(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new Ft(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(it.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(it.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(it.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(it.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();i!=null&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new kn("colorShader",this.scene,"boundingBoxRenderer",{attributes:[Z.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new kn("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[Z.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=MG({size:1});this._vertexBuffers[Z.PositionKind]=new Z(e,t.positions,Z.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[Z.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(this.renderList.length===0||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let r=0;r{let e=n._getComponent(it.NAME_DEPTHRENDERER);e||(e=new Q4e(n),n._addComponent(e))};const Rke="oitFinalPixelShader",Ike=`precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( frontColor.rgb+alphaMultiplier*backColor.rgb, frontColor.a+backColor.a );}`;Re.ShadersStore[Rke]=Ike;const Pke="oitBackBlendPixelShader",wke=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { discard;}}`;Re.ShadersStore[Pke]=wke;class Dke{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class V0{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){this._excludedMeshes.indexOf(e.uniqueId)===-1&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);t!==-1&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new ba(10),this._excludedSubMeshes=new ba(10),this._excludedMeshes=[],this._colorCache=[new Ze(V0._DEPTH_CLEAR_VALUE,V0._DEPTH_CLEAR_VALUE,0,0),new Ze(-V0._MIN_DEPTH,V0._MAX_DEPTH,0,0),new Ze(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){de.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let i=0;i uniform vec4 color; #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #include gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END }`;Re.ShadersStore[Oke]=Lke;const Nke="lineVertexShader",Bke=`#include #include attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN #include mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) vec4 worldPos=finalWorld*vec4(position,1.0); #include #endif #include #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[Nke]=Bke;di.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this};di.prototype.enableEdgesRendering=function(n=.95,e=!1,t){return this.disableEdgesRendering(),this._edgesRenderer=new N9(this,n,e,!0,t),this};Object.defineProperty(di.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0});i2.prototype.enableEdgesRendering=function(n=.95,e=!1){return this.disableEdgesRendering(),this._edgesRenderer=new Z4e(this,n,e),this};_ee.prototype.enableEdgesRendering=function(n=.95,e=!1){return i2.prototype.enableEdgesRendering.apply(this,arguments),this};class Fke{constructor(){this.edges=[],this.edgesConnectedCount=0}}class N9{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){const t=new kn("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,r=!0,s){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new ba(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=s??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Sn(e.getEngine())),this._prepareRessources(),r&&((s==null?void 0:s.useAlternateEdgeFinder)??!0?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=N9._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[Z.PositionKind];e&&e._rebuild(),e=this._buffers[Z.NormalKind],e&&e._rebuild();const i=this._source.getScene().getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var t;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[Z.PositionKind];e&&(e.dispose(),this._buffers[Z.PositionKind]=null),e=this._buffers[Z.NormalKind],e&&(e.dispose(),this._buffers[Z.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),(t=this._drawWrapper)==null||t.dispose()}_processEdgeForAdjacencies(e,t,i,r,s){return e===i&&t===r||e===r&&t===i?0:e===r&&t===s||e===s&&t===r?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,s){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)?1:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)?2:-1}_checkEdge(e,t,i,r,s){let a;t===void 0?a=!0:a=P.Dot(i[e],i[t]){D>=0&&N.push(D);for(let M=0;M=e[0].length&&e[1].length>=e[2].length?a=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(a=2);for(let S=0;S<3;++S)S===a?e[S].sort((N,D)=>N[1]D[1]?1:0):e[S].sort((N,D)=>N[1]>D[1]?-1:N[1]=a+1;--S)s(e[S%3],c,S!==a+2?r[i[t+(S+1)%3]]:-1);const h=c.length,u=0,d=0;i.push(r[i[t+a]],o[0],c[0]),i.push(r[i[t+(a+1)%3]],c[h-1],o[l-1]);const f=l<=h,p=f?l:h,_=f?h:l,m=f?l-1:h-1,g=f?0:1;let v=l+h-2,x=f?u:d,y=f?d:u;const C=f?o:c,b=f?c:o;let T=0;for(;v-- >0;){g?i.push(C[x],b[y]):i.push(b[y],C[x]),T+=p;let S;T>=_&&xx){const T=v;v=x,x=T}const C=v+"_"+x,b=o[C];b?b.done||(P.Dot(m,b.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}const i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances;let s=0;if(r)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const o=this._source._instanceDataStorage;if(s=this.customInstances.length,!o.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!o.isFrozen){let c=0;for(let l=0;l0&&(this._useSpecificClearForDepthTexture&&this._mrtLayout[s]===5?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;ec!=null),this._scene.autoClear=!0;const r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),a=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),a?o=a:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:s&&(o=s),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;er!=null),t)){for(let r=0;r=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw ci("PrePassRendererSceneComponent")};vl.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}];Object.defineProperty(pt.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(n){n&&n.isSupported&&(this._prePassRenderer=n)},enumerable:!0,configurable:!0});pt.prototype.enablePrePassRenderer=function(){return this._prePassRenderer?this._prePassRenderer:(this._prePassRenderer=new vl(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,de.Error(`PrePassRenderer needs WebGL 2 support. Maybe you tried to use the following features that need the PrePassRenderer : + Subsurface Scattering`)),this._prePassRenderer)};pt.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class q4e{constructor(e){this.name=it.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(it.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(it.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(it.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(it.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(it.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(it.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(it.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(it.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,r){if(!r)return;const s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}vl._SceneComponentInitialization=n=>{let e=n._getComponent(it.NAME_PREPASSRENDERER);e||(e=new q4e(n),n._addComponent(e))};const kke="fibonacci",Vke=`#define rcp(x) 1./x #define GOLDEN_RATIO 1.618033988749895 #define TWO_PI 6.2831855 vec2 Golden2dSeq(int i,float n) {return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} vec2 SampleDiskGolden(int i,int sampleCount) {vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;Re.IncludesShadersStore[kke]=Vke;const zke="diffusionProfile",Hke="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";Re.IncludesShadersStore[zke]=Hke;const Gke="subSurfaceScatteringPixelShader",Kke=`#include #include #include #include varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; #define rcp(x) 1./x #define Sq(x) x*x #define SSS_BILATERAL_FILTER true vec3 EvalBurleyDiffusionProfile(float r,vec3 S) {vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); vec3 expSum=exp_13*(1.+exp_13*exp_13); return (S*rcp(8.*PI))*expSum; } vec2 SampleBurleyDiffusionProfile(float u,float rcpS) {u=1.-u; float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); float p=(g*n)*n; float c=1.+p+n; float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); float x=(3./LOG2_E)*log2(c)-d; float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; return vec2(r,rcpPdf);} vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) { #ifndef SSS_BILATERAL_FILTER z=0.; #endif float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; #if SSS_CLAMP_ARTIFACT return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); #else return EvalBurleyDiffusionProfile(r,S)*area; #endif } void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) {float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) {float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} else {}} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) {centerDepth=texture2D(depthSampler,vUV).r;} if (!passedStencilTest) { gl_FragColor=inputColor;return;} float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) { #ifdef DEBUG_SSS_SAMPLES vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; #endif gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} #ifdef DEBUG_SSS_SAMPLES vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; #endif float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration){de.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}const h=this.texelSize;l.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),l.setFloat2("texelSize",h.x,h.y),l.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),l.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),l.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),l.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),l.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),l.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),l.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)})}}class B9{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=it.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Me(1,1,1)),this._scene=e,B9._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return de.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw ci("SubSurfaceSceneComponent")};da.AddParser(it.NAME_SUBSURFACE,(n,e)=>{if(n.ssDiffusionProfileColors!==void 0&&n.ssDiffusionProfileColors!==null&&(e.enableSubSurfaceForPrePass(),e.subSurfaceConfiguration))for(let t=0,i=n.ssDiffusionProfileColors.length;t{let e=n._getComponent(it.NAME_SUBSURFACE);e||(e=new J4e(n),n._addComponent(e))};const jke="outlinePixelShader",Xke=`#ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif uniform vec4 color; #ifdef ALPHATEST varying vec2 vUV;uniform sampler2D diffuseSampler; #endif #include #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #ifdef ALPHATEST if (texture2D(diffuseSampler,vUV).a<0.4) discard; #endif #include gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END }`;Re.ShadersStore[jke]=Xke;const Yke="outlineVertexShader",Qke=`attribute vec3 position;attribute vec3 normal; #include #include #include #include[0..maxSimultaneousMorphTargets] #include uniform float offset; #include uniform mat4 viewProjection; #ifdef ALPHATEST varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] vec3 offsetPosition=positionUpdated+(normalUpdated*offset); #include #include #include vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; #ifdef ALPHATEST #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif #include #include } `;Re.ShadersStore[Yke]=Qke;pt.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new l5(this)),this._outlineRenderer};Object.defineProperty(Se.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(n){n&&this.getScene().getOutlineRenderer(),this._renderOutline=n},enumerable:!0,configurable:!0});Object.defineProperty(Se.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(n){n&&this.getScene().getOutlineRenderer(),this._renderOverlay=n},enumerable:!0,configurable:!0});class l5{constructor(e){this.name=it.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let t=0;t<4;++t)this._passIdForDrawWrapper[t]=this._engine.createRenderPassId(`Outline Renderer (${t})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(it.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(it.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",m)}),a.setZOffset(0),a.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const r=[],s=[Z.PositionKind,Z.NormalKind],a=e.getMesh(),o=e.getMaterial();if(!o)return!1;const c=a.getScene();o.needAlphaTesting()&&(r.push("#define ALPHATEST"),a.isVerticesDataPresent(Z.UVKind)&&(s.push(Z.UVKind),r.push("#define UV1")),a.isVerticesDataPresent(Z.UV2Kind)&&(s.push(Z.UV2Kind),r.push("#define UV2"))),o.useLogarithmicDepth&&r.push("#define LOGARITHMICDEPTH"),d2(o,c,r),a.useBones&&a.computeBonesUsingShaders?(s.push(Z.MatricesIndicesKind),s.push(Z.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(Z.MatricesIndicesExtraKind),s.push(Z.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),r.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");const l=a.morphTargetManager;let h=0;l&&(h=l.numMaxInfluencers||l.numInfluencers,h>0&&(r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),Y6(s,a,h))),t&&(r.push("#define INSTANCES"),s_(s),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const u=e._getDrawWrapper(i,!0),d=u.defines,f=r.join(` `);if(d!==f){const p=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];Sa(p),u.setEffect(this.scene.getEngine().createEffect("outline",s,p,["diffuseSampler","morphTargets"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),f)}return u.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(l5._StencilReference),this._engine.setStencilFunctionReference(l5._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const r=this._engine.getAlphaMode(),s=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(r),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=s}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}l5._StencilReference=4;class Ote{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity===e||!this._hasVelocity()||(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){var e;return!!((e=this.vertexBuffers)!=null&&e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new Ae,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new H0({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new H0({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||e===0)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||e===0)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){var e,t;(e=this._depthEffectWrapper)==null||e.dispose(),(t=this._thicknessEffectWrapper)==null||t.dispose()}}class eve extends Ote{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add(()=>{this._engine.setAlphaMode(2)})))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class TY{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,this._blurPostProcesses!==null)){const t=this._blurPostProcesses[0],i=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let r=0;r{this._postProcessRunningIndex===0?m.setTexture("textureSampler",e):m._bindTexture("textureSampler",f.inputTexture.texture),m.setInt("filterSize",this.blurFilterSize),m.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),f.onSizeChangedObservable.add(()=>{f._textures.forEach(m=>{m.texture.wrapU=ve.CLAMP_ADDRESSMODE,m.texture.wrapV=ve.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(f);const p=new Pt("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);p.samples=this._samples,p.onApplyObservable.add(m=>{m.setInt("filterSize",this.blurFilterSize),m.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),p.onSizeChangedObservable.add(()=>{p._textures.forEach(m=>{m.texture.wrapU=ve.CLAMP_ADDRESSMODE,m.texture.wrapV=ve.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p),f.autoClear=!1,p.autoClear=!1;const _=[];for(let m=0;m{this._postProcessRunningIndex===0?g.setTexture("textureSampler",e):g._bindTexture("textureSampler",p.inputTexture.texture),g.setInt("maxFilterSize",this.blurMaxFilterSize),g.setFloat2("blurDir",1/this._blurTextureSizeX,0),g.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),g.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),p.onSizeChangedObservable.add(()=>{p._textures.forEach(g=>{g.texture.wrapU=ve.CLAMP_ADDRESSMODE,g.texture.wrapV=ve.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p);const _=new Pt("BilateralBlurY","fluidRenderingBilateralBlur",f,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);_.samples=this._samples,_.onApplyObservable.add(g=>{g.setInt("maxFilterSize",this.blurMaxFilterSize),g.setFloat2("blurDir",0,1/this._blurTextureSizeY),g.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),g.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),_.onSizeChangedObservable.add(()=>{_._textures.forEach(g=>{g.texture.wrapU=ve.CLAMP_ADDRESSMODE,g.texture.wrapV=ve.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(_),p.autoClear=!1,_.autoClear=!1;const m=[];for(let g=0;g{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}),e.onApplyObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}))}_getProjectedParticleConstant(){var e;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((((e=this._camera)==null?void 0:e.fov)??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,r;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),(e=this._rt)==null||e.dispose(),this._rt=null,(t=this._texture)==null||t.dispose(),this._texture=null,(i=this._rtBlur)==null||i.dispose(),this._rtBlur=null,(r=this._textureBlurred)==null||r.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var xu;(function(n){n[n.DepthTexture=0]="DepthTexture",n[n.DepthBlurredTexture=1]="DepthBlurredTexture",n[n.ThicknessTexture=2]="ThicknessTexture",n[n.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",n[n.DiffuseTexture=4]="DiffuseTexture",n[n.Normals=5]="Normals",n[n.DiffuseRendering=6]="DiffuseRendering"})(xu||(xu={}));class lZ{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new Me(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new P(-2,-1,1).normalize(),this._debugFeature=xu.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new Ae,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new ce,this._depthClearColor=new Ze(1e6,1e6,1e6,1),this._thicknessClearColor=new Ze(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=this._depthMapSize!==null?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new TY("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const s=this._diffuseMapSize??this._engine.getRenderWidth(),a=this._diffuseMapSize!==null?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new TY("Diffuse",this._scene,s,a,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),r=this._thicknessMapSize!==null?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new TY("Thickness",this._scene,i,r,i,r,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){(e===null||e===this._depthRenderTarget)&&this._setBlurDepthParameters(),(e===null||e===this._thicknessRenderTarget)&&this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){const e=this._scene.getEngine(),t=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],i=["depthSampler"],r=[];if(this.dispose(!0),!this._camera)return;const s=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new Be(1/s.getSize().width,1/s.getSize().height);this._scene.useRightHandedSystem&&r.push("#define FLUIDRENDERING_RHS"),this._environmentMap!==null&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),r.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),r.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),r.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),r.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._debug&&(r.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===xu.Normals?r.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===xu.DiffuseRendering?r.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(r.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),(this._debugFeature===xu.DepthTexture||this._debugFeature===xu.DepthBlurredTexture)&&r.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new Pt("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(r.join(` `)),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add(o=>{var c,l,h,u,d,f,p,_,m,g;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),e.isWebGPU&&o.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(o.setTexture("depthSampler",this._depthRenderTarget.textureBlur),e.isWebGPU&&o.setTextureSampler("depthSamplerSampler",((l=this._depthRenderTarget.textureBlur)==null?void 0:l.getInternalTexture())??null)):(o.setTexture("depthSampler",this._depthRenderTarget.texture),e.isWebGPU&&o.setTextureSampler("depthSamplerSampler",((c=this._depthRenderTarget.texture)==null?void 0:c.getInternalTexture())??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(o.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),e.isWebGPU&&o.setTextureSampler("diffuseSamplerSampler",((u=this._diffuseRenderTarget.textureBlur)==null?void 0:u.getInternalTexture())??null)):(o.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),e.isWebGPU&&o.setTextureSampler("diffuseSamplerSampler",((h=this._diffuseRenderTarget.texture)==null?void 0:h.getInternalTexture())??null)):o.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(o.setFloat("thickness",this.minimumThickness),o._bindTexture("bgDepthSampler",this._bgDepthTexture),e.isWebGPU&&o.setTextureSampler("bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(o.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),e.isWebGPU&&o.setTextureSampler("thicknessSamplerSampler",((f=this._thicknessRenderTarget.textureBlur)==null?void 0:f.getInternalTexture())??null)):(o.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),e.isWebGPU&&o.setTextureSampler("thicknessSamplerSampler",((d=this._thicknessRenderTarget.texture)==null?void 0:d.getInternalTexture())??null)),o.setFloat("minimumThickness",this.minimumThickness)),this._environmentMap!==null){const v=this._environmentMap??this._scene.environmentTexture;v&&(o.setTexture("reflectionSampler",v),e.isWebGPU&&o.setTextureSampler("reflectionSamplerSampler",(v==null?void 0:v.getInternalTexture())??null))}if(o.setMatrix("viewMatrix",this._scene.getViewMatrix()),o.setMatrix("invProjectionMatrix",this._invProjectionMatrix),o.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),o.setVector2("texelSize",a),o.setFloat("density",this.density),o.setFloat("refractionStrength",this.refractionStrength),o.setFloat("fresnelClamp",this.fresnelClamp),o.setFloat("specularPower",this.specularPower),o.setVector3("dirLight",this.dirLight),o.setFloat("cameraFar",this._camera.maxZ),this._debug){let v=null;switch(this._debugFeature){case xu.DepthTexture:v=this._depthRenderTarget.texture;break;case xu.DepthBlurredTexture:v=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case xu.ThicknessTexture:v=((p=this._thicknessRenderTarget)==null?void 0:p.texture)??null;break;case xu.ThicknessBlurredTexture:v=(_=this._thicknessRenderTarget)!=null&&_.enableBlur?((m=this._thicknessRenderTarget)==null?void 0:m.textureBlur)??null:((g=this._thicknessRenderTarget)==null?void 0:g.texture)??null;break;case xu.DiffuseTexture:this._diffuseRenderTarget&&(v=this._diffuseRenderTarget.texture);break}this._debugFeature!==xu.Normals&&(o.setTexture("debugSampler",v),e.isWebGPU&&o.setTextureSampler("debugSamplerSampler",(v==null?void 0:v.getInternalTexture())??null))}})}_clearTargets(){var e,t,i;(e=this._depthRenderTarget)!=null&&e.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(t=this._diffuseRenderTarget)!=null&&t.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(i=this._thicknessRenderTarget)!=null&&i.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){var i,r,s,a,o,c;if(this._needInitialization||!e.isReady())return;const t=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),(i=this._depthRenderTarget)!=null&&i.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(r=this._diffuseRenderTarget)!=null&&r.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(s=this._thicknessRenderTarget)!=null&&s.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),(a=this._depthRenderTarget)==null||a.applyBlurPostProcesses(),(o=this._diffuseRenderTarget)==null||o.applyBlurPostProcesses(),(c=this._thicknessRenderTarget)==null||c.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){var t,i,r,s;e||((t=this._depthRenderTarget)==null||t.dispose(),this._depthRenderTarget=null,(i=this._diffuseRenderTarget)==null||i.dispose(),this._diffuseRenderTarget=null,(r=this._thicknessRenderTarget)==null||r.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),(s=this._renderPostProcess)==null||s.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class tve extends Ote{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1;break}this._vertexBuffers[t]=new Z(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects();const e=["view","projection","size"],t=["position","offset","color"];this._diffuseEffectWrapper=new H0({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:t,uniformNames:e,samplerNames:[]})}isReady(){var e;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new Z(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(((e=this._diffuseEffectWrapper)==null?void 0:e.effect.isReady())??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||e===0)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),this._particleSize!==null&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){var e;super.dispose(),(e=this._diffuseEffectWrapper)==null||e.dispose();for(const t in this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}const $ke="copyTextureToTexturePixelShader",Zke=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; #include void main(void) {vec4 color=texture2D(textureSampler,vUV); #ifdef DEPTH_TEXTURE gl_FragDepth=color.r; #else if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} gl_FragColor=color; #endif } `;Re.ShadersStore[$ke]=Zke;var eH;(function(n){n[n.None=0]="None",n[n.ToLinearSpace=1]="ToLinearSpace",n[n.ToGammaSpace=2]="ToGammaSpace"})(eH||(eH={}));class ive{_textureIsInternal(e){return e.getInternalTexture===void 0}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new QO(e),this._effectWrapper=new H0({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add(()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)})}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=eH.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const r=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&r&&(this._engine.depthCullingState.depthFunc=r),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class qke{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new ive(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"});const s=this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil");s.label=`FluidDepthTextureCopy${t}x${i}x${r}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}const Jke="fluidRenderingParticleDepthVertexShader",eVe=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; #ifdef FLUIDRENDERING_VELOCITY attribute vec3 velocity;varying float velocityNorm; #endif void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; #ifdef FLUIDRENDERING_VELOCITY velocityNorm=length(velocity); #endif } `;Re.ShadersStore[Jke]=eVe;const tVe="fluidRenderingParticleDepthPixelShader",iVe=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; #ifdef FLUIDRENDERING_VELOCITY varying float velocityNorm; #endif void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); #ifndef FLUIDRENDERING_RHS normal.z=-normal.z; #endif vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; #ifdef WEBGPU gl_FragDepth=clipSpacePos.z/clipSpacePos.w; #else gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; #endif #ifdef FLUIDRENDERING_RHS realViewPos.z=-realViewPos.z; #endif #ifdef FLUIDRENDERING_VELOCITY glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); #else glFragColor=vec4(realViewPos.z,0.,0.,1.); #endif } `;Re.ShadersStore[tVe]=iVe;const rVe="fluidRenderingParticleThicknessVertexShader",sVe=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} `;Re.ShadersStore[rVe]=sVe;const nVe="fluidRenderingParticleThicknessPixelShader",aVe=`uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} `;Re.ShadersStore[nVe]=aVe;const oVe="fluidRenderingParticleDiffuseVertexShader",lVe=`attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} `;Re.ShadersStore[oVe]=lVe;const cVe="fluidRenderingParticleDiffusePixelShader",hVe=`uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} `;Re.ShadersStore[cVe]=hVe;const uVe="fluidRenderingBilateralBlurPixelShader",dVe=`uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} `;Re.ShadersStore[uVe]=dVe;const fVe="fluidRenderingStandardBlurPixelShader",pVe=`uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} sum/=wsum;glFragColor=vec4(sum.rgb,1.);} `;Re.ShadersStore[fVe]=pVe;const _Ve="fluidRenderingRenderPixelShader",mVe=`/* disable_uniformity_analysis */ #define IOR 1.333 #define ETA 1.0/IOR #define F0 0.02 uniform sampler2D textureSampler;uniform sampler2D depthSampler; #ifdef FLUIDRENDERING_DIFFUSETEXTURE uniform sampler2D diffuseSampler; #else uniform vec3 diffuseColor; #endif #ifdef FLUIDRENDERING_FIXED_THICKNESS uniform float thickness;uniform sampler2D bgDepthSampler; #else uniform float minimumThickness;uniform sampler2D thicknessSampler; #endif #ifdef FLUIDRENDERING_ENVIRONMENT uniform samplerCube reflectionSampler; #endif #if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) uniform sampler2D debugSampler; #endif uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; #ifdef FLUIDRENDERING_RHS ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; #else ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; #endif ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} void main(void) {vec2 texCoord=vUV; #if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) vec4 color=texture2D(debugSampler,texCoord); #ifdef FLUIDRENDERING_DEBUG_DEPTH glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} #else glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} #endif return; #endif vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; #ifndef FLUIDRENDERING_FIXED_THICKNESS float thickness=texture2D(thicknessSampler,texCoord).x; #else float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; #endif vec4 backColor=texture2D(textureSampler,texCoord); #ifndef FLUIDRENDERING_FIXED_THICKNESS if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { #else if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { #endif glFragColor=backColor;return;} vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} vec3 normal=normalize(cross(ddy,ddx)); #ifdef FLUIDRENDERING_RHS normal=-normal; #endif #ifndef WEBGPU if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} #endif #if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) glFragColor=vec4(normal*0.5+0.5,1.0);return; #endif vec3 rayDir=normalize(viewPos); #ifdef FLUIDRENDERING_DIFFUSETEXTURE vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; #endif vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); #ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; #endif vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); vec3 refractionColor=transmitted.rgb*transmittance; #ifdef FLUIDRENDERING_ENVIRONMENT vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; #else vec3 finalColor=refractionColor+specular; #endif #ifdef FLUIDRENDERING_VELOCITY float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); #endif glFragColor=vec4(finalColor,transmitted.a);} `;Re.ShadersStore[_Ve]=mVe;Object.defineProperty(pt.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(n){this._fluidRenderer=n},enumerable:!0,configurable:!0});pt.prototype.enableFluidRenderer=function(){return this._fluidRenderer?this._fluidRenderer:(this._fluidRenderer=new gK(this),this._fluidRenderer)};pt.prototype.disableFluidRenderer=function(){var n;(n=this._fluidRenderer)==null||n.dispose(),this._fluidRenderer=null};function gVe(n){return!!n.particleSystem}function vVe(n){return!!n.addBuffers}class rve{constructor(e){this.name=it.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(it.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(it.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;(t=this.scene.fluidRenderer)==null||t._prepareRendering()}_afterCameraDraw(e){var t;(t=this.scene.fluidRenderer)==null||t._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i{i._rebuild()})}dispose(){this.scene.disableFluidRenderer()}}class gK{static _SceneComponentInitialization(e){let t=e._getComponent(it.NAME_FLUIDRENDERER);t||(t=new rve(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,gK._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add(()=>{this._initialize()})}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return t!==-1?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){const s=new eve(this._scene,e);s.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new lZ(this._scene,r),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),t!==void 0&&(i.generateDiffuseTexture=t);const a={object:s,targetRenderer:i};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}addCustomParticles(e,t,i,r,s){const a=new tve(this._scene,e,t);a.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),r||(r=new lZ(this._scene,s),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),i!==void 0&&(r.generateDiffuseTexture=i);const o={object:a,targetRenderer:r};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return i===-1?!1:(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort((e,t)=>e.object.priorityt.object.priority?1:0)}_removeUnusedTargetRenderers(){const e={};for(let r=0;r{var l;a.inputTexture.depthStencilTexture||a.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,o[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${a.name}`);for(const h of o){const u=(l=h._thicknessRenderTarget)==null?void 0:l.renderTarget,d=u==null?void 0:u.texture;if(u&&d){const f=d.width+"_"+d.height;let p=c[f];p||(p=c[f]=new qke(this._engine,d.width,d.height)),p.depthRTWrapper._shareDepth(u)}}})}t=this._cameras.keys();for(let i=t.next();i.done!==!0;i=t.next()){const r=i.value,a=this._cameras.get(r)[1],o=e.get(r);if(o)for(const c in a)o[1][c]||a[c].dispose();else for(const c in a)a[c].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{i._depthRenderTarget&&(i._depthRenderTarget.particleSize=t)})}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization){this._initialize();return}}_render(e){var i;for(let r=0;r{const t=e[1];for(const i in t)t[i].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class xVe{get enable(){return this._enable}set enable(e){this._enable!==e&&(this._enable=e,this._customRenderTarget(e))}get positionWorldTexture(){return this._mrt.textures[0]}get normalWorldTexture(){return this._mrt.textures[1]}get fluxTexture(){return this._mrt.textures[2]}get renderList(){return this._mrt.renderList}get light(){return this._light}constructor(e,t,i={width:512,height:512}){this._lightTransformMatrix=ce.Identity(),this._enable=!1,this.forceUpdateLightParameters=!1,this._scene=e,this._light=t,this._textureDimensions=i,this._regularMatToMatWithPlugin=new Map,this._counters=[{name:"RSM Generation "+t.name,value:0}],this._createMultiRenderTarget(),this._recomputeLightTransformationMatrix(),this.enable=!0}setTextureDimensions(e){const t=this._mrt.renderList;this._textureDimensions=e,this._disposeMultiRenderTarget(),this._createMultiRenderTarget(),t==null||t.forEach(i=>{this._addMeshToMRT(i)})}addMesh(e){e?this._addMeshToMRT(e):this._scene.meshes.forEach(t=>{this._addMeshToMRT(t)}),this._recomputeLightTransformationMatrix()}updateLightParameters(){this._recomputeLightTransformationMatrix()}get lightTransformationMatrix(){return this.forceUpdateLightParameters&&this.updateLightParameters(),this._lightTransformMatrix}get countersGPU(){return this._counters}dispose(){this._disposeMultiRenderTarget()}_createMultiRenderTarget(){const e=this._light.name,t=this._scene.getEngine().getCaps(),i=t.rg11b10ufColorRenderable?13:2,r=t.rg11b10ufColorRenderable?4:5;this._mrt=new Sm("RSMmrt_"+e,this._textureDimensions,3,this._scene,{types:[2,11,i],samplingModes:[2,2,2],generateMipMaps:!1,targetTypes:[3553,3553,3553],formats:[5,5,r]},["RSMPosition_"+e,"RSMNormal_"+e,"RSMFlux_"+e]),this._mrt.renderList=[],this._mrt.clearColor=new Ze(0,0,0,1),this._mrt.noPrePassRenderer=!0;let s,a;const o=this._scene.getEngine().supportsUniformBuffers;o&&(s=this._scene.createSceneUniformBuffer(`Scene for RSM (light "${e}")`));let c;this._mrt.onBeforeBindObservable.add(()=>{a=this._scene.getSceneUniformBuffer(),c=this._light.shadowEnabled,this._light.shadowEnabled=!1}),this._mrt.onBeforeRenderObservable.add(l=>{s&&this._scene.setSceneUniformBuffer(s);const h=this._light.getViewMatrix(l),u=this._light.getProjectionMatrix(h||void 0,this._mrt.renderList||void 0);h&&u&&this._scene.setTransformMatrix(h,u),o&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._mrt.onAfterUnbindObservable.add(()=>{var l;s&&this._scene.setSceneUniformBuffer(a),this._scene.updateTransformMatrix(),this._light.shadowEnabled=c,this._counters[0].value=((l=this._mrt.renderTarget.gpuTimeInFrame)==null?void 0:l.counter.lastSecAverage)??0}),this._customRenderTarget(!0)}_customRenderTarget(e){const t=this._scene.customRenderTargets.indexOf(this._mrt);e?t===-1&&this._scene.customRenderTargets.push(this._mrt):t!==-1&&this._scene.customRenderTargets.splice(t,1)}_recomputeLightTransformationMatrix(){const e=this._light.getViewMatrix(),t=this._light.getProjectionMatrix(e||void 0,this._mrt.renderList||void 0);e&&t&&e.multiplyToRef(t,this._lightTransformMatrix)}_addMeshToMRT(e){var r;(r=this._mrt.renderList)==null||r.push(e);const t=e.material;if(e.getTotalVertices()===0||!t)return;let i=this._regularMatToMatWithPlugin.get(t);if(!i&&(i=t.clone("RSMCreate_"+t.name)||void 0,i)){Object.defineProperty(i,"canRenderToMRT",{get:function(){return!1},enumerable:!0,configurable:!0}),i.disableLighting=!0;const s=new g4(i);s.isEnabled=!0,s.light=this._light,this._regularMatToMatWithPlugin.set(t,i)}this._mrt.setMaterialForRendering(e,i)}_disposeMultiRenderTarget(){this._customRenderTarget(!1),this._mrt.dispose()}}class yVe extends Kr{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class g4 extends Wc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,g4.Name,300,new yVe),this._lightColor=new Me,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof xr?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===Ui.LIGHTTYPEID_SPOTLIGHT;if(t){const i=this.light;this._hasProjectionTexture=i.projectionTexture?i.projectionTexture.isReady():!1}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:`#ifdef RSMCREATE uniform mat4 rsmTextureProjectionMatrix; uniform vec4 rsmSpotInfo; uniform vec3 rsmLightColor; unfiorm vec3 rsmLightPosition; #endif`}}getSamplers(e){e.push("rsmTextureProjectionSampler")}bindForSubMesh(e){if(this._isEnabled&&(this.light.diffuse.scaleToRef(this.light.getScaledIntensity(),this._lightColor),e.updateColor3("rsmLightColor",this._lightColor),this.light.getTypeID()===Ui.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=ie.Vector3[0];t.computeTransformedInformation()?(e.updateFloat3("rsmLightPosition",this.light.transformedPosition.x,this.light.transformedPosition.y,this.light.transformedPosition.z),t.transformedDirection.normalizeToRef(i)):(e.updateFloat3("rsmLightPosition",this.light.position.x,this.light.position.y,this.light.position.z),t.direction.normalizeToRef(i)),e.updateFloat4("rsmSpotInfo",i.x,i.y,i.z,Math.cos(t.angle*.5))}}getCustomCode(e){return e==="vertex"?null:{CUSTOM_FRAGMENT_BEGIN:` #ifdef RSMCREATE #extension GL_EXT_draw_buffers : require #endif `,CUSTOM_FRAGMENT_DEFINITIONS:` #ifdef RSMCREATE #ifdef RSMCREATE_PROJTEXTURE uniform highp sampler2D rsmTextureProjectionSampler; #endif layout(location = 0) out highp vec4 glFragData[3]; vec4 glFragColor; #endif `,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:` #ifdef RSMCREATE vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor; #ifdef RSMCREATE_PROJTEXTURE { vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0); strq /= strq.w; rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb; } #endif #ifdef RSMCREATE_LIGHT_IS_SPOT { float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition))); rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor; } #endif glFragData[0] = vec4(vPositionW, 1.); glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.); glFragData[2] = vec4(rsmColor, 1.); #endif `}}}g4.Name="RSMCreate";B([K()],g4.prototype,"light",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],g4.prototype,"isEnabled",void 0);xe("BABYLON.RSMCreatePluginMaterial",g4);class AVe{constructor(e){this.numSamples=400,this.radius=.1,this.intensity=.1,this.edgeArtifactCorrection=.1,this.rotateSample=!0,this.noiseFactor=100,this.useFullTexture=!1,this.rsm=e}dispose(){this.rsm.dispose()}}const CVe="bilateralBlurPixelShader",bVe=`uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;} vec3 normal=textureLod(normalSampler,vUV,0.).rgb; #ifdef DECODE_NORMAL normal=normal*2.0-1.0; #endif float sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb; #ifdef DECODE_NORMAL sampleNormal=sampleNormal*2.0-1.0; #endif float r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;} glFragColor=vec4(sum/wsum,1.);} `;Re.ShadersStore[CVe]=bVe;const EVe="bilateralBlurQualityPixelShader",TVe=`uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;} vec3 normal=textureLod(normalSampler,vUV,0.).rgb; #ifdef DECODE_NORMAL normal=normal*2.0-1.0; #endif float sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb; #ifdef DECODE_NORMAL sampleNormal=sampleNormal*2.0-1.0; #endif float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}} glFragColor=vec4(sum/wsum,1.);} `;Re.ShadersStore[EVe]=TVe;const SVe="rsmGlobalIlluminationPixelShader",MVe=`/** * The implementation is an application of the formula found in http: * For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts). */ precision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples; #ifdef TRANSFORM_NORMAL uniform mat4 invView; #endif float mod289(float x){return x-floor(x*(1.0/289.0))*289.0;} vec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;} vec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);} float noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);} vec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; float dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);} return clamp(indirectDiffuse*intensity,0.0,1.0);} void main(void) {vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz; #ifdef DECODE_NORMAL normalW=normalW*2.0-1.0; #endif #ifdef TRANSFORM_NORMAL normalW=(invView*vec4(normalW,0.)).xyz; #endif gl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;} `;Re.ShadersStore[SVe]=MVe;const RVe="rsmFullGlobalIlluminationPixelShader",IVe=`/** * The implementation is a direct application of the formula found in http: */ precision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux; #ifdef TRANSFORM_NORMAL uniform mat4 invView; #endif vec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j{if(t.pluginManager){const i=t.pluginManager.getPlugin(Td.Name);i.isEnabled=e}}),this.recreateResources(!e))}get enableBlur(){return this._enableBlur}set enableBlur(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())}get useQualityBlur(){return this._useQualityBlur}set useQualityBlur(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())}get fullSizeBlur(){return this._forceFullSizeBlur}set fullSizeBlur(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())}get useQualityUpsampling(){return this._useQualityUpsampling}set useQualityUpsampling(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())}get showOnlyGI(){return this._showOnlyGI}set showOnlyGI(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)}setOutputDimensions(e){this._outputDimensions=e,this.recreateResources()}setGITextureDimensions(e){this._giTextureDimensions=e,this.recreateResources()}get giTextureType(){return this._giTextureType}set giTextureType(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())}get giRSM(){return this._giRSM}addGIRSM(e){Array.isArray(e)?this._giRSM.push(...e):this._giRSM.push(e),this.recreateResources()}removeGIRSM(e){if(Array.isArray(e))for(let t=0;t{t.getTotalVertices()>0&&t.isEnabled()&&t.material&&this._addGISupportToMaterial(t.material)})}get countersGPU(){return this._counters}recreateResources(e=!1){this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()}generateSampleTexture(e){var i;(i=this._sampleTexture)==null||i.dispose(),this._maxSamples=e;const t=new Float32Array(this._maxSamples*4);for(let r=0;r{var c,l;const a=this._engine._currentRenderTarget;let o=!1;if(this._enable){this.pause||(this._scene.postProcessManager.directRender(this._ppGlobalIllumination,this._ppGlobalIllumination[0].inputTexture),this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture,!0),this._engine.setAlphaMode(0),o=!0,this.enableBlur&&this._blurPostProcesses&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,this._blurRTT.renderTarget,!0),this._engine.unBindFramebuffer(this._blurRTT.renderTarget,!0)));for(let h=0;h{if(e.pluginManager){const t=e.pluginManager.getPlugin(Td.Name);t.textureGIContrib=this.enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height}})}_createPostProcesses(){var a,o;if(!this._enable)return;const e=this._giTextureType===13?4:5;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=((a=this._scene.geometryBufferRenderer)==null?void 0:a.enablePosition)??!1),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();const t=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,15,vK.GeometryBufferTextureTypesAndFormats);if(!t)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");t.enablePosition=!0,this._geomBufferEnabled||(t.generateNormalsInWorldSpace=!0);const i=t.normalsAreUnsigned,r=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let s="";i&&(s+=`#define DECODE_NORMAL `),r||(s+=`#define TRANSFORM_NORMAL `);for(let c=0;c{d.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(yr.POSITION_TEXTURE_TYPE)]),d.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(yr.NORMAL_TEXTURE_TYPE)]),d.setTexture("rsmPositionW",h.positionWorldTexture),d.setTexture("rsmNormalW",h.normalWorldTexture),d.setTexture("rsmFlux",h.fluxTexture),d.setMatrix("rsmLightMatrix",h.lightTransformationMatrix),l.useFullTexture?d.setFloat4("rsmInfo",h.fluxTexture.getInternalTexture().width,h.fluxTexture.getInternalTexture().height,l.intensity,l.edgeArtifactCorrection):(d.setTexture("rsmSamples",this._sampleTexture),d.setFloat4("rsmInfo",l.numSamples,l.radius,l.intensity,l.edgeArtifactCorrection),d.setFloat4("rsmInfo2",l.noiseFactor,l.rotateSample?1:0,h.fluxTexture.getInternalTexture().width,h.fluxTexture.getInternalTexture().height)),r||(this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix()),this._tempMatrix.invert(),d.setMatrix("invView",this._tempMatrix))})}for(const c of this._ppGlobalIllumination)c.inputTexture||c.resize(this._giTextureDimensions.width,this._giTextureDimensions.height);if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){const c=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new es("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:e,generateDepthBuffer:!1}),this._blurRTT.wrapU=0,this._blurRTT.wrapV=0,this._blurRTT.updateSamplingMode(1),this._blurRTT.skipInitialClear=!0;const l=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(l),this._blurXPostprocess=new Pt(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:c,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurXPostprocess.onApplyObservable.add(u=>{u._bindTexture("textureSampler",this._ppGlobalIllumination[0].inputTexture.texture),u.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(yr.DEPTH_TEXTURE_TYPE)]),u.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(yr.NORMAL_TEXTURE_TYPE)]),u.setInt("filterSize",this.blurKernel),u.setFloat2("blurDir",1/this._giTextureDimensions.width,this._useQualityBlur?1/this._giTextureDimensions.height:0),u.setFloat("depthThreshold",this.blurDepthThreshold),u.setFloat("normalThreshold",this.blurNormalThreshold)}),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new Pt("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:c,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add(u=>{u.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(yr.DEPTH_TEXTURE_TYPE)]),u.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(yr.NORMAL_TEXTURE_TYPE)]),u.setInt("filterSize",this.blurKernel),u.setFloat2("blurDir",0,1/this._giTextureDimensions.height),u.setFloat("depthThreshold",this.blurDepthThreshold),u.setFloat("normalThreshold",this.blurNormalThreshold)}),this._blurYPostprocess.resize(c.width,c.height),l.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),!(this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height)&&!this._forceFullSizeBlur){const u=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(u),this._upsamplingXPostprocess=new Pt(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:c,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add(d=>{d.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(yr.DEPTH_TEXTURE_TYPE)]),d.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(yr.NORMAL_TEXTURE_TYPE)]),d.setInt("filterSize",this.upsamplerKernel),d.setFloat2("blurDir",1/this._outputDimensions.width,this._useQualityUpsampling?1/this._outputDimensions.height:0),d.setFloat("depthThreshold",this.blurDepthThreshold),d.setFloat("normalThreshold",this.blurNormalThreshold)}),this._upsamplingXPostprocess.resize(c.width,c.height),l.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new Pt("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add(d=>{d.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(yr.DEPTH_TEXTURE_TYPE)]),d.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(yr.NORMAL_TEXTURE_TYPE)]),d.setInt("filterSize",this.upsamplerKernel),d.setFloat2("blurDir",0,1/this._outputDimensions.height),d.setFloat("depthThreshold",this.blurDepthThreshold),d.setFloat("normalThreshold",this.blurNormalThreshold)}),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),u.push(this._upsamplingYPostprocess.inputTexture)),u.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}else l.push(this._blurRTT.renderTarget)}(o=this._debugLayer.texture)==null||o.dispose(),this._debugLayer.texture=new Er(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){var i;if((i=e.pluginManager)!=null&&i.getPlugin(Td.Name))return;const t=new Td(e);this._enable&&this._ppGlobalIllumination.length>0&&(t.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height),t.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}}vK.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class PVe extends Kr{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class Td extends Wc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,Td.Name,310,new PVe),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof xr}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:`#ifdef RENDER_WITH_GIRSM uniform vec2 girsmTextureOutputSize; #endif`}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e){const t={CUSTOM_FRAGMENT_DEFINITIONS:` #ifdef RENDER_WITH_GIRSM uniform sampler2D girsmTextureGIContrib; vec3 computeIndirect() { vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize; return texture2D(girsmTextureGIContrib, uv).rgb; } #endif `,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:` #ifdef RENDER_WITH_GIRSM finalDiffuse += computeIndirect() * surfaceAlbedo.rgb; #endif `};return this._isPBR||(t.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR=` #ifdef RENDER_WITH_GIRSM color.rgb += computeIndirect() * baseColor.rgb; #endif `),e==="vertex"?null:t}}Td.Name="GIRSMRender";B([K()],Td.prototype,"textureGIContrib",void 0);B([K()],Td.prototype,"outputTextureWidth",void 0);B([K()],Td.prototype,"outputTextureHeight",void 0);B([K(),ze("_markAllSubMeshesAsTexturesDirty")],Td.prototype,"isEnabled",void 0);xe("BABYLON.GIRSMRenderPluginMaterial",Td);const wVe="spriteMapPixelShader",DVe=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else #define TEXTUREFUNC(s,c,b) texture2D(s,c,b) #endif precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4( texture2D(frameMap,vec2(fX,0.),0.), texture2D(frameMap,vec2(fX,fdStep*1.),0.), texture2D(frameMap,vec2(fX,fdStep*2.),0.), vec4(0.) );} void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV); #ifdef FLIPU tileUV.y=1.0-tileUV.y; #endif vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;} animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}} mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;} vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} color.xyz*=colorMul;gl_FragColor=color;}`;Re.ShadersStore[wVe]=DVe;const OVe="spriteMapVertexShader",LVe=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; gl_Position=worldViewProjection*p;}`;Re.ShadersStore[OVe]=LVe;class NVe{get spriteCount(){return this.sprites.length}get position(){return this._output.position}set position(e){this._output.position=e}get rotation(){return this._output.rotation}set rotation(e){this._output.rotation=e}get animationMap(){return this._animationMap}set animationMap(e){const t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)}constructor(e,t,i,r,s){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=r,r.stageSize=r.stageSize||new Be(1,1),r.outputSize=r.outputSize||r.stageSize,r.outputPosition=r.outputPosition||P.Zero(),r.outputRotation=r.outputRotation||P.Zero(),r.layerCount=r.layerCount||1,r.maxAnimationFrames=r.maxAnimationFrames||0,r.baseTile=r.baseTile||0,r.flipU=r.flipU||!1,r.colorMultiply=r.colorMultiply||new P(1,1,1),this._scene=s,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(let d=0;d{if(this.spriteSheet&&this.spriteSheet.isReady()&&this.spriteSheet._texture){this._material.setVector2("spriteMapSize",new Be(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1));return}l<100&&setTimeout(()=>{l++,h()},100)};h(),this._material.setVector3("colorMul",r.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=n_(e+":output",{size:1,updatable:!0},s),this._output.scaling.x=r.outputSize.x,this._output.scaling.y=r.outputSize.y,this.position=r.outputPosition,this.rotation=r.outputRotation;const u=()=>{this._time+=this._scene.getEngine().getDeltaTime(),this._material.setFloat("time",this._time)};this._scene.onBeforeRenderObservable.add(u),this._output.material=this._material}getTileID(){const e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||Be.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e}getMousePosition(){const e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,r=>r===e);if(!t||!t.hit||!t.getTextureCoordinates)return new Be(-1,-1);const i=t.getTextureCoordinates();return i||new Be(-1,-1)}_createFrameBuffer(){const e=[];for(let r=0;r0&&(e+=` \r`),e+=this._tileMaps[i]._texture._bufferView.toString();const t=document.createElement("a");t.href="data:octet/stream;charset=utf-8,"+encodeURI(e),t.target="_blank",t.download=this.name+".tilemaps",t.click(),t.remove()}loadTileMaps(e){const t=new XMLHttpRequest;t.open("GET",e);const i=this.options.layerCount||0;t.onload=()=>{const r=t.response.split(` \r`);for(let s=0;s{e.dispose()}),this._frameMap.dispose()}}class BVe extends qp{constructor(e,t,i,r,s=null,a=.01,o=ve.TRILINEAR_SAMPLINGMODE){super(e,t,i,64,r,a,o,!0,s),this.name=e}}var D0;(function(n){n[n.INIT=0]="INIT",n[n.RUNNING=1]="RUNNING",n[n.DONE=2]="DONE",n[n.ERROR=3]="ERROR"})(D0||(D0={}));class _1{constructor(e){this.name=e,this._isCompleted=!1,this._taskState=D0.INIT}get isCompleted(){return this._isCompleted}get taskState(){return this._taskState}get errorObject(){return this._errorObject}_setErrorObject(e,t){this._errorObject||(this._errorObject={message:e,exception:t})}run(e,t,i){this._taskState=D0.RUNNING,this.runTask(e,()=>{this._onDoneCallback(t,i)},(r,s)=>{this._onErrorCallback(i,r,s)})}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=D0.INIT}_onErrorCallback(e,t,i){this._taskState=D0.ERROR,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=D0.DONE,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(i){this._onErrorCallback(t,"Task is done, error executing success callback(s)",i)}}}class sve{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class nve extends _1{constructor(e,t,i,r,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=r,this.extension=s}runTask(e,t,i){ai.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,r=>{this.loadedContainer=r,this.loadedMeshes=r.meshes,this.loadedTransformNodes=r.transformNodes,this.loadedParticleSystems=r.particleSystems,this.loadedSkeletons=r.skeletons,this.loadedAnimationGroups=r.animationGroups,t()},null,(r,s,a)=>{i(s,a)},this.extension)}}class ave extends _1{constructor(e,t,i,r,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=r,this.extension=s}runTask(e,t,i){ai.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,(r,s,a,o,c)=>{this.loadedMeshes=r,this.loadedTransformNodes=c,this.loadedParticleSystems=s,this.loadedSkeletons=a,this.loadedAnimationGroups=o,t()},null,(r,s,a)=>{i(s,a)},this.extension)}}class FVe extends _1{constructor(e,t,i,r,s){super(e),this.name=e,this.rootUrl=t,this.filename=i,this.targetConverter=r,this.extension=s}runTask(e,t,i){const r=e.animatables.length,s=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],ai.ImportAnimations(this.rootUrl,this.filename,e,!1,T0.NoSync,this.targetConverter,()=>{this.loadedAnimatables=e.animatables.slice(r),this.loadedAnimationGroups=e.animationGroups.slice(s),t()},null,(a,o,c)=>{i(o,c)},this.extension)}}class ove extends _1{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,r=>{this.text=r,t()},void 0,!1,!1,(r,s)=>{r&&i(r.status+" "+r.statusText,s)})}}class lve extends _1{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,r=>{this.data=r,t()},void 0,!0,!0,(r,s)=>{r&&i(r.status+" "+r.statusText,s)})}}class cve extends _1{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const r=new Image;Ee.SetCorsBehavior(this.url,r),r.onload=()=>{this.image=r,t()},r.onerror=s=>{i("Error loading image",s)},r.src=this.url}}class hve extends _1{constructor(e,t,i,r=!0,s=ve.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=r,this.samplingMode=s}runTask(e,t,i){const r=()=>{t()},s=(a,o)=>{i(a,o)};this.texture=new ve(this.url,e,this.noMipmap,this.invertY,this.samplingMode,r,s)}}class uve extends _1{constructor(e,t,i,r,s,a){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=r,this.files=s,this.prefiltered=a}runTask(e,t,i){const r=()=>{t()},s=(a,o)=>{i(a,o)};this.texture=new Bn(this.url,e,this.extensions,this.noMipmap,this.files,r,s,void 0,this.prefiltered)}}class dve extends _1{constructor(e,t,i,r=!1,s=!0,a=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=r,this.generateHarmonics=s,this.gammaSpace=a,this.reserved=o}runTask(e,t,i){const r=()=>{t()},s=(a,o)=>{i(a,o)};this.texture=new K0(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,r,s)}}class fve extends _1{constructor(e,t,i,r=!1,s=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=r,this.gammaSpace=s}runTask(e,t,i){const r=()=>{t()},s=(a,o)=>{i(a,o)};this.texture=new $8(this.url,e,this.size,this.noMipmap,this.gammaSpace,r,s)}}class UVe{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new Ae,this.onTaskErrorObservable=new Ae,this.onTasksDoneObservable=new Ae,this.onProgressObservable=new Ae,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||bt.LastCreatedScene}addContainerTask(e,t,i,r,s){const a=new nve(e,t,i,r,s);return this._tasks.push(a),a}addMeshTask(e,t,i,r,s){const a=new ave(e,t,i,r,s);return this._tasks.push(a),a}addTextFileTask(e,t){const i=new ove(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new lve(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new cve(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,r,s=ve.TRILINEAR_SAMPLINGMODE){const a=new hve(e,t,i,r,s);return this._tasks.push(a),a}addCubeTextureTask(e,t,i,r,s,a){const o=new uve(e,t,i,r,s,a);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,r=!1,s=!0,a=!1,o=!1){const c=new dve(e,t,i,r,s,a,o);return this._tasks.push(c),c}addEquiRectangularCubeTextureAssetTask(e,t,i,r=!1,s=!0){const a=new fve(e,t,i,r,s);return this._tasks.push(a),a}removeTask(e){const t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)}_decreaseWaitingTasksCount(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new sve(this._waitingTasksCount,this._totalTasksCount,e))}catch(t){de.Error("Error running progress callbacks."),de.Log(t)}if(this._waitingTasksCount===0){try{const t=this._tasks.slice();this.onFinish&&this.onFinish(t);for(const i of t)if(i.taskState===D0.DONE){const r=this._tasks.indexOf(i);r>-1&&this._tasks.splice(r,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(t){de.Error("Error running tasks-done callbacks."),de.Log(t)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}}_runTask(e){const t=()=>{try{this.onTaskSuccess&&this.onTaskSuccess(e),this.onTaskSuccessObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)}catch(r){i("Error executing task success callbacks",r)}},i=(r,s)=>{e._setErrorObject(r,s),this.onTaskError?this.onTaskError(e):e.onError||de.Error(this._formatTaskErrorMessage(e)),this.onTaskErrorObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)};e.run(this._scene,t,i)}_formatTaskErrorMessage(e){let t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=`: ${e.errorObject.message}`),e.errorObject.exception&&(t+=`: ${e.errorObject.exception}`),t}reset(){return this._isLoading=!1,this._tasks=new Array,this}load(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,this._waitingTasksCount===0)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(let e=0;e{if(this._isLoading){e();return}this.onTasksDoneObservable.addOnce(i=>{i&&i.length?t(i):e()}),this.load()})}}class FS{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}class kVe{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new P(1,1,1),this._newPosition=P.Zero(),this._centerPosition=P.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh(),this._centerMesh.computeWorldMatrix(!0);const i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(let r=0;r!0,this.displayLoadingUI=!0,this.loadAsync=(u,d)=>this.useAppend?ai.AppendAsync("file:",u,this._currentScene,d):ai.LoadAsync("file:",u,this._engine,d),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=r,this._additionalRenderLoopLogicCallback=s,this._textureLoadingCallback=a,this._startingProcessingFilesCallback=o,this._onReloadCallback=c,this._errorCallback=l}monitorElementForDragNDrop(e){e&&(this._elementToMonitor=e,this._dragEnterHandler=t=>{this._drag(t)},this._dragOverHandler=t=>{this._drag(t)},this._dropHandler=t=>{this._drop(t)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))}get filesToLoad(){return this._filesToLoad}dispose(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))}_renderFunction(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){const e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}}_drag(e){e.stopPropagation(),e.preventDefault()}_drop(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)}_traverseFolder(e,t,i,r){const s=e.createReader(),a=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");s.readEntries(o=>{i.count+=o.length;for(const c of o)c.isFile?c.file(l=>{l.correctName=a+l.name,t.push(l),--i.count===0&&r()}):c.isDirectory&&this._traverseFolder(c,t,i,r);--i.count===0&&r()})}_processFiles(e){for(let t=0;tthis._sceneFileToLoad=s)&&(ai.IsPluginForExtensionAvailable("."+r)&&(this._sceneFileToLoad=e[t]),Lte.FilesToLoad[i]=e[t])}}loadFiles(e){if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),!(!this._filesToLoad||this._filesToLoad.length===0)&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){const t=[],i=[],r=e.dataTransfer?e.dataTransfer.items:null;for(let s=0;s{this._processFiles(t),s.count===0&&this._processReload()})}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){this._sceneFileToLoad?(this.useAppend||this._currentScene&&(de.errorsCount>0&&de.ClearLogCache(),this._engine.stopRenderLoop()),ai.ShowLoadingScreen=!1,this.displayLoadingUI&&this._engine.displayLoadingUI(),this.loadAsync(this._sceneFileToLoad,this._progressCallback).then(e=>{this.useAppend?this.displayLoadingUI&&this._engine.hideLoadingUI():(this._currentScene&&this._currentScene.dispose(),this._currentScene=e,this._currentScene.executeWhenReady(()=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._engine.runRenderLoop(()=>{this._renderFunction()})})),this._sceneLoadedCallback&&this._currentScene&&this._sceneLoadedCallback(this._sceneFileToLoad,this._currentScene)}).catch(e=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._errorCallback&&this._errorCallback(this._sceneFileToLoad,this._currentScene,e.message)})):de.Error("Please provide a valid .babylon file.")}}class Nte{dispose(){if(this._observers&&this._observables)for(let e=0;e{a.skipNextObservers||o._willBeUnregistered||o.mask&e&&(o.scope?s=s.then(c=>(a.lastReturnValue=c,o.callback.apply(o.scope,[n,a]))):s=s.then(c=>(a.lastReturnValue=c,o.callback(n,a))),o.unregisterOnNextCall&&this._deferUnregister(o))}),await s,n};class l_{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class ZV extends l_{getDescription(){return"Reducing render target texture size to "+this.maximumSize}constructor(e=0,t=1024,i=.5){super(e),this.priority=e,this.maximumSize=t,this.step=i}apply(e,t){let i=!0;for(let r=0;rthis.maximumSize&&(s.scale(this.step),i=!1)}return i}}class cZ extends l_{getDescription(){return"Setting hardware scaling level to "+this._currentScale}constructor(e=0,t=2,i=.25){super(e),this.priority=e,this.maximumScale=t,this.step=i,this._currentScale=-1,this._directionOffset=1}apply(e,t){return this._currentScale===-1&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),this._directionOffset===1?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale}}class qV extends l_{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class JV extends l_{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class ez extends l_{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class pve extends l_{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return this.onApply?this.onApply(e,t):!0}}class tz extends l_{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class hZ extends l_{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class jm extends l_{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Se))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||t.getTotalVertices()===0)}}static get UpdateSelectionTree(){return jm._UpdateSelectionTree}static set UpdateSelectionTree(e){jm._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const r=e.meshes.slice(0);let s=r.length;for(let o=0;o{this._sceneDisposeObserver=null,this.dispose()})}stop(){this._isRunning=!1}reset(){this._currentPriorityLevel=0}start(){this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady(()=>{setTimeout(()=>{this._checkCurrentState()},this._trackerDuration)}))}_checkCurrentState(){if(!this._isRunning)return;const e=this._scene,t=this._options;if(this._currentFrameRate=Math.round(e.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate){this._isRunning=!1,this.onSuccessObservable.notifyObservers(this);return}let i=!0,r=!0;for(let s=0;s{setTimeout(()=>{this._checkCurrentState()},this._trackerDuration)})}dispose(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)}static OptimizeAsync(e,t,i,r){const s=new Bte(e,t||Gy.ModerateDegradationAllowed(),!1);return i&&s.onSuccessObservable.add(()=>{i()}),r&&s.onFailureObservable.add(()=>{r()}),s.start(),s}}let uZ=[];const Fte=(n,e)=>{n.doNotSerialize||(e.vertexData.push(n.serializeVerticeData()),uZ[n.id]=!0)},_ve=(n,e)=>{const t={},i=n._geometry;return i&&(n.getScene().getGeometryById(i.id)||Fte(i,e.geometries)),n.serialize&&n.serialize(t),t},VVe=(n,e)=>{if(n._isMesh){const t=n;if(t.delayLoadState===1||t.delayLoadState===0){const i=s=>{e.materials=e.materials||[],t.material&&!e.materials.some(a=>a.id===t.material.id)&&e.materials.push(s.serialize())};if(t.material&&!t.material.doNotSerialize)if(t.material instanceof Fu){if(e.multiMaterials=e.multiMaterials||[],!e.multiMaterials.some(s=>s.id===t.material.id)){e.multiMaterials.push(t.material.serialize());for(const s of t.material.subMaterials)s&&i(s)}}else i(t.material);else t.material||i(t.getScene().defaultMaterial);const r=t._geometry;r&&(e.geometries||(e.geometries={},e.geometries.boxes=[],e.geometries.spheres=[],e.geometries.cylinders=[],e.geometries.toruses=[],e.geometries.grounds=[],e.geometries.planes=[],e.geometries.torusKnots=[],e.geometries.vertexData=[]),Fte(r,e.geometries)),t.skeleton&&!t.skeleton.doNotSerialize&&(e.skeletons=e.skeletons||[],e.skeletons.push(t.skeleton.serialize())),e.meshes=e.meshes||[],e.meshes.push(_ve(t,e))}}else if(n.getClassName()==="TransformNode"){const t=n;e.transformNodes.push(t.serialize())}else if(n.getClassName().indexOf("Camera")!==-1){const t=n;e.cameras.push(t.serialize())}else if(n.getClassName().indexOf("Light")!==-1){const t=n;e.lights.push(t.serialize())}};class Lm{static ClearCache(){uZ=[]}static Serialize(e){return Lm._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&ve.ForceSerializeBuffers&&de.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),Lm.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&e.fogMode!==0&&(i.fogMode=e.fogMode,i.fogColor=e.fogColor.asArray(),i.fogStart=e.fogStart,i.fogEnd=e.fogEnd,i.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){const c=e.getPhysicsEngine();c&&(i.physicsEnabled=!0,i.physicsGravity=c.gravity.asArray(),i.physicsEngine=c.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const c of e.meshes){const l=c.morphTargetManager;l&&i.morphTargetManagers.push(l.serialize())}i.lights=[];let r,s;for(r=0;r0){i.animationGroups=[];for(let c=0;c0)for(i.reflectionProbes=[],r=0;rt)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=s)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object){for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const r=e[i];r instanceof Promise?t.push(r.then(s=>e[i]=s)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}}static SerializeMesh(e,t=!1,i=!1){const r={};if(r.meshes=[],r.transformNodes=[],r.cameras=[],r.lights=[],Lm.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let s=0;s{e.indexOf(a)<0&&!a.doNotSerialize&&e.push(a)}),t&&e[s].parent&&e.indexOf(e[s].parent)<0&&!e[s].parent.doNotSerialize&&e.push(e[s].parent);return e.forEach(s=>{VVe(s,r)}),r}}class nO{static IsSupported(e,t){const i=t??e.getRenderingCanvas();return!!i&&typeof i.captureStream=="function"}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!nO.IsSupported(e,t.canvas))throw"Your browser does not support recording so far.";const i=t.canvas??e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options={...nO._DefaultOptions,...t};const r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const s of this._options.audioTracks)r.addTrack(s);this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=s=>this._handleDataAvailable(s),this._mediaRecorder.onerror=s=>this._handleError(s),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){!this._canvas||!this._mediaRecorder||this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout(()=>{this.stopRecording()},t*1e3),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise((i,r)=>{this._resolve=i,this._reject=r})}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),this._reject)this._reject(e.error);else throw new e.error}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&Ee.Download(e,this._fileName)}}nO._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let c3=null;function F9(n,e,t,i,r="image/png",s=!1,a){const{height:o,width:c}=gve(n,e,t);if(!(o&&c)){de.Error("Invalid 'size' parameter !");return}c3||(c3=document.createElement("canvas")),c3.width=c,c3.height=o;const l=c3.getContext("2d"),h=n.getRenderWidth()/n.getRenderHeight();let u=c,d=u/h;d>o&&(d=o,u=d*h);const f=Math.max(0,c-u)/2,p=Math.max(0,o-d)/2;e.getScene().activeCamera!==e?U9(n,e,t,m=>{if(s){const g=new Blob([m]);Ee.DownloadBlob(g),i&&i("")}else i&&i(m)},r,1,n.getCreationOptions().antialias,void 0,void 0,void 0,void 0,a):n.onEndFrameObservable.addOnce(()=>{const m=n.getRenderingCanvas();l&&m&&l.drawImage(m,f,p,u,d),c3&&(s?(Ee.EncodeScreenshotCanvasData(c3,void 0,r,void 0,a),i&&i("")):Ee.EncodeScreenshotCanvasData(c3,i,r,void 0,a))})}function Ute(n,e,t,i="image/png",r){return new Promise((s,a)=>{F9(n,e,t,o=>{typeof o<"u"?s(o):a(new Error("Data is undefined"))},i,void 0,r)})}function mve(n,e,t,i,r="image/png",s){return new Promise(a=>{F9(n,e,{width:t,height:i},()=>{a()},r,!0,s)})}function U9(n,e,t,i,r="image/png",s=1,a=!1,o,c=!1,l=!1,h=!0,u,d){const{height:f,width:p,finalWidth:_,finalHeight:m}=gve(n,e,t),g={width:p,height:f};if(!(f&&p)){de.Error("Invalid 'size' parameter !");return}const v={width:n.getRenderWidth(),height:n.getRenderHeight()};n.setSize(p,f);const x=e.getScene(),y=new es("screenShot",g,x,!1,!1,0,!1,ve.BILINEAR_SAMPLINGMODE,void 0,l,void 0,void 0,void 0,s);y.renderList=x.meshes.slice(),y.samples=s,y.renderSprites=c,y.activeCamera=e,y.forceLayerMaskCheck=h,d==null||d(y);const C=()=>{y.isReadyForRendering()&&e.isReady(!0)?(n.onEndFrameObservable.addOnce(()=>{_===p&&m===f?y.readPixels(void 0,void 0,void 0,!1).then(T=>{sl.DumpData(p,f,T,i,r,o,!0,void 0,u),y.dispose()}):BG("pass",y.getInternalTexture(),x,void 0,void 0,void 0,_,m).then(T=>{n._readTexturePixels(T,_,m,-1,0,null,!0,!1,0,0).then(S=>{sl.DumpData(_,m,S,i,r,o,!0,void 0,u),T.dispose()})})}),y.render(!0),x.incrementRenderId(),x.resetCachedMaterial(),n.setSize(v.width,v.height),e.getProjectionMatrix(!0),x.render()):setTimeout(C,16)},b=()=>{x.incrementRenderId(),x.resetCachedMaterial(),C()};if(a){const T=new nC("antialiasing",1,x.activeCamera);y.addPostProcess(T),T.getEffect().isReady()?b():T.getEffect().onCompiled=()=>{b()}}else b()}function kte(n,e,t,i="image/png",r=1,s=!1,a,o=!1,c=!1,l=!0,h){return new Promise((u,d)=>{U9(n,e,t,f=>{typeof f<"u"?u(f):d(new Error("Data is undefined"))},i,r,s,a,o,c,l,h)})}function gve(n,e,t){let i=0,r=0,s=0,a=0;if(typeof t=="object"){const o=t.precision?Math.abs(t.precision):1;t.width&&t.height?(i=t.height*o,r=t.width*o):t.width&&!t.height?(r=t.width*o,i=Math.round(r/n.getAspectRatio(e))):t.height&&!t.width?(i=t.height*o,r=Math.round(i*n.getAspectRatio(e))):(r=Math.round(n.getRenderWidth()*o),i=Math.round(r/n.getAspectRatio(e))),t.finalWidth&&t.finalHeight?(a=t.finalHeight,s=t.finalWidth):t.finalWidth&&!t.finalHeight?(s=t.finalWidth,a=Math.round(s/n.getAspectRatio(e))):t.finalHeight&&!t.finalWidth?(a=t.finalHeight,s=Math.round(a*n.getAspectRatio(e))):(s=r,a=i)}else isNaN(t)||(i=t,r=t,s=t,a=t);return r&&(r=Math.floor(r)),i&&(i=Math.floor(i)),s&&(s=Math.floor(s)),a&&(a=Math.floor(a)),{height:i|0,width:r|0,finalWidth:s|0,finalHeight:a|0}}const zVe={CreateScreenshot:F9,CreateScreenshotAsync:Ute,CreateScreenshotWithResizeAsync:mve,CreateScreenshotUsingRenderTarget:U9,CreateScreenshotUsingRenderTargetAsync:kte},HVe=()=>{Ee.CreateScreenshot=F9,Ee.CreateScreenshotAsync=Ute,Ee.CreateScreenshotUsingRenderTarget=U9,Ee.CreateScreenshotUsingRenderTargetAsync=kte};HVe();var dZ;(function(n){n[n.Checkbox=0]="Checkbox",n[n.Slider=1]="Slider",n[n.Vector3=2]="Vector3",n[n.Quaternion=3]="Quaternion",n[n.Color3=4]="Color3",n[n.String=5]="String",n[n.Button=6]="Button",n[n.Options=7]="Options",n[n.Tab=8]="Tab",n[n.FileButton=9]="FileButton",n[n.Vector2=10]="Vector2"})(dZ||(dZ={}));class Jw{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then(t=>{this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._dataByteOffset=0})}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return SJ(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class fZ{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return i===void 0?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return i!==null?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return i!==null?i==="true":t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return i!==null?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}fZ._Storage=fZ._GetStorage();class GVe{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,Qe.AllowLoadingUniqueId=!0,this._savedJSON=Lm.Serialize(e),Qe.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=ve.ForceSerializeBuffers;ve.ForceSerializeBuffers=!1,Qe.AllowLoadingUniqueId=!0;const t=Lm.Serialize(this._trackedScene);Qe.AllowLoadingUniqueId=!1;const i={};for(const r in t)this._compareCollections(r,this._savedJSON[r],t[r],i);return ve.ForceSerializeBuffers=e,i}_compareArray(e,t,i,r){if(t.length===0&&i.length===0)return!0;if(t.length&&!isNaN(t[0])||i.length&&!isNaN(i[0])){if(t.length!==i.length)return!1;if(t.length===0)return!0;for(let a=0;ah.uniqueId===c);if(l.length){const h=l[0],u={};this._compareObjects(o,h,u)||(r[e]||(r[e]=[]),u.__state={id:h.id||h.name},r[e].push(u))}else{const h={__state:{deleteId:o.id||o.name}};r[e]||(r[e]=[]),r[e].push(h)}}for(let a=0;ar.getShadowGenerators());for(const r of i)if(r){const s=r.values();for(let a=s.next();a.done!==!0;a=s.next()){const o=a.value;if(o&&o.id===t)return o}}return null}static ApplyDelta(e,t){typeof e=="string"&&(e=JSON.parse(e));const i=t;for(const r in e){const s=e[r],a=i[r];if(Array.isArray(a)||r==="shadowGenerators")switch(r){case"cameras":this._ApplyDeltaForEntity(s,t,t.getCameraById.bind(t),o=>Rt.Parse(o,t));break;case"lights":this._ApplyDeltaForEntity(s,t,t.getLightById.bind(t),o=>Ui.Parse(o,t));break;case"shadowGenerators":this._ApplyDeltaForEntity(s,t,o=>this.GetShadowGeneratorById(t,o),o=>si.Parse(o,t));break;case"meshes":this._ApplyDeltaForEntity(s,t,t.getMeshById.bind(t),o=>Se.Parse(o,t,""));break;case"skeletons":this._ApplyDeltaForEntity(s,t,t.getSkeletonById.bind(t),o=>a1.Parse(o,t));break;case"materials":this._ApplyDeltaForEntity(s,t,t.getMaterialById.bind(t),o=>Ye.Parse(o,t,""));break;case"multiMaterials":this._ApplyDeltaForEntity(s,t,t.getMaterialById.bind(t),o=>Fu.Parse(o,t,""));break;case"transformNodes":this._ApplyDeltaForEntity(s,t,t.getTransformNodeById.bind(t),o=>Et.Parse(o,t,""));break;case"particleSystems":this._ApplyDeltaForEntity(s,t,t.getParticleSystemById.bind(t),o=>Wr.Parse(o,t,""));break;case"morphTargetManagers":this._ApplyDeltaForEntity(s,t,t.getMorphTargetById.bind(t),o=>Of.Parse(o,t));break;case"postProcesses":this._ApplyDeltaForEntity(s,t,t.getPostProcessByName.bind(t),o=>Pt.Parse(o,t,""));break}else isNaN(a)?a.fromArray&&a.fromArray(s):i[r]=s}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const r=e[i],s=t[i];s!==void 0&&(!isNaN(s)||Array.isArray(s)?t[i]=r:s.fromArray?s.fromArray(r):typeof s=="object"&&s!==null&&this._ApplyPropertiesToEntity(r,s))}}static _ApplyDeltaForEntity(e,t,i,r){for(const s of e)if(s.__state&&s.__state.id!==void 0){const a=i(s.__state.id);a&&(this._ApplyPropertiesToEntity(s,a),Qe.ParseProperties(s,a,t,null))}else if(s.__state&&s.__state.deleteId!==void 0){const a=i(s.__state.deleteId);a==null||a.dispose()}else r(s)}}var c5;(function(n){class e{serialize(){const r={},s=new Array(this._characterToIdx.size);return this._characterToIdx.forEach((a,o)=>{s[a]=o}),r.characters=s,r.insertionCosts=this._insertionCosts,r.deletionCosts=this._deletionCosts,r.substitutionCosts=this._substitutionCosts,JSON.stringify(r)}static Deserialize(r){const s=JSON.parse(r),a=new e(s.characters);return a._insertionCosts=s.insertionCosts,a._deletionCosts=s.deletionCosts,a._substitutionCosts=s.substitutionCosts,a}constructor(r,s=null,a=null,o=null){s=s??(()=>1),a=a??(()=>1),o=o??((l,h)=>l===h?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(r.length),this._deletionCosts=new Array(r.length),this._substitutionCosts=new Array(r.length);let c;for(let l=0;lt._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+t._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=s,this._characters=r.map(a=>this._alphabet.getCharacterIdx(a))}distance(r){return t._Distance(this,r)}static _Distance(r,s){const a=r._alphabet;if(a!==s._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const o=r._characters,c=s._characters,l=o.length,h=c.length,u=t._CostMatrix;u[0][0]=0;for(let d=0;dnew Array(t._MAX_SEQUENCE_LENGTH+1)),n.Sequence=t})(c5||(c5={}));class ds{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new ds(t._segmentLength);return i._points=t._points.map(r=>new P(r._x,r._y,r._z)),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(t===0)this._points.push(e.clone());else{const i=()=>this._segmentLength/P.Distance(this._points[t-1],e);for(let r=i();r<=1;r=i()){const s=this._points[t-1].scale(1-r);e.scaleAndAddToRef(r,s),this._points.push(s),++t}}}resampleAtTargetResolution(e){const t=new ds(this.getLength()/e);return this._points.forEach(i=>{t.add(i)}),t}tokenize(e){const t=[],i=new P;for(let r=2;r.98?!1:(P.CrossToRef(ds._ForwardDir,ds._InverseFromVec,ds._UpDir),ds._UpDir.normalize(),ce.LookAtLHToRef(e,t,ds._UpDir,ds._LookMatrix),i.subtractToRef(t,ds._FromToVec),ds._FromToVec.normalize(),P.TransformNormalToRef(ds._FromToVec,ds._LookMatrix,r),!0)}static _TokenizeSegment(e,t){ds._BestMatch=0,ds._Score=P.Dot(e,t[0]),ds._BestScore=ds._Score;for(let i=1;ids._BestScore&&(ds._BestMatch=i,ds._BestScore=ds._Score);return ds._BestMatch}}ds._ForwardDir=new P;ds._InverseFromVec=new P;ds._UpDir=new P;ds._FromToVec=new P;ds._LookMatrix=new ce;class aO{static Generate(e=64,t=256,i=.1,r=.001,s=[]){const c=new aO(e);for(let p=0;p(1-m)*p+m*_;for(let p=0;p{c.chars[_].subtractToRef(m,d),h=d.lengthSquared(),h>1e-6&&d.scaleAndAddToRef(1/(d.lengthSquared()*h),u)}),u.scaleInPlace(l),c.chars[_].addInPlace(u),c.chars[_].normalize()}return c}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new aO(t.length);for(let r=0;re.serialize()))}static Deserialize(e,t){const i=new O0;return i._sequences=JSON.parse(e).map(r=>c5.Sequence.Deserialize(r,t)),i}static CreateFromTrajectory(e,t,i){return O0.CreateFromTokenizationPyramid(O0._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new O0;return i._sequences=e.map(r=>new c5.Sequence(r,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=O0._FINEST_DESCRIPTOR_RESOLUTION){const r=[];for(let s=i;s>4;s=Math.floor(s/2))r.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return r}distance(e){let t=0,i;for(let r=0;rt.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),r=new h5;return r._descriptors=i.descriptors.map(s=>O0.Deserialize(s,t)),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map(t=>t.distance(e)))}_refreshDescription(){this._centroidIdx=-1;let e;const t=this._descriptors.map(i=>(e=0,this._descriptors.forEach(r=>{e+=i.distance(r)}),e));for(let i=0;i{this._averageDistance+=i.distance(this._descriptors[this._centroidIdx])}),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,h5._MIN_AVERAGE_DISTANCE))}}h5._MIN_AVERAGE_DISTANCE=1;class tH{serialize(){const e={};return e.maximumAllowableMatchCost=this._maximumAllowableMatchCost,e.vector3Alphabet=this._vector3Alphabet.serialize(),e.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),e.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach((t,i)=>{e.nameToDescribedTrajectory.push(i),e.nameToDescribedTrajectory.push(t.serialize())}),JSON.stringify(e)}static Deserialize(e){const t=JSON.parse(e),i=new tH;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=aO.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=c5.Alphabet.Deserialize(t.levenshteinAlphabet);for(let r=0;rs===0?0:1,s=>s===0?0:1,(s,a)=>Math.min(1-P.Dot(e.chars[s],e.chars[a]),1)),r=new tH;return r._vector3Alphabet=e,r._levenshteinAlphabet=i,r}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new h5),this._nameToDescribedTrajectory.get(t).add(O0.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=O0.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach((o,c)=>{o.getMatchCost(t){const s=r.data;if(s.startsWith(oO._SERVER_PREFIX)){const a=s.substr(oO._SERVER_PREFIX.length);de.Log(`[Reflector] Received server message: ${a.substr(0,64)}`),this._handleServerMessage(a);return}else de.Log(`[Reflector] Received client message: ${s.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=r=>{de.Log(`[Reflector] Disconnected ${r.code} ${r.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){switch(e){case"connected":{Lm.SerializeAsync(this._scene).then(t=>{this._webSocket.send(`load|${JSON.stringify(t)}`)});break}}}_handleClientMessage(){}}oO._SERVER_PREFIX="$$";class xK{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new Ae,xK.IsAvailable&&(this._observer=new PressureObserver(t=>{this._currentState=t,this.onPressureChanged.notifyObservers(t)},e))}static get IsAvailable(){return typeof PressureObserver<"u"&&PressureObserver.supportedSources.includes("cpu")}observe(e){var t;try{(t=this._observer)==null||t.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch{}}unobserve(e){var t;try{(t=this._observer)==null||t.unobserve(e)}catch{}}dispose(){var e;(e=this._observer)==null||e.disconnect(),this._observer=null,this.onPressureChanged.clear()}}const KVe=1.5;class cm{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(this._view.length*KVe),t=new Float32Array(e);t.set(this._view),this._view=t}}const h3=1800,WVe=24,jVe="0",Kde="timestamp",Wde="numPoints",XVe=/\r/g,SY="@";class xf{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const i=gr.Now-this._startingTimestamp,r=this.datasets.ids.length,s=this.datasets.startingIndices.itemLength;let a=0;if(s>0){const o=this.datasets.startingIndices.at(s-1);a=o+this.datasets.data.at(o+xf.NumberOfPointsOffset)+xf.SliceDataOffset}if(this.datasets.startingIndices.push(a),this.datasets.data.push(i),this.datasets.data.push(r),this.datasets.ids.forEach(o=>{const c=this._strategies.get(o);c&&this.datasets.data.push(c.getData())}),this.datasetObservable.hasObservers()){const o=[i,r];for(let c=0;ci.callback(this._datasetMeta,new mJ(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var a;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&((a=this._strategies.get(e))==null||a.dispose(),this._strategies.delete(e));const r=o=>{let c=0,l=0;const h=o.onAfterRenderObservable.add(()=>{l=c,c=0}),u=this._customEventObservable.add(d=>{e===d.name&&(d.value!==void 0?c=d.value:c++)});return{id:e,getData:()=>l,dispose:()=>{o.onAfterRenderObservable.remove(h),this._customEventObservable.remove(u)}}},s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:r,category:i}),s}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach(e=>{this.registerEvent(e,!0)})}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:r}of e){const s=t(this._scene);if(this._strategies.has(s.id)){s.dispose();continue}this.datasets.ids.push(s.id),i&&(i=i.replace(new RegExp(SY,"g"),"")),this._datasetMeta.set(s.id,{color:this._getHexColorFromId(s.id),category:i,hidden:r}),this._strategies.set(s.id,s)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let r=0;r>r&255;i+=(jVe+s.toString(16)).substr(-2)}return i}getCurrentSlice(){const e=gr.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(r=>{const s=this._strategies.get(r);s&&this.datasetObservable.hasObservers()&&i.push(s.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){const r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new cm(h3),this.datasets.ids.length=0,this.datasets.startingIndices=new cm(h3),this._datasetMeta.clear(),this._strategies.forEach(t=>t.dispose()),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(XVe,"").split(` `).map(u=>u.split(",").filter(d=>d.length>0)).filter(u=>u.length>0),r=0,s=xf.NumberOfPointsOffset;if(i.length<2)return!1;const a={ids:[],data:new cm(h3),startingIndices:new cm(h3)},[o,...c]=i;if(o.length<2||o[r]!==Kde||o[s]!==Wde)return!1;const l=new Map;for(let u=xf.SliceDataOffset;uu.dispose()),this._strategies.clear(),!t)for(const u of this.datasets.ids){const d=l.get(u);this._datasetMeta.set(u,{category:d,color:this._getHexColorFromId(u)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${Kde},${Wde}`;for(let i=0;i{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}const ff=()=>{};class YVe{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:ff}}}static ThermalStrategy(){return this._PressureStrategy("Thermal utilization","thermal")}static PowerSupplyStrategy(){return this._PressureStrategy("Power supply utilization","power-supply")}static PressureStrategy(){return this._PressureStrategy("Pressure")}static _PressureStrategy(e,t=null){return()=>{let i=0;const r=new xK;return r.observe("cpu"),r.onPressureChanged.add(s=>{var a;for(const o of s)if(t&&o.factors.includes(t)||!t&&(((a=o.factors)==null?void 0:a.length)??0)===0)switch(o.state){case"nominal":i=0;break;case"fair":i=.25;break;case"serious":i=.5;break;case"critical":i=1;break}}),{id:e,getData:()=>i,dispose:()=>r.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:ff})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:ff})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:ff})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:ff})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:ff})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:ff})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add(()=>{e.getEngine()._drawCalls.fetchNewFrame()}),r=e.onAfterRenderObservable.add(()=>{t=e.getEngine()._drawCalls.current});return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(r)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:ff})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:ff})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:ff})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:ff})}static AbsoluteFpsStrategy(){return e=>{const t=new sge(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:ff}}}static MeshesSelectionStrategy(){return e=>{let t=gr.Now,i=0;const r=e.onBeforeActiveMeshesEvaluationObservable.add(()=>{t=gr.Now}),s=e.onAfterActiveMeshesEvaluationObservable.add(()=>{i=gr.Now-t});return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(r),e.onAfterActiveMeshesEvaluationObservable.remove(s)}}}}static RenderTargetsStrategy(){return e=>{let t=gr.Now,i=0;const r=e.onBeforeRenderTargetsRenderObservable.add(()=>{t=gr.Now}),s=e.onAfterRenderTargetsRenderObservable.add(()=>{i=gr.Now-t});return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(r),e.onAfterRenderTargetsRenderObservable.remove(s)}}}}static ParticlesStrategy(){return e=>{let t=gr.Now,i=0;const r=e.onBeforeParticlesRenderingObservable.add(()=>{t=gr.Now}),s=e.onAfterParticlesRenderingObservable.add(()=>{i=gr.Now-t});return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(r),e.onAfterParticlesRenderingObservable.remove(s)}}}}static SpritesStrategy(){return e=>{var a,o;let t=gr.Now,i=0;const r=(a=e.onBeforeSpritesRenderingObservable)==null?void 0:a.add(()=>{t=gr.Now}),s=(o=e.onAfterSpritesRenderingObservable)==null?void 0:o.add(()=>{i=gr.Now-t});return{id:"Sprites",getData:()=>i,dispose:()=>{var c,l;(c=e.onBeforeSpritesRenderingObservable)==null||c.remove(r),(l=e.onAfterSpritesRenderingObservable)==null||l.remove(s)}}}}static AnimationsStrategy(){return e=>{let t=gr.Now,i=0;const r=e.onBeforeAnimationsObservable.add(()=>{t=gr.Now}),s=e.onAfterAnimationsObservable.add(()=>{i=gr.Now-t});return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterAnimationsObservable.remove(s)}}}}static PhysicsStrategy(){return e=>{var a,o;let t=gr.Now,i=0;const r=(a=e.onBeforePhysicsObservable)==null?void 0:a.add(()=>{t=gr.Now}),s=(o=e.onAfterPhysicsObservable)==null?void 0:o.add(()=>{i=gr.Now-t});return{id:"Physics",getData:()=>i,dispose:()=>{var c,l;(c=e.onBeforePhysicsObservable)==null||c.remove(r),(l=e.onAfterPhysicsObservable)==null||l.remove(s)}}}}static RenderStrategy(){return e=>{let t=gr.Now,i=0;const r=e.onBeforeDrawPhaseObservable.add(()=>{t=gr.Now}),s=e.onAfterDrawPhaseObservable.add(()=>{i=gr.Now-t});return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(r),e.onAfterDrawPhaseObservable.remove(s)}}}}static FrameTotalStrategy(){return e=>{let t=gr.Now,i=0;const r=e.onBeforeAnimationsObservable.add(()=>{t=gr.Now}),s=e.onAfterRenderObservable.add(()=>{i=gr.Now-t});return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterRenderObservable.remove(s)}}}}static InterFrameStrategy(){return e=>{let t=gr.Now,i=0;const r=e.onBeforeAnimationsObservable.add(()=>{i=gr.Now-t}),s=e.onAfterRenderObservable.add(()=>{t=gr.Now});return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterRenderObservable.remove(s)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new rge(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(t.gpuFrameTimeCounter.current*1e-6,0),dispose:()=>{t.dispose()}}}}}pt.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new xf(this)),this._perfCollector};function QVe(n){const e=new Array,t=new Array,i=new Array,r=n.add(()=>{const a=e.length;for(let o=0;o{e.push(a),t.push(o),i.push(c)},dispose:()=>{n.remove(r)}}}Ae.prototype.runCoroutineAsync=function(n){if(!this._coroutineScheduler){const e=QVe(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return nG(n,this._coroutineScheduler)};Ae.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};const $Ve="equirectangularPanoramaPixelShader",ZVe=`#ifdef GL_ES precision highp float; #endif #define M_PI 3.1415926535897932384626433832795 varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3( - sin( longitude )*sin( latitude ), cos( latitude ), - cos( longitude )*sin( latitude ) );normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;Re.ShadersStore[$Ve]=ZVe;async function qVe(n,e){var a;const t=e.probe??new eC("tempProbe",e.size,n),i=!!e.probe;i||(e.position?t.position=e.position.clone():n.activeCamera&&(t.position=n.activeCamera.position.clone()));const r=e.meshesFilter?n.meshes.filter(e.meshesFilter):n.meshes;(a=t.renderList)==null||a.push(...r),t.refreshRate=es.REFRESHRATE_RENDER_ONCE,t.cubeTexture.render();const s=new xge("tempProceduralTexture","equirectangularPanorama",{width:e.size*2,height:e.size},n);return s.setTexture("cubeMap",t.cubeTexture),new Promise((o,c)=>{s.onGeneratedObservable.addOnce(()=>{const l=s.readPixels();if(!l){c(new Error("No Pixel Data found on procedural texture")),s.dispose(),i||t.dispose();return}l.then(h=>{s.dispose(),i||t.dispose(),e.filename?(sl.DumpData(e.size*2,e.size,h,void 0,"image/png",e.filename),o(null)):o(h)})})})}class Xm extends Lo{constructor(e,t={}){super(e),this.options=t,this._direction=new P(0,0,-1),this._mat=new ce,this._onSelectEnabled=!1,this._origin=new P(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new Ae,this._onHitTestResults=i=>{const r=i.map(s=>{const a=ce.FromArray(s.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||a.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&a.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),a),{xrHitResult:s,transformationMatrix:a}});this.lastNativeXRHitResults=i,this.onHitTestResultObservable.notifyObservers(r)},this._onSelect=i=>{this._onSelectEnabled&&Xm.XRHitTestWithSelectEvent(i,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Ee.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then(s=>{const a=r||(o=>!!o.hitMatrix);return s.filter(a)})}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return super.attach()?(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0):!1}detach(){return super.detach()?(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0):!1}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;ce.FromArrayToRef(t.transform.matrix,0,this._mat),P.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),P.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});Xm.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}Xm.Name=pr.HIT_TEST;Xm.Version=1;vn.AddWebXRFeature(Xm.Name,(n,e)=>()=>new Xm(n,e),Xm.Version,!1);let JVe=0;class h8 extends Lo{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new Ae,this.onAnchorRemovedObservable=new Ae,this.onAnchorUpdatedObservable=new Ae,this._tmpVector=new P,this._tmpQuaternion=new we,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new P,i=new we){this._populateTmpTransformation(t,i);const r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(e.xrHitResult.createAnchor)try{const s=await e.xrHitResult.createAnchor(r);return new Promise((a,o)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!0,xrTransformation:r,resolve:a,reject:o})})}catch(s){throw new Error(s)}else throw this.detach(),new Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new we,i=!1){this._populateTmpTransformation(e,t);const r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise((a,o)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:r,resolve:a,reject:o})})}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();if(e){try{e.remove()}catch{}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter(s=>!t.has(s.xrAnchor)).map(s=>this._trackedAnchors.indexOf(s));let r=0;i.forEach(s=>{const a=this._trackedAnchors.splice(s-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(a),r++}),t.forEach(s=>{if(this._lastFrameDetected.has(s)){const a=this._findIndexInAnchorArray(s),o=this._trackedAnchors[a];try{this._updateAnchorWithXRFrame(s,o,e),o.attachedNode&&(o.attachedNode.rotationQuaternion=o.attachedNode.rotationQuaternion||new we,o.transformationMatrix.decompose(o.attachedNode.scaling,o.attachedNode.rotationQuaternion,o.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(o)}catch{Ee.Warn("Anchor could not be updated")}}else{const a={id:JVe++,xrAnchor:s,remove:()=>s.delete()},o=this._updateAnchorWithXRFrame(s,a,e);this._trackedAnchors.push(o),this.onAnchorAddedObservable.notifyObservers(o);const l=this._futureAnchors.filter(h=>h.nativeAnchor===s)[0];l&&(l.resolve(o),l.resolved=!0)}}),this._lastFrameDetected=t}this._futureAnchors.forEach(i=>{!i.resolved&&!i.submitted&&(this._createAnchorAtTransformation(i.xrTransformation,e).then(r=>{i.nativeAnchor=r},r=>{i.resolved=!0,i.reject(r)}),i.submitted=!0)})}_findIndexInAnchorArray(e){for(let t=0;t()=>new h8(n,e),h8.Version);let eze=0;class u8 extends Lo{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new Ae,this.onPlaneRemovedObservable=new Ae,this.onPlaneUpdatedObservable=new Ae,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return typeof XRPlane<"u"}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){var i;if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||((i=e.worldInformation)==null?void 0:i.detectedPlanes);if(t){for(let r=0;r{if(this._lastFrameDetected.has(r)){if(r.lastChangedTime===this._xrSessionManager.currentTimestamp){const s=this._findIndexInPlaneArray(r),a=this._detectedPlanes[s];this._updatePlaneWithXRPlane(r,a,e),this.onPlaneUpdatedObservable.notifyObservers(a)}}else{const s={id:eze++,xrPlane:r,polygonDefinition:[]},a=this._updatePlaneWithXRPlane(r,s,e);this._detectedPlanes.push(a),this.onPlaneAddedObservable.notifyObservers(a)}}),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};if(this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),!this._xrSessionManager.session.updateWorldTrackingState){e();return}this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map(s=>{const a=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new P(s.x,s.y,s.z*a)});const r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){const s=t.transformationMatrix||new ce;ce.FromArrayToRef(r.transform.matrix,0,s),this._xrSessionManager.scene.useRightHandedSystem||s.toggleModelMatrixHandInPlace(),t.transformationMatrix=s,this._options.worldParentNode&&s.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),s)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new u8(n,e),u8.Version);class d8 extends Lo{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new Ae}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(i=>i.setEnabled(e)),this.onBackgroundStateChangedObservable.notifyObservers(e)}}d8.Name=pr.BACKGROUND_REMOVER;d8.Version=1;vn.AddWebXRFeature(d8.Name,(n,e)=>()=>new d8(n,e),d8.Version,!0);class tze{}class f8 extends Lo{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||Zt.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=Tl("impostor-mesh-"+e.uniqueId,{diameterX:typeof i=="number"?i:i.width,diameterY:typeof i=="number"?i:i.height,diameterZ:typeof i=="number"?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new we;const s=e.grip||e.pointer;r.position.copyFrom(s.position),r.rotationQuaternion.copyFrom(s.rotationQuaternion);const a=new Zt(r,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:a,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=i=>{this._controllers[i.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||de.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&i.inputSource.gamepad?i.onMotionControllerInitObservable.addOnce(r=>{r._doNotLoadControllerMesh?this._createPhysicsImpostor(i):r.onModelLoadedObservable.addOnce(()=>{const s=new Zt(r.rootMesh,Zt.MeshImpostor,{mass:0,...this._options.physicsProperties}),a=i.grip||i.pointer;this._controllers[i.uniqueId]={xrController:i,impostor:s,oldPos:a.position.clone(),oldRotation:a.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(i))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new we,this._tmpVector=new P,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach(e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)})}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:Zt.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=Tl("headset-mesh",{diameterX:typeof t=="number"?t:t.width,diameterY:typeof t=="number"?t:t.height,diameterZ:typeof t=="number"?t:t.depth}),this._headsetMesh.rotationQuaternion=new we,this._headsetMesh.isVisible=!1,this._headsetImpostor=new Zt(this._headsetMesh,e.impostorType,{mass:0,...e})}return!0}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._headsetMesh&&this._headsetMesh.dispose(),!0):!1}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t=typeof e=="string"?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){var t,i;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),(t=this._options.xrInput.xrCamera._lastXRViewerPose)!=null&&t.linearVelocity){const r=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(r.x,r.y,r.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if((i=this._options.xrInput.xrCamera._lastXRViewerPose)!=null&&i.angularVelocity){const r=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(r.x,r.y,r.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach(r=>{var l,h;const s=this._controllers[r],a=s.xrController.grip||s.xrController.pointer,o=s.oldPos||s.impostorMesh.position;if((l=s.xrController._lastXRPose)!=null&&l.linearVelocity){const u=s.xrController._lastXRPose.linearVelocity;this._tmpVector.set(u.x,u.y,u.z),s.impostor.setLinearVelocity(this._tmpVector)}else a.position.subtractToRef(o,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),s.impostor.setLinearVelocity(this._tmpVector);o.copyFrom(a.position),this._debugMode&&de.Log([this._tmpVector,"linear"]);const c=s.oldRotation||s.impostorMesh.rotationQuaternion;if((h=s.xrController._lastXRPose)!=null&&h.angularVelocity){const u=s.xrController._lastXRPose.angularVelocity;this._tmpVector.set(u.x,u.y,u.z),s.impostor.setAngularVelocity(this._tmpVector)}else if(!c.equalsWithEpsilon(a.rotationQuaternion)){c.conjugateInPlace().multiplyToRef(a.rotationQuaternion,this._tmpQuaternion);const u=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),u<.001)this._tmpVector.scaleInPlace(2);else{const d=2*Math.atan2(u,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(d/(u*(this._delta/1e3)))}s.impostor.setAngularVelocity(this._tmpVector)}c.copyFrom(a.rotationQuaternion),this._debugMode&&de.Log([this._tmpVector,this._tmpQuaternion,"angular"])})}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}f8.Name=pr.PHYSICS_CONTROLLERS;f8.Version=1;vn.AddWebXRFeature(f8.Name,(n,e)=>()=>new f8(n,e),f8.Version,!0);class p8 extends Lo{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new ce,this._tmpPos=new P,this._tmpQuat=new we,this._initHitTestSource=i=>{if(!i)return;const r=new XRRay(this.options.offsetRay||{}),s={space:this.options.useReferenceSpace?i:this._xrSessionManager.viewerReferenceSpace,offsetRay:r};if(this.options.entityTypes&&(s.entityTypes=this.options.entityTypes),!s.space){Ee.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(s).then(a=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=a})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new Ae,this.paused=!1,this.xrNativeFeatureName="hit-test",Ee.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach()||!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then(t=>{this._transientXrHitTestSource=t})}return!0}detach(){return super.detach()?(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0):!1}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!(!this.attached||this.paused)){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach(i=>{this._processWebXRHitTestResult(i.results,i.inputSource)})}}_processWebXRHitTestResult(e,t){const i=[];e.forEach(r=>{const s=r.getPose(this._xrSessionManager.referenceSpace);if(!s)return;const a=s.transform.position,o=s.transform.orientation;this._tmpPos.set(a.x,a.y,a.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(o.x,o.y,o.z,o.w),ce.FromFloat32ArrayToRefScaled(s.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const c={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:r};i.push(c)}),this.onHitTestResultObservable.notifyObservers(i)}}p8.Name=pr.HIT_TEST;p8.Version=2;vn.AddWebXRFeature(p8.Name,(n,e)=>()=>new p8(n,e),p8.Version,!1);class _8 extends Lo{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new Ae,this.onFeaturePointsUpdatedObservable=new Ae,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return super.detach()?(this.featurePointCloud.length=0,!0):!1}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(!(!t||t.length===0)){if(t.length%5!==0)throw new Error("Received malformed feature point cloud of length: "+t.length);const i=t.length/5,r=[],s=[];for(let a=0;a0&&this.onFeaturePointsAddedObservable.notifyObservers(s),r.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(r)}}_init(){!this._xrSessionManager.session.trySetFeaturePointCloudEnabled||!this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)||(this._enabled=!0)}}_8.Name=pr.FEATURE_POINTS;_8.Version=1;vn.AddWebXRFeature(_8.Name,n=>()=>new _8(n),_8.Version);let ize=0;class m8 extends Lo{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new Ae,this.onMeshRemovedObservable=new Ae,this.onMeshUpdatedObservable=new Ae,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return super.detach()?(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach(e=>{this.onMeshRemovedObservable.notifyObservers(e)}),this._detectedMeshes.clear()),!0):!1}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){var t;try{if(!this.attached||!e)return;const i=e.detectedMeshes||((t=e.worldInformation)==null?void 0:t.detectedMeshes);if(i){const r=new Set;this._detectedMeshes.forEach((s,a)=>{i.has(a)||r.add(a)}),r.forEach(s=>{const a=this._detectedMeshes.get(s);a&&(this.onMeshRemovedObservable.notifyObservers(a),this._detectedMeshes.delete(s))}),i.forEach(s=>{if(this._detectedMeshes.has(s)){if(s.lastChangedTime===this._xrSessionManager.currentTimestamp){const a=this._detectedMeshes.get(s);a&&(this._updateVertexDataWithXRMesh(s,a,e),this.onMeshUpdatedObservable.notifyObservers(a))}}else{const a={id:ize++,xrMesh:s},o=this._updateVertexDataWithXRMesh(s,a,e);this._detectedMeshes.set(s,o),this.onMeshAddedObservable.notifyObservers(o)}})}}catch(i){de.Log(i.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){var s;t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const r=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=r,t.normals=e.normals;else{t.positions=new Float32Array(r.length);for(let o=0;o()=>new m8(n,e),m8.Version,!1);var x0;(function(n){n[n.NotReceived=0]="NotReceived",n[n.Waiting=1]="Waiting",n[n.Received=2]="Received"})(x0||(x0={}));class g8 extends Lo{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new Ae,this.onTrackableImageFoundObservable=new Ae,this.onTrackedImageUpdatedObservable=new Ae,this._trackableScoreStatus=x0.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach(e=>{e.originalBitmap.close()}),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map(t=>typeof t.src=="string"?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(t.src):Promise.resolve(t.src));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map((i,r)=>({image:i,widthInMeters:this.options.images[r].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch{return Ee.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===x0.Waiting)return;if(this._trackableScoreStatus===x0.NotReceived){this._checkScoresAsync();return}const t=e.getImageTrackingResults();for(const i of t){let r=!1;const s=i.index,a=this._trackedImages[s];if(!a)continue;a.xrTrackingResult=i,a.realWorldWidth!==i.measuredWidthInMeters&&(a.realWorldWidth=i.measuredWidthInMeters,r=!0);const o=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(o){const h=a.transformationMatrix;ce.FromArrayToRef(o.transform.matrix,0,h),this._xrSessionManager.scene.useRightHandedSystem||h.toggleModelMatrixHandInPlace(),r=!0}const l=i.trackingState==="emulated";a.emulated!==l&&(a.emulated=l,r=!0),r&&this.onTrackedImageUpdatedObservable.notifyObservers(a)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==x0.NotReceived)return;this._trackableScoreStatus=x0.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||e.length===0){this._trackableScoreStatus=x0.NotReceived;return}for(let t=0;t0?x0.Received:x0.NotReceived}}g8.Name=pr.IMAGE_TRACKING;g8.Version=1;vn.AddWebXRFeature(g8.Name,(n,e)=>()=>new g8(n,e),g8.Version,!1);class v8 extends Lo{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Ee.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!super.attach()||!this._xrSessionManager.session.domOverlayState||this._xrSessionManager.session.domOverlayState.type===null?!1:(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,this._element!==null&&this.options.supressXRSelectEvents===!0&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),!0)}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),this._element!==null&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(this.options.element===void 0)return Ee.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if(typeof this.options.element=="string"){const e=document.querySelector(this.options.element);if(e===null)return Ee.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}v8.Name=pr.DOM_OVERLAY;v8.Version=1;vn.AddWebXRFeature(v8.Name,(n,e)=>()=>new v8(n,e),v8.Version,!1);class Ym extends Lo{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new we,this._tmpRotationMatrix=ce.Identity(),this._tmpTranslationDirection=new P,this._tmpMovementTranslation=new P,this._tempCacheQuaternion=new we,this._attachController=i=>{if(this._controllers[i.uniqueId])return;this._controllers[i.uniqueId]={xrController:i,registeredComponents:[]};const r=this._controllers[i.uniqueId];if(r.xrController.inputSource.targetRayMode==="tracked-pointer"&&r.xrController.inputSource.gamepad){const s=()=>{if(i.motionController)for(const a of this._currentRegistrationConfigurations){let o=null;if(a.allowedComponentTypes)for(const l of a.allowedComponentTypes){const h=i.motionController.getComponentOfType(l);if(h!==null){o=h;break}}if(a.mainComponentOnly){const l=i.motionController.getMainComponent();if(l===null)continue;o=l}if(typeof a.componentSelectionPredicate=="function"&&(o=a.componentSelectionPredicate(i)),o&&a.forceHandedness&&i.inputSource.handedness!==a.forceHandedness||o===null)continue;const c={registrationConfiguration:a,component:o};r.registeredComponents.push(c),"axisChangedHandler"in a&&(c.onAxisChangedObserver=o.onAxisValueChangedObservable.add(l=>{a.axisChangedHandler(l,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in a&&(c.onButtonChangedObserver=o.onButtonStateChangedObservable.add(()=>{o.changes.pressed&&a.buttonChangedhandler(o.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};i.motionController?s():i.onMotionControllerInitObservable.addOnce(()=>{s()})}},!t||t.xrInput===void 0){Ee.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=Ym.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput}attach(){return super.attach()?(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0):!1}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._controllers={},!0):!1}_onXRFrame(e){if(this.attached){if(this._movementState.rotateX!==0&&this._featureContext.rotationEnabled){const i=this._xrSessionManager.scene.getEngine().getDeltaTime()*.001*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=i,we.RotationYawPitchRollToRef(i,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(we.RotationYawPitchRollToRef(i*3,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(ce.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),P.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const i of t.registeredComponents)i.onAxisChangedObserver&&i.component.onAxisValueChangedObservable.remove(i.onAxisChangedObserver),i.onButtonChangedObserver&&i.component.onButtonStateChangedObservable.remove(i.onButtonChangedObserver);delete this._controllers[e]}}}Ym.Name=pr.MOVEMENT;Ym.REGISTRATIONS={default:[{allowedComponentTypes:[Yh.THUMBSTICK_TYPE,Yh.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(n,e,t)=>{e.rotateX=Math.abs(n.x)>t.rotationThreshold?n.x:0,e.rotateY=Math.abs(n.y)>t.rotationThreshold?n.y:0}},{allowedComponentTypes:[Yh.THUMBSTICK_TYPE,Yh.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(n,e,t)=>{e.moveX=Math.abs(n.x)>t.movementThreshold?n.x:0,e.moveY=Math.abs(n.y)>t.movementThreshold?n.y:0}}]};Ym.Version=1;vn.AddWebXRFeature(Ym.Name,(n,e)=>()=>new Ym(n,e),Ym.Version,!0);class x8 extends Lo{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=P.Up().negateInPlace(),this._lightColor=Me.White(),this._intensity=1,this._sphericalHarmonics=new r4,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new Ae,this._updateReflectionCubeMap=()=>{var r;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const s=Date.now();if(s-this._cubeMapPollTime{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)}))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new Wl("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new P(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=os.FALLOFF_GLTF),this._hdrFilter=new Fee(this._xrSessionManager.scene.getEngine()),Ee.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return this._canvasContext===null&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(this._xrWebGLBinding===null){const e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){if(!super.attach())return!1;const e=this.options.reflectionFormat??(this._xrSessionManager.session.preferredReflectionFormat||"srgba8");return this.options.reflectionFormat=e,this._xrSessionManager.session.requestLightProbe({reflectionFormat:e}).then(t=>{this._xrLightProbe=t,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new Er(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))}),!0}detach(){const e=super.detach();return this._xrLightProbe!==null&&!this.options.disableCubeMapReflection&&(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),this._reflectionCubeMap!==null&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){var t;if(this._xrLightProbe!==null){if(this.options.lightEstimationPollInterval){const i=Date.now();if(i-this._lightEstimationPollTime()=>new x8(n,e),x8.Version,!1);class y8 extends Lo{constructor(e){super(e),this.onEyeTrackingStartedObservable=new Ae,this.onEyeTrackingEndedObservable=new Ae,this.onEyeTrackingFrameUpdateObservable=new Ae,this._eyeTrackingStartListener=t=>{this._latestEyeSpace=t.gazeSpace,this._gazeRay=new Fi(P.Zero(),P.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(!(!this.attached||!e)&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);const i=t.transform.orientation;ie.Quaternion[0].set(i.x,i.y,i.z,i.w),this._xrSessionManager.scene.useRightHandedSystem?P.RightHandedForwardReadOnly.rotateByQuaternionToRef(ie.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,ie.Quaternion[0].z*=-1,ie.Quaternion[0].w*=-1,P.LeftHandedForwardReadOnly.rotateByQuaternionToRef(ie.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}y8.Name=pr.EYE_TRACKING;y8.Version=1;vn.AddWebXRFeature(y8.Name,n=>()=>new y8(n),y8.Version,!1);class rze{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class sze{constructor(){this._samples=new rze(20),this._entropy=0,this.onFirstStepDetected=new Ae}update(e,t,i,r){this._samples.push(e,t);const s=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=Be.Distance(s,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let a;for(a=this._samePointCheckStartIdx;ao&&(c=C,o=y);if(oa*this._squaredProjectionDistanceThreshold)return;const _=ie.Vector3[0];_.set(i,r,0);const m=ie.Vector3[1];m.set(h.x,h.y,0);const g=P.Cross(_,m).z>0,v=s.clone(),x=s.clone();l.subtractToRef(s,h),g?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,v),h.scaleAndAddToRef(this._axisToApexExtendFactor,x)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,v),h.scaleAndAddToRef(this._axisToApexShrinkFactor,x)),this.onFirstStepDetected.notifyObservers({leftApex:v,rightApex:x,currentPosition:s,currentStepDirection:g?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))}get _vitalityThreshold(){return .1}get forward(){return this._forward}}class vD{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new sze,this._walker=null,this._movement=new Be,this._millisecondsSinceLastUpdate=vD._MillisecondsPerUpdate,this.movementThisFrame=P.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(t=>{this._walker||(this._walker=new nze(t.leftApex,t.rightApex,t.currentPosition,t.currentStepDirection),this._walker.onFootfall.add(()=>{de.Log("Footfall!")}),this._walker.onMovement.add(i=>{this._walker.forward.scaleAndAddToRef(.024*i.deltaT,this._movement)}))})}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=vD._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=vD._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&(this._walker.update(e.x,e.z)||(this._walker=null)),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class iz extends Lo{static get Name(){return pr.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera=this._locomotionTarget.getClassName()==="WebXRCamera"}constructor(e,t){super(e),this._up=new P,this._forward=new P,this._position=new P,this._movement=new P,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&de.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return this._sessionManager.sessionMode===void 0||this._sessionManager.sessionMode==="immersive-vr"}attach(){return!this.isCompatible||!super.attach()?!1:(this._walker=new vD(this._sessionManager.scene.getEngine()),!0)}detach(){return super.detach()?(this._walker=null,!0):!1}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||P.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}vn.AddWebXRFeature(iz.Name,(n,e)=>()=>new iz(n,e),iz.Version,!1);class vve extends see{constructor(e,t,i,r,s,a,o=null){super(e,t,i,r,a),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=s,this.createRTTProvider=a,this._originalInternalTexture=o}}class xve extends AG{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new Ae,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),r=t=="right"?1:0,s=e.colorTextureWidth??e.textureWidth,a=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[r]||(i==null?void 0:i.textureWidth)!==s||(i==null?void 0:i.textureHeight)!==a){let o;const c=e.depthStencilTextureWidth??s,l=e.depthStencilTextureHeight??a;(s===c||a===l)&&(o=e.depthStencilTexture),this._renderTargetTextures[r]=this._createRenderTargetTexture(s,a,null,e.colorTexture,o,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:a},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[r],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[r]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e==null?void 0:e.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,r=t.colorTextureHeight??t.textureHeight,s=t.viewport;e.x=s.x/i,e.y=s.y/r,e.width=s.width/i,e.height=s.height/r}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return i?(this._setViewportForSubImage(e,i),!0):!1}}class aze extends vve{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,r=>new oze(r,i,this)),this.layer=e}}class oze extends xve{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return i?(this._setViewportForSubImage(e,i),!0):!1}}const jde={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},lze={};class A8 extends Lo{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this._isMultiviewEnabled=!1,this._projectionLayerInitialized=!1,this._compositionLayerTextureMapping=new WeakMap,this._layerToRTTProviderMapping=new WeakMap,this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t={...jde,...this._options.projectionLayerInit};return this._isMultiviewEnabled=this._options.preferMultiviewOnInit&&e.getCaps().multiview,this.createProjectionLayer(t),this._projectionLayerInitialized=!0,!0}detach(){return super.detach()?(this._existingLayers.forEach(e=>{e.dispose()}),this._existingLayers.length=0,this._projectionLayerInitialized=!1,!0):!1}createXRWebGLLayer(e=lze){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new nee(t)}_validateLayerInit(e,t=this._isMultiviewEnabled){if(!this._xrSessionManager.inXRSession)throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");if(t&&e.textureType!=="texture-array")throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&e.textureType==="texture-array")throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.")}_extendXRLayerInit(e,t=this._isMultiviewEnabled){return t&&(e.textureType="texture-array"),e}createProjectionLayer(e=jde,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),r=new aze(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(r),r}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,r=this._existingLayers[0].layer.textureHeight,s={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:r,clearOnAccess:!0,...e.params};this._validateLayerInit(s,!1);const a=this._xrWebGLBinding.createQuadLayer(s);a.width=this._isMultiviewEnabled?1:2,a.height=1;const o=new vve(()=>a.width,()=>a.height,a,"XRQuadLayer",!1,l=>new xve(l,this._xrWebGLBinding,o));t&&this._compositionLayerTextureMapping.set(a,t);const c=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(a,c),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),r=i.layer,a={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)},o={x:0,y:0,z:0,w:1};r.transform=new XRRigidTransform(a,o);const c=this._layerToRTTProviderMapping.get(r);if(!c)throw new Error("Could not find the RTT provider for the layer");const l=this._xrSessionManager.scene.layers.find(h=>h.texture===e);if(!l)throw new Error("Could not find the babylon layer for the texture");return c.onRenderTargetTextureCreatedObservable.add(h=>{h.eye&&h.eye==="right"||(h.texture.clearColor=new Ze(0,0,0,0),l.renderTargetTextures.push(h.texture),l.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add(()=>{h.texture.render()}),l.renderTargetTextures.push(h.texture),l.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce(()=>{l.renderTargetTextures.splice(l.renderTargetTextures.indexOf(h.texture),1),l.renderOnlyInRenderTargetTextures=!1}))}),i}_addLensFlareSystem(e){const t=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}}),i=t.layer;i.width=2,i.height=1;const s={x:0,y:0,z:-10},a={x:0,y:0,z:0,w:1};i.transform=new XRRigidTransform(s,a);const o=this._layerToRTTProviderMapping.get(i);if(!o)throw new Error("Could not find the RTT provider for the layer");return o.onRenderTargetTextureCreatedObservable.add(c=>{c.texture.clearColor=new Ze(0,0,0,0),c.texture.customRenderFunction=()=>{e.render()}}),this._xrSessionManager.onXRSessionInit.add(()=>{this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)}),this._xrSessionManager.onXRSessionEnded.add(()=>{this._xrSessionManager.scene.lensFlareSystems.push(e)}),t}addXRSessionLayer(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)}setXRSessionLayers(e=this._existingLayers){const t={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map(i=>i.layer),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&typeof XRWebGLBinding<"u"&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new A8(n,e),A8.Version,!1);class C8 extends Lo{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){if(!this._cachedWebGLTexture)return null;const e=this._xrSessionManager.scene.getEngine(),t=new Ar(e,mi.Unknown);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format=this.depthDataFormat==="ushort"?2:5,t.generateMipMaps=!1,t.type=this.depthDataFormat==="ushort"?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new j6(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?this.depthDataFormat==="ushort"?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new Ae,this.xrNativeFeatureName="depth-sensing",Ee.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!super.attach(e)||this._xrSessionManager.session.depthDataFormat==null||this._xrSessionManager.session.depthUsage==null?!1:(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0)}dispose(){var e;(e=this._cachedDepthImageTexture)==null||e.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(i!=null)for(const r of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,r,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,r,this.depthDataFormat);break;default:Ee.Error("Unknown depth usage"),this.detach();break}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const r=e.getDepthInformation(t);if(r===null)return;const{data:s,width:a,height:o,rawValueToMeters:c,getDepthInMeters:l}=r;switch(this._width=a,this._height=o,this._rawValueToMeters=c,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=$s.CreateRTexture(null,a,o,this._xrSessionManager.scene,!1,!0,ve.NEAREST_SAMPLINGMODE,De.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map(h=>h*c));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map(h=>h*c));break}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const r=e.getDepthInformation(t);if(r===null)return;const{texture:s,width:a,height:o}=r;this._width=a,this._height=o,this._cachedWebGLTexture=s;const c=this._xrSessionManager.scene,h=c.getEngine().wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=$s.CreateRTexture(null,a,o,c,!1,!0,ve.NEAREST_SAMPLINGMODE,i==="ushort"?De.TEXTURETYPE_UNSIGNED_BYTE:De.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=h}getXRSessionInitExtension(){const e=this.options.usagePreference!=null&&this.options.usagePreference.length!==0,t=this.options.dataFormatPreference!=null&&this.options.dataFormatPreference.length!==0;return new Promise(i=>{if(e&&t){const r=this.options.usagePreference.map(a=>{switch(a){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),s=this.options.dataFormatPreference.map(a=>{switch(a){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:r,dataFormatPreference:s}})}else i({})})}}C8.Name=pr.DEPTH_SENSING;C8.Version=1;vn.AddWebXRFeature(C8.Name,(n,e)=>()=>new C8(n,e),C8.Version,!1);const cze="velocityPixelShader",hze=`precision highp float; #define CUSTOM_FRAGMENT_BEGIN varying vec4 clipPos;varying vec4 previousClipPos; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; #define CUSTOM_FRAGMENT_MAIN_END }`;Re.ShadersStore[cze]=hze;const uze="velocityVertexShader",dze=`#define CUSTOM_VERTEX_BEGIN #define VELOCITY attribute vec3 position; #include uniform mat4 viewProjection;uniform mat4 previousViewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; #endif varying vec4 clipPos;varying vec4 previousClipPos; #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 positionUpdated=position; #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} #elif clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; #endif #define CUSTOM_VERTEX_MAIN_END }`;Re.ShadersStore[uze]=dze;class yve extends es{constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[ce.Identity(),ce.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new kn("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(s=>{this._previousWorldMatrices[s.uniqueId]=this._previousWorldMatrices[s.uniqueId]||s.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[s.uniqueId]),this._previousWorldMatrices[s.uniqueId]=s.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)}),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach(r=>{this._originalPairing.push([r,r.material]),r.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(r=>{r[0].material=r[1]})}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class Ave{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if(t.layerType!=="XRProjectionLayer")throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,s){if(!this._engine)throw new Error("Engine is disposed");const a={width:e,height:t},o=new yve(r,s,this._scene,a),c=o.renderTarget;return i&&(c._framebuffer=i),c._colorTextureArray=r,c._depthStencilTextureArray=s,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let r=this._renderTargetTextures.get(t.eye);const s=e.motionVectorTextureWidth,a=e.motionVectorTextureHeight;return(!r||(i==null?void 0:i.textureWidth)!==s||(i==null?void 0:i.textureHeight)!=a)&&(r=this._createRenderTargetTexture(s,a,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:a}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return i?(this._setViewportForSubImage(e,i),!0):!1}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}}class b8 extends Lo{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[pr.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new Ave(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add(()=>this._onAfterRender()),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}b8.Name=pr.SPACE_WARP;b8.Version=1;vn.AddWebXRFeature(b8.Name,n=>()=>new b8(n),b8.Version,!1);class E8 extends Lo{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new Ae,this.xrNativeFeatureName="camera-access"}attach(e){return super.attach(e)?(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0):!1}detach(){return super.detach()?(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach(e=>e.dispose()),this.texturesData.forEach(e=>e.dispose()),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0):!1}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},r=e.projectionMatrix,s=(1-r[8])*i.width/2+i.x,a=(1-r[9])*i.height/2+i.y,o=i.width/2*r[0],c=i.height/2*r[5],l=i.width/2*r[4];this.cameraIntrinsics[t]={u0:s,v0:a,ax:o,ay:c,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){var r,s;if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=(r=this._glBinding)==null?void 0:r.getCameraImage(e.camera);if(this._cachedInternalTextures[t])(s=this._cachedInternalTextures[t]._hardwareTexture)==null||s.set(i);else{const a=new Ar(this._xrSessionManager.scene.getEngine(),mi.Unknown,!0);a.isCube=!0,a.invertY=!1,a.format=5,a.generateMipMaps=!0,a.type=1,a.samplingMode=3,a.width=e.camera.width,a.height=e.camera.height,a._cachedWrapU=1,a._cachedWrapV=1,a._hardwareTexture=new j6(i,this._glContext),this._cachedInternalTextures[t]=a;const o=new Er(this._xrSessionManager.scene);o.name=`WebXR Raw Camera Access (${t})`,o._texture=this._cachedInternalTextures[t],this.texturesData[t]=o,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let r=!0;i.views.forEach((s,a)=>{r=r&&this._updateInternalTextures(s,a)}),r&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}E8.Name=pr.RAW_CAMERA_ACCESS;E8.Version=1;vn.AddWebXRFeature(E8.Name,(n,e)=>()=>new E8(n,e),E8.Version,!1);class Cve extends J6{constructor(e,t,i){super(e,fze[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}So.RegisterController("generic-hand-select-grasp",(n,e)=>new Cve(e,n.gamepad,n.handedness));const fze={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class Qm extends J6{constructor(e,t,i){super(e,pze["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=Qm.MODEL_LEFT_FILENAME:e=Qm.MODEL_RIGHT_FILENAME;const i=Qm.MODEL_BASE_URL+"default"+"/";return{filename:e,path:i}}_getModelLoadingConstraints(){const e=ai.IsPluginForExtensionAvailable(".glb");return e||de.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach((t,i)=>{if(!this.disableAnimation&&t&&this.rootMesh){const r=this._mapping.buttons[t],s=r.rootNodeName;if(!s){de.Log("Skipping unknown button at index: "+i+" with mapped name: "+t);return}const a=this._getChildByName(this.rootMesh,s);if(!a){de.Warn("Missing button mesh with name: "+s);return}if(r.valueMesh=this._getImmediateChildByName(a,this._mapping.defaultButton.valueNodeName),r.pressedMesh=this._getImmediateChildByName(a,this._mapping.defaultButton.pressedNodeName),r.unpressedMesh=this._getImmediateChildByName(a,this._mapping.defaultButton.unpressedNodeName),r.valueMesh&&r.pressedMesh&&r.unpressedMesh){const o=this.getComponent(t);o&&o.onButtonStateChangedObservable.add(c=>{this._lerpTransform(r,c.value)},void 0,!0)}else de.Warn("Missing button submesh under mesh with name: "+s)}}),this.getComponentIds().forEach(t=>{const i=this.getComponent(t);i.isAxes()&&["x-axis","y-axis"].forEach(r=>{if(!this.rootMesh)return;const s=this._mapping.axes[t][r],a=this._getChildByName(this.rootMesh,s.rootNodeName);if(!a){de.Warn("Missing axis mesh with name: "+s.rootNodeName);return}s.valueMesh=this._getImmediateChildByName(a,this._mapping.defaultAxis.valueNodeName),s.minMesh=this._getImmediateChildByName(a,this._mapping.defaultAxis.minNodeName),s.maxMesh=this._getImmediateChildByName(a,this._mapping.defaultAxis.maxNodeName),s.valueMesh&&s.minMesh&&s.maxMesh?i&&i.onAxisValueChangedObservable.add(o=>{const c=r==="x-axis"?o.x:o.y;this._lerpTransform(s,c,!0)},void 0,!0):de.Warn("Missing axis submesh under mesh with name: "+s.rootNodeName)})}))}_setRootMesh(e){this.rootMesh=new Se(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;inew Qm(e,n.gamepad,n.handedness));const pze={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class Nf extends J6{constructor(e,t,i,r=!1,s=!1){super(e,_ze[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=Nf.MODEL_LEFT_FILENAME:e=Nf.MODEL_RIGHT_FILENAME;const t=this._isQuest()?Nf.QUEST_MODEL_BASE_URL:Nf.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i=this.handedness==="right"?-1:1;this.getComponentIds().forEach(r=>{const s=r&&this.getComponent(r);s&&s.onButtonStateChangedObservable.add(a=>{if(!(!this.rootMesh||this.disableAnimation))switch(r){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-a.value*.2,this._modelRootNode.getChildren()[3].position.y=-a.value*.005,this._modelRootNode.getChildren()[3].position.z=-a.value*.005);return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*a.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(a.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(a.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new Se(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=we.FromEulerAngles(0,Math.PI,0)),e.forEach(t=>{t.isPickable=!1}),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}Nf.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/";Nf.MODEL_LEFT_FILENAME="left.babylon";Nf.MODEL_RIGHT_FILENAME="right.babylon";Nf.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/";So.RegisterController("oculus-touch",(n,e)=>new Nf(e,n.gamepad,n.handedness));So.RegisterController("oculus-touch-legacy",(n,e)=>new Nf(e,n.gamepad,n.handedness,!0));const _ze={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class cA extends J6{constructor(e,t,i){super(e,mze[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){const e=cA.MODEL_FILENAME,t=cA.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(t=>{const i=t&&this.getComponent(t);i&&i.onButtonStateChangedObservable.add(r=>{if(!(!this.rootMesh||this.disableAnimation))switch(t){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-r.value*.15;return;case"xr-standard-touchpad":return;case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new Se(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1}),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=we.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}cA.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/";cA.MODEL_FILENAME="wand.babylon";So.RegisterController("htc-vive",(n,e)=>new cA(e,n.gamepad,n.handedness));const mze={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};class bve{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}B2e("NativeXRFrame",bve);var Qh;(function(n){n[n.Input=0]="Input",n[n.Output=1]="Output"})(Qh||(Qh={}));class iH{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=mh(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=Ee.Instantiate(e.className),r=new i(e.name,e._connectionType,t);return r.deserialize(e),r}}class ua{constructor(e){this.value=this._toInt(e)}_toInt(e){return e|0}add(e){return new ua(this.value+e.value)}subtract(e){return new ua(this.value-e.value)}multiply(e){return new ua(Math.imul(this.value,e.value))}divide(e){return new ua(this.value/e.value)}getClassName(){return ua.ClassName}equals(e){return this.value===e.value}static Parse(e){return new ua(e.value)}}ua.ClassName="FlowGraphInteger";xe("FlowGraphInteger",ua);class Ch{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new Ch(e.typeName,e.defaultValue)}}const Mt=new Ch("any",void 0),Eve=new Ch("string",""),Cs=new Ch("number",0),Yo=new Ch("boolean",!1),rH=new Ch("Vector2",Be.Zero()),W0=new Ch("Vector3",P.Zero()),Tve=new Ch("Vector4",Ct.Zero()),$m=new Ch("Matrix",ce.Identity()),Sve=new Ch("Color3",Me.Black()),Mve=new Ch("Color4",new Ze(0,0,0,0)),Rve=new Ch("Quaternion",we.Identity()),Zn=new Ch("FlowGraphInteger",new ua(0));function Ive(n){switch(typeof n){case"string":return Eve;case"number":return Cs;case"boolean":return Yo;case"object":return n instanceof Be?rH:n instanceof P?W0:n instanceof Ct?Tve:n instanceof Me?Sve:n instanceof Ze?Mve:n instanceof we?Rve:n instanceof ua?Zn:Mt;default:return Mt}}class sH extends iH{constructor(e,t,i,r){super(e,t,i),this.richType=r}_isSingularConnection(){return this.connectionType===Qh.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===Qh.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=iH.Parse(e,t);return i.richType=Ch.Parse(e.richType),i}}xe("FGDataConnection",sH);function Pve(n){return n==="Mesh"||n==="AbstractMesh"||n==="GroundMesh"||n==="InstanceMesh"||n==="LinesMesh"||n==="GoldbergMesh"||n==="GreasedLineMesh"||n==="TrailMesh"}function wve(n){return n==="Vector2"||n==="Vector3"||n==="Vector4"||n==="Quaternion"||n==="Color3"||n==="Color4"}function gze(n,e){if(n==="Vector2")return Be.FromArray(e);if(n==="Vector3")return P.FromArray(e);if(n==="Vector4")return Ct.FromArray(e);if(n==="Quaternion")return we.FromArray(e);if(n==="Color3")return new Me(e[0],e[1],e[2]);if(n==="Color4")return new Ze(e[0],e[1],e[2],e[3]);throw new Error(`Unknown vector class name ${n}`)}function Vte(n,e,t){var r;const i=((r=e==null?void 0:e.getClassName)==null?void 0:r.call(e))??"";Pve(i)?t[n]={name:e.name,className:i}:wve(i)?t[n]={value:e.asArray(),className:i}:t[n]=e}function yK(n,e,t){const i=e[n];let r;const s=i==null?void 0:i.className;return Pve(s)?r=t.getMeshByName(i.name):wve(s)?r=gze(s,i.value):s==="Matrix"?r=ce.FromArray(i.value):s===ua.ClassName?r=ua.Parse(i):i&&i.value!==void 0?r=i.value:r=i,r}function vze(n){return n==="FGSetPropertyBlock"||n==="FGGetPropertyBlock"||n==="FGPlayAnimationBlock"||n==="FGMeshPickEventBlock"}class v2{constructor(e){var t;this.config=e,this.uniqueId=mh(),this.name=((t=this.config)==null?void 0:t.name)??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new sH(e,Qh.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new sH(e,Qh.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find(t=>t.name===e)}getDataOutput(e){return this.dataOutputs.find(t=>t.name===e)}serialize(e={},t=Vte){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const i of this.dataInputs){const r={};i.serialize(r),e.dataInputs.push(r)}for(const i of this.dataOutputs){const r={};i.serialize(r),e.dataOutputs.push(r)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Ee.Instantiate(e.className),r={},s=t.valueParseFunction??yK;if(e.config)for(const o in e.config)r[o]=s(o,e.config,t.scene);vze(e.className)&&(r.pathConverter=t.pathConverter);const a=new i(r);a.uniqueId=e.uniqueId;for(let o=0;ot.name===e)}getSignalOutput(e){return this.signalOutputs.find(t=>t.name===e)}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{var a,o,c;s.type===ft.POINTERPICK&&((a=s.pickInfo)!=null&&a.pickedMesh)&&(((o=s.pickInfo)==null?void 0:o.pickedMesh)===i||Hte((c=s.pickInfo)==null?void 0:c.pickedMesh,i))&&this._execute(e)});const r=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",r)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return hA.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}hA.ClassName="FGMeshPickEventBlock";xe(hA.ClassName,hA);var S3;(function(n){n[n.Stopped=0]="Stopped",n[n.Started=1]="Started"})(S3||(S3={}));class uA{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=S3.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){const e=new aH({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==S3.Started){this.state=S3.Started,this._executionContexts.length===0&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===hA.ClassName){const i=t._getReferencedMesh();let r=0;for(;r0;){const r=t.pop();e(r);for(const s of r.dataInputs)for(const a of s._connectedPoint)i.has(a._ownerBlock.uniqueId)||(t.push(a._ownerBlock),i.add(a._ownerBlock.uniqueId));if(r instanceof r1)for(const s of r.signalOutputs)for(const a of s._connectedPoint)i.has(a._ownerBlock.uniqueId)||(t.push(a._ownerBlock),i.add(a._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks(i=>{const r={};i.serialize(r),e.allBlocks.push(r)}),e.executionContexts=[];for(const i of this._executionContexts){const r={};i.serialize(r,t),e.executionContexts.push(r)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const r of i.dataOutputs)if(r.uniqueId===t)return r;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof r1){for(const r of i.signalInputs)if(r.uniqueId===t)return r}throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),r=[],s=t.valueParseFunction??yK;for(const a of e.allBlocks){const o=v2.Parse(a,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:s});r.push(o),o instanceof j5&&i.addEventBlock(o)}for(const a of r){for(const o of a.dataInputs)for(const c of o.connectedPointIds){const l=uA.GetDataOutConnectionByUniqueId(r,c);o.connectTo(l)}if(a instanceof r1)for(const o of a.signalOutputs)for(const c of o.connectedPointIds){const l=uA.GetSignalInConnectionByUniqueId(r,c);o.connectTo(l)}}for(const a of e.executionContexts)aH.Parse(a,{graph:i,valueParseFunction:s});return i}}class Ky{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add(()=>{this.dispose()}),(Ky.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new uA({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);t!==-1&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach(e=>e.start())}dispose(){this._flowGraphs.forEach(i=>i.dispose()),this._flowGraphs.length=0;const e=Ky.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);t!==-1&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach(i=>{const r={};i.serialize(r,t),e._flowGraphs.push(r)})}static Parse(e,t){var s;const i=t.valueParseFunction??yK,r=new Ky({scene:t.scene});return(s=e._flowGraphs)==null||s.forEach(a=>{uA.Parse(a,{coordinator:r,valueParseFunction:i,pathConverter:t.pathConverter})}),r}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new Ae,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}Ky.SceneCoordinators=new Map;class xze{constructor(e){this._context=e,this._context.onNodeExecutedObservable.add(t=>{Ee.Log(`Node executed: ${t.getClassName()}`)})}}class kd extends r1{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class dA extends kd{constructor(e){super(e),this.message=this.registerDataInput("message",Mt)}_execute(e){const t=this.message.getValue(e);de.Log(t),this.out._activateSignal(e)}getClassName(){return dA.ClassName}}dA.ClassName="FGConsoleLogBlock";xe(dA.ClassName,dA);class fA extends kd{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Mt)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return fA.ClassName}}fA.ClassName="FGSetVariableBlock";xe(fA.ClassName,fA);const Xde=new RegExp(/\{(\w+)\}/g);class oH{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=Xde.exec(e);for(;i;){const[,r]=i;this.templatedInputs.push(t.registerDataInput(r,Zn)),i=Xde.exec(e)}}getAccessor(e,t){let i=this.path;for(const r of this.templatedInputs){const s=r.getValue(t).value;i=i.replace(`{${r.name}}`,s.toString())}return e.convert(i)}}class X5 extends kd{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Mt),this.templateComponent=new oH(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return X5.ClassName}}X5.ClassName="FGSetPropertyBlock";xe("FGSetPropertyBlock",X5);class Y5 extends kd{constructor(e){super(e),this.config=e;for(let t=0;tr.getValue(e));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return Y5.ClassName}}Y5.ClassName="FGSendCustomEventBlock";xe("FGSendCustomEventBlock",Y5);class Dve extends r1{constructor(e){super(e),this.condition=this.registerDataInput("condition",Yo),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}}xe("FGBranchBlock",Dve);class pA extends kd{constructor(e={startIndex:new ua(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",Zn),this.value=this.registerDataOutput("value",Zn)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const i=this.value.getValue(e);i.valuer)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",s);else{const a=r-(s-i);this.timeRemaining.setValue(a,e)}}getClassName(){return"FGThrottleBlock"}}xe("FGThrottleBlock",Lve);class Q5 extends zte{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",Cs)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(t!==void 0&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],r=e.configuration.scene,s=new ige({timeout:t,contextObservable:r.onBeforeRenderObservable,onEnded:()=>this._onEnded(s,e)});s.start(),i.push(s),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);r!==-1?i.splice(r,1):Ee.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const i of t)i.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return Q5.ClassName}}Q5.ClassName="FGTimerBlock";xe("FGTimerBlock",Q5);class Nve extends r1{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",Cs),this.config.startIndex=this.config.startIndex!==void 0?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let t=0;t=this.config.numberOutputFlows&&this.config.loop)s=0;else if(s>=this.config.numberOutputFlows&&!this.config.loop)return;if(r=r.filter(a=>a!==s),r.length===0)for(let a=0;a=0&&(i[r+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(r=>r)){this.out._activateSignal(e);for(let r=0;r=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}xe("FGDebounceBlock",kve);class Vve extends r1{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",Yo)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}}xe("FGFlipFlopBlock",Vve);class mA extends r1{constructor(e){super(e),this.config=e,this.outFlows=[];for(let t=0;tthis._onAnimationEnd(l,e));this.runningAnimatable.setValue(l,e),a.push(l)}e._setExecutionVariable(this,"runningAnimatables",a)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],r=i.indexOf(e);r!==-1&&i.splice(r,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const i of t)i.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return u5.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}u5.ClassName="FGPlayAnimationBlock";xe(u5.ClassName,u5);class zve extends kd{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",Mt)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}xe("FGStopAnimationBlock",zve);class Hve extends kd{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",Mt)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}xe("FGPauseAnimationBlock",Hve);class Gve extends v2{constructor(e){super(e),this.condition=this.registerDataInput("condition",Yo),this.trueValue=this.registerDataInput("trueValue",Mt),this.falseValue=this.registerDataInput("falseValue",Mt),this.output=this.registerDataOutput("output",Mt)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}xe("FGConditionalDataBlock",Gve);class gA extends v2{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Mt)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return gA.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}gA.ClassName="FGGetVariableBlock";xe(gA.ClassName,gA);class Kve extends v2{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",Mt),this.destinationSystem=this.registerDataInput("destinationSystem",Mt),this.inputCoordinates=this.registerDataInput("inputCoordinates",W0),this.outputCoordinates=this.registerDataOutput("outputCoordinates",W0)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),s=t.getWorldMatrix(),a=i.getWorldMatrix(),o=ie.Matrix[0].copyFrom(a);o.invert();const c=ie.Matrix[1];o.multiplyToRef(s,c);const l=this.outputCoordinates.getValue(e);P.TransformCoordinatesToRef(r,c,l)}getClassName(){return"FGCoordinateTransformBlock"}}xe("FGCoordinateTransformBlock",Kve);class Wve extends v2{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",Ive(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=Vte){super.serialize(e),t("value",this.config.value,e.config)}}xe("FGConstantBlock",Wve);class vA extends v2{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Mt),this.templateComponent=new oH(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return vA.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}vA.ClassName="FGGetPropertyBlock";xe(vA.ClassName,vA);const Yde="cachedOperationValue",Qde="cachedExecutionId";class AK extends v2{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,Qde),i=e._getExecutionVariable(this,Yde);if(i!==void 0&&t===e.executionId)this.value.setValue(i,e);else{const r=this._doOperation(e);e._setExecutionVariable(this,Yde,r),e._setExecutionVariable(this,Qde,e.executionId),this.value.setValue(r,e)}}}class Wa extends AK{constructor(e,t,i,r,s,a){super(i,a),this._operation=r,this._className=s,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class ts extends AK{constructor(e,t,i,r,s){super(t,s),this._operation=i,this._className=r,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const $5="FGLogic",jve="AndBlock",Xve="OrBlock",Yve="NotBlock";class Qve extends Wa{constructor(e){super(Yo,Yo,Yo,(t,i)=>t&&i,`${$5}${jve}`,e)}}xe(`${$5}${jve}`,Qve);class $ve extends Wa{constructor(e){super(Yo,Yo,Yo,(t,i)=>t||i,`${$5}${Xve}`,e)}}xe(`${$5}${Xve}`,$ve);class Zve extends ts{constructor(e){super(Yo,Yo,t=>!t,`${$5}${Yve}`,e)}}xe(`${$5}${Yve}`,Zve);class k9 extends AK{constructor(e,t,i,r){super(e,r),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Gte extends AK{constructor(e,t,i,r,s,a,o){super(r,o),this._operation=s,this._className=a,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function Il(n){return n.getClassName?n.getClassName():""}function V9(n,e){return n==="Vector2"&&e==="Vector2"||n==="Vector3"&&e==="Vector3"||n==="Vector4"&&e==="Vector4"}function z9(n,e){return n==="Matrix"&&e==="Matrix"}function H9(n,e){return n==="FlowGraphInteger"&&e==="FlowGraphInteger"}class xA extends Wa{constructor(e){super(Mt,Mt,Mt,(t,i)=>this._polymorphicAdd(t,i),xA.ClassName,e)}_polymorphicAdd(e,t){const i=Il(e),r=Il(t);return V9(i,r)||z9(i,r)||H9(i,r)?e.add(t):e+t}}xA.ClassName="FGAddBlock";xe(xA.ClassName,xA);class yA extends Wa{constructor(e){super(Mt,Mt,Mt,(t,i)=>this._polymorphicAdd(t,i),yA.ClassName,e)}_polymorphicAdd(e,t){const i=Il(e),r=Il(t);return V9(i,r)||H9(i,r)?e.subtract(t):z9(i,r)?e.add(t.scale(-1)):e-t}}yA.ClassName="FGSubBlock";xe(yA.ClassName,yA);class AA extends Wa{constructor(e){super(Mt,Mt,Mt,(t,i)=>this._polymorphicMultiply(t,i),AA.ClassName,e)}_polymorphicMultiply(e,t){const i=Il(e),r=Il(t);return V9(i,r)||H9(i,r)?e.multiply(t):z9(i,r)?ce.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}AA.ClassName="FGMultiplyBlock";xe(AA.ClassName,AA);class CA extends Wa{constructor(e){super(Mt,Mt,Mt,(t,i)=>this._polymorphicDivide(t,i),CA.ClassName,e)}_polymorphicDivide(e,t){const i=Il(e),r=Il(t);return V9(i,r)||H9(i,r)?e.divide(t):z9(i,r)?ce.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}CA.ClassName="FGDivideBlock";xe(CA.ClassName,CA);class bA extends k9{constructor(e){super(Cs,()=>Math.random(),bA.ClassName,e)}}bA.ClassName="FGRandomBlock";xe(bA.ClassName,bA);class EA extends Wa{constructor(e){super(Mt,Mt,Cs,(t,i)=>this._polymorphicDot(t,i),EA.ClassName,e)}_polymorphicDot(e,t){switch(Il(e)){case"Vector2":return Be.Dot(e,t);case"Vector3":return P.Dot(e,t);case"Vector4":return Ct.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}EA.ClassName="FGDotBlock";xe(EA.ClassName,EA);class TA extends k9{constructor(e){super(Cs,()=>Math.E,TA.ClassName,e)}}TA.ClassName="FGEBlock";xe(TA.ClassName,TA);class SA extends k9{constructor(e){super(Cs,()=>Math.PI,SA.ClassName,e)}}SA.ClassName="FGPIBlock";xe(SA.ClassName,SA);class MA extends k9{constructor(e){super(Cs,()=>Number.POSITIVE_INFINITY,MA.ClassName,e)}}MA.ClassName="FGInfBlock";xe(MA.ClassName,MA);class RA extends k9{constructor(e){super(Cs,()=>Number.NaN,RA.ClassName,e)}}RA.ClassName="FGNaNBlock";xe(RA.ClassName,RA);function Jn(n,e){switch(Il(n)){case"FlowGraphInteger":return new ua(e(n.value));case"Vector2":return new Be(e(n.x),e(n.y));case"Vector3":return new P(e(n.x),e(n.y),e(n.z));case"Vector4":return new Ct(e(n.x),e(n.y),e(n.z),e(n.w));case"Matrix":return ce.FromValues(e(n.m[0]),e(n.m[4]),e(n.m[8]),e(n.m[12]),e(n.m[1]),e(n.m[5]),e(n.m[9]),e(n.m[13]),e(n.m[2]),e(n.m[6]),e(n.m[10]),e(n.m[14]),e(n.m[3]),e(n.m[7]),e(n.m[11]),e(n.m[15]));default:return e(n)}}class IA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicAbs(t),IA.ClassName,e)}_polymorphicAbs(e){return Jn(e,Math.abs)}}IA.ClassName="FGAbsBlock";xe(IA.ClassName,IA);class PA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicSign(t),PA.ClassName,e)}_polymorphicSign(e){return Jn(e,Math.sign)}}PA.ClassName="FGSignBlock";xe(PA.ClassName,PA);class wA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicTrunc(t),wA.ClassName,e)}_polymorphicTrunc(e){return Jn(e,Math.trunc)}}wA.ClassName="FGTruncBlock";xe(wA.ClassName,wA);class DA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicFloor(t),DA.ClassName,e)}_polymorphicFloor(e){return Jn(e,Math.floor)}}DA.ClassName="FGFloorBlock";xe(DA.ClassName,DA);class OA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicCeiling(t),OA.ClassName,e)}_polymorphicCeiling(e){return Jn(e,Math.ceil)}}OA.ClassName="FGCeilBlock";xe(OA.ClassName,OA);class LA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicFract(t),LA.ClassName,e)}_polymorphicFract(e){return Jn(e,t=>t-Math.floor(t))}}LA.ClassName="FGFractBlock";xe(LA.ClassName,LA);class NA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicNeg(t),NA.ClassName,e)}_polymorphicNeg(e){return Jn(e,t=>-t)}}NA.ClassName="FGNegBlock";xe(NA.ClassName,NA);function G9(n,e,t){switch(Il(n)){case"FlowGraphInteger":return new ua(t(n.value,e.value));case"Vector2":return new Be(t(n.x,e.x),t(n.y,e.y));case"Vector3":return new P(t(n.x,e.x),t(n.y,e.y),t(n.z,e.z));case"Vector4":return new Ct(t(n.x,e.x),t(n.y,e.y),t(n.z,e.z),t(n.w,e.w));case"Matrix":return ce.FromValues(t(n.m[0],e.m[0]),t(n.m[4],e.m[4]),t(n.m[8],e.m[8]),t(n.m[12],e.m[12]),t(n.m[1],e.m[1]),t(n.m[5],e.m[5]),t(n.m[9],e.m[9]),t(n.m[13],e.m[13]),t(n.m[2],e.m[2]),t(n.m[6],e.m[6]),t(n.m[10],e.m[10]),t(n.m[14],e.m[14]),t(n.m[3],e.m[3]),t(n.m[7],e.m[7]),t(n.m[11],e.m[11]),t(n.m[15],e.m[15]));default:return t(n,e)}}class BA extends Wa{constructor(e){super(Mt,Mt,Mt,(t,i)=>this._polymorphicRemainder(t,i),BA.ClassName,e)}_polymorphicRemainder(e,t){return G9(e,t,(i,r)=>i%r)}}BA.ClassName="FGRemainderBlock";xe(BA.ClassName,BA);class FA extends Wa{constructor(e){super(Mt,Mt,Mt,(t,i)=>this._polymorphicMin(t,i),FA.ClassName,e)}_polymorphicMin(e,t){return G9(e,t,Math.min)}}FA.ClassName="FGMinBlock";xe(FA.ClassName,FA);class UA extends Wa{constructor(e){super(Mt,Mt,Mt,(t,i)=>this._polymorphicMax(t,i),UA.ClassName,e)}_polymorphicMax(e,t){return G9(e,t,Math.max)}}UA.ClassName="FGMaxBlock";xe(UA.ClassName,UA);function yze(n,e,t){return Math.min(Math.max(n,Math.min(e,t)),Math.max(e,t))}function qve(n,e,t,i){switch(Il(n)){case"FlowGraphInteger":return new ua(i(n.value,e.value,t.value));case"Vector2":return new Be(i(n.x,e.x,t.x),i(n.y,e.y,t.y));case"Vector3":return new P(i(n.x,e.x,t.x),i(n.y,e.y,t.y),i(n.z,e.z,t.z));case"Vector4":return new Ct(i(n.x,e.x,t.x),i(n.y,e.y,t.y),i(n.z,e.z,t.z),i(n.w,e.w,t.w));case"Matrix":return ce.FromValues(i(n.m[0],e.m[0],t.m[0]),i(n.m[4],e.m[4],t.m[4]),i(n.m[8],e.m[8],t.m[8]),i(n.m[12],e.m[12],t.m[12]),i(n.m[1],e.m[1],t.m[1]),i(n.m[5],e.m[5],t.m[5]),i(n.m[9],e.m[9],t.m[9]),i(n.m[13],e.m[13],t.m[13]),i(n.m[2],e.m[2],t.m[2]),i(n.m[6],e.m[6],t.m[6]),i(n.m[10],e.m[10],t.m[10]),i(n.m[14],e.m[14],t.m[14]),i(n.m[3],e.m[3],t.m[3]),i(n.m[7],e.m[7],t.m[7]),i(n.m[11],e.m[11],t.m[11]),i(n.m[15],e.m[15],t.m[15]));default:return i(n,e,t)}}class kA extends Gte{constructor(e){super(Mt,Mt,Mt,Mt,(t,i,r)=>this._polymorphicClamp(t,i,r),kA.ClassName,e)}_polymorphicClamp(e,t,i){return qve(e,t,i,yze)}}kA.ClassName="FGClampBlock";xe(kA.ClassName,kA);function Aze(n){return Math.min(Math.max(n,0),1)}class VA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicSaturate(t),VA.ClassName,e)}_polymorphicSaturate(e){return Jn(e,Aze)}}VA.ClassName="FGSaturateBlock";xe(VA.ClassName,VA);class zA extends Gte{constructor(e){super(Mt,Mt,Mt,Mt,(t,i,r)=>this._polymorphicInterpolate(t,i,r),zA.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return qve(e,t,i,this._interpolate)}}zA.ClassName="FGInterpolateBlock";xe(zA.ClassName,zA);class HA extends Wa{constructor(e){super(Mt,Mt,Yo,(t,i)=>this._polymorphicEq(t,i),HA.ClassName,e)}_polymorphicEq(e,t){const i=Il(e),r=Il(t);return V9(i,r)||z9(i,r)||H9(i,r)?e.equals(t):e===t}}HA.ClassName="FGEqBlock";xe(HA.ClassName,HA);function CK(n,e,t){const i=Il(n),r=Il(e);if(i===r){if(i==="")return t(n,e);if(i==="FlowGraphInteger")return t(n.value,e.value);throw new Error(`Cannot compare ${n} and ${e}`)}throw new Error(`${n} and ${e} are of different types.`)}class GA extends Wa{constructor(e){super(Mt,Mt,Yo,(t,i)=>this._polymorphicLessThan(t,i),GA.ClassName,e)}_polymorphicLessThan(e,t){return CK(e,t,(i,r)=>ithis._polymorphicLessThanOrEqual(t,i),K9.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return CK(e,t,(i,r)=>i<=r)}}K9.ClassName="FGLessThanOrEqualBlock";class KA extends Wa{constructor(e){super(Mt,Mt,Yo,(t,i)=>this._polymorphicGreaterThan(t,i),KA.ClassName,e)}_polymorphicGreaterThan(e,t){return CK(e,t,(i,r)=>i>r)}}KA.ClassName="FGGreaterThanBlock";xe(KA.ClassName,KA);class WA extends Wa{constructor(e){super(Mt,Mt,Yo,(t,i)=>this._polymorphicGreaterThanOrEqual(t,i),WA.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return CK(e,t,(i,r)=>i>=r)}}WA.ClassName="FGGreaterThanOrEqualBlock";xe(WA.ClassName,WA);class jA extends ts{constructor(e){super(Mt,Yo,t=>this._polymorphicIsNan(t),jA.ClassName,e)}_polymorphicIsNan(e){const t=Il(e);if(t==="")return isNaN(e);if(t==="FlowGraphInteger")return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}jA.ClassName="FGIsNanBlock";xe(jA.ClassName,jA);class W9 extends ts{constructor(e){super(Mt,Yo,t=>this._polymorphicIsInf(t),W9.ClassName,e)}_polymorphicIsInf(e){const t=Il(e);if(t==="")return!isFinite(e);if(t==="FlowGraphInteger")return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}W9.ClassName="FGIsInfBlock";class XA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicDegToRad(t),XA.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return Jn(e,this._degToRad)}}XA.ClassName="FGDegToRadBlock";xe(XA.ClassName,XA);class YA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicRadToDeg(t),YA.ClassName,e)}_radToDeg(e){return e*180/Math.PI}_polymorphicRadToDeg(e){return Jn(e,this._radToDeg)}}YA.ClassName="FGRadToDegBlock";xe(YA.ClassName,YA);class QA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicSin(t),QA.ClassName,e)}_polymorphicSin(e){return Jn(e,Math.sin)}}QA.ClassName="FGSinBlock";xe(QA.ClassName,QA);class $A extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicCos(t),$A.ClassName,e)}_polymorphicCos(e){return Jn(e,Math.cos)}}$A.ClassName="FGCosBlock";xe($A.ClassName,$A);class ZA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicTan(t),ZA.ClassName,e)}_polymorphicTan(e){return Jn(e,Math.tan)}}ZA.ClassName="FGTanBlock";xe(ZA.ClassName,ZA);class qA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicAsin(t),qA.ClassName,e)}_polymorphicAsin(e){return Jn(e,Math.asin)}}qA.ClassName="FGAsinBlock";xe(qA.ClassName,qA);class JA extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicAcos(t),JA.ClassName,e)}_polymorphicAcos(e){return Jn(e,Math.acos)}}JA.ClassName="FGAcosBlock";xe(JA.ClassName,JA);class e6 extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicAtan(t),e6.ClassName,e)}_polymorphicAtan(e){return Jn(e,Math.atan)}}e6.ClassName="FGAtanBlock";xe(e6.ClassName,e6);class t6 extends Wa{constructor(e){super(Mt,Mt,Mt,(t,i)=>this._polymorphicAtan2(t,i),t6.ClassName,e)}_polymorphicAtan2(e,t){return G9(e,t,Math.atan2)}}t6.ClassName="FGAtan2Block";xe(t6.ClassName,t6);class i6 extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicSinh(t),i6.ClassName,e)}_polymorphicSinh(e){return Jn(e,Math.sinh)}}i6.ClassName="FGSinhBlock";xe(i6.ClassName,i6);class r6 extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicCosh(t),r6.ClassName,e)}_polymorphicCosh(e){return Jn(e,Math.cosh)}}r6.ClassName="FGCoshBlock";xe(r6.ClassName,r6);class s6 extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicTanh(t),s6.ClassName,e)}_polymorphicTanh(e){return Jn(e,Math.tanh)}}s6.ClassName="FGTanhBlock";xe(s6.ClassName,s6);class n6 extends ts{constructor(e){super(Mt,Cs,t=>this._polymorphicAsinh(t),n6.ClassName,e)}_polymorphicAsinh(e){return Jn(e,Math.asinh)}}n6.ClassName="FGAsinhBlock";xe(n6.ClassName,n6);class a6 extends ts{constructor(e){super(Mt,Cs,t=>this._polymorphicAcosh(t),a6.ClassName,e)}_polymorphicAcosh(e){return Jn(e,Math.acosh)}}a6.ClassName="FGAcoshBlock";xe(a6.ClassName,a6);class o6 extends ts{constructor(e){super(Mt,Cs,t=>this._polymorphicAtanh(t),o6.ClassName,e)}_polymorphicAtanh(e){return Jn(e,Math.atanh)}}o6.ClassName="FGAtanhBlock";xe(o6.ClassName,o6);class l6 extends ts{constructor(e){super(Mt,Cs,t=>this._polymorphicExp(t),l6.ClassName,e)}_polymorphicExp(e){return Jn(e,Math.exp)}}l6.ClassName="FGExpBlock";xe(l6.ClassName,l6);class c6 extends ts{constructor(e){super(Mt,Cs,t=>this._polymorphicLog(t),c6.ClassName,e)}_polymorphicLog(e){return Jn(e,Math.log)}}c6.ClassName="FGLogBlock";xe(c6.ClassName,c6);class h6 extends ts{constructor(e){super(Mt,Cs,t=>this._polymorphicLog2(t),h6.ClassName,e)}_polymorphicLog2(e){return Jn(e,Math.log2)}}h6.ClassName="FGLog2Block";xe(h6.ClassName,h6);class u6 extends ts{constructor(e){super(Mt,Cs,t=>this._polymorphicLog10(t),u6.ClassName,e)}_polymorphicLog10(e){return Jn(e,Math.log10)}}u6.ClassName="FGLog10Block";xe(u6.ClassName,u6);class d6 extends ts{constructor(e){super(Mt,Cs,t=>this._polymorphicSqrt(t),d6.ClassName,e)}_polymorphicSqrt(e){return Jn(e,Math.sqrt)}}d6.ClassName="FGSqrtBlock";xe(d6.ClassName,d6);class f6 extends ts{constructor(e){super(Mt,Cs,t=>this._polymorphicCubeRoot(t),f6.ClassName,e)}_polymorphicCubeRoot(e){return Jn(e,Math.cbrt)}}f6.ClassName="FGCubeRootBlock";xe(f6.ClassName,f6);class p6 extends Wa{constructor(e){super(Mt,Cs,Cs,(t,i)=>this._polymorphicPow(t,i),p6.ClassName,e)}_polymorphicPow(e,t){return G9(e,t,Math.pow)}}p6.ClassName="FGPowBlock";xe(p6.ClassName,p6);class _6 extends ts{constructor(e){super(Mt,Cs,t=>this._polymorphicLength(t),_6.ClassName,e)}_polymorphicLength(e){switch(Il(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}_6.ClassName="FGLengthBlock";xe(_6.ClassName,_6);class m6 extends ts{constructor(e){super(Mt,Mt,t=>this._polymorphicNormalize(t),m6.ClassName,e)}_polymorphicNormalize(e){switch(Il(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}m6.ClassName="FGNormalizeBlock";xe(m6.ClassName,m6);class g6 extends Wa{constructor(e){super(W0,W0,W0,(t,i)=>P.Cross(t,i),g6.ClassName,e)}}g6.ClassName="FGCrossBlock";xe(g6.ClassName,g6);class v6 extends Wa{constructor(e){super(rH,Cs,rH,(t,i)=>Be.Transform(t,ce.RotationZ(i)),v6.ClassName,e)}}v6.ClassName="FGRotate2DBlock";xe(v6.ClassName,v6);class x6 extends Gte{constructor(e){super(W0,W0,Cs,W0,(t,i,r)=>P.TransformCoordinates(t,ce.RotationAxis(i,r)),x6.ClassName,e)}}x6.ClassName="FGRotate3DBlock";xe(x6.ClassName,x6);class y6 extends ts{constructor(e){super($m,$m,t=>ce.Transpose(t),y6.ClassName,e)}}y6.ClassName="FGTransposeBlock";xe(y6.ClassName,y6);class A6 extends ts{constructor(e){super($m,Cs,t=>t.determinant(),A6.ClassName,e)}}A6.ClassName="FGDeterminantBlock";xe(A6.ClassName,A6);class C6 extends ts{constructor(e){super($m,$m,t=>ce.Invert(t),C6.ClassName,e)}}C6.ClassName="FGInvertMatrixBlock";xe(C6.ClassName,C6);class b6 extends Wa{constructor(e){super($m,$m,$m,(t,i)=>i.multiply(t),b6.ClassName,e)}}b6.ClassName="FGMatMulBlock";xe(b6.ClassName,b6);class E6 extends ts{constructor(e){super(Zn,Zn,t=>new ua(~t.value),E6.ClassName,e)}}E6.ClassName="FGBitwiseNotBlock";xe(E6.ClassName,E6);class T6 extends Wa{constructor(e){super(Zn,Zn,Zn,(t,i)=>new ua(t.value&i.value),T6.ClassName,e)}}T6.ClassName="FGBitwiseAndBlock";xe(T6.ClassName,T6);class S6 extends Wa{constructor(e){super(Zn,Zn,Zn,(t,i)=>new ua(t.value|i.value),S6.ClassName,e)}}S6.ClassName="FGBitwiseOrBlock";xe(S6.ClassName,S6);class M6 extends Wa{constructor(e){super(Zn,Zn,Zn,(t,i)=>new ua(t.value^i.value),M6.ClassName,e)}}M6.ClassName="FGBitwiseXorBlock";xe(M6.ClassName,M6);class R6 extends Wa{constructor(e){super(Zn,Zn,Zn,(t,i)=>new ua(t.value<new ua(t.value>>i.value),I6.ClassName,e)}}I6.ClassName="FGBitwiseRightShiftBlock";xe(I6.ClassName,I6);class P6 extends ts{constructor(e){super(Zn,Zn,t=>new ua(Math.clz32(t.value)),P6.ClassName,e)}}P6.ClassName="FGCountLeadingZerosBlock";xe(P6.ClassName,P6);class w6 extends ts{constructor(e){super(Zn,Zn,t=>new ua(t.value?31-Math.clz32(t.value&-t.value):32),w6.ClassName,e)}}w6.ClassName="FGCountTrailingZerosBlock";xe(w6.ClassName,w6);function Cze(n){let e=0;for(;n;)e+=n&1,n>>=1;return e}class D6 extends ts{constructor(e){super(Zn,Zn,t=>new ua(Cze(t.value)),D6.ClassName,e)}}D6.ClassName="FGCountOneBitsBlock";xe(D6.ClassName,D6);class Z5 extends j5{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const i=e.configuration.scene.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return Z5.ClassName}}Z5.ClassName="FGSceneReadyEventBlock";xe("FGSceneReadyEventBlock",Z5);class O6 extends j5{constructor(e){super(e),this.config=e;for(let t=0;t{for(let r=0;r{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return L6.ClassName}}L6.ClassName="FGSceneTickEventBlock";xe(L6.ClassName,L6);const bze=Object.freeze(Object.defineProperty({__proto__:null,AbstractActionManager:Kh,AbstractAssetTask:_1,AbstractMesh:di,AbstractScene:da,AcquireNativeObjectAsync:N2e,Action:Ms,ActionEvent:pn,ActionManager:kr,AddBlock:kge,get AddressMode(){return by},AdvancedTimer:ige,AlignBlock:J3e,AlphaState:J_e,AmmoJSPlugin:Zp,AnaglyphArcRotateCamera:Qme,AnaglyphFreeCamera:$me,AnaglyphGamepadCamera:Zme,AnaglyphPostProcess:iee,AnaglyphUniversalCamera:qme,Analyser:lRe,AndOrNotEvaluator:x3,Angle:jp,Animatable:LJ,get AnimatedInputBlockTypes(){return Tm},Animation:ke,AnimationAssetTask:FVe,AnimationEvent:rG,AnimationGroup:Up,AnimationGroupMask:JMe,get AnimationGroupMaskMode(){return VD},get AnimationKeyInterpolation(){return ND},AnimationPropertiesOverride:KMe,AnimationRange:$y,AnisotropyBlock:S9,ApplyPostProcess:BG,Arc2:dme,ArcFollowCamera:Kme,ArcRotateCamera:Rr,ArcRotateCameraGamepadInput:JO,ArcRotateCameraInputsManager:mG,ArcRotateCameraKeyboardMoveInput:Qf,ArcRotateCameraMouseWheelInput:B5,ArcRotateCameraPointersInput:yh,ArcRotateCameraVRDeviceOrientationInput:ZJ,ArcTan2Block:n3e,AssetContainer:jO,get AssetTaskState(){return D0},AssetsManager:UVe,AssetsProgressEvent:sve,AsyncLoop:md,AttachToBoxBehavior:uRe,AudioEngine:Rme,AudioSceneComponent:vh,get AutoLayoutMode(){return j8},AutoReleaseWorkerPool:k5,AutoRotationBehavior:Lme,AxesViewer:Dm,Axis:$n,AxisDragGizmo:gd,AxisScaleGizmo:vd,BRDFTextureTools:pOe,BabylonFileLoaderConfiguration:gD,BackEase:pme,BackgroundMaterial:nr,BakedVertexAnimationManager:Q6,BallAndSocketConstraint:AFe,BaseCameraMouseWheelInput:ZO,BaseCameraPointersInput:_G,BaseError:Zy,BaseParticleSystem:yo,BaseSixDofDragBehavior:E0,BaseTexture:Er,BasisFileInfo:KNe,BasisTools:qG,BasisToolsOptions:n2,BasisTranscodeConfiguration:WNe,BezierCurve:ume,BezierCurveEase:ZMe,BiPlanarBlock:E3e,BinaryFileAssetTask:lve,BindBonesParameters:Yl,BindFogParameters:Oo,BindLight:HO,BindLightProperties:Eme,BindLights:gc,BindLogDepth:Ha,BindMorphTargetParameters:d1,BindSceneUniformBuffer:L5,BindTextureMatrix:ms,BlackAndWhitePostProcess:D9,get BlendFactor(){return Ul},get BlendOperation(){return vm},BloomEffect:aZ,BloomMergePostProcess:pK,BlurPostProcess:ao,Bone:_s,BoneAxesViewer:y7e,BoneIKController:Cu,BoneLookController:gl,BonesBlock:yge,BooleanGeometryBlock:oK,get BooleanGeometryOperations(){return Yp},BounceEase:WMe,BouncingBehavior:V3,BoundingBlock:h4e,BoundingBox:yd,BoundingBoxGizmo:Oee,BoundingBoxRenderer:Y4e,BoundingInfo:uc,BoundingSphere:e1,BoxBlock:iK,BoxBuilder:A7e,BoxParticleEmitter:Gm,Buffer:no,get BufferBindingType(){return Hm},get BufferMapState(){return H$},get BufferUsage(){return ys},CSG:Vp,Camera:Rt,CameraGizmo:n8,CameraInputTypes:Rl,CameraInputsManager:qO,CannonJSPlugin:Yz,get CanvasAlphaMode(){return YD},CapsuleBlock:nte,CapsuleBuilder:b7e,CascadedShadowGenerator:ko,ChromaticAberrationPostProcess:f1,CircleEase:fme,CircleOfConfusionPostProcess:sC,ClampBlock:eK,ClearCoatBlock:oA,ClipPlanesBlock:Nge,ClipboardEventTypes:Pd,ClipboardInfo:XV,CloudBlock:Xee,CloudPoint:V4e,Collider:h9,Color3:Me,Color3Gradient:P4e,Color4:Ze,ColorCorrectionPostProcess:O9,ColorCurves:an,ColorGradient:Tte,ColorGradingTexture:K3,ColorMergerBlock:Wge,ColorSplitterBlock:QJ,get ColorWrite(){return j$},CombineAction:V_e,get CompareFunction(){return zo},CompatibilityOptions:br,get CompilationMessageType(){return K$},CompleteGreasedLineColorTable:V3e,CompleteGreasedLineWidthTable:k3e,get ComputeBindingType(){return xs},ComputeEffect:tA,ComputeNormalsBlock:j3e,get ComputePassTimestampLocation(){return X$},ComputeShader:Vm,ComputeShaderParticleSystem:I4e,Condition:V8,ConditionBlock:dte,get ConditionBlockTests(){return Co},ConditionalBlock:A3e,get ConditionalBlockConditions(){return vu},ConeParticleEmitter:M9,Constants:Le,ContainerAssetTask:nve,get ConversionMode(){return eH},ConvolutionPostProcess:p1,get Coordinate(){return y3},CopyTextureToTexture:ive,CopyTools:cRe,CreateBox:zf,CreateBoxVertexData:MG,CreateCapsule:u9,CreateCapsuleVertexData:IG,CreateCylinder:dc,CreateCylinderVertexData:SG,CreateDashedLines:DG,CreateDashedLinesVertexData:gee,CreateDecal:NG,CreateDisc:U5,CreateDiscVertexData:PG,CreateEnvTextureAsync:D2e,CreateGeodesic:x2e,CreateGoldberg:A2e,CreateGoldbergVertexData:y2e,CreateGreasedLine:QBe,CreateGreasedLineMaterial:U3e,CreateGround:Z6,CreateGroundFromHeightMap:bG,CreateGroundFromHeightMapVertexData:oee,CreateGroundVertexData:S0,CreateHemisphere:QD,CreateIcoSphere:$O,CreateIcoSphereVertexData:pG,CreateImageDataArrayBufferViews:UG,CreateLathe:OG,CreateLineSystem:Uy,CreateLineSystemVertexData:mee,CreateLines:Us,CreatePlane:n_,CreatePlaneVertexData:fG,CreatePolygon:d9,CreatePolygonVertexData:vee,CreatePolyhedron:sA,CreatePolyhedronVertexData:xee,CreateResizedCopy:I2e,CreateRibbon:q0,CreateRibbonVertexData:hee,CreateScreenshot:F9,CreateScreenshotAsync:Ute,CreateScreenshotUsingRenderTarget:U9,CreateScreenshotUsingRenderTargetAsync:kte,CreateScreenshotWithResizeAsync:mve,CreateSegmentedBoxVertexData:m2e,CreateSphere:Tl,CreateSphereVertexData:RG,CreateText:C2e,CreateTextShapePaths:Aee,CreateTiledBox:fee,CreateTiledBoxVertexData:dee,CreateTiledGround:CG,CreateTiledGroundVertexData:aee,CreateTiledPlane:uee,CreateTiledPlaneVertexData:i8,CreateTorus:o1,CreateTorusKnot:wG,CreateTorusKnotVertexData:pee,CreateTorusVertexData:EG,CreateTube:LG,CrossBlock:zge,CubeMapToSphericalPolynomialTools:q6,CubeTexture:Bn,CubeTextureAssetTask:uve,CubicEase:jMe,get CullMode(){return r8},CurrentScreenBlock:WJ,Curve3:Cf,CurveBlock:M3e,get CurveBlockTypes(){return Qs},CustomBlock:Hge,CustomOptimization:pve,CustomParticleEmitter:Km,CustomProceduralTexture:xge,CylinderBlock:ste,CylinderBuilder:x7e,CylinderDirectedParticleEmitter:R9,CylinderParticleEmitter:H5,DDSTools:fs,DataBuffer:Jp,DataReader:Jw,DataStorage:fZ,Database:Lc,DebugBlock:n4e,DebugLayer:rA,get DebugLayerTab(){return U$},DecalBuilder:X7e,DecalMapConfiguration:z5,DecalMapDefines:R3e,Decode:SJ,DecodeBase64ToBinary:FO,DecodeBase64ToString:JH,DecodeBase64UrlToBinary:D5,DecodeBase64UrlToString:DJ,DeepCopier:ol,DefaultCollisionCoordinator:_2e,DefaultKTX2DecoderOptions:$2e,DefaultLoadingScreen:Om,DefaultRenderingPipeline:Qo,Deferred:FS,DepthCullingState:MJ,DepthOfFieldBlurPostProcess:sO,DepthOfFieldEffect:oZ,get DepthOfFieldEffectBlurLevel(){return Hy},DepthOfFieldMergePostProcess:G4e,DepthPeelingRenderer:V0,DepthPeelingSceneComponent:$4e,DepthReducer:cge,DepthRenderer:f4,DepthRendererSceneComponent:Q4e,DepthSortedParticle:U4e,DerivativeBlock:Tge,DesaturateBlock:v3e,DetailMapConfiguration:a_,get DeviceInputEventType(){return w$},get DeviceLostReason(){return Q$},DeviceOrientationCamera:gG,DeviceSource:D$,DeviceSourceManager:hme,get DeviceType(){return ii},DirectionalLight:Wl,DirectionalLightFrustumViewer:Z7e,DiscBlock:ate,DiscBuilder:T7e,DiscardBlock:bge,DisplayPassPostProcess:_K,DistanceBlock:e3e,DistanceConstraint:CFe,DistanceJoint:gRe,DivideBlock:Yge,DoNothingAction:gJ,DomManagement:CMe,DotBlock:Gge,DracoCompression:cc,DrawWrapper:Sn,get DualSenseInput(){return R$},get DualShockButton(){return fd},get DualShockDpad(){return Ay},get DualShockInput(){return M$},DualShockPad:jme,DumpTools:sl,DynamicFloat32Array:cm,DynamicTexture:Id,EasingFunction:Un,EdgesRenderer:N9,Effect:bi,EffectFallbacks:Hn,EffectLayer:Vu,EffectLayerSceneComponent:nge,EffectRenderer:QO,EffectWrapper:H0,ElasticEase:XMe,ElbowBlock:b3e,EncodeArrayBufferToBase64:BO,EndsWith:$_e,Engine:De,EngineFactory:UDe,get EngineFormat(){return Wz},EngineInstrumentation:rge,EngineStore:bt,EngineView:J7e,EnvironmentHelper:s4,EnvironmentTextureTools:lwe,Epsilon:ni,EquiRectangularCubeTexture:$8,EquiRectangularCubeTextureAssetTask:fve,ErrorCodes:z0,get ErrorFilter(){return $$},EventConstants:X6,EventState:mJ,ExecuteCodeAction:z_e,ExponentialEase:_me,ExternalTexture:Tee,ExtractHighlightsPostProcess:fK,ExtrudePolygon:f9,ExtrudeShape:p9,ExtrudeShapeCustom:_9,FactorGradient:Ste,FadeInOutBehavior:dRe,get FeatureName(){return kp},get FileTools(){return IS},FileToolsOptions:eo,FilesInput:Lte,FilesInputStore:By,get FilterMode(){return fr},FilterPostProcess:L9,FlowGraph:uA,FlowGraphAbsBlock:IA,FlowGraphAcosBlock:JA,FlowGraphAcoshBlock:a6,FlowGraphAddBlock:xA,FlowGraphAsinBlock:qA,FlowGraphAsinhBlock:n6,FlowGraphAtan2Block:t6,FlowGraphAtanBlock:e6,FlowGraphAtanhBlock:o6,FlowGraphBitwiseAndBlock:T6,FlowGraphBitwiseLeftShiftBlock:R6,FlowGraphBitwiseNotBlock:E6,FlowGraphBitwiseOrBlock:S6,FlowGraphBitwiseRightShiftBlock:I6,FlowGraphBitwiseXorBlock:M6,FlowGraphBlock:v2,FlowGraphBranchBlock:Dve,FlowGraphCeilBlock:OA,FlowGraphClampBlock:kA,FlowGraphConditionalDataBlock:Gve,FlowGraphConnection:iH,get FlowGraphConnectionType(){return Qh},FlowGraphConsoleLogBlock:dA,FlowGraphConstantBlock:Wve,FlowGraphContext:aH,FlowGraphContextLogger:xze,FlowGraphCoordinateTransformBlock:Kve,FlowGraphCoordinator:Ky,FlowGraphCosBlock:$A,FlowGraphCoshBlock:r6,FlowGraphCountLeadingZerosBlock:P6,FlowGraphCountOneBitsBlock:D6,FlowGraphCountTrailingZerosBlock:w6,FlowGraphCounterBlock:Uve,FlowGraphCrossBlock:g6,FlowGraphCubeRootBlock:f6,FlowGraphDataConnection:sH,FlowGraphDebounceBlock:kve,FlowGraphDegToRadBlock:XA,FlowGraphDeterminantBlock:A6,FlowGraphDivideBlock:CA,FlowGraphDoNBlock:pA,FlowGraphDotBlock:EA,FlowGraphEBlock:TA,FlowGraphEqBlock:HA,FlowGraphEventBlock:j5,FlowGraphExecutionBlock:r1,FlowGraphExpBlock:l6,FlowGraphFlipFlopBlock:Vve,FlowGraphFloorBlock:DA,FlowGraphForLoopBlock:Ove,FlowGraphFractBlock:LA,FlowGraphGetPropertyBlock:vA,FlowGraphGetVariableBlock:gA,FlowGraphGreaterThanBlock:KA,FlowGraphGreaterThanOrEqualBlock:WA,FlowGraphInfBlock:MA,FlowGraphInterpolateBlock:zA,FlowGraphInvertMatrixBlock:C6,FlowGraphIsInfBlock:W9,FlowGraphIsNanBlock:jA,FlowGraphLengthBlock:_6,FlowGraphLessThanBlock:GA,FlowGraphLessThanOrEqualBlock:K9,FlowGraphLog10Block:u6,FlowGraphLog2Block:h6,FlowGraphLogBlock:c6,FlowGraphLogicAndBlock:Qve,FlowGraphLogicNotBlock:Zve,FlowGraphLogicOrBlock:$ve,FlowGraphMatMulBlock:b6,FlowGraphMaxBlock:UA,FlowGraphMeshPickEventBlock:hA,FlowGraphMinBlock:FA,FlowGraphMultiGateBlock:Nve,FlowGraphMultiplyBlock:AA,FlowGraphNaNBlock:RA,FlowGraphNegBlock:NA,FlowGraphNormalizeBlock:m6,FlowGraphPauseAnimationBlock:Hve,FlowGraphPiBlock:SA,FlowGraphPlayAnimationBlock:u5,FlowGraphPowBlock:p6,FlowGraphRadToDegBlock:YA,FlowGraphRandomBlock:bA,FlowGraphReceiveCustomEventBlock:O6,FlowGraphRemainderBlock:BA,FlowGraphRotate2DBlock:v6,FlowGraphRotate3DBlock:x6,FlowGraphSaturateBlock:VA,FlowGraphSceneReadyEventBlock:Z5,FlowGraphSceneTickEventBlock:L6,FlowGraphSendCustomEventBlock:Y5,FlowGraphSequenceBlock:mA,FlowGraphSetPropertyBlock:X5,FlowGraphSetVariableBlock:fA,FlowGraphSignBlock:PA,FlowGraphSignalConnection:nH,FlowGraphSinBlock:QA,FlowGraphSinhBlock:i6,FlowGraphSqrtBlock:d6,get FlowGraphState(){return S3},FlowGraphStopAnimationBlock:zve,FlowGraphSubtractBlock:yA,FlowGraphSwitchBlock:Bve,FlowGraphTanBlock:ZA,FlowGraphTanhBlock:s6,FlowGraphThrottleBlock:Lve,FlowGraphTimerBlock:Q5,FlowGraphTransposeBlock:y6,FlowGraphTruncBlock:wA,FlowGraphWaitAllBlock:Fve,FlowGraphWhileLoopBlock:_A,FluidRenderer:gK,FluidRendererSceneComponent:rve,get FluidRenderingDebug(){return xu},FluidRenderingObject:Ote,FluidRenderingObjectCustomParticles:tve,FluidRenderingObjectParticleSystem:eve,FluidRenderingTargetRenderer:lZ,FlyCamera:n9,FlyCameraInputsManager:Hme,FlyCameraKeyboardInput:f2,FlyCameraMouseInput:e9,FogBlock:Oge,FollowBehavior:mRe,FollowCamera:Fc,FollowCameraInputsManager:Gme,FollowCameraKeyboardMoveInput:ll,FollowCameraMouseWheelInput:c4,FollowCameraPointersInput:Ah,FragCoordBlock:Sge,FragDepthBlock:Pge,FragmentOutputBlock:Pm,FramingBehavior:fh,FreeCamera:El,FreeCameraDeviceOrientationInput:qJ,FreeCameraGamepadInput:s9,FreeCameraInputsManager:r9,FreeCameraKeyboardMoveInput:ku,FreeCameraMouseInput:t9,FreeCameraMouseWheelInput:$f,FreeCameraTouchInput:i9,FreeCameraVirtualJoystickInput:JJ,FresnelBlock:Zge,FresnelParameters:$D,FromHalfFloat:Np,get FrontFace(){return WD},FrontFacingBlock:Ege,Frustum:Tu,FxaaPostProcess:nC,GIRSM:AVe,GIRSMManager:vK,GIRSMRenderPluginMaterial:Td,GPUParticleSystem:wu,GUID:UMe,Gamepad:Io,GamepadCamera:vG,GamepadManager:Xme,GamepadSystemSceneComponent:Yme,GaussianSplattingMaterial:e5,GaussianSplattingMesh:j3,GenerateBase64StringFromPixelData:dG,GenerateBase64StringFromTexture:VJ,GenerateBase64StringFromTextureAsync:zJ,GenericPad:zme,GeodesicData:m9,Geometry:Ua,GeometryArcTan2Block:u4e,GeometryBufferRenderer:yr,GeometryBufferRendererSceneComponent:W4e,GeometryClampBlock:lK,GeometryCollectionBlock:_te,GeometryCrossBlock:v4e,GeometryCurveBlock:Ete,get GeometryCurveBlockTypes(){return qi},GeometryDesaturateBlock:x4e,GeometryDistanceBlock:C4e,GeometryDotBlock:b4e,GeometryElbowBlock:W3e,GeometryInfoBlock:a4e,GeometryInputBlock:Ta,GeometryLengthBlock:E4e,GeometryLerpBlock:d4e,GeometryModBlock:m4e,GeometryNLerpBlock:f4e,GeometryOptimizeBlock:rK,GeometryOutputBlock:Zee,GeometryPosterizeBlock:y4e,GeometryPowBlock:g4e,GeometryReplaceColorBlock:A4e,GeometryRotate2dBlock:T4e,GeometrySmoothStepBlock:_4e,GeometryStepBlock:p4e,GeometryTextureBlock:Cte,GeometryTextureFetchBlock:bte,GeometryTransformBlock:vte,GeometryTrigonometryBlock:gte,get GeometryTrigonometryBlockOperations(){return Mr},GetClass:gn,GetDOMTextContent:NO,GetEnvInfo:FG,GetEnvironmentBRDFTexture:A9,GetFogState:oG,GetInternalFormatFromBasisFormat:gge,GetTGAHeader:b9,GetTextureDataAsync:P2e,Gizmo:mn,get GizmoAnchorPoint(){return GD},get GizmoCoordinatesMode(){return t4},GizmoManager:kDe,GlowLayer:Uc,GoldbergMesh:g9,GradientBlock:u3e,GradientBlockColorStep:YV,GradientHelper:Nh,GrainPostProcess:aC,GreasedLineBaseMesh:$ee,GreasedLineMaterialDefaults:Wo,GreasedLineMesh:Wn,get GreasedLineMeshColorDistribution(){return M0},get GreasedLineMeshColorDistributionType(){return k0},get GreasedLineMeshColorMode(){return Su},get GreasedLineMeshMaterialType(){return J8},get GreasedLineMeshWidthDistribution(){return Mm},GreasedLinePluginMaterial:i_,get GreasedLineRibbonAutoDirectionMode(){return W3},get GreasedLineRibbonFacesMode(){return i5},GreasedLineRibbonMesh:oa,get GreasedLineRibbonPointsMode(){return bf},GreasedLineSimpleMaterial:Qee,GreasedLineTools:jr,GridBlock:ite,GroundBuilder:_7e,GroundMesh:F5,HDRCubeTexture:K0,HDRCubeTextureAssetTask:dve,HDRFiltering:Fee,HDRTools:Xz,Halton2DSequence:w3e,HandConstraintBehavior:wRe,get HandConstraintOrientation(){return mm},get HandConstraintVisibility(){return C3},get HandConstraintZone(){return A3},get HandPart(){return _m},HandleFallbacksForShadows:uo,HardwareScalingOptimization:cZ,HavokPlugin:wFe,HeightToNormalBlock:E9,HemisphereBuilder:VDe,HemisphericLight:Vf,HemisphericParticleEmitter:I9,HighlightLayer:Gl,HighlightsPostProcess:uUe,Hinge2Joint:xRe,HingeConstraint:bFe,HingeJoint:vRe,HtmlElementTexture:ZG,IWebXRControllerPhysicsOptions:tze,IcoSphereBlock:ete,IcoSphereBuilder:IRe,ImageAssetTask:cve,ImageProcessingBlock:Gee,ImageProcessingConfiguration:Ji,ImageProcessingPostProcess:mK,ImageSourceBlock:Hf,IncrementValueAction:F_e,get IndexFormat(){return s2},InputBlock:Gi,get InspectableType(){return dZ},InstancedLinesMesh:_ee,InstancedMesh:Kf,InstancesBlock:Age,InstantiateBlock:t4e,InstantiateLinearBlock:i4e,InstantiateOnFacesBlock:xte,InstantiateOnVerticesBlock:nK,InstantiateOnVolumeBlock:yte,InstantiateRadialBlock:r4e,InstantiatedEntries:Mme,IntFloatConverterBlock:s4e,InternalTexture:Ar,get InternalTextureSource(){return mi},InterpolateValueAction:X_e,IntersectionInfo:Lz,IsBase64DataUrl:UO,IsDocumentAvailable:Ny,IsFileURL:wJ,IsNavigatorAvailable:xy,IsWindowObjectExist:io,get JoystickAxis(){return go},KeepAssets:Sme,KeyboardEventTypes:Z0,KeyboardInfo:Oz,KeyboardInfoPre:S$,KhronosTextureContainer:Bc,KhronosTextureContainer2:bs,LatheBuilder:U7e,Layer:Bee,LayerSceneComponent:age,LengthBlock:t3e,LensFlare:YG,LensFlareSystem:aA,LensFlareSystemSceneComponent:oge,LensFlaresOptimization:ez,LensRenderingPipeline:NUe,LerpBlock:Xge,Light:Ui,LightBlock:qz,LightGizmo:Af,LightInformationBlock:Cge,LineEdgesRenderer:Z4e,LinesBuilder:O7e,LinesMesh:i2,LoadFile:t2,LoadFileError:G8,LoadImage:w5,get LoadOp(){return Ja},LoadTextureFromTranscodeResult:Zz,LockConstraint:TFe,Logger:de,get MapMode(){return z3},MapRangeBlock:G3e,MappingBlock:Ate,get MappingTypes(){return Xp},Material:Ye,MaterialAnisotropicDefines:K2e,MaterialClearCoatDefines:H2e,MaterialDefines:Kr,MaterialDetailMapDefines:c2e,MaterialFlags:$e,MaterialGreasedLineDefines:I3e,MaterialHelper:en,MaterialIridescenceDefines:G2e,MaterialPluginBase:Wc,get MaterialPluginEvent(){return Ko},MaterialPluginManager:wm,MaterialSheenDefines:W2e,MaterialSubSurfaceDefines:j2e,MathBlock:ute,get MathBlockOperations(){return Nc},Matrix:ce,MatrixBuilderBlock:y3e,MatrixComposeBlock:o4e,MatrixDeterminantBlock:T3e,MatrixTransposeBlock:S3e,MaxBlock:qge,MergeGeometryBlock:pte,MergeMeshesOptimization:jm,Mesh:Se,MeshAssetTask:ave,MeshAttributeExistsBlock:Yee,get MeshAttributeExistsBlockTypes(){return Es},MeshBlock:Jee,MeshBuilder:kh,get MeshDebugMode(){return Vy},MeshDebugPluginMaterial:Po,MeshExploder:kVe,MeshLODLevel:Tme,MeshParticleEmitter:cK,MeshUVSpaceRenderer:v0,MeshoptCompression:w0,MinBlock:Jge,MinMaxReducer:lge,get MipmapFilterMode(){return G$},MirrorTexture:H3,ModBlock:x3e,ModelShape:nZ,MorphTarget:G3,MorphTargetManager:Of,MorphTargetsBlock:Hee,MotionBlurPostProcess:_4,MotorEnabledJoint:HJ,MultiMaterial:Fu,MultiObserver:Nte,MultiPointerScaleBehavior:pRe,MultiRenderTarget:Sm,MultiplyBlock:Fz,NLerpBlock:d3e,NativeDataStream:i4,NativeEngine:nA,get NativePointerInput(){return kD},NativeXRFrame:bve,NativeXRLayerRenderTargetTextureProvider:f2e,NativeXRLayerWrapper:d2e,NativeXRRenderTarget:p2e,NegateBlock:i3e,Node:Lr,NodeGeometry:Hh,NodeGeometryBlock:vi,get NodeGeometryBlockConnectionPointTypes(){return fe},NodeGeometryBuildState:z3e,NodeGeometryConnectionPoint:rZ,get NodeGeometryConnectionPointCompatibilityStates(){return ym},get NodeGeometryConnectionPointDirection(){return r5},get NodeGeometryContextualSources(){return Nr},NodeMaterial:Ss,NodeMaterialBlock:zt,get NodeMaterialBlockConnectionPointMode(){return ml},get NodeMaterialBlockConnectionPointTypes(){return se},get NodeMaterialBlockTargets(){return Ce},NodeMaterialConnectionPoint:Jy,get NodeMaterialConnectionPointCompatibilityStates(){return Au},NodeMaterialConnectionPointCustomObject:Tn,get NodeMaterialConnectionPointDirection(){return Zs},NodeMaterialDefines:$w,get NodeMaterialModes(){return wc},NodeMaterialOptimizer:tBe,get NodeMaterialSystemValues(){return Zi},NodeMaterialTeleportInBlock:Fge,NodeMaterialTeleportOutBlock:Uge,NoiseBlock:K3e,NoiseProceduralTexture:ZD,NormalBlendBlock:p3e,NormalizeBlock:Kge,NormalizeVectorBlock:Y3e,NullBlock:H3e,NullEngine:E2e,NullEngineOptions:b2e,Observable:Ae,Observer:R_e,OcclusionMaterial:bNe,Octree:iA,OctreeBlock:HD,OctreeSceneComponent:cee,OimoJSPlugin:eZ,OnAfterEnteringVRObservableEvent:g7e,OneMinusBlock:Kee,get Orientation(){return Fy},OutlineRenderer:l5,PBRAnisotropicConfiguration:d4,PBRBaseMaterial:xr,PBRBaseSimpleMaterial:jc,PBRClearCoatConfiguration:lo,PBRIridescenceConfiguration:jl,PBRMaterial:Nt,PBRMaterialDefines:q$,PBRMetallicRoughnessBlock:ho,PBRMetallicRoughnessMaterial:e_,PBRSheenConfiguration:qf,PBRSpecularGlossinessMaterial:t_,PBRSubSurfaceConfiguration:In,PHI:Ba,PadNumber:q_e,PanoramaToCubeMapTools:p2,Particle:s5,ParticleBlendMultiplyBlock:YJ,ParticleHelper:lA,ParticleRampGradientBlock:XJ,ParticleSystem:Wr,ParticleSystemSet:a2,ParticleTextureBlock:jJ,ParticlesOptimization:tz,PassCubePostProcess:tee,PassPostProcess:Zf,Path2:O5,Path3D:qy,PathCursor:qMe,PerfCollectionStrategy:YVe,PerfCounter:Fa,PerformanceConfigurator:bo,PerformanceMonitor:yme,PerformanceViewerCollector:xf,PerturbNormalBlock:V5,PhotoDome:X8,Physics6DoFConstraint:z4e,Physics6DoFLimit:yFe,get PhysicsActivationControl(){return l8},PhysicsAggregate:H4e,PhysicsBody:uK,PhysicsConstraint:_2,get PhysicsConstraintAxis(){return zp},get PhysicsConstraintAxisLimitMode(){return C0},get PhysicsConstraintMotorType(){return T3},get PhysicsConstraintType(){return xl},PhysicsEngine:kee,PhysicsEngineV2:hK,get PhysicsEventType(){return vf},PhysicsHelper:OFe,PhysicsImpostor:Zt,PhysicsJoint:as,get PhysicsMaterialCombineMode(){return Bh},get PhysicsMotionType(){return Wh},PhysicsRadialExplosionEventOptions:c8,get PhysicsRadialImpulseFalloff(){return rO},PhysicsRaycastResult:C9,PhysicsShape:o_,PhysicsShapeBox:Pte,PhysicsShapeCapsule:Rte,PhysicsShapeContainer:xFe,PhysicsShapeConvexHull:gFe,PhysicsShapeCylinder:Ite,PhysicsShapeMesh:vFe,PhysicsShapeSphere:Mte,get PhysicsShapeType(){return ca},PhysicsUpdraftEventOptions:wte,get PhysicsUpdraftMode(){return o5},PhysicsViewer:$7e,PhysicsVortexEventOptions:Dte,PickingInfo:Ro,get PipelineErrorReason(){return W$},PivotTools:Vr,Plane:yl,PlaneBlock:qee,PlaneBuilder:fRe,PlaneDragGizmo:s8,PlaneRotationGizmo:Df,PlayAnimationAction:U_e,PlaySoundAction:H_e,get PointColor(){return Ic},PointLight:G0,PointParticleEmitter:P9,PointerDragBehavior:Ao,PointerEventTypes:ft,PointerInfo:pd,PointerInfoBase:OJ,PointerInfoPre:cme,get PointerInput(){return yi},PointsCloudSystem:mFe,PointsGroup:$V,Polar:_f,Polygon:N7e,PolygonBuilder:B7e,PolygonMeshBuilder:g2e,PolyhedronBuilder:V7e,PolyhedronData:Vz,PositionGizmo:HG,PositionNormalTextureVertex:KJ,PositionNormalVertex:GJ,PostProcess:Pt,PostProcessManager:UD,PostProcessRenderEffect:Cr,PostProcessRenderPipeline:m2,PostProcessRenderPipelineManager:j4e,PostProcessRenderPipelineManagerSceneComponent:X4e,PostProcessesOptimization:JV,PosterizeBlock:c3e,PowBlock:r3e,PowerEase:YMe,get PowerPreference(){return z$},PrePassOutputBlock:Dge,PrePassRenderer:vl,PrePassRendererSceneComponent:q4e,PrePassTextureBlock:Bge,PrecisionDate:gr,PredicateCondition:D_e,PrepareAttributesForBakedVertexAnimation:zO,PrepareAttributesForBones:Kc,PrepareAttributesForInstances:pa,PrepareAttributesForMorphTargets:VO,PrepareAttributesForMorphTargetsInfluencers:Y6,PrepareDefinesForAttributes:qn,PrepareDefinesForBakedVertexAnimation:UJ,PrepareDefinesForBones:lG,PrepareDefinesForCamera:uG,PrepareDefinesForFrameBoundValues:$l,PrepareDefinesForLight:GO,PrepareDefinesForLights:vc,PrepareDefinesForMergedUV:ks,PrepareDefinesForMisc:Ql,PrepareDefinesForMorphTargets:cG,PrepareDefinesForMultiview:N5,PrepareDefinesForOIT:hG,PrepareDefinesForPrePass:KO,PrepareUniformsAndSamplersForLight:WO,PrepareUniformsAndSamplersList:Ma,PressureObserverWrapper:xK,get PrimitiveTopology(){return Uh},PrismaticConstraint:SFe,ProceduralTexture:Yf,ProceduralTextureSceneComponent:Ume,get PropertyTypeForEdition(){return Gt},ProximityCastResult:NFe,PushAttributesForInstances:s_,PushMaterial:Rn,QuadraticEase:NJ,QuadraticErrorSimplification:B3e,QuarticEase:QMe,Quaternion:we,get QueryType(){return XD},QuinticEase:$Me,RGBDTextureTools:zz,RSMCreatePluginMaterial:g4,Ragdoll:IFe,RagdollBoneProperties:RFe,RandomBlock:fte,get RandomBlockLocks(){return Tf},RandomGUID:mh,RandomNumberBlock:s3e,RawCubeTexture:JG,RawTexture:$s,RawTexture2DArray:QG,RawTexture3D:qNe,Ray:Fi,RayHelper:Cee,ReadFile:K8,ReadFileError:eG,RecastJSCrowd:S4e,RecastJSPlugin:$Be,ReciprocalBlock:o3e,ReflectBlock:m3e,ReflectionBlock:rC,ReflectionProbe:eC,ReflectionTextureBaseBlock:Z8,ReflectionTextureBlock:Lge,ReflectiveShadowMap:xVe,Reflector:oO,RefractBlock:g3e,RefractionBlock:p4,RefractionPostProcess:m4,RefractionTexture:zee,RegisterClass:xe,RegisterMaterialPlugin:d7e,RegisterNativeTypeAsync:B2e,RemapBlock:YO,get RenderPassTimestampLocation(){return Y$},RenderTargetTexture:es,RenderTargetWrapper:XO,RenderTargetsOptimization:hZ,RenderingGroup:yf,RenderingGroupInfo:lme,RenderingManager:rl,ReplaceColorBlock:l3e,RequestFile:iG,RequestFileError:BD,RetryStrategy:Q_e,RibbonBuilder:E7e,RichType:Ch,RichTypeAny:Mt,RichTypeBoolean:Yo,RichTypeColor3:Sve,RichTypeColor4:Mve,RichTypeFlowGraphInteger:Zn,RichTypeMatrix:$m,RichTypeNumber:Cs,RichTypeQuaternion:Rve,RichTypeString:Eve,RichTypeVector2:rH,RichTypeVector3:W0,RichTypeVector4:Tve,RollingAverage:Ame,Rotate2dBlock:_3e,RotationGizmo:Lee,RotationXBlock:Q3e,RotationYBlock:$3e,RotationZBlock:Z3e,RuntimeAnimation:Y_e,RuntimeError:kf,SSAO2RenderingPipeline:co,SSAORenderingPipeline:K5,SSRRenderingPipeline:Is,get SamplerBindingType(){return r2},Scalar:_t,ScaleBlock:Vge,ScaleGizmo:Nee,ScalingBlock:q3e,Scene:pt,SceneComponentConstants:it,SceneDepthBlock:T9,SceneInstrumentation:sge,SceneLoader:ai,get SceneLoaderAnimationGroupLoadingMode(){return T0},SceneLoaderFlags:ro,SceneOptimization:l_,SceneOptimizer:Bte,SceneOptimizerOptions:Gy,get ScenePerformancePriority(){return $p},SceneRecorder:GVe,SceneSerializer:Lm,ScreenSizeBlock:Mge,ScreenSpaceBlock:Rge,ScreenSpaceCurvaturePostProcess:W5,ScreenSpaceReflectionPostProcess:Ud,ScreenshotTools:zVe,SerializationHelper:Qe,SetBasisTranscoderWorker:QNe,SetColorsBlock:cte,SetCorsBehavior:tG,SetMaterialIDBlock:mte,SetNormalsBlock:lte,SetParentAction:vJ,SetPositionsBlock:ote,SetStateAction:N_e,SetTangentsBlock:hte,SetUVsBlock:sK,SetValueAction:B_e,ShaderCodeInliner:zm,get ShaderLanguage(){return Vs},ShaderMaterial:kn,get ShaderStage(){return gm},ShaderStore:Re,ShadowDepthWrapper:rBe,ShadowGenerator:si,ShadowGeneratorSceneComponent:hge,ShadowLight:u4,ShadowMapBlock:wge,ShadowsOptimization:qV,ShapeBuilder:F7e,ShapeCastResult:BFe,SharpenPostProcess:oC,SheenBlock:iC,SimplexPerlin3DBlock:f3e,SimplicationQueueSceneComponent:F3e,SimplificationQueue:N3e,SimplificationSettings:WBe,get SimplificationType(){return iO},SineEase:BJ,SixDofDragBehavior:Nme,Size:lc,Skeleton:a1,SkeletonViewer:dh,SliderConstraint:EFe,SmartArray:ba,SmartArrayNoDuplicate:pm,SmoothStepBlock:a3e,SolidParticle:sZ,SolidParticleSystem:_Fe,SolidParticleVertex:k4e,Sound:wf,SoundTrack:Ime,get SourceTextureFormat(){return J$},get Space(){return Ci},SphereBlock:tte,SphereBuilder:C7e,SphereDirectedParticleEmitter:w9,SphereParticleEmitter:G5,Spherical:mf,SphericalHarmonics:r4,SphericalPolynomial:J0,SpotLight:Sl,SpringConstraint:MFe,Sprite:$G,SpriteManager:qp,SpriteMap:NVe,SpritePackedManager:BVe,SpriteSceneComponent:dge,Stage:na,StandardMaterial:tt,StandardMaterialDefines:h2e,StandardRenderingPipeline:Br,StartsWith:Z_e,StateCondition:O_e,get StencilOperation(){return gf},StencilState:U0,StencilStateComposer:PJ,StepBlock:$ge,StereoscopicArcRotateCamera:e2e,StereoscopicFreeCamera:t2e,StereoscopicGamepadCamera:i2e,StereoscopicInterlacePostProcess:VRe,StereoscopicInterlacePostProcessI:Jme,StereoscopicScreenUniversalCamera:zRe,StereoscopicUniversalCamera:r2e,StickValues:DRe,StopAnimationAction:k_e,StopSoundAction:G_e,StorageBuffer:Vme,get StorageTextureAccess(){return Hz},get StoreOp(){return bu},StringDictionary:Dz,StringTools:bMe,SubEmitter:Wm,get SubEmitterType(){return n5},SubMesh:Xo,SubSurfaceBlock:q8,SubSurfaceSceneComponent:J4e,SubtractBlock:Qge,SurfaceMagnetismBehavior:_Re,SwitchBooleanAction:L_e,get SwitchInput(){return P$},TAARenderingPipeline:g2,TBNBlock:tC,TGATools:pge,Tags:vr,TargetCamera:Ln,TargetedAnimation:mme,TeleportInBlock:l4e,TeleportOutBlock:c4e,TestBase64DataUrl:rme,TextFileAssetTask:ove,Texture:ve,get TextureAspect(){return If},TextureAssetTask:hve,TextureBlock:qD,get TextureDimension(){return bd},get TextureFormat(){return me},TextureOptimization:ZV,TexturePacker:Lf,TexturePackerFrame:tZ,get TextureSampleType(){return jh},TextureSampler:RJ,TextureTools:w2e,get TextureUsage(){return rn},get TextureViewDimension(){return Jr},ThinEngine:yt,ThinRenderTargetTexture:JNe,ThinTexture:Im,TiledBoxBuilder:M7e,TiledPlaneBuilder:S7e,get TimerState(){return E3},TmpColors:wr,TmpVectors:ie,ToGammaSpace:ZS,ToHalfFloat:Gp,ToLinearSpace:hD,TonemapPostProcess:cke,get TonemappingOperator(){return Sy},Tools:Ee,TorusBlock:rte,TorusBuilder:m7e,TorusKnotBuilder:R7e,TouchCamera:eee,TrailMesh:tO,Trajectory:ds,TrajectoryClassifier:tH,TranscodeAsync:$z,get TranscodeTarget(){return a8},TransformBlock:Bz,TransformNode:Et,TranslationBlock:e4e,TriPlanarBlock:tK,TrigonometryBlock:$J,get TrigonometryBlockOperations(){return qa},TubeBuilder:k7e,TwirlBlock:Ige,UniformBuffer:Ft,UniversalCamera:h4,UnregisterAllMaterialPlugins:ree,UnregisterMaterialPlugin:f7e,UploadContent:Vee,UploadEnvLevelsAsync:Eee,UploadEnvSpherical:kG,UploadLevelsAsync:KD,UtilityLayerRenderer:Or,VRCameraMetrics:$6,VRDeviceOrientationArcRotateCamera:o2e,VRDeviceOrientationFreeCamera:yG,VRDeviceOrientationGamepadCamera:l2e,VRDistortionCorrectionPostProcess:L$,VRExperienceHelper:eA,VRMultiviewToSingleviewPostProcess:a2e,ValidatedNativeDataStream:F2e,ValueCondition:vo,Vector2:Be,Vector2ToFixed:D3e,Vector3:P,Vector3ToFixed:O3e,Vector4:Ct,Vector4ToFixed:L3e,VectorConverterBlock:X3e,VectorMergerBlock:_D,VectorSplitterBlock:jge,VertexAnimationBaker:hRe,VertexBuffer:Z,VertexData:et,VertexDataMaterialInfo:fD,get VertexFormat(){return dn},VertexOutputBlock:pD,get VertexStepMode(){return jD},VideoDome:XG,VideoRecorder:nO,VideoTexture:wd,ViewDirectionBlock:Wee,Viewport:bl,VirtualJoystick:Qt,VirtualJoysticksCamera:s2e,VolumetricLightScatteringPostProcess:zu,VoronoiNoiseBlock:C3e,WaveBlock:h3e,get WaveBlockKind(){return Ey},WebGL2ParticleSystem:R4e,WebGL2ShaderProcessor:IJ,WebGLDataBuffer:z8,WebGLHardwareTexture:j6,WebGLPipelineContext:eme,WebGPUCacheBindGroups:ps,WebGPUCacheRenderPipeline:sn,WebGPUCacheRenderPipelineTree:Ef,WebGPUCacheSampler:P3,WebGPUDataBuffer:k2e,WebGPUDrawContext:x9,WebGPUEngine:gi,WebGPURenderTargetWrapper:z2e,WebGPUTintWASM:zh,WebRequest:on,WebXRAbstractFeature:Lo,WebXRAbstractMotionController:J6,WebXRAnchorSystem:h8,WebXRBackgroundRemover:d8,WebXRCamera:Y8,WebXRControllerComponent:Yh,WebXRControllerMovement:Ym,WebXRControllerPhysics:f8,WebXRControllerPointerSelection:t1,WebXRDefaultExperience:jG,WebXRDefaultExperienceOptions:aLe,WebXRDepthSensing:C8,WebXRDomOverlay:v8,WebXREnterExitUI:WG,WebXREnterExitUIButton:tge,WebXREnterExitUIOptions:nLe,WebXRExperienceHelper:KG,WebXREyeTracking:y8,WebXRFeatureName:pr,WebXRFeaturePointSystem:_8,WebXRFeaturesManager:vn,WebXRGenericHandController:Cve,WebXRGenericTriggerMotionController:Q8,WebXRHTCViveMotionController:cA,WebXRHand:kme,get WebXRHandJoint(){return li},WebXRHandTracking:ss,WebXRHitTest:p8,WebXRHitTestLegacy:Xm,WebXRImageTracking:g8,WebXRInput:ege,WebXRInputSource:J2e,WebXRLayerRenderTargetTextureProvider:AG,WebXRLayers:A8,WebXRLightEstimation:x8,WebXRManagedOutputCanvas:u2e,WebXRManagedOutputCanvasOptions:l9,WebXRMeshDetector:m8,WebXRMicrosoftMixedRealityController:Qm,WebXRMotionControllerManager:So,WebXRMotionControllerTeleportation:ky,get WebXRNearControllerMode(){return b3},WebXRNearInteraction:i1,WebXROculusTouchMotionController:Nf,WebXRPlaneDetector:u8,WebXRProfiledMotionController:q2e,WebXRRawCameraAccess:E8,WebXRSessionManager:c9,WebXRSpaceWarp:b8,WebXRSpaceWarpRenderTargetTextureProvider:Ave,get WebXRState(){return to},get WebXRTrackingState(){return Cy},WebXRWalkingLocomotion:iz,WeightedSound:Pme,WorkerPool:Q2e,WorleyNoise3DBlock:jee,XRSpaceWarpRenderTarget:yve,get Xbox360Button(){return Fh},get Xbox360Dpad(){return yy},Xbox360Pad:Wme,get XboxInput(){return I$},_BabylonLoaderRegistered:ANe,_BasisTextureLoader:vge,_CreationDataStorage:kJ,_DDSTextureLoader:X2e,_ENVTextureLoader:Y2e,_HDRTextureLoader:mge,_InstancesBatch:O$,_KTXTextureLoader:Z2e,_MeshCollisionData:Cme,_OcclusionDataStorage:S2e,_PrimaryIsoTriangle:yee,_TGATextureLoader:_ge,_TimeToken:T2e,_UpdateRGBDAsync:O2e,_forceSceneHelpersToBundle:oLe,_forceTransformFeedbackToBundle:q7e,_injectLTSFileTools:sme,_staticOffsetValueColor3:EJ,_staticOffsetValueColor4:TJ,_staticOffsetValueQuaternion:yJ,_staticOffsetValueSize:bJ,_staticOffsetValueVector2:CJ,_staticOffsetValueVector3:AJ,addClipPlaneUniforms:Sa,allocateAndCopyTypedBuffer:Nz,bindClipPlane:fa,captureEquirectangularFromScene:qVe,className:kMe,createDetailMapPlugin:hBe,createPBRAnisotropicPlugin:sBe,createPBRBRDFPlugin:nBe,createPBRClearCoatPlugin:aBe,createPBRIridescencePlugin:oBe,createPBRSheenPlugin:lBe,createPBRSubSurfacePlugin:cBe,createYieldingScheduler:gme,editableInPropertyPage:Xt,expandToProperty:ze,extractMinAndMax:W8,extractMinAndMaxIndexed:xme,getRichTypeFromValue:Ive,inlineScheduler:zD,makeAsyncFunction:eRe,makeSyncFunction:vme,nativeOverride:e2,normalizeEnvInfo:v9,prepareDefinesForClipPlanes:bme,prepareStringDefinesForClipPlanes:d2,runCoroutine:FJ,runCoroutineAsync:nG,runCoroutineSync:sG,serialize:K,serializeAsCameraReference:j_e,serializeAsColor3:or,serializeAsColor4:P5,serializeAsColorCurves:K_e,serializeAsFresnelParameters:R5,serializeAsImageProcessingConfiguration:xJ,serializeAsMatrix:qH,serializeAsMeshReference:I5,serializeAsQuaternion:W_e,serializeAsTexture:$t,serializeAsVector2:LO,serializeAsVector3:Js,setAndStartTimer:qw,setStereoscopicAnaglyphRigMode:a9,setStereoscopicRigMode:o9,setVRRigMode:xG},Symbol.toStringTag,{value:"Module"}));function Eze(n){return{all:n=n||new Map,on:function(e,t){var i=n.get(e);i?i.push(t):n.set(e,[t])},off:function(e,t){var i=n.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):n.set(e,[]))},emit:function(e,t){var i=n.get(e);i&&i.slice().map(function(r){r(t)}),(i=n.get("*"))&&i.slice().map(function(r){r(e,t)})}}}const Tze="/view/assets/draco_decoder_gltf.js",Sze="/view/assets/draco_decoder_gltf.wasm",Mze="/view/assets/draco_wasm_wrapper_gltf.js",Jve="/view/assets/cloudy.env",exe="/view/assets/default.env",txe="/view/assets/dusk.env",ixe="/view/assets/night.env",rxe="/view/assets/sunny.env",sxe="/view/assets/cloudy.jpg",nxe="/view/assets/dusk.jpg",axe="/view/assets/night.jpg",oxe="/view/assets/sunny.jpg";function pZ(n,e,t,i){const r={externalResourceFunction:i};return t&&(r.uri=e==="file:"?t:e+t),ArrayBuffer.isView(n)?GLTFValidator.validateBytes(n,r):GLTFValidator.validateString(n,r)}function Rze(){const n=[];onmessage=e=>{const t=e.data;switch(t.id){case"init":{importScripts(t.url);break}case"validate":{pZ(t.data,t.rootUrl,t.fileName,i=>new Promise((r,s)=>{const a=n.length;n.push({resolve:r,reject:s}),postMessage({id:"getExternalResource",index:a,uri:i})})).then(i=>{postMessage({id:"validate.resolve",value:i})},i=>{postMessage({id:"validate.reject",reason:i})});break}case"getExternalResource.resolve":{n[t.index].resolve(t.value);break}case"getExternalResource.reject":{n[t.index].reject(t.reason);break}}}}class lxe{static ValidateAsync(e,t,i,r){return typeof Worker=="function"?new Promise((s,a)=>{const o=`${pZ}(${Rze})()`,c=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),l=new Worker(c),h=d=>{l.removeEventListener("error",h),l.removeEventListener("message",u),a(d)},u=d=>{const f=d.data;switch(f.id){case"getExternalResource":{r(f.uri).then(p=>{l.postMessage({id:"getExternalResource.resolve",index:f.index,value:p},[p])},p=>{l.postMessage({id:"getExternalResource.reject",index:f.index,reason:p})});break}case"validate.resolve":{l.removeEventListener("error",h),l.removeEventListener("message",u),s(f.value),l.terminate();break}case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",u),a(f.reason),l.terminate()}};if(l.addEventListener("error",h),l.addEventListener("message",u),l.postMessage({id:"init",url:Ee.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const d=e.slice();l.postMessage({id:"validate",data:d,rootUrl:t,fileName:i},[d.buffer])}else l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})}):(this._LoadScriptPromise||(this._LoadScriptPromise=Ee.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>pZ(e,t,i,r)))}}lxe.Configuration={url:`${Ee._DefaultCdnUrl}/gltf_validator.js`};function $de(n,e,t){try{return Promise.resolve(new Uint8Array(n,e,t))}catch(i){return Promise.reject(i)}}function Ize(n,e,t){try{if(e<0||e>=n.byteLength)throw new RangeError("Offset is out of range.");if(e+t>n.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(n.buffer,n.byteOffset+e,t))}catch(i){return Promise.reject(i)}}var lO;(function(n){n[n.AUTO=0]="AUTO",n[n.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"})(lO||(lO={}));var T8;(function(n){n[n.NONE=0]="NONE",n[n.FIRST=1]="FIRST",n[n.ALL=2]="ALL"})(T8||(T8={}));var yu;(function(n){n[n.LOADING=0]="LOADING",n[n.READY=1]="READY",n[n.COMPLETE=2]="COMPLETE"})(yu||(yu={}));class jn{constructor(){this.onParsedObservable=new Ae,this.coordinateSystemMode=lO.AUTO,this.animationStartMode=T8.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new Ae,this.onSkinLoadedObservable=new Ae,this.onTextureLoadedObservable=new Ae,this.onMaterialLoadedObservable=new Ae,this.onCameraLoadedObservable=new Ae,this.onCompleteObservable=new Ae,this.onErrorObservable=new Ae,this.onDisposeObservable=new Ae,this.onExtensionLoadedObservable=new Ae,this.validate=!1,this.onValidatedObservable=new Ae,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new Ae,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,r,s,a,o,c){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,r,o,c),null;this._progressCallback=s;const l=t.name||Ee.GetFilename(t);if(a){if(this.useRangeRequests){this.validate&&de.Warn("glTF validation is not supported when range requests are enabled");const h={abort:()=>{},onCompleteObservable:new Ae},u={readAsync:(d,f)=>new Promise((p,_)=>{this._loadFile(e,t,m=>{p(new Uint8Array(m))},!0,m=>{_(m)},m=>{m.setRequestHeader("Range",`bytes=${d}-${d+f-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new Jw(u)).then(d=>{h.onCompleteObservable.notifyObservers(h),r(d)},o?d=>o(void 0,d):void 0),h}return this._loadFile(e,t,h=>{this._validate(e,new Uint8Array(h,0,h.byteLength),i,l),this._unpackBinaryAsync(new Jw({readAsync:(u,d)=>$de(h,u,d),byteLength:h.byteLength})).then(u=>{r(u)},o?u=>o(void 0,u):void 0)},!0,o)}else return this._loadFile(e,t,h=>{this._validate(e,h,i,l),r({json:this._parseJson(h)})},!1,o)}_loadBinary(e,t,i,r,s,a){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,a),this._unpackBinaryAsync(new Jw({readAsync:(o,c)=>Ize(t,o,c),byteLength:t.byteLength})).then(o=>{r(o)},s?o=>s(void 0,o):void 0)}importMeshAsync(e,t,i,r,s,a){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${a||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,r,s,a)))}loadAsync(e,t,i,r,s){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,r,s)))}loadAssetContainerAsync(e,t,i,r,s){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t);const a=new jO(e),o=[];this.onMaterialLoadedObservable.add(u=>{o.push(u)});const c=[];this.onTextureLoadedObservable.add(u=>{c.push(u)});const l=[];this.onCameraLoadedObservable.add(u=>{l.push(u)});const h=[];return this.onMeshLoadedObservable.add(u=>{u.morphTargetManager&&h.push(u.morphTargetManager)}),this._loader.importMeshAsync(null,e,a,t,i,r,s).then(u=>(Array.prototype.push.apply(a.geometries,u.geometries),Array.prototype.push.apply(a.meshes,u.meshes),Array.prototype.push.apply(a.particleSystems,u.particleSystems),Array.prototype.push.apply(a.skeletons,u.skeletons),Array.prototype.push.apply(a.animationGroups,u.animationGroups),Array.prototype.push.apply(a.materials,o),Array.prototype.push.apply(a.textures,c),Array.prototype.push.apply(a.lights,u.lights),Array.prototype.push.apply(a.transformNodes,u.transformNodes),Array.prototype.push.apply(a.cameras,l),Array.prototype.push.apply(a.morphTargetManagers,h),a))})}canDirectLoad(e){return e.indexOf("asset")!==-1&&e.indexOf("version")!==-1||e.startsWith("data:base64,"+jn._MagicBase64Encoded)||e.startsWith("data:;base64,"+jn._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+jn._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+jn._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+jn._MagicBase64Encoded)||t.startsWith(";base64,"+jn._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+jn._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+jn._MagicBase64Encoded)){const i=D5(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new Jw({readAsync:(r,s)=>$de(i,r,s),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new jn}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(i=>{t(i)})})}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(yu[this._state]))}_loadFile(e,t,i,r,s,a){const o=e._loadFile(t,i,c=>{this._onProgress(c,o)},!0,r,s,a);return o.onCompleteObservable.add(c=>{this._requests.splice(this._requests.indexOf(c),1)}),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,r=0,s=0;for(const a of this._requests){if(a._lengthComputable===void 0||a._loaded===void 0||a._total===void 0)return;i=i&&a._lengthComputable,r+=a._loaded,s+=a._total}this._progressCallback({lengthComputable:i,loaded:r,total:i?s:0})}_validate(e,t,i="",r=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),lxe.ValidateAsync(t,i,r,s=>this.preprocessUrlAsync(i+s).then(a=>e._loadFileAsync(a,void 0,!0,!0).then(o=>new Uint8Array(o,0,o.byteLength)))).then(s=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(s),this.onValidatedObservable.clear()},s=>{this._endPerformanceCounter("Validate JSON"),Ee.Warn(`Failed to validate: ${s.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const i=jn._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(t.minVersion!==void 0){const a=jn._parseVersion(t.minVersion);if(!a)throw new Error("Invalid minimum version: "+t.minVersion);if(jn._compareVersion(a,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const s={1:jn._CreateGLTF1Loader,2:jn._CreateGLTF2Loader}[i.major];if(!s)throw new Error("Unsupported version: "+t.version);return s(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{const t={Magic:1179937895},i=e.readUint32();if(i!==t.Magic)throw new kf("Unexpected magic: "+i,z0.GLTFLoaderUnexpectedMagicError);const r=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${r}`);const s=e.readUint32();!this.useRangeRequests&&s!==e.buffer.byteLength&&de.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`);let a;switch(r){case 1:{a=this._unpackBinaryV1Async(e,s);break}case 2:{a=this._unpackBinaryV2Async(e,s);break}default:throw new Error("Unsupported version: "+r)}return this._endPerformanceCounter("Unpack Binary"),a})}_unpackBinaryV1Async(e,t){const i={JSON:0},r=e.readUint32(),s=e.readUint32();if(s!==i.JSON)throw new Error(`Unexpected content format: ${s}`);const a=t-e.byteOffset,o={json:this._parseJson(e.readString(r)),bin:null};if(a!==0){const c=e.byteOffset;o.bin={readAsync:(l,h)=>e.buffer.readAsync(c+l,h),byteLength:a}}return Promise.resolve(o)}_unpackBinaryV2Async(e,t){const i={JSON:1313821514,BIN:5130562},r=e.readUint32();if(e.readUint32()!==i.JSON)throw new Error("First chunk format is not JSON");return e.byteOffset+r===t?e.loadAsync(r).then(()=>({json:this._parseJson(e.readString(r)),bin:null})):e.loadAsync(r+8).then(()=>{const a={json:this._parseJson(e.readString(r)),bin:null},o=()=>{const c=e.readUint32();switch(e.readUint32()){case i.JSON:throw new Error("Unexpected JSON chunk");case i.BIN:{const h=e.byteOffset;a.bin={readAsync:(u,d)=>e.buffer.readAsync(h+u,d),byteLength:c},e.skipBytes(c);break}default:{e.skipBytes(c);break}}return e.byteOffset!==t?e.loadAsync(8).then(o):Promise.resolve(a)};return o()})}static _parseVersion(e){if(e==="1.0"||e==="1.0.1")return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.majort.minor?1:e.minora.byteLength)throw new Error("Buffer access is out of range");const o=a.buffer;switch(i+=a.byteOffset,s){case O3.BYTE:return new Int8Array(o,i,r);case O3.UNSIGNED_BYTE:return new Uint8Array(o,i,r);case O3.SHORT:return new Int16Array(o,i,r);case O3.UNSIGNED_SHORT:return new Uint16Array(o,i,r);default:return new Float32Array(o,i,r)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],r=t.count*jo.GetByteStrideFromType(t);return jo.GetBufferFromBufferView(e,i,t.byteOffset,r,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let r=0;r=this._maxPos}}const cxe=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],hxe=["world","view","projection","worldView","worldViewProjection","mBones"],Pze=["translation","rotation","scale"],wze=["position","rotationQuaternion","scaling"],Dze=(n,e)=>{for(const t in n){const i=n[t];e.buffers[t]=i,e.buffersCount++}},Oze=(n,e)=>{for(const t in n){const i=n[t];e.shaders[t]=i,e.shaderscount++}},ah=(n,e,t)=>{for(const i in n){const r=n[i];t[e][i]=r}},Lze=n=>{if(n)for(let e=0;e{if(n.semantic==="NORMAL")return"normal";if(n.semantic==="POSITION")return"position";if(n.semantic==="JOINT")return"matricesIndices";if(n.semantic==="WEIGHT")return"matricesWeights";if(n.semantic==="COLOR")return"color";if(n.semantic&&n.semantic.indexOf("TEXCOORD_")!==-1){const e=Number(n.semantic.split("_")[1]);return"uv"+(e===0?"":e+1)}return null},Nze=n=>{for(const e in n.animations){const t=n.animations[e];if(!t.channels||!t.samplers)continue;let i=null;for(let r=0;r{let e=null;if(n.translation||n.rotation||n.scale){const t=P.FromArray(n.scale||[1,1,1]),i=we.FromArray(n.rotation||[0,0,0,1]),r=P.FromArray(n.translation||[0,0,0]);e=ce.Compose(t,i,r)}else e=ce.FromArray(n.matrix);return e},uxe=(n,e,t,i)=>{for(let s=0;s{for(let t=0;t{const t=n.nodes;let i=t[e];if(i)return{node:i,id:e};for(const r in t)if(i=t[r],i.jointName===e)return{node:i,id:r};return null},Fze=(n,e)=>{for(let t=0;t{for(const r in n.nodes){const s=n.nodes[r],a=r;if(!s.jointName||Fze(t,s.jointName))continue;const o=Kte(s),c=new _s(s.name||"",e,null,o);c.id=a,i.push({bone:c,node:s,id:a})}for(let r=0;r{if(i||(i=new a1(e.name||"","",n.scene)),!e.babylonSkeleton)return i;const r=[],s=[];Uze(n,i,e,r),i.bones=[];for(let o=0;o0&&(f=Bze(r,h),f&&s.indexOf(f)===-1&&s.push(f));const _=new _s(l.jointName||"",i,f,p);_.id=h}const a=i.bones;i.bones=[];for(let o=0;o{if(r||(n.scene._blockEntityCollection=!!n.assetContainer,r=new Se(e.name||"",n.scene),r._parentContainer=n.assetContainer,n.scene._blockEntityCollection=!1,r.id=i),!e.babylonNode)return r;const s=[];let a=null;const o=[],c=[],l=[],h=[];for(let f=0;f1?(u=new Fu("multimat"+i,n.scene),u.subMaterials=s):u=new tt("multimat"+i,n.scene),s.length===1&&(u=s[0]),u._parentContainer=n.assetContainer,r.material||(r.material=u),new Ua(i,n.scene,a,!1,r),r.computeWorldMatrix(!0),n.scene._blockEntityCollection=!1,r.subMeshes=[];let d=0;for(let f=0;f{n.position&&(n.position=e),(n.rotationQuaternion||n.rotation)&&(n.rotationQuaternion=t),n.scaling&&(n.scaling=i)},Vze=(n,e)=>{if(e.matrix){const t=new P(0,0,0),i=new we,r=new P(0,0,0);ce.FromArray(e.matrix).decompose(r,i,t),gZ(n,t,i,r)}else e.translation&&e.rotation&&e.scale&&gZ(n,P.FromArray(e.translation),we.FromArray(e.rotation),P.FromArray(e.scale));n.computeWorldMatrix(!0)},zze=(n,e,t)=>{let i=null;if(n.importOnlyMeshes&&(e.skin||e.meshes)&&n.importMeshesNames&&n.importMeshesNames.length>0&&n.importMeshesNames.indexOf(e.name||"")===-1)return null;if(e.skin){if(e.meshes){const r=n.skins[e.skin],s=efe(n,e,e.meshes,t,e.babylonNode);s.skeleton=n.scene.getLastSkeletonById(e.skin),s.skeleton===null&&(s.skeleton=kze(n,r,s,r.babylonSkeleton),r.babylonSkeleton||(r.babylonSkeleton=s.skeleton)),i=s}}else if(e.meshes)i=efe(n,e,e.mesh?[e.mesh]:e.meshes,t,e.babylonNode);else if(e.light&&!e.babylonNode&&!n.importOnlyMeshes){const r=n.lights[e.light];if(r){if(r.type==="ambient"){const s=r[r.type],a=new Vf(e.light,P.Zero(),n.scene);a.name=e.name||"",s.color&&(a.diffuse=Me.FromArray(s.color)),i=a}else if(r.type==="directional"){const s=r[r.type],a=new Wl(e.light,P.Zero(),n.scene);a.name=e.name||"",s.color&&(a.diffuse=Me.FromArray(s.color)),i=a}else if(r.type==="point"){const s=r[r.type],a=new G0(e.light,P.Zero(),n.scene);a.name=e.name||"",s.color&&(a.diffuse=Me.FromArray(s.color)),i=a}else if(r.type==="spot"){const s=r[r.type],a=new Sl(e.light,P.Zero(),P.Zero(),0,0,n.scene);a.name=e.name||"",s.color&&(a.diffuse=Me.FromArray(s.color)),s.fallOfAngle&&(a.angle=s.fallOfAngle),s.fallOffExponent&&(a.exponent=s.fallOffExponent),i=a}}}else if(e.camera&&!e.babylonNode&&!n.importOnlyMeshes){const r=n.cameras[e.camera];if(r){if(n.scene._blockEntityCollection=!!n.assetContainer,r.type==="orthographic"){const s=new El(e.camera,P.Zero(),n.scene,!1);s.name=e.name||"",s.mode=Rt.ORTHOGRAPHIC_CAMERA,s.attachControl(),i=s,s._parentContainer=n.assetContainer}else if(r.type==="perspective"){const s=r[r.type],a=new El(e.camera,P.Zero(),n.scene,!1);a.name=e.name||"",a.attachControl(),s.aspectRatio||(s.aspectRatio=n.scene.getEngine().getRenderWidth()/n.scene.getEngine().getRenderHeight()),s.znear&&s.zfar&&(a.maxZ=s.zfar,a.minZ=s.znear),i=a,a._parentContainer=n.assetContainer}n.scene._blockEntityCollection=!1}}if(!e.jointName){if(e.babylonNode)return e.babylonNode;if(i===null){n.scene._blockEntityCollection=!!n.assetContainer;const r=new Se(e.name||"",n.scene);r._parentContainer=n.assetContainer,n.scene._blockEntityCollection=!1,e.babylonNode=r,i=r}}if(i!==null){if(e.matrix&&i instanceof Se)Vze(i,e);else{const r=e.translation||[0,0,0],s=e.rotation||[0,0,0,1],a=e.scale||[1,1,1];gZ(i,P.FromArray(r),we.FromArray(s),P.FromArray(a))}i.updateCache(!0),e.babylonNode=i}return i},cO=(n,e,t,i=!1)=>{const r=n.nodes[e];let s=null;if(n.importOnlyMeshes&&!i&&n.importMeshesNames?n.importMeshesNames.indexOf(r.name||"")!==-1||n.importMeshesNames.length===0?i=!0:i=!1:i=!0,!r.jointName&&i&&(s=zze(n,r,e),s!==null&&(s.id=e,s.parent=t)),r.children)for(let a=0;a{let e=n.currentScene;if(e)for(let t=0;t{const o=s.values||r.parameters;for(const c in t){const l=t[c],h=l.type;if(h===Gh.FLOAT_MAT2||h===Gh.FLOAT_MAT3||h===Gh.FLOAT_MAT4){if(l.semantic&&!l.source&&!l.node)jo.SetMatrix(e.scene,n,l,c,i.getEffect());else if(l.semantic&&(l.source||l.node)){let u=e.scene.getNodeByName(l.source||l.node||"");if(u===null&&(u=e.scene.getNodeById(l.source||l.node||"")),u===null)continue;jo.SetMatrix(e.scene,u,l,c,i.getEffect())}}else{const u=o[r.uniforms[c]];if(!u)continue;if(h===Gh.SAMPLER_2D){const d=e.textures[s.values?u:l.value].babylonTexture;if(d==null)continue;i.getEffect().setTexture(c,d)}else jo.SetUniform(i.getEffect(),c,u,h)}}a(i)},Gze=(n,e,t,i,r)=>{const s=i.values||t.parameters,a=t.uniforms;for(const o in r){const c=r[o],l=c.type;let h=s[a[o]];if(h===void 0&&(h=c.value),!h)continue;const u=d=>f=>{c.value&&d&&(e.setTexture(d,f),delete r[d])};l===Gh.SAMPLER_2D?kl.LoadTextureAsync(n,i.values?h:c.value,u(o),()=>u(null)):c.value&&jo.SetUniform(e,o,i.values?h:c.value,l)&&delete r[o]}},Kze=(n,e,t)=>(i,r)=>{e.dispose(!0),t("Cannot compile program named "+n.name+". Error: "+r+". Default material will be applied")},Wze=(n,e,t,i,r,s)=>a=>{Gze(n,e,t,i,r),e.onBind=o=>{Hze(o,n,r,e,t,i,s)}},ife=(n,e,t)=>{for(const i in e.uniforms){const r=e.uniforms[i],s=e.parameters[r];if(n.currentIdentifier===i&&s.semantic&&!s.source&&!s.node){const a=cxe.indexOf(s.semantic);if(a!==-1)return delete t[i],hxe[a]}}return n.currentIdentifier},rfe=n=>{for(const e in n.materials)kl.LoadMaterialAsync(n,e,()=>{},()=>{})};class Am{static CreateRuntime(e,t,i){const r={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&ah(e.extensions,"extensions",r),e.extensionsUsed&&ah(e.extensionsUsed,"extensionsUsed",r),e.buffers&&Dze(e.buffers,r),e.bufferViews&&ah(e.bufferViews,"bufferViews",r),e.accessors&&ah(e.accessors,"accessors",r),e.meshes&&ah(e.meshes,"meshes",r),e.lights&&ah(e.lights,"lights",r),e.cameras&&ah(e.cameras,"cameras",r),e.nodes&&ah(e.nodes,"nodes",r),e.images&&ah(e.images,"images",r),e.textures&&ah(e.textures,"textures",r),e.shaders&&Oze(e.shaders,r),e.programs&&ah(e.programs,"programs",r),e.samplers&&ah(e.samplers,"samplers",r),e.techniques&&ah(e.techniques,"techniques",r),e.materials&&ah(e.materials,"materials",r),e.animations&&ah(e.animations,"animations",r),e.skins&&ah(e.skins,"skins",r),e.scenes&&(r.scenes=e.scenes),e.scene&&e.scenes&&(r.currentScene=e.scenes[e.scene]),r}static LoadBufferAsync(e,t,i,r,s){const a=e.buffers[t];Ee.IsBase64(a.uri)?setTimeout(()=>i(new Uint8Array(Ee.DecodeBase64(a.uri)))):Ee.LoadFile(e.rootUrl+a.uri,o=>i(new Uint8Array(o)),s,void 0,!0,o=>{o&&r(o.status+" "+o.statusText)})}static LoadTextureBufferAsync(e,t,i,r){const s=e.textures[t];if(!s||!s.source){r("");return}if(s.babylonTexture){i(null);return}const a=e.images[s.source];Ee.IsBase64(a.uri)?setTimeout(()=>i(new Uint8Array(Ee.DecodeBase64(a.uri)))):Ee.LoadFile(e.rootUrl+a.uri,o=>i(new Uint8Array(o)),void 0,void 0,!0,o=>{o&&r(o.status+" "+o.statusText)})}static CreateTextureAsync(e,t,i,r){const s=e.textures[t];if(s.babylonTexture){r(s.babylonTexture);return}const a=e.samplers[s.sampler],o=a.minFilter===Qp.NEAREST_MIPMAP_NEAREST||a.minFilter===Qp.NEAREST_MIPMAP_LINEAR||a.minFilter===Qp.LINEAR_MIPMAP_NEAREST||a.minFilter===Qp.LINEAR_MIPMAP_LINEAR,c=ve.BILINEAR_SAMPLINGMODE,l=i==null?new Blob:new Blob([i]),h=URL.createObjectURL(l),u=()=>URL.revokeObjectURL(h),d=new ve(h,e.scene,!o,!0,c,u,u);a.wrapS!==void 0&&(d.wrapU=jo.GetWrapMode(a.wrapS)),a.wrapT!==void 0&&(d.wrapV=jo.GetWrapMode(a.wrapT)),d.name=t,s.babylonTexture=d,r(d)}static LoadShaderStringAsync(e,t,i,r){const s=e.shaders[t];if(Ee.IsBase64(s.uri)){const a=atob(s.uri.split(",")[1]);i&&i(a)}else Ee.LoadFile(e.rootUrl+s.uri,i,void 0,void 0,!1,a=>{a&&r&&r(a.status+" "+a.statusText)})}static LoadMaterialAsync(e,t,i,r){const s=e.materials[t];if(!s.technique){r&&r("No technique found.");return}const a=e.techniques[s.technique];if(!a){e.scene._blockEntityCollection=!!e.assetContainer;const b=new tt(t,e.scene);b._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,b.diffuseColor=new Me(.5,.5,.5),b.sideOrientation=Ye.CounterClockWiseSideOrientation,i(b);return}const o=e.programs[a.program],c=a.states,l=bi.ShadersStore[o.vertexShader+"VertexShader"],h=bi.ShadersStore[o.fragmentShader+"PixelShader"];let u="",d="";const f=new qde(l),p=new qde(h),_={},m=[],g=[],v=[];for(const b in a.uniforms){const T=a.uniforms[b],S=a.parameters[T];if(_[b]=S,S.semantic&&!S.node&&!S.source){const N=cxe.indexOf(S.semantic);N!==-1?(m.push(hxe[N]),delete _[b]):m.push(b)}else S.type===Gh.SAMPLER_2D?v.push(b):m.push(b)}for(const b in a.attributes){const T=a.attributes[b],S=a.parameters[T];if(S.semantic){const N=Jde(S);N&&g.push(N)}}for(;!f.isEnd()&&f.getNextToken();){if(f.currentToken!==L3.IDENTIFIER){u+=f.currentString;continue}let T=!1;for(const S in a.attributes){const N=a.attributes[S],D=a.parameters[N];if(f.currentIdentifier===S&&D.semantic){u+=Jde(D),T=!0;break}}T||(u+=ife(f,a,_))}for(;!p.isEnd()&&p.getNextToken();){if(p.currentToken!==L3.IDENTIFIER){d+=p.currentString;continue}d+=ife(p,a,_)}const x={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},y={attributes:g,uniforms:m,samplers:v,needAlphaBlending:c&&c.enable&&c.enable.indexOf(3042)!==-1};bi.ShadersStore[o.vertexShader+t+"VertexShader"]=u,bi.ShadersStore[o.fragmentShader+t+"PixelShader"]=d;const C=new kn(t,e.scene,x,y);if(C.onError=Kze(o,C,r),C.onCompiled=Wze(e,C,a,s,_,i),C.sideOrientation=Ye.CounterClockWiseSideOrientation,c&&c.functions){const b=c.functions;b.cullFace&&b.cullFace[0]!==mZ.BACK&&(C.backFaceCulling=!1);const T=b.blendFuncSeparate;T&&(T[0]===ya.SRC_ALPHA&&T[1]===ya.ONE_MINUS_SRC_ALPHA&&T[2]===ya.ONE&&T[3]===ya.ONE?C.alphaMode=Le.ALPHA_COMBINE:T[0]===ya.ONE&&T[1]===ya.ONE&&T[2]===ya.ZERO&&T[3]===ya.ONE?C.alphaMode=Le.ALPHA_ONEONE:T[0]===ya.SRC_ALPHA&&T[1]===ya.ONE&&T[2]===ya.ZERO&&T[3]===ya.ONE?C.alphaMode=Le.ALPHA_ADD:T[0]===ya.ZERO&&T[1]===ya.ONE_MINUS_SRC_COLOR&&T[2]===ya.ONE&&T[3]===ya.ONE?C.alphaMode=Le.ALPHA_SUBTRACT:T[0]===ya.DST_COLOR&&T[1]===ya.ZERO&&T[2]===ya.ONE&&T[3]===ya.ONE?C.alphaMode=Le.ALPHA_MULTIPLY:T[0]===ya.SRC_ALPHA&&T[1]===ya.ONE_MINUS_SRC_COLOR&&T[2]===ya.ONE&&T[3]===ya.ONE&&(C.alphaMode=Le.ALPHA_MAXIMIZED))}}}let d5=class vZ{static RegisterExtension(e){if(vZ.Extensions[e.name]){Ee.Error('Tool with the same name "'+e.name+'" already exists');return}vZ.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,r,s,a,o,c){return t.useRightHandedSystem=!0,kl.LoadRuntimeAsync(t,i,r,l=>{l.assetContainer=s,l.importOnlyMeshes=!0,e===""?l.importMeshesNames=[]:typeof e=="string"?l.importMeshesNames=[e]:e&&!(e instanceof Array)?l.importMeshesNames=[e]:(l.importMeshesNames=[],Ee.Warn("Argument meshesNames must be of type string or string[]")),this._createNodes(l);const h=[],u=[];for(const d in l.nodes){const f=l.nodes[d];f.babylonNode instanceof di&&h.push(f.babylonNode)}for(const d in l.skins){const f=l.skins[d];f.babylonSkeleton instanceof a1&&u.push(f.babylonSkeleton)}this._loadBuffersAsync(l,()=>{this._loadShadersAsync(l,()=>{rfe(l),tfe(l),!jn.IncrementalLoading&&a&&a(h,u)})}),jn.IncrementalLoading&&a&&a(h,u)},c),!0}importMeshAsync(e,t,i,r,s,a){return new Promise((o,c)=>{this._importMeshAsync(e,t,r,s,i,(l,h)=>{o({meshes:l,particleSystems:[],skeletons:h,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},a,l=>{c(new Error(l))})})}_loadAsync(e,t,i,r,s,a){e.useRightHandedSystem=!0,kl.LoadRuntimeAsync(e,t,i,o=>{kl.LoadRuntimeExtensionsAsync(o,()=>{this._createNodes(o),this._loadBuffersAsync(o,()=>{this._loadShadersAsync(o,()=>{rfe(o),tfe(o),jn.IncrementalLoading||r()})}),jn.IncrementalLoading&&r()},a)},a)}loadAsync(e,t,i,r){return new Promise((s,a)=>{this._loadAsync(e,t,i,()=>{s()},r,o=>{a(new Error(o))})})}_loadShadersAsync(e,t){let i=!1;const r=(s,a)=>{kl.LoadShaderStringAsync(e,s,o=>{o instanceof ArrayBuffer||(e.loadedShaderCount++,o&&(bi.ShadersStore[s+(a.type===_Z.VERTEX?"VertexShader":"PixelShader")]=o),e.loadedShaderCount===e.shaderscount&&t())},()=>{Ee.Error("Error when loading shader program named "+s+" located at "+a.uri)})};for(const s in e.shaders){i=!0;const a=e.shaders[s];a?r.bind(this,s,a)():Ee.Error("No shader named: "+s)}i||t()}_loadBuffersAsync(e,t){let i=!1;const r=(s,a)=>{kl.LoadBufferAsync(e,s,o=>{e.loadedBufferCount++,o&&(o.byteLength!=e.buffers[s].byteLength&&Ee.Error("Buffer named "+s+" is length "+o.byteLength+". Expected: "+a.byteLength),e.loadedBufferViews[s]=o),e.loadedBufferCount===e.buffersCount&&t()},()=>{Ee.Error("Error when loading buffer named "+s+" located at "+a.uri)})};for(const s in e.buffers){i=!0;const a=e.buffers[s];a?r.bind(this,s,a)():Ee.Error("No buffer named: "+s)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;ia.loadRuntimeAsync(e,t,i,r,s),()=>{setTimeout(()=>{r&&r(Am.CreateRuntime(t.json,e,i))})})}static LoadRuntimeExtensionsAsync(e,t,i){kl._ApplyExtensions(r=>r.loadRuntimeExtensionsAsync(e,t,i),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,i,r,s){kl._ApplyExtensions(a=>a.loadBufferAsync(e,t,i,r,s),()=>{Am.LoadBufferAsync(e,t,i,r,s)})}static LoadTextureAsync(e,t,i,r){kl._LoadTextureBufferAsync(e,t,s=>{s&&kl._CreateTextureAsync(e,t,s,i,r)},r)}static LoadShaderStringAsync(e,t,i,r){kl._ApplyExtensions(s=>s.loadShaderStringAsync(e,t,i,r),()=>{Am.LoadShaderStringAsync(e,t,i,r)})}static LoadMaterialAsync(e,t,i,r){kl._ApplyExtensions(s=>s.loadMaterialAsync(e,t,i,r),()=>{Am.LoadMaterialAsync(e,t,i,r)})}static _LoadTextureBufferAsync(e,t,i,r){kl._ApplyExtensions(s=>s.loadTextureBufferAsync(e,t,i,r),()=>{Am.LoadTextureBufferAsync(e,t,i,r)})}static _CreateTextureAsync(e,t,i,r,s){kl._ApplyExtensions(a=>a.createTextureAsync(e,t,i,r,s),()=>{Am.CreateTextureAsync(e,t,i,r)})}static _ApplyExtensions(e,t){for(const i in d5.Extensions){const r=d5.Extensions[i];if(e(r))return}t()}}jn._CreateGLTF1Loader=()=>new d5;const jze="binary_glTF";class Xze extends kl{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,r){const s=t.json.extensionsUsed;return!s||s.indexOf(this.name)===-1||!t.bin?!1:(this._bin=t.bin,r(Am.CreateRuntime(t.json,e,i)),!0)}loadBufferAsync(e,t,i,r){return e.extensionsUsed.indexOf(this.name)===-1||t!==jze?!1:(this._bin.readAsync(0,this._bin.byteLength).then(i,s=>r(s.message)),!0)}loadTextureBufferAsync(e,t,i){const r=e.textures[t],s=e.images[r.source];if(!s.extensions||!(this.name in s.extensions))return!1;const a=s.extensions[this.name],o=e.bufferViews[a.bufferView],c=jo.GetBufferFromBufferView(e,o,0,o.byteLength,O3.UNSIGNED_BYTE);return i(c),!0}loadShaderStringAsync(e,t,i){const r=e.shaders[t];if(!r.extensions||!(this.name in r.extensions))return!1;const s=r.extensions[this.name],a=e.bufferViews[s.bufferView],o=jo.GetBufferFromBufferView(e,a,0,a.byteLength,O3.UNSIGNED_BYTE);return setTimeout(()=>{const c=jo.DecodeBufferToText(o);i(c)}),!0}}d5.RegisterExtension(new Xze);class Yze extends kl{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const r in i){const s=i[r];switch(s.type){case"ambient":{const a=new Vf(s.name,new P(0,1,0),e.scene),o=s.ambient;o&&(a.diffuse=Me.FromArray(o.color||[1,1,1]));break}case"point":{const a=new G0(s.name,new P(10,10,10),e.scene),o=s.point;o&&(a.diffuse=Me.FromArray(o.color||[1,1,1]));break}case"directional":{const a=new Wl(s.name,new P(0,-1,0),e.scene),o=s.directional;o&&(a.diffuse=Me.FromArray(o.color||[1,1,1]));break}case"spot":{const a=s.spot;if(a){const o=new Sl(s.name,new P(0,10,0),new P(0,-1,0),a.fallOffAngle||Math.PI,a.fallOffExponent||0,e.scene);o.diffuse=Me.FromArray(a.color||[1,1,1])}break}default:Ee.Warn('GLTF Material Common extension: light type "'+s.type+"” not supported");break}}return!1}loadMaterialAsync(e,t,i,r){const s=e.materials[t];if(!s||!s.extensions)return!1;const a=s.extensions[this.name];if(!a)return!1;const o=new tt(t,e.scene);return o.sideOrientation=Ye.CounterClockWiseSideOrientation,a.technique==="CONSTANT"&&(o.disableLighting=!0),o.backFaceCulling=a.doubleSided===void 0?!1:!a.doubleSided,o.alpha=a.values.transparency===void 0?1:a.values.transparency,o.specularPower=a.values.shininess===void 0?0:a.values.shininess,typeof a.values.ambient=="string"?this._loadTexture(e,a.values.ambient,o,"ambientTexture",r):o.ambientColor=Me.FromArray(a.values.ambient||[0,0,0]),typeof a.values.diffuse=="string"?this._loadTexture(e,a.values.diffuse,o,"diffuseTexture",r):o.diffuseColor=Me.FromArray(a.values.diffuse||[0,0,0]),typeof a.values.emission=="string"?this._loadTexture(e,a.values.emission,o,"emissiveTexture",r):o.emissiveColor=Me.FromArray(a.values.emission||[0,0,0]),typeof a.values.specular=="string"?this._loadTexture(e,a.values.specular,o,"specularTexture",r):o.specularColor=Me.FromArray(a.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,r,s){Am.LoadTextureBufferAsync(e,t,a=>{Am.CreateTextureAsync(e,t,a,o=>i[r]=o)},s)}}d5.RegisterExtension(new Yze);function sfe(n,e,t,i){return P.FromArray(e,t).scaleInPlace(i)}function Qze(n,e,t,i){return we.FromArray(e,t).scaleInPlace(i)}function $ze(n,e,t,i){const r=new Array(n._numMorphTargets);for(let s=0;s({frame:c.frame,inTangent:c.inTangent?c.inTangent[a]:void 0,value:c.value[a],outTangent:c.outTangent?c.outTangent[a]:void 0,interpolation:c.interpolation}))),e._primitiveBabylonMeshes){for(const c of e._primitiveBabylonMeshes)if(c.morphTargetManager){const l=c.morphTargetManager.getTarget(a),h=o.clone();l.animations.push(h),s(l,h)}}}}}const eD={translation:[new RY(ke.ANIMATIONTYPE_VECTOR3,"position",sfe,()=>3)],rotation:[new RY(ke.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",Qze,()=>4)],scale:[new RY(ke.ANIMATIONTYPE_VECTOR3,"scaling",sfe,()=>3)],weights:[new Zze(ke.ANIMATIONTYPE_FLOAT,"influence",$ze,n=>n._numMorphTargets)]};function dxe(...n){const e=t=>t&&typeof t=="object";return n.reduce((t,i)=>(Object.keys(i).forEach(r=>{const s=t[r],a=i[r];Array.isArray(s)&&Array.isArray(a)?t[r]=s.concat(...a):e(s)&&e(a)?t[r]=dxe(s,a):t[r]=a}),t),{})}class wi{static Get(e,t,i){if(!t||i==null||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return!e||t==null||!e[t]?null:e[t]}static Assign(e){if(e)for(let t=0;te.dispose&&e.dispose()),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,r,s,a,o=""){return Promise.resolve().then(()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(r);let c=null;if(e){const l={};if(this._gltf.nodes)for(const u of this._gltf.nodes)u.name&&(l[u.name]=u.index);c=(e instanceof Array?e:[e]).map(u=>{const d=l[u];if(d===void 0)throw new Error(`Failed to find node '${u}'`);return d})}return this._loadAsync(s,o,c,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))})}loadAsync(e,t,i,r,s=""){return Promise.resolve().then(()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,s,null,()=>{})))}_loadAsync(e,t,i,r){return Promise.resolve().then(()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const s=`${yu[yu.LOADING]} => ${yu[yu.READY]}`,a=`${yu[yu.LOADING]} => ${yu[yu.COMPLETE]}`;this._parent._startPerformanceCounter(s),this._parent._startPerformanceCounter(a),this._parent._setState(yu.LOADING),this._extensionsOnLoading();const o=new Array,c=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials){if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(this._gltf.scene!=null||this._gltf.scenes&&this._gltf.scenes[0]){const h=wi.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${h.index}`,h))}}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let h=0;h{}))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=c:this._babylonScene._forceBlockMaterialDirtyMechanism(c),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),Promise.all(o).then(()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(yu.READY),this._startAnimations(),r())).then(h=>(this._parent._endPerformanceCounter(s),Ee.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(a),this._parent._setState(yu.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},u=>{this._parent.onErrorObservable.notifyObservers(u),this._parent.onErrorObservable.clear(),this.dispose()})}),h))}).catch(s=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(s),this._parent.onErrorObservable.clear(),this.dispose()),s})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLengthe.bin.byteLength)&&de.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else de.Warn("Unexpected BIN chunk")}}_setupData(){if(wi.Assign(this._gltf.accessors),wi.Assign(this._gltf.animations),wi.Assign(this._gltf.buffers),wi.Assign(this._gltf.bufferViews),wi.Assign(this._gltf.cameras),wi.Assign(this._gltf.images),wi.Assign(this._gltf.materials),wi.Assign(this._gltf.meshes),wi.Assign(this._gltf.nodes),wi.Assign(this._gltf.samplers),wi.Assign(this._gltf.scenes),wi.Assign(this._gltf.skins),wi.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const i of this._gltf.nodes)if(i.children)for(const r of i.children)e[r]=i.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const r=e[i.index];i.parent=r===void 0?t:this._gltf.nodes[r]}}}_loadExtensions(){for(const e in Ht._RegisteredExtensions){const t=Ht._RegisteredExtensions[e].factory(this);t.name!==e&&de.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired){for(const e of this._gltf.extensionsRequired)if(!this._extensions.some(i=>i.name===e&&i.enabled))throw new Error(`Required extension ${e} is not available`)}}_createRootNode(){if(this._parent.customRootNode!==void 0)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:this._rootBabylonMesh===null?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new Se("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case lO.AUTO:{this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],Ht._LoadTransform(t,this._rootBabylonMesh));break}case lO.FORCE_RIGHT_HANDED:{this._babylonScene.useRightHandedSystem=!0;break}default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const r=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const s of t.nodes){const a=wi.Get(`${e}/nodes/${s}`,this._gltf.nodes,s);r.push(this.loadNodeAsync(`/nodes/${a.index}`,a,o=>{o.parent=this._rootBabylonMesh}))}for(const s of this._postSceneLoadActions)s();return r.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(r).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,r=>{const s=r.geometry;s&&e.indexOf(s)===-1&&e.push(s)});return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof di&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,r=>{e.push(r)});return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&i._babylonTransformNode.getClassName()==="TransformNode"&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case T8.NONE:break;case T8.FIRST:{const e=this._getAnimationGroups();e.length!==0&&e[0].start(!0);break}case T8.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:{de.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);return}}}loadNodeAsync(e,t,i=()=>{}){const r=this._extensionsLoadNodeAsync(e,t,i);if(r)return r;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const s=new Array;this.logOpen(`${e} ${t.name||""}`);const a=o=>{if(Ht.AddPointerMetadata(o,e),Ht._LoadTransform(t,o),t.camera!=null){const c=wi.Get(`${e}/camera`,this._gltf.cameras,t.camera);s.push(this.loadCameraAsync(`/cameras/${c.index}`,c,l=>{l.parent=o}))}if(t.children)for(const c of t.children){const l=wi.Get(`${e}/children/${c}`,this._gltf.nodes,c);s.push(this.loadNodeAsync(`/nodes/${l.index}`,l,h=>{h.parent=o}))}i(o)};if(t.mesh==null||t.skin!=null){const o=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const c=new Et(o,this._babylonScene);c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t.mesh==null?t._babylonTransformNode=c:t._babylonTransformNodeForSkin=c,a(c)}if(t.mesh!=null)if(t.skin==null){const o=wi.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${o.index}`,t,o,a))}else{const o=wi.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${o.index}`,t,o,c=>{const l=t._babylonTransformNodeForSkin;c.metadata=dxe(l.metadata,c.metadata||{});const h=wi.Get(`${e}/skin`,this._gltf.skins,t.skin);s.push(this._loadSkinAsync(`/skins/${h.index}`,t,h,u=>{this._forEachPrimitive(t,d=>{d.skeleton=u}),this._postSceneLoadActions.push(()=>{if(h.skeleton!=null){const d=wi.Get(`/skins/${h.index}/skeleton`,this._gltf.nodes,h.skeleton).parent;t.index===d.index?c.parent=l.parent:c.parent=d._babylonTransformNode}else c.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:l,skinnedNode:c})})}))}))}return this.logClose(),Promise.all(s).then(()=>(this._forEachPrimitive(t,o=>{o.geometry&&o.geometry.useBoundingInfoFromGeometry?o._updateBoundingInfo():o.refreshBoundingInfo(!0,!0)}),t._babylonTransformNode))}_loadMeshAsync(e,t,i,r){const s=i.primitives;if(!s||!s.length)throw new Error(`${e}: Primitives are missing`);s[0].index==null&&wi.Assign(s);const a=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(s.length===1){const c=i.primitives[0];a.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${c.index}`,o,t,i,c,l=>{t._babylonTransformNode=l,t._primitiveBabylonMeshes=[l]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Et(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const c of s)a.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${c.index}`,`${o}_primitive${c.index}`,t,i,c,l=>{l.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(l)}))}return r(t._babylonTransformNode),this.logClose(),Promise.all(a).then(()=>t._babylonTransformNode)}_loadMeshPrimitiveAsync(e,t,i,r,s,a){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,a);if(o)return o;this.logOpen(`${e}`);const c=this._disableInstancedMesh===0&&this._parent.createInstances&&i.skin==null&&!r.primitives[0].targets;let l,h;if(c&&s._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=s._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=s._instanceData.promise;else{const u=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const d=new Se(t,this._babylonScene);d._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,d.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?Ye.CounterClockWiseSideOrientation:Ye.ClockWiseSideOrientation,this._createMorphTargets(e,i,r,s,d),u.push(this._loadVertexDataAsync(e,s,d).then(p=>this._loadMorphTargetsAsync(e,s,d,p).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,p.applyToMesh(d),p._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})));const f=Ht._GetDrawMode(e,s.mode);if(s.material==null){let p=this._defaultBabylonMaterialData[f];p||(p=this._createDefaultMaterial("__GLTFLoader._default",f),this._parent.onMaterialLoadedObservable.notifyObservers(p),this._defaultBabylonMaterialData[f]=p),d.material=p}else if(!this.parent.skipMaterials){const p=wi.Get(`${e}/material`,this._gltf.materials,s.material);u.push(this._loadMaterialAsync(`/materials/${p.index}`,p,d,f,_=>{d.material=_}))}h=Promise.all(u),c&&(s._instanceData={babylonSourceMesh:d,promise:h}),l=d}return Ht.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),a(l),this.logClose(),h.then(()=>l)}_loadVertexDataAsync(e,t,i){const r=this._extensionsLoadVertexDataAsync(e,t,i);if(r)return r;const s=t.attributes;if(!s)throw new Error(`${e}: Attributes are missing`);const a=new Array,o=new Ua(i.name,this._babylonScene);if(t.indices==null)i.isUnIndexed=!0;else{const l=wi.Get(`${e}/indices`,this._gltf.accessors,t.indices);a.push(this._loadIndicesAccessorAsync(`/accessors/${l.index}`,l).then(h=>{o.setIndices(h)}))}const c=(l,h,u)=>{if(s[l]==null)return;i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(h)===-1&&i._delayInfo.push(h);const d=wi.Get(`${e}/attributes/${l}`,this._gltf.accessors,s[l]);a.push(this._loadVertexAccessorAsync(`/accessors/${d.index}`,d,h).then(f=>{if(f.getKind()===Z.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&d.min&&d.max){const p=ie.Vector3[0].copyFromFloats(...d.min),_=ie.Vector3[1].copyFromFloats(...d.max);if(d.normalized&&d.componentType!==5126){let m=1;switch(d.componentType){case 5120:m=127;break;case 5121:m=255;break;case 5122:m=32767;break;case 5123:m=65535;break}const g=1/m;p.scaleInPlace(g),_.scaleInPlace(g)}o._boundingInfo=new uc(p,_),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(f,d.count)})),h==Z.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),u&&u(d)};return c("POSITION",Z.PositionKind),c("NORMAL",Z.NormalKind),c("TANGENT",Z.TangentKind),c("TEXCOORD_0",Z.UVKind),c("TEXCOORD_1",Z.UV2Kind),c("TEXCOORD_2",Z.UV3Kind),c("TEXCOORD_3",Z.UV4Kind),c("TEXCOORD_4",Z.UV5Kind),c("TEXCOORD_5",Z.UV6Kind),c("JOINTS_0",Z.MatricesIndicesKind),c("WEIGHTS_0",Z.MatricesWeightsKind),c("JOINTS_1",Z.MatricesIndicesExtraKind),c("WEIGHTS_1",Z.MatricesWeightsExtraKind),c("COLOR_0",Z.ColorKind,l=>{l.type==="VEC4"&&(i.hasVertexAlpha=!0)}),Promise.all(a).then(()=>o)}_createMorphTargets(e,t,i,r,s){if(!r.targets)return;if(t._numMorphTargets==null)t._numMorphTargets=r.targets.length;else if(r.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const a=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,s.morphTargetManager=new Of(this._babylonScene),s.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.morphTargetManager.areUpdatesFrozen=!0;for(let o=0;o{a.areUpdatesFrozen=!1})}_loadMorphTargetVertexDataAsync(e,t,i,r){const s=new Array,a=(o,c,l)=>{if(i[o]==null)return;const h=t.getVertexBuffer(c);if(!h)return;const u=wi.Get(`${e}/${o}`,this._gltf.accessors,i[o]);s.push(this._loadFloatAccessorAsync(`/accessors/${u.index}`,u).then(d=>{l(h,d)}))};return a("POSITION",Z.PositionKind,(o,c)=>{const l=new Float32Array(c.length);o.forEach(c.length,(h,u)=>{l[u]=c[u]+h}),r.setPositions(l)}),a("NORMAL",Z.NormalKind,(o,c)=>{const l=new Float32Array(c.length);o.forEach(l.length,(h,u)=>{l[u]=c[u]+h}),r.setNormals(l)}),a("TANGENT",Z.TangentKind,(o,c)=>{const l=new Float32Array(c.length/3*4);let h=0;o.forEach(c.length/3*4,(u,d)=>{(d+1)%4!==0&&(l[h]=c[h]+u,h++)}),r.setTangents(l)}),Promise.all(s).then(()=>{})}static _LoadTransform(e,t){if(e.skin!=null)return;let i=P.Zero(),r=we.Identity(),s=P.One();e.matrix?ce.FromArray(e.matrix).decompose(s,r,i):(e.translation&&(i=P.FromArray(e.translation)),e.rotation&&(r=we.FromArray(e.rotation)),e.scale&&(s=P.FromArray(e.scale))),t.position=i,t.rotationQuaternion=r,t.scaling=s}_loadSkinAsync(e,t,i,r){const s=this._extensionsLoadSkinAsync(e,t,i);if(s)return s;if(i._data)return r(i._data.babylonSkeleton),i._data.promise;const a=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new a1(i.name||a,a,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const c=this._loadSkinInverseBindMatricesDataAsync(e,i).then(l=>{this._updateBoneMatrices(o,l)});return i._data={babylonSkeleton:o,promise:c},r(o),c}_loadBones(e,t,i){if(t.skeleton==null||this._parent.alwaysComputeSkeletonRootNode){const s=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(s)if(t.skeleton===void 0)t.skeleton=s.index;else{const a=(c,l)=>{for(;l.parent;l=l.parent)if(l.parent===c)return!0;return!1},o=wi.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);o!==s&&!a(o,s)&&(de.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=s.index)}else de.Warn(`${e}: Failed to find common root`)}const r={};for(const s of t.joints){const a=wi.Get(`${e}/joints/${s}`,this._gltf.nodes,s);this._loadBone(a,t,i,r)}}_findSkeletonRootNode(e,t){if(t.length===0)return null;const i={};for(const s of t){const a=[];let o=wi.Get(`${e}/${s}`,this._gltf.nodes,s);for(;o.index!==-1;)a.unshift(o),o=o.parent;i[s]=a}let r=null;for(let s=0;;++s){let a=i[t[0]];if(s>=a.length)return r;const o=a[s];for(let c=1;c=a.length||o!==a[s])return r;r=o}}_loadBone(e,t,i,r){let s=r[e.index];if(s)return s;let a=null;e.index!==t.skeleton&&(e.parent&&e.parent.index!==-1?a=this._loadBone(e.parent,t,i,r):t.skeleton!==void 0&&de.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return s=new _s(e.name||`joint${e.index}`,i,a,this._getNodeMatrix(e),null,null,o),r[e.index]=s,this._postSceneLoadActions.push(()=>{s.linkTransformNode(e._babylonTransformNode)}),s}_loadSkinInverseBindMatricesDataAsync(e,t){if(t.inverseBindMatrices==null)return Promise.resolve(null);const i=wi.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const r=ce.Identity(),s=i._index;t&&s!==-1&&(ce.FromArrayToRef(t,s*16,r),r.invertToRef(r));const a=i.getParent();a&&r.multiplyToRef(a.getAbsoluteInverseBindMatrix(),r),i.updateMatrix(r,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?ce.FromArray(e.matrix):ce.Compose(e.scale?P.FromArray(e.scale):P.One(),e.rotation?we.FromArray(e.rotation):we.Identity(),e.translation?P.FromArray(e.translation):P.Zero())}loadCameraAsync(e,t,i=()=>{}){const r=this._extensionsLoadCameraAsync(e,t,i);if(r)return r;const s=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new El(t.name||`camera${t.index}`,P.Zero(),this._babylonScene,!1);switch(a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.ignoreParentScaling=!0,t._babylonCamera=a,a.rotation.set(0,Math.PI,0),t.type){case"perspective":{const o=t.perspective;if(!o)throw new Error(`${e}: Camera perspective properties are missing`);a.fov=o.yfov,a.minZ=o.znear,a.maxZ=o.zfar||0;break}case"orthographic":{if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);a.mode=Rt.ORTHOGRAPHIC_CAMERA,a.orthoLeft=-t.orthographic.xmag,a.orthoRight=t.orthographic.xmag,a.orthoBottom=-t.orthographic.ymag,a.orthoTop=t.orthographic.ymag,a.minZ=t.orthographic.znear,a.maxZ=t.orthographic.zfar;break}default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return Ht.AddPointerMetadata(a,e),this._parent.onCameraLoadedObservable.notifyObservers(a),i(a),this.logClose(),Promise.all(s).then(()=>a)}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{s.targetedAnimations.length===0&&s.dispose()}))}return Promise.all(t).then(()=>{})}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const r=new Up(t.name||`animation${t.index}`,this._babylonScene);r._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=r;const s=new Array;wi.Assign(t.channels),wi.Assign(t.samplers);for(const a of t.channels)s.push(this._loadAnimationChannelAsync(`${e}/channels/${a.index}`,e,t,a,(o,c)=>{o.animations=o.animations||[],o.animations.push(c),r.addTargetedAnimation(c,o)}));return Promise.all(s).then(()=>(r.normalize(0),r))}_loadAnimationChannelAsync(e,t,i,r,s){const a=this._extensionsLoadAnimationChannelAsync(e,t,i,r,s);if(a)return a;if(r.target.node==null)return Promise.resolve();const o=wi.Get(`${e}/target/node`,this._gltf.nodes,r.target.node);if(r.target.path==="weights"&&!o._numMorphTargets||r.target.path!=="weights"&&!o._babylonTransformNode)return Promise.resolve();let c;switch(r.target.path){case"translation":{c=eD.translation;break}case"rotation":{c=eD.rotation;break}case"scale":{c=eD.scale;break}case"weights":{c=eD.weights;break}default:throw new Error(`${e}/target/path: Invalid value (${r.target.path})`)}const l={object:o,info:c};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,r,l,s)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,r,s,a){const o=this.parent.targetFps,c=1/o,l=wi.Get(`${e}/sampler`,i.samplers,r.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${r.sampler}`,l).then(h=>{let u=0;const d=s.object,f=s.info;for(const p of f){const _=p.getStride(d),m=h.input,g=h.output,v=new Array(m.length);let x=0;switch(h.interpolation){case"STEP":{for(let y=0;y0){const y=`${i.name||`animation${i.index}`}_channel${r.index}_${u}`;p.buildAnimations(d,y,o,v,(C,b)=>{++u,a(C,b)})}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const r=wi.Get(`${e}/input`,this._gltf.accessors,t.input),s=wi.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${r.index}`,r),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then(([a,o])=>({input:a,interpolation:i,output:o})),t._data}loadBufferAsync(e,t,i,r){const s=this._extensionsLoadBufferAsync(e,t,i,r);if(s)return s;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(a=>{try{return new Uint8Array(a.buffer,a.byteOffset+i,r)}catch(o){throw new Error(`${e}: ${o.message}`)}})}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const r=wi.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${r.index}`,r,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const r=Ht._GetNumComponents(e,t.type),s=r*Z.GetTypeByteLength(t.componentType),a=r*t.count;if(t.bufferView==null)t._data=Promise.resolve(new i(a));else{const o=wi.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then(c=>{if(t.componentType===5126&&!t.normalized&&(!o.byteStride||o.byteStride===s))return Ht._GetTypedArray(e,t.componentType,c,t.byteOffset,a);{const l=new i(a);return Z.ForEach(c,t.byteOffset||0,o.byteStride||s,r,t.componentType,l.length,t.normalized||!1,(h,u)=>{l[u]=h}),l}})}if(t.sparse){const o=t.sparse;t._data=t._data.then(c=>{const l=c,h=wi.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,o.indices.bufferView),u=wi.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,o.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${h.index}`,h),this.loadBufferViewAsync(`/bufferViews/${u.index}`,u)]).then(([d,f])=>{const p=Ht._GetTypedArray(`${e}/sparse/indices`,o.indices.componentType,d,o.indices.byteOffset,o.count),_=r*o.count;let m;if(t.componentType===5126&&!t.normalized)m=Ht._GetTypedArray(`${e}/sparse/values`,t.componentType,f,o.values.byteOffset,_);else{const v=Ht._GetTypedArray(`${e}/sparse/values`,t.componentType,f,o.values.byteOffset,_);m=new i(_),Z.ForEach(v,0,s,r,t.componentType,m.length,t.normalized||!1,(x,y)=>{m[y]=x})}let g=0;for(let v=0;vHt._GetTypedArray(e,t.componentType,r,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(i=>new no(t,i,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var s;if((s=t._babylonVertexBuffer)!=null&&s[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const r=this._babylonScene.getEngine();if(t.sparse||t.bufferView==null)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then(a=>new Z(r,a,i,!1));else{const a=wi.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(a).then(o=>{const c=Ht._GetNumComponents(e,t.type);return new Z(r,o,i,!1,void 0,a.byteStride,void 0,t.byteOffset,c,t.componentType,t.normalized,!0,void 0,!0)})}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const r=new Array;return t&&(t.baseColorFactor?(i.albedoColor=Me.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=Me.White(),i.metallic=t.metallicFactor==null?1:t.metallicFactor,i.roughness=t.roughnessFactor==null?1:t.roughnessFactor,t.baseColorTexture&&r.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,s=>{s.name=`${i.name} (Base Color)`,i.albedoTexture=s})),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,s=>{s.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=s})),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(r).then(()=>{})}_loadMaterialAsync(e,t,i,r,s=()=>{}){const a=this._extensionsLoadMaterialAsync(e,t,i,r,s);if(a)return a;t._data=t._data||{};let o=t._data[r];if(!o){this.logOpen(`${e} ${t.name||""}`);const c=this.createMaterial(e,t,r);o={babylonMaterial:c,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,c)},t._data[r]=o,Ht.AddPointerMetadata(c,e),this._parent.onMaterialLoadedObservable.notifyObservers(c),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce(()=>{const c=o.babylonMeshes.indexOf(i);c!==-1&&o.babylonMeshes.splice(c,1)})),s(o.babylonMaterial),o.promise.then(()=>o.babylonMaterial)}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Nt(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=Nt.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const r=this._extensionsCreateMaterial(e,t,i);if(r)return r;const s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,i)}loadMaterialPropertiesAsync(e,t,i){const r=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(r)return r;const s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then(()=>{})}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.emissiveColor=t.emissiveFactor?Me.FromArray(t.emissiveFactor):new Me(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,s=>{s.name=`${i.name} (Normal)`,i.bumpTexture=s})),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,t.normalTexture.scale!=null&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,s=>{s.name=`${i.name} (Occlusion)`,i.ambientTexture=s})),i.useAmbientInGrayScale=!0,t.occlusionTexture.strength!=null&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&r.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,s=>{s.name=`${i.name} (Emissive)`,i.emissiveTexture=s})),Promise.all(r).then(()=>{})}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":{i.transparencyMode=Nt.PBRMATERIAL_OPAQUE,i.alpha=1;break}case"MASK":{i.transparencyMode=Nt.PBRMATERIAL_ALPHATEST,i.alphaCutOff=t.alphaCutoff==null?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break}case"BLEND":{i.transparencyMode=Nt.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break}default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=()=>{}){const r=this._extensionsLoadTextureInfoAsync(e,t,i);if(r)return r;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const s=wi.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;const a=this._loadTextureAsync(`/textures/${t.index}`,s,o=>{o.coordinatesIndex=t.texCoord||0,Ht.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),i(o)});return this.logClose(),a}_loadTextureAsync(e,t,i=()=>{}){const r=this._extensionsLoadTextureAsync(e,t,i);if(r)return r;this.logOpen(`${e} ${t.name||""}`);const s=t.sampler==null?Ht.DefaultSampler:wi.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),a=wi.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,s,a,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,r=()=>{},s,a){const o=this._loadSampler(`/samplers/${t.index}`,t),c=new Array,l=new FS;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(d,f)=>{this._disposed||l.reject(new Error(`${e}: ${f&&f.message?f.message:d||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:s,useSRGBBuffer:!!a&&this._parent.useSRGBBuffers},u=new ve(null,this._babylonScene,h);return u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c.push(l.promise),c.push(this.loadImageAsync(`/images/${i.index}`,i).then(d=>{const f=i.uri||`${this._fileName}#image${i.index}`,p=`data:${this._uniqueRootUrl}${f}`;u.updateURL(p,d)})),u.wrapU=o.wrapU,u.wrapV=o.wrapV,r(u),Promise.all(c).then(()=>u)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:t.minFilter===9728||t.minFilter===9729,samplingMode:Ht._GetTextureSamplingMode(e,t),wrapU:Ht._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:Ht._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const i=wi.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const r=this._extensionsLoadUriAsync(e,t,i);if(r)return r;if(!Ht._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(UO(i)){const s=new Uint8Array(D5(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${s.length} bytes)`),Promise.resolve(s)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then(s=>new Promise((a,o)=>{this._parent._loadFile(this._babylonScene,s,c=>{this._disposed||(this.log(`${e}: Loaded ${i} (${c.byteLength} bytes)`),a(new Uint8Array(c)))},!0,c=>{o(new G8(`${e}: Failed to load '${i}'${c?": "+c.status+" "+c.statusText:""}`,c))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},r=i.gltf=i.gltf||{};(r.pointers=r.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=t??10497,t){case 33071:return ve.CLAMP_ADDRESSMODE;case 33648:return ve.MIRROR_ADDRESSMODE;case 10497:return ve.WRAP_ADDRESSMODE;default:return de.Warn(`${e}: Invalid value (${t})`),ve.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=t.magFilter==null?9729:t.magFilter,r=t.minFilter==null?9987:t.minFilter;if(i===9729)switch(r){case 9728:return ve.LINEAR_NEAREST;case 9729:return ve.LINEAR_LINEAR;case 9984:return ve.LINEAR_NEAREST_MIPNEAREST;case 9985:return ve.LINEAR_LINEAR_MIPNEAREST;case 9986:return ve.LINEAR_NEAREST_MIPLINEAR;case 9987:return ve.LINEAR_LINEAR_MIPLINEAR;default:return de.Warn(`${e}/minFilter: Invalid value (${r})`),ve.LINEAR_LINEAR_MIPLINEAR}else switch(i!==9728&&de.Warn(`${e}/magFilter: Invalid value (${i})`),r){case 9728:return ve.NEAREST_NEAREST;case 9729:return ve.NEAREST_LINEAR;case 9984:return ve.NEAREST_NEAREST_MIPNEAREST;case 9985:return ve.NEAREST_LINEAR_MIPNEAREST;case 9986:return ve.NEAREST_NEAREST_MIPLINEAR;case 9987:return ve.NEAREST_LINEAR_MIPLINEAR;default:return de.Warn(`${e}/minFilter: Invalid value (${r})`),ve.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,r,s){const a=i.buffer;r=i.byteOffset+(r||0);const o=Ht._GetTypedArrayConstructor(`${e}/componentType`,t),c=Z.GetTypeByteLength(t);return r%c!==0?(de.Warn(`${e}: Copying buffer as byte offset (${r}) is not a multiple of component type byte length (${c})`),new o(a.slice(r,r+s*c),0)):new o(a,r,s)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return Ee.IsBase64(e)||e.indexOf("..")===-1}static _GetDrawMode(e,t){switch(t==null&&(t=4),t){case 0:return Ye.PointListDrawMode;case 1:return Ye.LineListDrawMode;case 2:return Ye.LineLoopDrawMode;case 3:return Ye.LineStripDrawMode;case 4:return Ye.TriangleFillMode;case 5:return Ye.TriangleStripDrawMode;case 6:return Ye.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials){for(const t of this._gltf.materials)if(t._data)for(const i in t._data){const r=t._data[i];for(const s of r.babylonMeshes){s.computeWorldMatrix(!0);const a=r.babylonMaterial;e.push(a.forceCompilationAsync(s)),e.push(a.forceCompilationAsync(s,{useInstances:!0})),this._parent.useClipPlane&&(e.push(a.forceCompilationAsync(s,{clipPlane:!0})),e.push(a.forceCompilationAsync(s,{clipPlane:!0,useInstances:!0})))}}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile materials")})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const i of t){const r=i.getShadowGenerator();r&&e.push(r.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(const r of this._extensions)if(r.enabled){const s=`${r.name}.${t}`,a=e;a._activeLoaderExtensionFunctions=a._activeLoaderExtensionFunctions||{};const o=a._activeLoaderExtensionFunctions;if(!o[s]){o[s]=!0;try{const c=i(r);if(c)return c}finally{delete o[s]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&e.onReady())}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",i=>i.loadSceneAsync&&i.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",r=>r.loadNodeAsync&&r.loadNodeAsync(e,t,i))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",r=>r.loadCameraAsync&&r.loadCameraAsync(e,t,i))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",r=>r._loadVertexDataAsync&&r._loadVertexDataAsync(e,t,i))}_extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,a){return this._applyExtensions(s,"loadMeshPrimitive",o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,r,s,a))}_extensionsLoadMaterialAsync(e,t,i,r,s){return this._applyExtensions(t,"loadMaterial",a=>a._loadMaterialAsync&&a._loadMaterialAsync(e,t,i,r,s))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",r=>r.createMaterial&&r.createMaterial(e,t,i))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",r=>r.loadMaterialPropertiesAsync&&r.loadMaterialPropertiesAsync(e,t,i))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",r=>r.loadTextureInfoAsync&&r.loadTextureInfoAsync(e,t,i))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",r=>r._loadTextureAsync&&r._loadTextureAsync(e,t,i))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,i,r,s){return this._applyExtensions(i,"loadAnimationChannel",a=>a._loadAnimationChannelAsync&&a._loadAnimationChannelAsync(e,t,i,r,s))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",r=>r._loadSkinAsync&&r._loadSkinAsync(e,t,i))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",r=>r._loadUriAsync&&r._loadUriAsync(e,t,i))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,i,r){return this._applyExtensions(t,"loadBuffer",s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,i,r))}static LoadExtensionAsync(e,t,i,r){if(!t.extensions)return null;const a=t.extensions[i];return a?r(`${e}/extensions/${i}`,a):null}static LoadExtraAsync(e,t,i,r){if(!t.extras)return null;const a=t.extras[i];return a?r(`${e}/extras/${i}`,a):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&this._gltf.extensionsUsed.indexOf(e)!==-1}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}Ht._RegisteredExtensions={};Ht.DefaultSampler={index:-1};jn._CreateGLTF2Loader=n=>new Ht(n);const xZ="EXT_lights_image_based";class qze{constructor(e){this.name=xZ,this._loader=e,this.enabled=this._loader.isExtensionUsed(xZ)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return Ht.LoadExtensionAsync(e,t,this.name,(i,r)=>{this._loader._allMaterialsDirtyRequired=!0;const s=new Array;s.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const a=wi.Get(`${i}/light`,this._lights,r.light);return s.push(this._loadLightAsync(`/extensions/${this.name}/lights/${r.light}`,a).then(o=>{this._loader.babylonScene.environmentTexture=o})),this._loader.logClose(),Promise.all(s).then(()=>{})})}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const r=new Array(t.specularImages.length);for(let s=0;s{r[s][o]=u})),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then(()=>{const s=new JG(this._loader.babylonScene,null,t.specularImageSize);if(s.name=t.name||"environment",t._babylonTexture=s,t.intensity!=null&&(s.level=t.intensity),t.rotation){let l=we.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(l=we.Inverse(l)),ce.FromQuaternionToRef(l,s.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const a=r4.FromArray(t.irradianceCoefficients);a.scaleInPlace(t.intensity),a.convertIrradianceToLambertianRadiance();const o=J0.FromHarmonics(a),c=(r.length-1)/_t.Log2(t.specularImageSize);return s.updateRGBDAsync(r,o,c)})}return t._loaded.then(()=>t._babylonTexture)}}Ht.RegisterExtension(xZ,n=>new qze(n));const yZ="EXT_mesh_gpu_instancing";class Jze{constructor(e){this.name=yZ,this._loader=e,this.enabled=this._loader.isExtensionUsed(yZ)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{this._loader._disableInstancedMesh++;const a=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return a;const o=new Array;let c=0;const l=h=>{if(s.attributes[h]==null){o.push(Promise.resolve(null));return}const u=wi.Get(`${r}/attributes/${h}`,this._loader.gltf.accessors,s.attributes[h]);if(o.push(this._loader._loadFloatAccessorAsync(`/accessors/${u.bufferView}`,u)),c===0)c=u.count;else if(c!==u.count)throw new Error(`${r}/attributes: Instance buffer accessors do not have the same count.`)};return l("TRANSLATION"),l("ROTATION"),l("SCALE"),a.then(h=>Promise.all(o).then(([u,d,f])=>{const p=new Float32Array(c*16);ie.Vector3[0].copyFromFloats(0,0,0),ie.Quaternion[0].copyFromFloats(0,0,0,1),ie.Vector3[1].copyFromFloats(1,1,1);for(let _=0;_new Jze(n));const AZ="EXT_meshopt_compression";class eHe{constructor(e){this.name=AZ,this.enabled=e.isExtensionUsed(AZ),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return Ht.LoadExtensionAsync(e,t,this.name,(i,r)=>{const s=t;if(s._meshOptData)return s._meshOptData;const a=wi.Get(`${e}/buffer`,this._loader.gltf.buffers,r.buffer);return s._meshOptData=this._loader.loadBufferAsync(`/buffers/${a.index}`,a,r.byteOffset||0,r.byteLength).then(o=>w0.Default.decodeGltfBufferAsync(o,r.count,r.byteStride,r.mode,r.filter)),s._meshOptData})}}Ht.RegisterExtension(AZ,n=>new eHe(n));const CZ="EXT_texture_webp";class tHe{constructor(e){this.name=CZ,this._loader=e,this.enabled=e.isExtensionUsed(CZ)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=t.sampler==null?Ht.DefaultSampler:wi.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=wi.Get(`${r}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,a,o,c=>{i(c)},void 0,!t._textureInfo.nonColorData)})}}Ht.RegisterExtension(CZ,n=>new tHe(n));const bZ="KHR_draco_mesh_compression";class iHe{constructor(e){this.name=bZ,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=cc.DecoderAvailable&&this._loader.isExtensionUsed(bZ)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{if(t.mode!=null&&t.mode!==4&&t.mode!==5)throw new Error(`${e}: Unsupported mode ${t.mode}`);const a={},o={},c=(h,u)=>{const d=s.attributes[h];if(d!=null&&(i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(u)===-1&&i._delayInfo.push(u),a[u]=d,this.useNormalizedFlagFromAccessor)){const f=wi.TryGet(this._loader.gltf.accessors,t.attributes[h]);f&&(o[u]=f.normalized||!1)}};c("POSITION",Z.PositionKind),c("NORMAL",Z.NormalKind),c("TANGENT",Z.TangentKind),c("TEXCOORD_0",Z.UVKind),c("TEXCOORD_1",Z.UV2Kind),c("TEXCOORD_2",Z.UV3Kind),c("TEXCOORD_3",Z.UV4Kind),c("TEXCOORD_4",Z.UV5Kind),c("TEXCOORD_5",Z.UV6Kind),c("JOINTS_0",Z.MatricesIndicesKind),c("WEIGHTS_0",Z.MatricesWeightsKind),c("COLOR_0",Z.ColorKind);const l=wi.Get(r,this._loader.gltf.bufferViews,s.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then(h=>(this.dracoCompression||cc.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,h,a,o).catch(d=>{throw new Error(`${e}: ${d.message}`)}))),l._dracoBabylonGeometry})}}Ht.RegisterExtension(bZ,n=>new iHe(n));const EZ="KHR_lights_punctual";class rHe{constructor(e){this.name=EZ,this._loader=e,this.enabled=this._loader.isExtensionUsed(EZ)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,wi.Assign(this._lights)}}loadNodeAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,a=>{let o;const c=wi.Get(r,this._lights,s.light),l=c.name||a.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,c.type){case"directional":{const h=new Wl(l,P.Backward(),this._loader.babylonScene);h.position.setAll(0),o=h;break}case"point":{o=new G0(l,P.Zero(),this._loader.babylonScene);break}case"spot":{const h=new Sl(l,P.Zero(),P.Backward(),0,1,this._loader.babylonScene);h.angle=(c.spot&&c.spot.outerConeAngle||Math.PI/4)*2,h.innerAngle=(c.spot&&c.spot.innerConeAngle||0)*2,o=h;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${r}: Invalid light type (${c.type})`)}o._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,c._babylonLight=o,o.falloffType=Ui.FALLOFF_GLTF,o.diffuse=c.color?Me.FromArray(c.color):Me.White(),o.intensity=c.intensity==null?1:c.intensity,o.range=c.range==null?Number.MAX_VALUE:c.range,o.parent=a,this._loader._babylonLights.push(o),Ht.AddPointerMetadata(o,r),i(a)})))}}Ht.RegisterExtension(EZ,n=>new rHe(n));const TZ="KHR_materials_pbrSpecularGlossiness";class sHe{constructor(e){this.name=TZ,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(TZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),a.push(this._loadSpecularGlossinessPropertiesAsync(r,s,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(a).then(()=>{})})}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=Me.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=Me.White(),i.reflectivityColor=t.specularFactor?Me.FromArray(t.specularFactor):Me.White(),i.microSurface=t.glossinessFactor==null?1:t.glossinessFactor,t.diffuseTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,s=>{s.name=`${i.name} (Diffuse)`,i.albedoTexture=s})),t.specularGlossinessTexture&&(r.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,s=>{s.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=s,i.reflectivityTexture.hasAlpha=!0})),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(r).then(()=>{})}}Ht.RegisterExtension(TZ,n=>new sHe(n));const SZ="KHR_materials_unlit";class nHe{constructor(e){this.name=SZ,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(SZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,()=>this._loadUnlitPropertiesAsync(e,t,i))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const r=new Array;i.unlit=!0;const s=t.pbrMetallicRoughness;return s&&(s.baseColorFactor?(i.albedoColor=Me.FromArray(s.baseColorFactor),i.alpha=s.baseColorFactor[3]):i.albedoColor=Me.White(),s.baseColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,s.baseColorTexture,a=>{a.name=`${i.name} (Base Color)`,i.albedoTexture=a}))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then(()=>{})}}Ht.RegisterExtension(SZ,n=>new nHe(n));const MZ="KHR_materials_clearcoat";class aHe{constructor(e){this.name=MZ,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(MZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),a.push(this._loadClearCoatPropertiesAsync(r,s,i)),Promise.all(a).then(()=>{})})}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,t.clearcoatFactor!=null?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,s=>{s.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=s})),t.clearcoatRoughnessFactor!=null?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,s=>{s.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=s}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,s=>{s.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=s})),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,t.clearcoatNormalTexture.scale!=null&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(r).then(()=>{})}}Ht.RegisterExtension(MZ,n=>new aHe(n));const RZ="KHR_materials_iridescence";class oHe{constructor(e){this.name=RZ,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(RZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),a.push(this._loadIridescencePropertiesAsync(r,s,i)),Promise.all(a).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=t.iridescenceFactor??0,i.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,i.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,i.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,s=>{s.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=s})),t.iridescenceThicknessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,s=>{s.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=s})),Promise.all(r).then(()=>{})}}Ht.RegisterExtension(RZ,n=>new oHe(n));const IZ="KHR_materials_anisotropy";class lHe{constructor(e){this.name=IZ,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(IZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),a.push(this._loadIridescencePropertiesAsync(r,s,i)),Promise.all(a).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,s=>{s.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=s})),Promise.all(r).then(()=>{})}}Ht.RegisterExtension(IZ,n=>new lHe(n));const PZ="KHR_materials_emissive_strength";class cHe{constructor(e){this.name=PZ,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(PZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then(()=>{this._loadEmissiveProperties(r,s,i)}))}_loadEmissiveProperties(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);t.emissiveStrength!==void 0&&i.emissiveColor.scaleToRef(t.emissiveStrength,i.emissiveColor)}}Ht.RegisterExtension(PZ,n=>new cHe(n));const wZ="KHR_materials_sheen";class hHe{constructor(e){this.name=wZ,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(wZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),a.push(this._loadSheenPropertiesAsync(r,s,i)),Promise.all(a).then(()=>{})})}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,t.sheenColorFactor!=null?i.sheen.color=Me.FromArray(t.sheenColorFactor):i.sheen.color=Me.Black(),t.sheenColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,s=>{s.name=`${i.name} (Sheen Color)`,i.sheen.texture=s})),t.sheenRoughnessFactor!==void 0?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,s=>{s.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=s}))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(r).then(()=>{})}}Ht.RegisterExtension(wZ,n=>new hHe(n));const DZ="KHR_materials_specular";class uHe{constructor(e){this.name=DZ,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(DZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),a.push(this._loadSpecularPropertiesAsync(r,s,i)),Promise.all(a).then(()=>{})})}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const r=new Array;return t.specularFactor!==void 0&&(i.metallicF0Factor=t.specularFactor),t.specularColorFactor!==void 0&&(i.metallicReflectanceColor=Me.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,s=>{s.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=s,i.useOnlyMetallicFromMetallicReflectanceTexture=!0}))),t.specularColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,s=>{s.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=s})),Promise.all(r).then(()=>{})}}Ht.RegisterExtension(DZ,n=>new uHe(n));const OZ="KHR_materials_ior";class bK{constructor(e){this.name=OZ,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(OZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),a.push(this._loadIorPropertiesAsync(r,s,i)),Promise.all(a).then(()=>{})})}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);return t.ior!==void 0?i.indexOfRefraction=t.ior:i.indexOfRefraction=bK._DEFAULT_IOR,Promise.resolve()}}bK._DEFAULT_IOR=1.5;Ht.RegisterExtension(OZ,n=>new bK(n));const Lh="KHR_materials_variants";class _3{constructor(e){this.name=Lh,this._loader=e,this.enabled=this._loader.isExtensionUsed(Lh)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return _3.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${Lh} extension`);const r=s=>{const a=i.variants[s];if(a)for(const o of a)o.mesh.material=o.material};if(t instanceof Array)for(const s of t)r(s);else r(t);i.lastSelected=t}selectVariant(e,t){_3.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${Lh} extension`);for(const i of t.original)i.mesh.material=i.material;t.lastSelected=null}reset(e){_3.Reset(e)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${Lh} extension`);return t.lastSelected}getLastSelectedVariant(e){return _3.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){var t,i;return((i=(t=e==null?void 0:e._internalMetadata)==null?void 0:t.gltf)==null?void 0:i[Lh])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,r,s,a){return Ht.LoadExtensionAsync(e,s,this.name,(o,c)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,r,s,h=>{if(a(h),h instanceof Se){const u=Ht._GetDrawMode(e,s.mode),d=this._loader.rootBabylonMesh,f=d?d._internalMetadata=d._internalMetadata||{}:{},p=f.gltf=f.gltf||{},_=p[Lh]=p[Lh]||{lastSelected:null,original:[],variants:{}};_.original.push({mesh:h,material:h.material});for(let m=0;m{for(let y=0;y{const S=T;let N=null,D=S;do{if(D=D.parent,!D)return;N=_3._GetExtensionMetadata(D)}while(N===null);if(d&&N===_3._GetExtensionMetadata(d)){D._internalMetadata={};for(const M in d._internalMetadata)D._internalMetadata[M]=d._internalMetadata[M];D._internalMetadata.gltf=[];for(const M in d._internalMetadata.gltf)D._internalMetadata.gltf[M]=d._internalMetadata.gltf[M];D._internalMetadata.gltf[Lh]={lastSelected:null,original:[],variants:{}};for(const M of N.original)D._internalMetadata.gltf[Lh].original.push({mesh:M.mesh,material:M.material});for(const M in N.variants)if(Object.prototype.hasOwnProperty.call(N.variants,M)){D._internalMetadata.gltf[Lh].variants[M]=[];for(const I of N.variants[M])D._internalMetadata.gltf[Lh].variants[M].push({mesh:I.mesh,material:I.material})}N=D._internalMetadata.gltf[Lh]}for(const M of N.original)M.mesh===h&&(M.mesh=S);for(const M of N.variants[b.name])M.mesh===h&&(M.mesh=S)})}}))}}})),Promise.all(l).then(([h])=>h)})}}Ht.RegisterExtension(Lh,n=>new _3(n));class Wte{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:Le.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...Wte._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new Ae,this._scene.onDisposeObservable.addOnce(()=>{this.dispose()}),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter(s=>this._options[s]!==e[s]).length)return;const i={...this._options,...e},r=this._options;this._options=i,i.renderSize!==r.renderSize||i.renderTargetTextureType!==r.renderTargetTextureType||i.generateMipmaps!==r.generateMipmaps||!this._opaqueRenderTarget?this._setupRenderTargets():(this._opaqueRenderTarget.samples=i.samples,this._opaqueRenderTarget.lodGenerationScale=i.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=i.lodGenerationOffset)}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return e?!!(e instanceof Nt&&e.subSurface.isRefractionEnabled):!1}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Ee.SetImmediate(()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,this._transparentMeshesCache.indexOf(e)===-1&&this._transparentMeshesCache.push(e)):this._opaqueMeshesCache.indexOf(e)===-1&&this._opaqueMeshesCache.push(e)})}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);t!==-1&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),t!==-1&&this._opaqueMeshesCache.splice(t,1)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof Nt&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),i!==-1?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):t===-1&&this._transparentMeshesCache.push(e)):t!==-1?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):i===-1&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){var e;return((e=this._opaqueRenderTarget)==null?void 0:e.getInternalTexture())!==null}_setupRenderTargets(){var i;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new es("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=((i=this._options.clearColor)==null?void 0:i.clone())??this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0;let e,t;this._opaqueRenderTarget.onBeforeBindObservable.add(r=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?r.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(r.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0}),this._opaqueRenderTarget.onAfterUnbindObservable.add(()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e}),this._transparentMeshesCache.forEach(r=>{this._shouldRenderAsTransmission(r.material)&&(r.material.refractionTexture=this._opaqueRenderTarget)})}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const LZ="KHR_materials_transmission";class dHe{constructor(e){this.name=LZ,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(LZ),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),a.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),a.push(this._loadTransparentPropertiesAsync(r,t,i,s)),Promise.all(a).then(()=>{})})}_loadTransparentPropertiesAsync(e,t,i,r){var a,o;if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const s=i;if(s.subSurface.isRefractionEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.useAlbedoToTintRefraction=!0,r.transmissionFactor!==void 0){s.subSurface.refractionIntensity=r.transmissionFactor;const c=s.getScene();s.subSurface.refractionIntensity&&!c._transmissionHelper?new Wte({},s.getScene()):s.subSurface.refractionIntensity&&!((a=c._transmissionHelper)!=null&&a._isRenderTargetValid())&&((o=c._transmissionHelper)==null||o._setupRenderTargets())}else return s.subSurface.refractionIntensity=0,s.subSurface.isRefractionEnabled=!1,Promise.resolve();return s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,r.transmissionTexture?(r.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,r.transmissionTexture,void 0).then(c=>{s.subSurface.refractionIntensityTexture=c,s.subSurface.useGltfStyleTextures=!0})):Promise.resolve()}}Ht.RegisterExtension(LZ,n=>new dHe(n));const NZ="KHR_materials_translucency";class fHe{constructor(e){this.name=NZ,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(NZ),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),a.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),a.push(this._loadTranslucentPropertiesAsync(r,t,i,s)),Promise.all(a).then(()=>{})})}_loadTranslucentPropertiesAsync(e,t,i,r){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);const s=i;if(s.subSurface.isTranslucencyEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,s.subSurface.useAlbedoToTintTranslucency=!0,r.translucencyFactor!==void 0)s.subSurface.translucencyIntensity=r.translucencyFactor;else return s.subSurface.translucencyIntensity=0,s.subSurface.isTranslucencyEnabled=!1,Promise.resolve();return r.translucencyTexture?(r.translucencyTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/translucencyTexture`,r.translucencyTexture).then(a=>{s.subSurface.translucencyIntensityTexture=a})):Promise.resolve()}}Ht.RegisterExtension(NZ,n=>new fHe(n));const BZ="KHR_materials_volume";class pHe{constructor(e){this.name=BZ,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(BZ),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),a.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),a.push(this._loadVolumePropertiesAsync(r,t,i,s)),Promise.all(a).then(()=>{})})}_loadVolumePropertiesAsync(e,t,i,r){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!r.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const s=r.attenuationDistance!==void 0?r.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=s,r.attenuationColor!==void 0&&r.attenuationColor.length==3&&i.subSurface.tintColor.copyFromFloats(r.attenuationColor[0],r.attenuationColor[1],r.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=r.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,r.thicknessTexture?(r.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,r.thicknessTexture).then(a=>{i.subSurface.thicknessTexture=a,i.subSurface.useGltfStyleTextures=!0})):Promise.resolve()}}Ht.RegisterExtension(BZ,n=>new pHe(n));const FZ="KHR_materials_dispersion";class _He{constructor(e){this.name=FZ,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(FZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return a.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),a.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),a.push(this._loadDispersionPropertiesAsync(r,t,i,s)),Promise.all(a).then(()=>{})})}_loadDispersionPropertiesAsync(e,t,i,r){if(!(i instanceof Nt))throw new Error(`${e}: Material type not supported`);return!i.subSurface.isRefractionEnabled||!r.dispersion||(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=r.dispersion),Promise.resolve()}}Ht.RegisterExtension(FZ,n=>new _He(n));const UZ="KHR_mesh_quantization";class mHe{constructor(e){this.name=UZ,this.enabled=e.isExtensionUsed(UZ)}dispose(){}}Ht.RegisterExtension(UZ,n=>new mHe(n));const kZ="KHR_texture_basisu";class gHe{constructor(e){this.name=kZ,this._loader=e,this.enabled=e.isExtensionUsed(kZ)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=t.sampler==null?Ht.DefaultSampler:wi.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=wi.Get(`${r}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,a,o,c=>{i(c)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)})}}Ht.RegisterExtension(kZ,n=>new gHe(n));const VZ="KHR_texture_transform";class vHe{constructor(e){this.name=VZ,this._loader=e,this.enabled=this._loader.isExtensionUsed(VZ)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>this._loader.loadTextureInfoAsync(e,t,a=>{if(!(a instanceof ve))throw new Error(`${r}: Texture type not supported`);s.offset&&(a.uOffset=s.offset[0],a.vOffset=s.offset[1]),a.uRotationCenter=0,a.vRotationCenter=0,s.rotation&&(a.wAng=-s.rotation),s.scale&&(a.uScale=s.scale[0],a.vScale=s.scale[1]),s.texCoord!=null&&(a.coordinatesIndex=s.texCoord),i(a)}))}}Ht.RegisterExtension(VZ,n=>new vHe(n));const zZ="KHR_xmp_json_ld";class xHe{constructor(e){this.name=zZ,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(zZ)}dispose(){this._loader=null}onLoading(){var i,r,s;if(this._loader.rootBabylonMesh===null)return;const e=(i=this._loader.gltf.extensions)==null?void 0:i.KHR_xmp_json_ld,t=(s=(r=this._loader.gltf.asset)==null?void 0:r.extensions)==null?void 0:s.KHR_xmp_json_ld;if(e&&t){const a=+t.packet;e.packets&&anew xHe(n));function wS(n,e,t,i){return Me.FromArray(e,t).scale(i)}function yHe(n,e,t,i){return e[t+3]*i}function On(n,e,t,i){return e[t]*i}function HZ(n,e,t,i){return-e[t]*i}function lH(n,e,t,i){return e[t+1]*i}function nfe(n,e,t,i){return e[t]*i*2}function IY(n){return{scale:[new fn(ke.ANIMATIONTYPE_FLOAT,`${n}.uScale`,On,()=>2),new fn(ke.ANIMATIONTYPE_FLOAT,`${n}.vScale`,lH,()=>2)],offset:[new fn(ke.ANIMATIONTYPE_FLOAT,`${n}.uOffset`,On,()=>2),new fn(ke.ANIMATIONTYPE_FLOAT,`${n}.vOffset`,lH,()=>2)],rotation:[new fn(ke.ANIMATIONTYPE_FLOAT,`${n}.wAng`,HZ,()=>1)]}}class om extends j9{buildAnimations(e,t,i,r,s){s(e._babylonCamera,this._buildAnimation(t,i,r))}}class fn extends j9{buildAnimations(e,t,i,r,s){for(const a in e._data)s(e._data[a].babylonMaterial,this._buildAnimation(t,i,r))}}class Dw extends j9{buildAnimations(e,t,i,r,s){s(e._babylonLight,this._buildAnimation(t,i,r))}}const AHe={__array__:{__target__:!0,...eD}},CHe={__array__:{__target__:!0,orthographic:{xmag:[new om(ke.ANIMATIONTYPE_FLOAT,"orthoLeft",HZ,()=>1),new om(ke.ANIMATIONTYPE_FLOAT,"orthoRight",lH,()=>1)],ymag:[new om(ke.ANIMATIONTYPE_FLOAT,"orthoBottom",HZ,()=>1),new om(ke.ANIMATIONTYPE_FLOAT,"orthoTop",lH,()=>1)],zfar:[new om(ke.ANIMATIONTYPE_FLOAT,"maxZ",On,()=>1)],znear:[new om(ke.ANIMATIONTYPE_FLOAT,"minZ",On,()=>1)]},perspective:{yfov:[new om(ke.ANIMATIONTYPE_FLOAT,"fov",On,()=>1)],zfar:[new om(ke.ANIMATIONTYPE_FLOAT,"maxZ",On,()=>1)],znear:[new om(ke.ANIMATIONTYPE_FLOAT,"minZ",On,()=>1)]}}},bHe={__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new fn(ke.ANIMATIONTYPE_COLOR3,"albedoColor",wS,()=>4),new fn(ke.ANIMATIONTYPE_FLOAT,"alpha",yHe,()=>4)],metallicFactor:[new fn(ke.ANIMATIONTYPE_FLOAT,"metallic",On,()=>1)],roughnessFactor:[new fn(ke.ANIMATIONTYPE_FLOAT,"roughness",On,()=>1)],baseColorTexture:{extensions:{KHR_texture_transform:IY("albedoTexture")}}},emissiveFactor:[new fn(ke.ANIMATIONTYPE_COLOR3,"emissiveColor",wS,()=>3)],normalTexture:{scale:[new fn(ke.ANIMATIONTYPE_FLOAT,"bumpTexture.level",On,()=>1)]},occlusionTexture:{strength:[new fn(ke.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",On,()=>1)],extensions:{KHR_texture_transform:IY("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:IY("emissiveTexture")}},extensions:{KHR_materials_ior:{ior:[new fn(ke.ANIMATIONTYPE_FLOAT,"indexOfRefraction",On,()=>1)]},KHR_materials_clearcoat:{clearcoatFactor:[new fn(ke.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",On,()=>1)],clearcoatRoughnessFactor:[new fn(ke.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",On,()=>1)]},KHR_materials_sheen:{sheenColorFactor:[new fn(ke.ANIMATIONTYPE_COLOR3,"sheen.color",wS,()=>3)],sheenRoughnessFactor:[new fn(ke.ANIMATIONTYPE_FLOAT,"sheen.roughness",On,()=>1)]},KHR_materials_specular:{specularFactor:[new fn(ke.ANIMATIONTYPE_FLOAT,"metallicF0Factor",On,()=>1)],specularColorFactor:[new fn(ke.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",wS,()=>3)]},KHR_materials_emissive_strength:{emissiveStrength:[new fn(ke.ANIMATIONTYPE_FLOAT,"emissiveIntensity",On,()=>1)]},KHR_materials_transmission:{transmissionFactor:[new fn(ke.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",On,()=>1)]},KHR_materials_volume:{attenuationColor:[new fn(ke.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",wS,()=>3)],attenuationDistance:[new fn(ke.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",On,()=>1)],thicknessFactor:[new fn(ke.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",On,()=>1)]},KHR_materials_dispersion:{dispersion:[new fn(ke.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",On,()=>1)]},KHR_materials_iridescence:{iridescenceFactor:[new fn(ke.ANIMATIONTYPE_FLOAT,"iridescence.intensity",On,()=>1)],iridescenceIor:[new fn(ke.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",On,()=>1)],iridescenceThicknessMinimum:[new fn(ke.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",On,()=>1)],iridescenceThicknessMaximum:[new fn(ke.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",On,()=>1)]},KHR_materials_anisotropy:{anisotropyStrength:[new fn(ke.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",On,()=>1)],anisotropyRotation:[new fn(ke.ANIMATIONTYPE_FLOAT,"anisotropy.angle",On,()=>1)]}}}},EHe={KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new Dw(ke.ANIMATIONTYPE_COLOR3,"diffuse",wS,()=>3)],intensity:[new Dw(ke.ANIMATIONTYPE_FLOAT,"intensity",On,()=>1)],range:[new Dw(ke.ANIMATIONTYPE_FLOAT,"range",On,()=>1)],spot:{innerConeAngle:[new Dw(ke.ANIMATIONTYPE_FLOAT,"innerAngle",nfe,()=>1)],outerConeAngle:[new Dw(ke.ANIMATIONTYPE_FLOAT,"angle",nfe,()=>1)]}}}}},THe={nodes:AHe,materials:bHe,cameras:CHe,extensions:EHe};class fxe{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t=this._gltf,i=this._infoTree,r;if(!e.startsWith("/"))throw new Error("Path must start with a /");const s=e.split("/");s.shift();for(const a of s){if(i.__array__)i=i.__array__;else if(i=i[a],!i)throw new Error(`Path ${e} is invalid`);if(t===void 0)throw new Error(`Path ${e} is invalid`);t=t[a],i.__target__&&(r=t)}return{object:r,info:i}}}const GZ="KHR_animation_pointer";class SHe extends fxe{constructor(e){super(e,THe)}}class MHe{constructor(e){this.name=GZ,this._loader=e,this._pathToObjectConverter=new SHe(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(GZ)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,r,s){var l;const a=(l=r.target.extensions)==null?void 0:l.KHR_animation_pointer;if(!a||!this._pathToObjectConverter)return null;r.target.path!=="pointer"&&de.Warn(`${e}/target/path: Value (${r.target.path}) must be (pointer) when using the ${this.name} extension`),r.target.node!=null&&de.Warn(`${e}/target/node: Value (${r.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,c=a.pointer;if(!c)throw new Error(`${o}: Pointer is missing`);try{const h=this._pathToObjectConverter.convert(c);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,r,h,s)}catch{return de.Warn(`${o}/pointer: Invalid pointer (${c}) skipped`),null}}}Ht.RegisterExtension(GZ,n=>new MHe(n));const KZ="MSFT_audio_emitter";class RHe{constructor(e){this.name=KZ,this._loader=e,this.enabled=this._loader.isExtensionUsed(KZ)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,wi.Assign(this._clips),wi.Assign(this._emitters)}}loadSceneAsync(e,t){return Ht.LoadExtensionAsync(e,t,this.name,(i,r)=>{const s=new Array;s.push(this._loader.loadSceneAsync(e,t));for(const a of r.emitters){const o=wi.Get(`${i}/emitters`,this._emitters,a);if(o.refDistance!=null||o.maxDistance!=null||o.rolloffFactor!=null||o.distanceModel!=null||o.innerAngle!=null||o.outerAngle!=null)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);s.push(this._loadEmitterAsync(`${i}/emitters/${o.index}`,o))}return Promise.all(s).then(()=>{})})}loadNodeAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{const a=new Array;return this._loader.loadNodeAsync(r,t,o=>{for(const c of s.emitters){const l=wi.Get(`${r}/emitters`,this._emitters,c);a.push(this._loadEmitterAsync(`${r}/emitters/${l.index}`,l).then(()=>{for(const h of l._babylonSounds)h.attachToMesh(o),(l.innerAngle!=null||l.outerAngle!=null)&&(h.setLocalDirectionToMesh(P.Forward()),h.setDirectionalCone(2*Ee.ToDegrees(l.innerAngle==null?Math.PI:l.innerAngle),2*Ee.ToDegrees(l.outerAngle==null?Math.PI:l.outerAngle),0))}))}i(o)}).then(o=>Promise.all(a).then(()=>o))})}loadAnimationAsync(e,t){return Ht.LoadExtensionAsync(e,t,this.name,(i,r)=>this._loader.loadAnimationAsync(e,t).then(s=>{const a=new Array;wi.Assign(r.events);for(const o of r.events)a.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,s));return Promise.all(a).then(()=>s)}))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const r=wi.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${r.index}`,r)}return t._objectURL=i.then(r=>URL.createObjectURL(new Blob([r],{type:t.mimeType}))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const i=new Array,r=t.name||`emitter${t.index}`,s={loop:!1,autoplay:!1,volume:t.volume==null?1:t.volume};for(let o=0;o{const u=t._babylonSounds[o]=new wf(r,h,this._loader.babylonScene,null,s);u.refDistance=t.refDistance||1,u.maxDistance=t.maxDistance||256,u.rolloffFactor=t.rolloffFactor||1,u.distanceModel=t.distanceModel||"exponential"}))}const a=Promise.all(i).then(()=>{const o=t.clips.map(l=>l.weight||1),c=new Pme(t.loop||!1,t._babylonSounds,o);t.innerAngle&&(c.directionalConeInnerAngle=2*Ee.ToDegrees(t.innerAngle)),t.outerAngle&&(c.directionalConeOuterAngle=2*Ee.ToDegrees(t.outerAngle)),t.volume&&(c.volume=t.volume),t._babylonData.sound=c});t._babylonData={loaded:a}}return t._babylonData.loaded}_getEventAction(e,t,i,r,s){switch(i){case"play":return a=>{const o=(s||0)+(a-r);t.play(o)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,r,s){if(s.targetedAnimations.length==0)return Promise.resolve();const a=s.targetedAnimations[0],o=r.emitter,c=wi.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,c).then(()=>{const l=c._babylonData.sound;if(l){const h=new rG(r.time,this._getEventAction(e,l,r.action,r.time,r.startOffset));a.animation.addEvent(h),s.onAnimationGroupEndObservable.add(()=>{l.stop()}),s.onAnimationGroupPauseObservable.add(()=>{l.pause()})}})}}Ht.RegisterExtension(KZ,n=>new RHe(n));const WZ="MSFT_lod";class IHe{constructor(e){this.name=WZ,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new Ae,this.onMaterialLODsLoadedObservable=new Ae,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(WZ)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e{e!==0&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())});this._loader._completePromises.push(t)}for(let e=0;e{e!==0&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())});this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return Ht.LoadExtensionAsync(e,t,this.name,(r,s)=>{let a;const o=this._getLODs(r,t,this._loader.gltf.nodes,s.ids);this._loader.logOpen(`${r}`);for(let c=0;c{i(d),d.setEnabled(!1)},u=this._loader.loadNodeAsync(`/nodes/${l.index}`,l,h).then(d=>{if(c!==0){const f=o[c-1];f._babylonTransformNode&&(this._disposeTransformNode(f._babylonTransformNode),delete f._babylonTransformNode)}return d.setEnabled(!0),d});this._nodePromiseLODs[c]=this._nodePromiseLODs[c]||[],c===0?a=u:(this._nodeIndexLOD=null,this._nodePromiseLODs[c].push(u))}return this._loader.logClose(),a})}_loadMaterialAsync(e,t,i,r,s){return this._nodeIndexLOD?null:Ht.LoadExtensionAsync(e,t,this.name,(a,o)=>{let c;const l=this._getLODs(a,t,this._loader.gltf.materials,o.ids);this._loader.logOpen(`${a}`);for(let h=0;h{h===0&&s(f)}).then(f=>{if(h!==0){s(f);const p=l[h-1]._data;p[r]&&(this._disposeMaterials([p[r].babylonMaterial]),delete p[r])}return f});this._materialPromiseLODs[h]=this._materialPromiseLODs[h]||[],h===0?c=d:(this._materialIndexLOD=null,this._materialPromiseLODs[h].push(d))}return this._loader.logClose(),c})}_loadUriAsync(e,t,i){if(this._nodeIndexLOD!==null){this._loader.log("deferred");const r=this._nodeIndexLOD-1;return this._nodeSignalLODs[r]=this._nodeSignalLODs[r]||new FS,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(()=>this._loader.loadUriAsync(e,t,i))}else if(this._materialIndexLOD!==null){this._loader.log("deferred");const r=this._materialIndexLOD-1;return this._materialSignalLODs[r]=this._materialSignalLODs[r]||new FS,this._materialSignalLODs[r].promise.then(()=>this._loader.loadUriAsync(e,t,i))}return null}loadBufferAsync(e,t,i,r){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const s=(a,o)=>{const c=i,l=c+r-1;let h=a[o];return h?(h.start=Math.min(h.start,c),h.end=Math.max(h.end,l)):(h={start:c,end:l,loaded:new FS},a[o]=h),h.loaded.promise.then(u=>new Uint8Array(u.buffer,u.byteOffset+i-h.start,r))};return this._loader.log("deferred"),this._nodeIndexLOD!==null?s(this._nodeBufferLODs,this._nodeIndexLOD):this._materialIndexLOD!==null?s(this._materialBufferLODs,this._materialIndexLOD):s(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then(r=>{i.loaded.resolve(r)},r=>{i.loaded.reject(r)}))}_getLODs(e,t,i,r){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const s=[];for(let a=r.length-1;a>=0;a--)if(s.push(wi.Get(`${e}/ids/${r[a]}`,i,r[a])),s.length===this.maxLODsToLoad)return s;return s.push(t),s}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const s of e.getChildMeshes())s.material&&t.push(s.material);e.dispose();const r=t.filter(s=>this._loader.babylonScene.meshes.every(a=>a.material!=s));this._disposeMaterials(r)}_disposeMaterials(e){const t={};for(const i of e){for(const r of i.getActiveTextures())t[r.uniqueId]=r;i.dispose()}for(const i in t)for(const r of this._loader.babylonScene.materials)r.hasTexture(t[i])&&delete t[i];for(const i in t)t[i].dispose()}}Ht.RegisterExtension(WZ,n=>new IHe(n));const jZ="MSFT_minecraftMesh";class PHe{constructor(e){this.name=jZ,this._loader=e,this.enabled=this._loader.isExtensionUsed(jZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtraAsync(e,t,this.name,(r,s)=>{if(s){if(!(i instanceof Nt))throw new Error(`${r}: Material type not supported`);const a=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,a}return null})}}Ht.RegisterExtension(jZ,n=>new PHe(n));const XZ="MSFT_sRGBFactors";class wHe{constructor(e){this.name=XZ,this._loader=e,this.enabled=this._loader.isExtensionUsed(XZ)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ht.LoadExtraAsync(e,t,this.name,(r,s)=>{if(s){if(!(i instanceof Nt))throw new Error(`${r}: Material type not supported`);const a=this._loader.loadMaterialPropertiesAsync(e,t,i),o=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,o),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,o),a}return null})}}Ht.RegisterExtension(XZ,n=>new wHe(n));const DHe={"lifecycle/onStart":Z5.ClassName,"lifecycle/onTick":L6.ClassName,log:dA.ClassName,"flow/delay":Q5.ClassName,"customEvent/send":Y5.ClassName,"customEvent/receive":O6.ClassName,"flow/sequence":mA.ClassName,"world/get":vA.ClassName,"world/set":X5.ClassName,"flow/doN":pA.ClassName,"variable/get":gA.ClassName,"variable/set":fA.ClassName,"flow/whileLoop":_A.ClassName,"math/random":bA.ClassName,"math/e":TA.ClassName,"math/pi":SA.ClassName,"math/inf":MA.ClassName,"math/nan":RA.ClassName,"math/abs":IA.ClassName,"math/sign":PA.ClassName,"math/trunc":wA.ClassName,"math/floor":DA.ClassName,"math/ceil":OA.ClassName,"math/fract":LA.ClassName,"math/neg":NA.ClassName,"math/add":xA.ClassName,"math/sub":yA.ClassName,"math/mul":AA.ClassName,"math/div":CA.ClassName,"math/rem":BA.ClassName,"math/min":FA.ClassName,"math/max":UA.ClassName,"math/clamp":kA.ClassName,"math/saturate":VA.ClassName,"math/mix":zA.ClassName,"math/eq":HA.ClassName,"math/lt":GA.ClassName,"math/le":K9.ClassName,"math/gt":KA.ClassName,"math/ge":WA.ClassName,"math/isnan":jA.ClassName,"math/isinf":W9.ClassName,"math/rad":XA.ClassName,"math/deg":YA.ClassName,"math/sin":QA.ClassName,"math/cos":$A.ClassName,"math/tan":ZA.ClassName,"math/asin":qA.ClassName,"math/acos":JA.ClassName,"math/atan":e6.ClassName,"math/atan2":t6.ClassName,"math/sinh":i6.ClassName,"math/cosh":r6.ClassName,"math/tanh":s6.ClassName,"math/asinh":n6.ClassName,"math/acosh":a6.ClassName,"math/atanh":o6.ClassName,"math/exp":l6.ClassName,"math/log":c6.ClassName,"math/log2":h6.ClassName,"math/log10":u6.ClassName,"math/sqrt":d6.ClassName,"math/cbrt":f6.ClassName,"math/pow":p6.ClassName,"math/length":_6.ClassName,"math/normalize":m6.ClassName,"math/dot":EA.ClassName,"math/cross":g6.ClassName,"math/rotate2d":v6.ClassName,"math/rotate3d":x6.ClassName,"math/transpose":y6.ClassName,"math/determinant":A6.ClassName,"math/inverse":C6.ClassName,"math/matmul":b6.ClassName,"math/not":E6.ClassName,"math/and":T6.ClassName,"math/or":S6.ClassName,"math/xor":M6.ClassName,"math/asr":I6.ClassName,"math/lsl":R6.ClassName,"math/clz":P6.ClassName,"math/ctz":w6.ClassName,"math/popcnt":D6.ClassName},OHe={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function YZ(n,e,t){if(n.type!==void 0){const i=e.types&&e.types[n.type];if(!i)throw new Error(`${t}: Unknown type: ${n.type}`);const r=i.signature;if(!r)throw new Error(`${t}: Type ${n.type} has no signature`);const s=OHe[r];return{value:n.value,className:s}}else return n.value}function LHe(n,e,t){const i={},r=n.configuration??[];for(const s of r)if(s.id==="customEvent"){const a=e.customEvents&&e.customEvents[s.value];if(!a)throw new Error(`/extensions/KHR_interactivity/nodes/${t}: Unknown custom event: ${s.value}`);i.eventId=a.id,i.eventData=a.values.map(o=>o.id)}else if(s.id==="variable"){const a=e.variables&&e.variables[s.value];if(!a)throw new Error(`/extensions/KHR_interactivity/nodes/${t}: Unknown variable: ${s.value}`);i.variableName=a.id}else if(s.id==="path"){const a=s.value;i.path=a}else i[s.id]=YZ(s,e,`/extensions/KHR_interactivity/nodes/${t}`);return i}function NHe(n,e,t){const i=DHe[e.type];if(!i)throw new Error(`/extensions/KHR_interactivity/nodes/${n}: Unknown block type: ${e.type}`);const r=n.toString(),s=LHe(e,t,r),a=e.metadata;return{className:i,config:s,uniqueId:r,metadata:a,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}function BHe(n){const e={uniqueId:mh(),_userVariables:{},_connectionValues:{}},t=[e],i=[];for(let s=0;sg.name===p);m||(m={uniqueId:mh(),name:p,_connectionType:Qh.Input,connectedPointIds:[]},_.signalInputs.push(m)),m.connectedPointIds.push(d.uniqueId),d.connectedPointIds.push(m.uniqueId)}const l=a.values??[];for(const h of l){const u=h.id,d={uniqueId:mh(),name:u,_connectionType:Qh.Input,connectedPointIds:[]};if(o.dataInputs.push(d),h.value!==void 0){const f=YZ(h,n,`/extensions/KHR_interactivity/nodes/${s}`);e._connectionValues[d.uniqueId]=f}else if(h.node!==void 0&&h.socket!==void 0){const f=h.node,p=h.socket,_=i[f];if(!_)throw new Error(`/extensions/KHR_interactivity/nodes/${s}: Could not find node with id ${f} that connects its output with node${s}'s input ${u}`);let m=_.dataOutputs.find(g=>g.name===p);m||(m={uniqueId:mh(),name:p,_connectionType:Qh.Output,connectedPointIds:[]},_.dataOutputs.push(m)),d.connectedPointIds.push(m.uniqueId),m.connectedPointIds.push(d.uniqueId)}else throw new Error(`/extensions/KHR_interactivity/nodes/${s}: Invalid socket ${u} in node ${s}`)}}const r=n.variables??[];for(let s=0;sn._babylonTransformNode.position,set:(n,e)=>{const t=e._babylonTransformNode;t.position=n},getObject(n){return n._babylonTransformNode}}}},kHe={nodes:UHe},QZ="KHR_interactivity";class VHe{constructor(e){this._loader=e,this.name=QZ,this.enabled=this._loader.isExtensionUsed(QZ),this._pathConverter=new FHe(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){var s;if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=(s=this._loader.gltf.extensions)==null?void 0:s.KHR_interactivity,i=BHe(t),r=new Ky({scene:e});uA.Parse(i,{coordinator:r,pathConverter:this._pathConverter}),r.start()}}Ht.RegisterExtension(QZ,n=>new VHe(n));const pxe="ExtrasAsMetadata";class zHe{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{},r=i.gltf=i.gltf||{};r.extras=t.extras}}constructor(e){this.name=pxe,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,r=>{this._assignExtras(r,t),i(r)})}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,r=>{this._assignExtras(r,t),i(r)})}createMaterial(e,t,i){const r=this._loader.createMaterial(e,t,i);return this._assignExtras(r,t),r}}Ht.RegisterExtension(pxe,n=>new zHe(n));class Kp{constructor(){this.materials=[]}parseMTL(e,t,i,r){if(t instanceof ArrayBuffer)return;const s=t.split(` `),a=/\s+/;let o,c=null;for(let l=0;l=0?h.substring(0,u):h;d=d.toLowerCase();const f=u>=0?h.substring(u+1).trim():"";if(d==="newmtl")c&&this.materials.push(c),e._blockEntityCollection=!!r,c=new tt(f,e),c._parentContainer=r,e._blockEntityCollection=!1;else if(d==="kd"&&c)o=f.split(a,3).map(parseFloat),c.diffuseColor=Me.FromArray(o);else if(d==="ka"&&c)o=f.split(a,3).map(parseFloat),c.ambientColor=Me.FromArray(o);else if(d==="ks"&&c)o=f.split(a,3).map(parseFloat),c.specularColor=Me.FromArray(o);else if(d==="ke"&&c)o=f.split(a,3).map(parseFloat),c.emissiveColor=Me.FromArray(o);else if(d==="ns"&&c)c.specularPower=parseFloat(f);else if(d==="d"&&c)c.alpha=parseFloat(f);else if(d==="map_ka"&&c)c.ambientTexture=Kp._GetTexture(i,f,e);else if(d==="map_kd"&&c)c.diffuseTexture=Kp._GetTexture(i,f,e);else if(d==="map_ks"&&c)c.specularTexture=Kp._GetTexture(i,f,e);else if(d!=="map_ns")if(d==="map_bump"&&c){const p=f.split(a),_=p.indexOf("-bm");let m=null;_>=0&&(m=p[_+1],p.splice(_,2)),c.bumpTexture=Kp._GetTexture(i,p.join(" "),e),c.bumpTexture&&m!==null&&(c.bumpTexture.level=parseFloat(m))}else d==="map_d"&&c&&(c.opacityTexture=Kp._GetTexture(i,f,e))}c&&this.materials.push(c)}static _GetTexture(e,t,i){if(!t)return null;let r=e;if(e==="file:"){let s=t.lastIndexOf("\\");s===-1&&(s=t.lastIndexOf("/")),s>-1?r+=t.substr(s+1):r+=t}else r+=t;return new ve(r,i,!1,Kp.INVERT_TEXTURE_Y)}}Kp.INVERT_TEXTURE_Y=!0;class Fs{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new Ze(.5,.5,.5,1),this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const i=e[t[0]].normals.indexOf(t[1]);return i===-1?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const i=e[t[0]].normals.indexOf(t[1]);return i!=1&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,r,s,a,o){let c;this._loadingOptions.optimizeWithUV?c=this._isInArrayUV(this._tuplePosNorm,[e,i,t]):c=this._isInArray(this._tuplePosNorm,[e,i]),c===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(r),this._wrappedUvsForBabylon.push(s),this._wrappedNormalsForBabylon.push(a),o!==void 0&&this._wrappedColorsForBabylon.push(o),this._tuplePosNorm[e].normals.push(i),this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e].uv.push(t)):this._indicesForBabylon.push(c)}_unwrapData(){for(let e=0;e0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0)}_optimizeNormals(e){const t=e.getVerticesData(Z.PositionKind),i=e.getVerticesData(Z.NormalKind),r={};if(!t||!i)return;for(let a=0;a=7){const u=parseFloat(h[4]),d=parseFloat(h[5]),f=parseFloat(h[6]);this._colors.push(new Ze(u>1?u/255:u,d>1?d/255:d,f>1?f/255:f,h.length===7||h[7]===void 0?1:parseFloat(h[7])))}else this._colors.push(this._grayColor)}else if((h=Fs.NormalPattern.exec(l))!==null)this._normals.push(new P(parseFloat(h[1]),parseFloat(h[2]),parseFloat(h[3])));else if((h=Fs.UVPattern.exec(l))!==null)this._uvs.push(new Be(parseFloat(h[1])*this._loadingOptions.UVScaling.x,parseFloat(h[2])*this._loadingOptions.UVScaling.y));else if((h=Fs.FacePattern3.exec(l))!==null)this._setDataForCurrentFaceWithPattern3(h[1].trim().split(" "),1);else if((h=Fs.FacePattern4.exec(l))!==null)this._setDataForCurrentFaceWithPattern4(h[1].trim().split(" "),1);else if((h=Fs.FacePattern5.exec(l))!==null)this._setDataForCurrentFaceWithPattern5(h[1].trim().split(" "),1);else if((h=Fs.FacePattern2.exec(l))!==null)this._setDataForCurrentFaceWithPattern2(h[1].trim().split(" "),1);else if((h=Fs.FacePattern1.exec(l))!==null)this._setDataForCurrentFaceWithPattern1(h[1].trim().split(" "),1);else if((h=Fs.LinePattern1.exec(l))!==null)this._setDataForCurrentFaceWithPattern1(h[1].trim().split(" "),0);else if((h=Fs.LinePattern2.exec(l))!==null)this._setDataForCurrentFaceWithPattern2(h[1].trim().split(" "),0);else if((h=Fs.LinePattern3.exec(l))!==null)this._setDataForCurrentFaceWithPattern3(h[1].trim().split(" "),0);else if(Fs.GroupDescriptor.test(l)||Fs.ObjectDescriptor.test(l)){const u={name:l.substring(2).trim(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:this._materialNameFromObj,isObject:Fs.ObjectDescriptor.test(l)};this._addPreviousObjMesh(),this._meshesFromObj.push(u),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(Fs.UseMtlDescriptor.test(l)){if(this._materialNameFromObj=l.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const u={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(u),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else Fs.MtlLibGroupDescriptor.test(l)?s(l.substring(7).trim()):Fs.SmoothDescriptor.test(l)||de.Log("Unhandled expression at line : "+l)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let c=null;if(this._indicesForBabylon.length)this._indicesForBabylon.reverse(),this._unwrapData();else{for(const l of this._positions)this._unwrappedPositionsForBabylon.push(l.x,l.y,l.z);if(this._normals.length)for(const l of this._normals)this._unwrappedNormalsForBabylon.push(l.x,l.y,l.z);if(this._uvs.length)for(const l of this._uvs)this._unwrappedUVForBabylon.push(l.x,l.y);if(this._colors.length)for(const l of this._colors)this._unwrappedColorsForBabylon.push(l.r,l.g,l.b,l.a);this._materialNameFromObj||(c=new tt(Ua.RandomId(),i),c.pointsCloud=!0,this._materialNameFromObj=c.name,this._normals.length||(c.disableLighting=!0,c.emissiveColor=Me.White()))}this._meshesFromObj.push({name:Ua.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:c,isObject:!0})}for(let c=0;c=0;--u)if(this._meshesFromObj[u].isObject&&this._meshesFromObj[u]._babylonMesh){l.parent=this._meshesFromObj[u]._babylonMesh;break}}if(this._materialToUse.push(this._meshesFromObj[c].materialName),((o=this._handledMesh.positions)==null?void 0:o.length)===0){this._babylonMeshesArray.push(l);continue}const h=new et;if(h.uvs=this._handledMesh.uvs,h.indices=this._handledMesh.indices,h.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const u=new Array;et.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,u),h.normals=u}else h.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(h.colors=this._handledMesh.colors),h.applyToMesh(l),this._loadingOptions.invertY&&(l.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(l),this._babylonMeshesArray.push(l),this._handledMesh.directMaterial&&(l.material=this._handledMesh.directMaterial)}}}Fs.ObjectDescriptor=/^o/;Fs.GroupDescriptor=/^g/;Fs.MtlLibGroupDescriptor=/^mtllib /;Fs.UseMtlDescriptor=/^usemtl /;Fs.SmoothDescriptor=/^s /;Fs.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/;Fs.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Fs.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Fs.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/;Fs.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Fs.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Fs.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;Fs.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;Fs.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/;Fs.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;Fs.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class Vo{static get INVERT_TEXTURE_Y(){return Kp.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){Kp.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||Vo._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:Vo.COMPUTE_NORMALS,optimizeNormals:Vo.OPTIMIZE_NORMALS,importVertexColors:Vo.IMPORT_VERTEX_COLORS,invertY:Vo.INVERT_Y,invertTextureY:Vo.INVERT_TEXTURE_Y,UVScaling:Vo.UV_SCALING,materialLoadingFailsSilently:Vo.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:Vo.OPTIMIZE_WITH_UV,skipMaterials:Vo.SKIP_MATERIALS}}_loadMTL(e,t,i,r){const s=t+e;Ee.LoadFile(s,i,void 0,void 0,!1,(a,o)=>{r(s,o)})}createPlugin(){return new Vo(Vo._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,r){return this._parseSolid(e,t,i,r).then(s=>({meshes:s,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then(()=>{})}loadAssetContainerAsync(e,t,i){const r=new jO(e);return this._assetContainer=r,this.importMeshAsync(null,e,t,i).then(s=>(s.meshes.forEach(a=>r.meshes.push(a)),s.meshes.forEach(a=>{const o=a.material;o&&r.materials.indexOf(o)==-1&&(r.materials.push(o),o.getActiveTextures().forEach(l=>{r.textures.indexOf(l)==-1&&r.textures.push(l)}))}),this._assetContainer=null,r)).catch(s=>{throw this._assetContainer=null,s})}_parseSolid(e,t,i,r){let s="";const a=new Kp,o=[],c=[];new Fs(o,c,this._loadingOptions).parse(e,i,t,this._assetContainer,u=>{s=u});const h=[];return s!==""&&!this._loadingOptions.skipMaterials&&h.push(new Promise((u,d)=>{this._loadMTL(s,r,f=>{try{a.parseMTL(t,f,r,this._assetContainer);for(let p=0;p-1;)m.push(g),_=g+1;if(g===-1&&m.length===0)a.materials[p].dispose();else for(let v=0;v{Ee.Warn(`Error downloading MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?u():d(p)})})),Promise.all(h).then(()=>c)}}Vo.OPTIMIZE_WITH_UV=!0;Vo.INVERT_Y=!1;Vo.IMPORT_VERTEX_COLORS=!1;Vo.COMPUTE_NORMALS=!1;Vo.OPTIMIZE_NORMALS=!1;Vo.UV_SCALING=new Be(1,1);Vo.SKIP_MATERIALS=!1;Vo.MATERIAL_LOADING_FAILS_SILENTLY=!0;ai&&ai.RegisterPlugin(new Vo);class N3{constructor(){this.solidPattern=/solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,this.normalPattern=/normal[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.vertexPattern=/vertex[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.name="stl",this.extensions={".stl":{isBinary:!0}}}importMesh(e,t,i,r,s){let a;if(typeof i!="string"){if(this._isBinary(i)){const o=new Se("stlmesh",t);return this._parseBinary(o,i),s&&s.push(o),!0}i=new TextDecoder().decode(new Uint8Array(i))}for(;a=this.solidPattern.exec(i);){let o=a[1];const c=a[3];if(c&&o!=c)return Ee.Error("Error in STL, solid name != endsolid name"),!1;if(e&&o){if(e instanceof Array){if(!e.indexOf(o))continue}else if(o!==e)continue}o=o||"stlmesh";const l=new Se(o,t);this._parseASCII(l,a[2]),s&&s.push(l)}return!0}load(e,t,i){return this.importMesh(null,e,t,i,null)}loadAssetContainer(e,t,i){const r=new jO(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,i,r.meshes),e._blockEntityCollection=!1,r}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;const i=32/8*3+32/8*3*3+16/8,r=t.getUint32(80,!0);if(80+32/8+r*i===t.byteLength)return!0;const s=[115,111,108,105,100];for(let a=0;a<5;a++)if(t.getUint8(a)!==s[a])return!0;return!1}_parseBinary(e,t){const i=new DataView(t),r=i.getUint32(80,!0),s=84,a=12*4+2;let o=0;const c=new Float32Array(r*3*3),l=new Float32Array(r*3*3),h=new Uint32Array(r*3);let u=0;for(let d=0;d(n[n.String=0]="String",n[n.Number=1]="Number",n[n.Boolean=2]="Boolean",n))(la||{}),X9=(n=>(n[n.Value=0]="Value",n[n.DynamicData=1]="DynamicData",n))(X9||{}),j0=(n=>(n.None="None",n.PX_PY_PZ="PX_PY_PZ",n.PX_CY_PZ="PX_CY_PZ",n.PX_NY_PZ="PX_NY_PZ",n.PX_PY_CZ="PX_PY_CZ",n.PX_PY_NZ="PX_PY_NZ",n.PX_CY_CZ="PX_CY_CZ",n.PX_CY_NZ="PX_CY_NZ",n.PX_NY_CZ="PX_NY_CZ",n.PX_NY_NZ="PX_NY_NZ",n.CX_PY_PZ="CX_PY_PZ",n.CX_CY_PZ="CX_CY_PZ",n.CX_NY_PZ="CX_NY_PZ",n.CX_PY_CZ="CX_PY_CZ",n.CX_PY_NZ="CX_PY_NZ",n.CX_CY_CZ="CX_CY_CZ",n.CX_CY_NZ="CX_CY_NZ",n.CX_NY_CZ="CX_NY_CZ",n.CX_NY_NZ="CX_NY_NZ",n.NX_PY_PZ="NX_PY_PZ",n.NX_CY_PZ="NX_CY_PZ",n.NX_NY_PZ="NX_NY_PZ",n.NX_PY_CZ="NX_PY_CZ",n.NX_PY_NZ="NX_PY_NZ",n.NX_CY_CZ="NX_CY_CZ",n.NX_CY_NZ="NX_CY_NZ",n.NX_NY_CZ="NX_NY_CZ",n.NX_NY_NZ="NX_NY_NZ",n))(j0||{});const c_="le5le",HHe=c_+"_arcRotateCamera",GHe=c_+"_arcRotateCamera",KHe=c_+"_highlight",PY=c_+"_skybox",WHe=c_+"_ground",jHe=c_+"_placeholder",XHe=c_+"_targetMesh",YHe=c_+"_selectorMesh";var q=(n=>(n[n.Number=0]="Number",n[n.Vector3=1]="Vector3",n[n.Quaternion=2]="Quaternion",n[n.Matrix=3]="Matrix",n[n.Color3=4]="Color3",n[n.Vector2=5]="Vector2",n[n.Size=6]="Size",n[n.Color4=7]="Color4",n[n.String=8]="String",n[n.Boolean=9]="Boolean",n[n.Null=10]="Null",n[n.Void=11]="Void",n[n.Unknown=12]="Unknown",n[n.Texture=13]="Texture",n[n.VideoTexture=14]="VideoTexture",n[n.CubeTexture=15]="CubeTexture",n[n.StandardMaterial=16]="StandardMaterial",n[n.PBRMaterial=17]="PBRMaterial",n[n.GradientMaterial=18]="GradientMaterial",n[n.Object=19]="Object",n[n.Array=20]="Array",n[n.GridMaterial=21]="GridMaterial",n[n.Vector4=23]="Vector4",n[n.ShaderMaterial=24]="ShaderMaterial",n[n.NodeMaterial=25]="NodeMaterial",n[n.MirrorTexture=26]="MirrorTexture",n[n.WaterMaterial=27]="WaterMaterial",n[n.CityMaterial=28]="CityMaterial",n[n.Scene=1e3]="Scene",n[n.TransformNode=1001]="TransformNode",n[n.AbstractMesh=1002]="AbstractMesh",n[n.Mesh=1003]="Mesh",n[n.InstancedMesh=1004]="InstancedMesh",n[n.PointLight=1005]="PointLight",n[n.SpotLight=1006]="SpotLight",n[n.HemisphericLight=1007]="HemisphericLight",n[n.DirectionalLight=1008]="DirectionalLight",n[n.ArcRotateCamera=1009]="ArcRotateCamera",n[n.FollowCamera=1010]="FollowCamera",n[n.FreeCamera=1011]="FreeCamera",n[n.OrthographicCamera=1012]="OrthographicCamera",n))(q||{});function Nm(n,e=t=>{}){try{n&&n()}catch(t){console.error(t),e(t)}}function Ki(n){return`${n||""}${Ee.RandomId()}`}const QHe=n=>Object.prototype.toString.call(n)==="[object Number]",$He=n=>Object.prototype.toString.call(n)==="[object String]",ZHe=n=>Object.prototype.toString.call(n)==="[object Boolean]",$Z=n=>Object.prototype.toString.call(n)==="[object Array]",Bf=n=>Object.prototype.toString.call(n)==="[object Object]",Op=(n,e)=>{const t={[la.Boolean]:"boolean",[la.Number]:"number",[la.String]:"string"}[e];if(typeof n===t)return n;if(t==="boolean")return!!n;if(t==="number"){let i=Number(n);return!isNaN(i)||(i=parseFloat(n),!isNaN(i))?i:0}if(t==="string")return n==null?"":String(n)},qHe=(n,e)=>{if(e===q.Array)return $Z(n)?n:[];if(e===q.Object)return Bf(n)?n:{};if(e===q.String)return $He(n)?n:n==null?"":String(n);if(e===q.Number)return QHe(n)&&!isNaN(n)||(n=Number(n),!isNaN(n))||(n=parseFloat(n),!isNaN(n))?n:0;if(e===q.Boolean)return ZHe(n)?n:!1},JHe=n=>({string:la.String,integer:la.Number,float:la.Number,bool:la.Boolean})[n]||la.String;var _xe=typeof global=="object"&&global&&global.Object===Object&&global,eGe=typeof self=="object"&&self&&self.Object===Object&&self,m1=_xe||eGe||Function("return this")(),n4=m1.Symbol,mxe=Object.prototype,tGe=mxe.hasOwnProperty,iGe=mxe.toString,Ow=n4?n4.toStringTag:void 0;function rGe(n){var e=tGe.call(n,Ow),t=n[Ow];try{n[Ow]=void 0;var i=!0}catch{}var r=iGe.call(n);return i&&(e?n[Ow]=t:delete n[Ow]),r}var sGe=Object.prototype,nGe=sGe.toString;function aGe(n){return nGe.call(n)}var oGe="[object Null]",lGe="[object Undefined]",afe=n4?n4.toStringTag:void 0;function q5(n){return n==null?n===void 0?lGe:oGe:afe&&afe in Object(n)?rGe(n):aGe(n)}function J5(n){return n!=null&&typeof n=="object"}var cGe="[object Symbol]";function gxe(n){return typeof n=="symbol"||J5(n)&&q5(n)==cGe}function hGe(n,e){for(var t=-1,i=n==null?0:n.length,r=Array(i);++t-1&&n%1==0&&n-1&&n%1==0&&n<=XGe}function Txe(n){return n!=null&&Exe(n.length)&&!yxe(n)}var YGe=Object.prototype;function Xte(n){var e=n&&n.constructor,t=typeof e=="function"&&e.prototype||YGe;return n===t}function QGe(n,e){for(var t=-1,i=Array(n);++t-1}function rWe(n,e){var t=this.__data__,i=SK(t,n);return i<0?(++this.size,t.push([n,e])):t[i][1]=e,this}function x2(n){var e=-1,t=n==null?0:n.length;for(this.clear();++e(n.Grad="Grad",n.OutLine="OutLine",n))(Pc||{});function Yje(n,e){bi.ShadersStore[n+"VertexShader"]=`\r precision highp float;\r //attribute\r attribute vec3 position;\r attribute vec2 uv;\r attribute vec3 normal;\r //uniform\r uniform mat4 worldViewProjection;\r //varying\r varying vec3 vPosition;\r varying vec2 vUV;\r varying vec3 vNormal;\r void main(void) {\r gl_Position = worldViewProjection*vec4(position,1.0);\r vPosition = position;\r vUV = uv;\r vNormal = normal;\r }\r `,bi.ShadersStore[n+"FragmentShader"]=`\r precision highp float;\r varying vec3 vPosition;\r varying vec3 vNormal;\r uniform float distance;\r uniform vec3 changeColor;\r uniform vec3 center;\r uniform float power;\r uniform float k;\r uniform vec3 viewPoint;\r float distanceTwoVec3(vec3 p1,vec3 p2){\r float d = sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)+(p1.z-p2.z)*(p1.z-p2.z));\r return d;\r }\r void main(void) {\r float modelDot = abs(dot(viewPoint,vNormal)/(length(viewPoint)*length(vNormal)));\r float alpha = distanceTwoVec3(center,vPosition)*k /distance;\r vec3 color = changeColor;\r alpha = modelDot * pow(alpha,power);\r gl_FragColor = vec4(color,alpha);\r }\r `;let t=new kn("effectGlShader"+n,e,{vertex:n,fragment:n},{attributes:["normal","position","uv"],uniforms:["world","worldView","worldViewProjection","view","projection"],needAlphaBlending:!0,needAlphaTesting:!0});return t.onBind=i=>{const r=i.getBoundingInfo().boundingBox,s=P.Normalize(r.centerWorld),a=P.Distance(r.centerWorld,r.maximumWorld);t.setFloat("distance",a),t.setVector3("center",s),t.setVector3("viewPoint",P.Normalize(i.getScene().activeCamera.position)),t.onBind=null},t.setFloat("distance",20),t.setVector3("center",new P(10,10*Math.random(),10)),t.setVector3("viewPoint",new P(10,10*Math.random(),10)),t}function Qje(n,e){return bi.ShadersStore["gradient"+n+"VertexShader"]=`\r precision highp float;\r //attribute\r attribute vec3 position;\r attribute vec2 uv;\r attribute vec3 normal;\r //uniform\r uniform mat4 worldViewProjection;\r //varying\r varying vec3 vPosition;\r varying vec2 vUV;\r varying vec3 vNormal;\r void main(void) {\r gl_Position = worldViewProjection*vec4(position,1.0);\r vPosition = position;\r vUV = uv;\r vNormal = normal;\r }\r `,bi.ShadersStore["gradient"+n+"FragmentShader"]=`\r precision highp float;\r varying vec3 vPosition;\r float distanceTwoVec3(vec3 p1,vec3 p2){\r float d = sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)+(p1.z-p2.z)*(p1.z-p2.z));\r return d;\r }\r uniform vec3 mainColor;\r uniform float maxHeight;\r uniform float minHeight;\r uniform float alphaK;\r void main(void) {\r float height = maxHeight - minHeight;\r vec3 color = mainColor;\r float alpha = (vPosition.y-minHeight)/height;\r gl_FragColor = vec4(color,alphaK+pow(alpha,0.5)*alpha*(1.0-alphaK));\r }\r `,new kn("effectGradAlpha"+n,e,{vertex:"gradient"+n,fragment:"gradient"+n},{attributes:["normal","position","uv"],uniforms:["world","worldView","worldViewProjection","view","projection"],needAlphaBlending:!0,needAlphaTesting:!0})}var zxe={exports:{}};const $je=c0e(bze);(function(n,e){(function(i,r){n.exports=r($je)})(typeof self<"u"?self:kt,t=>(()=>{var i={"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../dev/sharedUiComponents/dist/colorPicker/colorPicker.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.color-picker-container { width: 320px; height: 300px; background-color: white; display: grid; grid-template-columns: 100%; grid-template-rows: 50% 50px 60px 40px 1fr auto; font-family: "acumin-pro-condensed"; font-weight: normal; font-size: 14px; } .color-picker-container.with-hints { height: 380px; } .color-picker-container .color-picker-saturation { grid-row: 1; grid-column: 1; display: grid; grid-template-columns: 100%; grid-template-rows: 100%; position: relative; cursor: pointer; } .color-picker-container .color-picker-saturation .color-picker-saturation-white { grid-row: 1; grid-column: 1; background: -webkit-linear-gradient(to right, #fff, rgba(255, 255, 255, 0)); background: linear-gradient(to right, #fff, rgba(255, 255, 255, 0)); } .color-picker-container .color-picker-saturation .color-picker-saturation-black { grid-row: 1; grid-column: 1; background: -webkit-linear-gradient(to top, #000, rgba(0, 0, 0, 0)); background: linear-gradient(to top, #000, rgba(0, 0, 0, 0)); } .color-picker-container .color-picker-saturation .color-picker-saturation-cursor { pointer-events: none; width: 4px; height: 4px; box-shadow: 0 0 0 1.5px #fff, inset 0 0 1px 1px rgba(0, 0, 0, 0.3), 0 0 1px 2px rgba(0, 0, 0, 0.4); border-radius: 50%; transform: translate(-2px, -2px); position: absolute; } .color-picker-container .color-picker-hue { grid-row: 2; grid-column: 1; display: grid; margin: 10px; grid-template-columns: 24% 76%; grid-template-rows: 100%; } .color-picker-container .color-picker-hue .color-picker-hue-color { grid-row: 1; grid-column: 1; align-self: center; justify-self: center; width: 30px; height: 30px; border-radius: 15px; border: 1px solid black; } .color-picker-container .color-picker-hue .color-picker-hue-slider { grid-row: 1; grid-column: 2; align-self: center; height: 16px; position: relative; cursor: pointer; background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%); background: -webkit-linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%); } .color-picker-container .color-picker-hue .color-picker-hue-slider .color-picker-hue-cursor { pointer-events: none; width: 8px; height: 18px; transform: translate(-4px, -2px); background-color: rgb(248, 248, 248); box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.37); position: absolute; } .color-picker-container .color-picker-component { display: grid; margin: 5px; grid-template-columns: 100%; grid-template-rows: 50% 50%; } .color-picker-container .color-picker-component .color-picker-component-value { justify-self: center; align-self: center; grid-row: 1; grid-column: 1; margin-bottom: 4px; } .color-picker-container .color-picker-component .color-picker-component-value input { width: 50px; } .color-picker-container .color-picker-component .color-picker-component-label { justify-self: center; align-self: center; grid-row: 2; grid-column: 1; color: black; } .color-picker-container .color-picker-rgb { grid-row: 3; grid-column: 1; display: grid; margin: 10px; grid-template-columns: 20% 6.66% 20% 6.66% 20% 6.66% 20%; grid-template-rows: 100%; } .color-picker-container .red { grid-row: 1; grid-column: 1; } .color-picker-container .green { grid-row: 1; grid-column: 3; } .color-picker-container .blue { grid-row: 1; grid-column: 5; } .color-picker-container .alpha { grid-row: 1; grid-column: 7; } .color-picker-container .alpha.grayed { opacity: 0.5; } .color-picker-container .color-picker-hex { grid-row: 4; grid-column: 1; display: grid; grid-template-columns: 20% 80%; grid-template-rows: 100%; } .color-picker-container .color-picker-hex .color-picker-hex-label { justify-self: center; align-self: center; grid-row: 1; grid-column: 1; margin-left: 10px; color: black; } .color-picker-container .color-picker-hex .color-picker-hex-value { justify-self: left; align-self: center; grid-row: 1; grid-column: 2; margin-left: 10px; margin-right: 10px; } .color-picker-container .color-picker-hex .color-picker-hex-value input { width: 70px; } .color-picker-container .color-picker-warning { color: black; font-size: 11px; padding: 4px; justify-self: left; align-self: center; grid-row: 6; grid-column: 1; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/colorPicker/colorPicker.scss"],names:[],mappings:"AAAA;EACI,YAAA;EACA,aAAA;EACA,uBAAA;EACA,aAAA;EACA,2BAAA;EACA,+CAAA;EACA,mCAAA;EACA,mBAAA;EACA,eAAA;AACJ;AACI;EACI,aAAA;AACR;AAEI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,2BAAA;EACA,wBAAA;EACA,kBAAA;EACA,eAAA;AAAR;AAEQ;EACI,WAAA;EACA,cAAA;EAEA,2EAAA;EACA,mEAAA;AADZ;AAIQ;EACI,WAAA;EACA,cAAA;EAEA,mEAAA;EACA,2DAAA;AAHZ;AAMQ;EACI,oBAAA;EACA,UAAA;EACA,WAAA;EACA,kGACI;EAGJ,kBAAA;EACA,gCAAA;EACA,kBAAA;AAPZ;AAWI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,YAAA;EACA,8BAAA;EACA,wBAAA;AATR;AAWQ;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,oBAAA;EACA,WAAA;EACA,YAAA;EACA,mBAAA;EACA,uBAAA;AATZ;AAYQ;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;EAEA,2GAAA;EACA,mHAAA;AAXZ;AAaY;EACI,oBAAA;EACA,UAAA;EACA,YAAA;EACA,gCAAA;EACA,oCAAA;EACA,2CAAA;EACA,kBAAA;AAXhB;AAgBI;EACI,aAAA;EACA,WAAA;EACA,2BAAA;EACA,2BAAA;AAdR;AAgBQ;EACI,oBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,kBAAA;AAdZ;AAgBY;EACI,WAAA;AAdhB;AAkBQ;EACI,oBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,YAAA;AAhBZ;AAoBI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,YAAA;EACA,wDAAA;EACA,wBAAA;AAlBR;AAqBI;EACI,WAAA;EACA,cAAA;AAnBR;AAsBI;EACI,WAAA;EACA,cAAA;AApBR;AAuBI;EACI,WAAA;EACA,cAAA;AArBR;AAwBI;EACI,WAAA;EACA,cAAA;AAtBR;AAwBQ;EACI,YAAA;AAtBZ;AA0BI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,8BAAA;EACA,wBAAA;AAxBR;AA0BQ;EACI,oBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,YAAA;AAxBZ;AA2BQ;EACI,kBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,kBAAA;AAzBZ;AA2BY;EACI,WAAA;AAzBhB;AA8BI;EACI,YAAA;EACA,eAAA;EACA,YAAA;EACA,kBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;AA5BR",sourcesContent:[`.color-picker-container {\r width: 320px;\r height: 300px;\r background-color: white;\r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 50% 50px 60px 40px 1fr auto;\r font-family: "acumin-pro-condensed";\r font-weight: normal;\r font-size: 14px;\r \r &.with-hints {\r height: 380px;\r }\r \r .color-picker-saturation {\r grid-row: 1;\r grid-column: 1;\r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 100%;\r position: relative;\r cursor: pointer;\r \r .color-picker-saturation-white {\r grid-row: 1;\r grid-column: 1;\r \r background: -webkit-linear-gradient(to right, #fff, rgba(255, 255, 255, 0));\r background: linear-gradient(to right, #fff, rgba(255, 255, 255, 0));\r }\r \r .color-picker-saturation-black {\r grid-row: 1;\r grid-column: 1;\r \r background: -webkit-linear-gradient(to top, #000, rgba(0, 0, 0, 0));\r background: linear-gradient(to top, #000, rgba(0, 0, 0, 0));\r }\r \r .color-picker-saturation-cursor {\r pointer-events: none;\r width: 4px;\r height: 4px;\r box-shadow:\r 0 0 0 1.5px #fff,\r inset 0 0 1px 1px rgba(0, 0, 0, 0.3),\r 0 0 1px 2px rgba(0, 0, 0, 0.4);\r border-radius: 50%;\r transform: translate(-2px, -2px);\r position: absolute;\r }\r }\r \r .color-picker-hue {\r grid-row: 2;\r grid-column: 1;\r display: grid;\r margin: 10px;\r grid-template-columns: 24% 76%;\r grid-template-rows: 100%;\r \r .color-picker-hue-color {\r grid-row: 1;\r grid-column: 1;\r align-self: center;\r justify-self: center;\r width: 30px;\r height: 30px;\r border-radius: 15px;\r border: 1px solid black;\r }\r \r .color-picker-hue-slider {\r grid-row: 1;\r grid-column: 2;\r align-self: center;\r height: 16px;\r position: relative;\r cursor: pointer;\r \r background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\r background: -webkit-linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\r \r .color-picker-hue-cursor {\r pointer-events: none;\r width: 8px;\r height: 18px;\r transform: translate(-4px, -2px);\r background-color: rgb(248, 248, 248);\r box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.37);\r position: absolute;\r }\r }\r }\r \r .color-picker-component {\r display: grid;\r margin: 5px;\r grid-template-columns: 100%;\r grid-template-rows: 50% 50%;\r \r .color-picker-component-value {\r justify-self: center;\r align-self: center;\r grid-row: 1;\r grid-column: 1;\r margin-bottom: 4px;\r \r input {\r width: 50px;\r }\r }\r \r .color-picker-component-label {\r justify-self: center;\r align-self: center;\r grid-row: 2;\r grid-column: 1;\r color: black;\r }\r }\r \r .color-picker-rgb {\r grid-row: 3;\r grid-column: 1;\r display: grid;\r margin: 10px;\r grid-template-columns: 20% 6.66% 20% 6.66% 20% 6.66% 20%;\r grid-template-rows: 100%;\r }\r \r .red {\r grid-row: 1;\r grid-column: 1;\r }\r \r .green {\r grid-row: 1;\r grid-column: 3;\r }\r \r .blue {\r grid-row: 1;\r grid-column: 5;\r }\r \r .alpha {\r grid-row: 1;\r grid-column: 7;\r \r &.grayed {\r opacity: 0.5;\r }\r }\r \r .color-picker-hex {\r grid-row: 4;\r grid-column: 1;\r display: grid;\r grid-template-columns: 20% 80%;\r grid-template-rows: 100%;\r \r .color-picker-hex-label {\r justify-self: center;\r align-self: center;\r grid-row: 1;\r grid-column: 1;\r margin-left: 10px;\r color: black;\r }\r \r .color-picker-hex-value {\r justify-self: left;\r align-self: center;\r grid-row: 1;\r grid-column: 2;\r margin-left: 10px;\r margin-right: 10px;\r \r input {\r width: 70px;\r }\r }\r }\r \r .color-picker-warning {\r color: black;\r font-size: 11px;\r padding: 4px;\r justify-self: left;\r align-self: center;\r grid-row: 6;\r grid-column: 1;\r }\r }\r `],sourceRoot:""}]),p.locals={};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/searchBox.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`#graph-search-container { position: absolute; width: 100%; height: 100%; left: 0; top: 0; } #graph-search-container #graph-search-picking-blocker { position: absolute; width: 100%; height: 100%; left: 0; top: 0; cursor: default; } #graph-search-container #graph-search-box { width: 300px; height: 400px; position: absolute; left: calc(50% - 150px); top: calc(50% - 200px); background: rgb(72, 72, 72); border: 2px solid black; z-index: 100; cursor: auto; display: grid; grid-template-rows: auto auto 1fr; } #graph-search-container #graph-search-box .graph-search-box-title { border-bottom: 1px solid rgb(40, 40, 40); margin: 4px; padding-bottom: 4px; color: white; grid-row: 1; } #graph-search-container #graph-search-box .graph-search-box-filter { margin: 4px; padding-bottom: 4px; border-radius: 4px; width: calc(100% - 16px); grid-row: 2; } #graph-search-container #graph-search-box .graph-search-box-list { grid-row: 3; overflow-y: auto; display: flex; flex-direction: column; } #graph-search-container #graph-search-box .graph-search-box-list .graph-search-box-list-item { margin-left: 4px; cursor: pointer; color: white; margin-top: 4px; margin-bottom: 4px; } #graph-search-container #graph-search-box .graph-search-box-list .graph-search-box-list-item:hover { background: rgb(30, 30, 30); } #graph-search-container #graph-search-box .graph-search-box-list .graph-search-box-list-item.selected { background: rgb(230, 230, 230); color: black; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/searchBox.scss"],names:[],mappings:"AAAA;EACI,kBAAA;EACA,WAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;AACJ;AACI;EACI,kBAAA;EACA,WAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;EACA,eAAA;AACR;AAEI;EACI,YAAA;EACA,aAAA;EACA,kBAAA;EACA,uBAAA;EACA,sBAAA;EACA,2BAAA;EACA,uBAAA;EACA,YAAA;EACA,YAAA;EACA,aAAA;EACA,iCAAA;AAAR;AAEQ;EACI,wCAAA;EACA,WAAA;EACA,mBAAA;EACA,YAAA;EACA,WAAA;AAAZ;AAGQ;EACI,WAAA;EACA,mBAAA;EACA,kBAAA;EACA,wBAAA;EACA,WAAA;AADZ;AAIQ;EACI,WAAA;EACA,gBAAA;EACA,aAAA;EACA,sBAAA;AAFZ;AAIY;EACI,gBAAA;EACA,eAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;AAFhB;AAIgB;EACI,2BAAA;AAFpB;AAKgB;EACI,8BAAA;EACA,YAAA;AAHpB",sourcesContent:[`#graph-search-container {\r position: absolute;\r width: 100%;\r height: 100%;\r left: 0;\r top: 0;\r \r #graph-search-picking-blocker {\r position: absolute;\r width: 100%;\r height: 100%;\r left: 0;\r top: 0;\r cursor: default;\r }\r \r #graph-search-box {\r width: 300px;\r height: 400px;\r position: absolute;\r left: calc(50% - 150px);\r top: calc(50% - 200px);\r background: rgb(72, 72, 72);\r border: 2px solid black;\r z-index: 100;\r cursor: auto;\r display: grid;\r grid-template-rows: auto auto 1fr;\r \r .graph-search-box-title {\r border-bottom: 1px solid rgb(40, 40, 40);\r margin: 4px;\r padding-bottom: 4px;\r color: white;\r grid-row: 1;\r }\r \r .graph-search-box-filter {\r margin: 4px;\r padding-bottom: 4px;\r border-radius: 4px;\r width: calc(100% - 16px);\r grid-row: 2;\r }\r \r .graph-search-box-list {\r grid-row: 3;\r overflow-y: auto;\r display: flex;\r flex-direction: column;\r \r .graph-search-box-list-item {\r margin-left: 4px;\r cursor: pointer;\r color: white;\r margin-top: 4px;\r margin-bottom: 4px;\r \r &:hover {\r background: rgb(30, 30, 30);\r }\r \r &.selected {\r background: rgb(230, 230, 230);\r color: black;\r }\r }\r }\r }\r }\r `],sourceRoot:""}]),p.locals={};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../tools/nodeEditor/dist/components/log/log.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`#nme-log-console { background: #333333; height: 120px; box-sizing: border-box; margin: 0; padding: 10px; width: 100%; overflow: hidden; overflow-y: auto; grid-row: 2; grid-column: 3; } #nme-log-console .log { color: white; font-size: 14px; font-family: "Courier New", Courier, monospace; } #nme-log-console .log.error { color: red; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/components/log/log.scss"],names:[],mappings:"AAAA;EACI,mBAAA;EACA,aAAA;EACA,sBAAA;EACA,SAAA;EACA,aAAA;EACA,WAAA;EACA,gBAAA;EACA,gBAAA;EACA,WAAA;EACA,cAAA;AACJ;AACI;EACI,YAAA;EACA,eAAA;EACA,8CAAA;AACR;AACQ;EACI,UAAA;AACZ",sourcesContent:[`#nme-log-console {\r background: #333333;\r height: 120px;\r box-sizing: border-box;\r margin: 0;\r padding: 10px;\r width: 100%;\r overflow: hidden;\r overflow-y: auto;\r grid-row: 2;\r grid-column: 3;\r \r .log {\r color: white;\r font-size: 14px;\r font-family: "Courier New", Courier, monospace;\r \r &.error {\r color: red;\r }\r }\r }\r `],sourceRoot:""}]),p.locals={};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../tools/nodeEditor/dist/components/nodeList/nodeList.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`#nmeNodeList { background: #333333; height: 100%; margin: 0; padding: 0; display: grid; width: 100%; overflow: hidden; } #nmeNodeList .panes { overflow: hidden; } #nmeNodeList .panes .pane { color: white; overflow: hidden; height: 100%; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } #nmeNodeList .panes .pane .filter { display: flex; align-items: stretch; } #nmeNodeList .panes .pane .filter input { width: 100%; margin: 10px 10px 5px 10px; display: block; border: none; padding: 0; border-bottom: solid 1px rgb(51, 122, 183); background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 96%, rgb(51, 122, 183) 4%); background-position: -1000px 0; background-size: 1000px 100%; background-repeat: no-repeat; color: white; } #nmeNodeList .panes .pane .filter input:focus { box-shadow: none; outline: none; background-position: 0 0; } #nmeNodeList .panes .pane .filter input::placeholder { color: gray; } #nmeNodeList .panes .pane .list-container { overflow-x: hidden; overflow-y: auto; height: calc(100% - 32px); } #nmeNodeList .panes .pane .list-container .underline { border-bottom: 0.5px solid rgba(255, 255, 255, 0.5); } #nmeNodeList .panes .pane .list-container .draggableLine { height: 30px; display: grid; align-items: center; justify-items: stretch; background: #222222; cursor: grab; text-align: center; margin: 0; box-sizing: border-box; } #nmeNodeList .panes .pane .list-container .draggableLine:hover { background: rgb(51, 122, 183); color: white; } #nmeNodeList .panes .pane .list-container .nonDraggableLine { height: 30px; display: grid; align-items: center; justify-items: stretch; background: #222222; text-align: center; margin: 0; box-sizing: border-box; } #nmeNodeList .panes .pane .list-container .withButton { height: 30px; position: relative; } #nmeNodeList .panes .pane .list-container .withButton .icon { position: absolute; right: 4px; top: 5px; } #nmeNodeList .panes .pane .list-container .withButton .icon:hover { cursor: pointer; } #nmeNodeList .panes .pane .list-container .withButton .icon .img { height: 17px; width: 17px; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine { height: 30px; display: grid; align-items: center; justify-items: stretch; padding-bottom: 5px; position: absolute; right: 0px; top: 2px; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine input[type=file] { display: none; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine .file-upload { background: transparent; border: transparent; padding: 15px 200px; opacity: 0.9; cursor: pointer; text-align: center; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine .file-upload:hover { opacity: 1; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine .file-upload:active { transform: scale(0.98); transform-origin: 0.5 0.5; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine button { background: transparent; border: transparent; margin: 5px 10px 5px 10px; color: white; padding: 4px 5px; opacity: 0.9; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine button:hover { opacity: 0; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine button:active { background: transparent; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine button:focus { border: transparent; outline: 0px; } #nmeNodeList .panes .pane .list-container .paneContainer { margin-top: 3px; display: grid; grid-template-rows: 100%; grid-template-columns: 100%; } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content { grid-row: 1; grid-column: 1; } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content .header { display: grid; grid-template-columns: 1fr auto; background: #555555; height: 30px; padding-right: 5px; cursor: pointer; } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content .header .title { border-left: 3px solid transparent; padding-left: 5px; grid-column: 1; display: flex; align-items: center; } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content .header .collapse { grid-column: 2; display: flex; align-items: center; justify-items: center; transform-origin: center; } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content .header .collapse.closed { transform: rotate(180deg); } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content .paneList > div:not(:last-child) { border-bottom: 1px solid rgba(255, 255, 255, 0.3); }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/components/nodeList/nodeList.scss"],names:[],mappings:"AAAA;EACI,mBAAA;EACA,YAAA;EACA,SAAA;EACA,UAAA;EACA,aAAA;EACA,WAAA;EACA,gBAAA;AACJ;AACI;EACI,gBAAA;AACR;AACQ;EACI,YAAA;EAEA,gBAAA;EACA,YAAA;EAEA,yBAAA;EACA,sBAAA;EACA,qBAAA;EACA,iBAAA;AADZ;AAGY;EACI,aAAA;EACA,oBAAA;AADhB;AAGgB;EACI,WAAA;EACA,0BAAA;EACA,cAAA;EACA,YAAA;EACA,UAAA;EACA,0CAAA;EACA,wFAAA;EACA,8BAAA;EACA,4BAAA;EACA,4BAAA;EACA,YAAA;AADpB;AAIgB;EACI,gBAAA;EACA,aAAA;EACA,wBAAA;AAFpB;AAKgB;EACI,WAAA;AAHpB;AAOY;EACI,kBAAA;EACA,gBAAA;EACA,yBAAA;AALhB;AAOgB;EACI,mDAAA;AALpB;AAQgB;EACI,YAAA;EACA,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,mBAAA;EACA,YAAA;EACA,kBAAA;EACA,SAAA;EACA,sBAAA;AANpB;AAQoB;EACI,6BAAA;EACA,YAAA;AANxB;AAUgB;EACI,YAAA;EACA,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,mBAAA;EACA,kBAAA;EACA,SAAA;EACA,sBAAA;AARpB;AAWgB;EACI,YAAA;EACA,kBAAA;AATpB;AAUoB;EACI,kBAAA;EACA,UAAA;EACA,QAAA;AARxB;AASwB;EACI,eAAA;AAP5B;AAUwB;EACI,YAAA;EACA,WAAA;AAR5B;AAYoB;EACI,YAAA;EACA,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,mBAAA;EACA,kBAAA;EACA,UAAA;EACA,QAAA;AAVxB;AAWwB;EACI,aAAA;AAT5B;AAYwB;EACI,uBAAA;EACA,mBAAA;EACA,mBAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;AAV5B;AAawB;EACI,UAAA;AAX5B;AAcwB;EACI,sBAAA;EACA,yBAAA;AAZ5B;AAewB;EACI,uBAAA;EACA,mBAAA;EACA,yBAAA;EACA,YAAA;EACA,gBAAA;EACA,YAAA;AAb5B;AAgBwB;EACI,UAAA;AAd5B;AAiBwB;EACI,uBAAA;AAf5B;AAkBwB;EACI,mBAAA;EACA,YAAA;AAhB5B;AAqBgB;EACI,eAAA;EACA,aAAA;EACA,wBAAA;EACA,2BAAA;AAnBpB;AAqBoB;EACI,WAAA;EACA,cAAA;AAnBxB;AAqBwB;EACI,aAAA;EACA,+BAAA;EACA,mBAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;AAnB5B;AAqB4B;EACI,kCAAA;EACA,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;AAnBhC;AAsB4B;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,wBAAA;AApBhC;AAsBgC;EACI,yBAAA;AApBpC;AAyBwB;EACI,iDAAA;AAvB5B",sourcesContent:[`#nmeNodeList {\r background: #333333;\r height: 100%;\r margin: 0;\r padding: 0;\r display: grid;\r width: 100%;\r overflow: hidden;\r \r .panes {\r overflow: hidden;\r \r .pane {\r color: white;\r \r overflow: hidden;\r height: 100%;\r \r -webkit-user-select: none;\r -moz-user-select: none;\r -ms-user-select: none;\r user-select: none;\r \r .filter {\r display: flex;\r align-items: stretch;\r \r input {\r width: 100%;\r margin: 10px 10px 5px 10px;\r display: block;\r border: none;\r padding: 0;\r border-bottom: solid 1px rgb(51, 122, 183);\r background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 96%, rgb(51, 122, 183) 4%);\r background-position: -1000px 0;\r background-size: 1000px 100%;\r background-repeat: no-repeat;\r color: white;\r }\r \r input:focus {\r box-shadow: none;\r outline: none;\r background-position: 0 0;\r }\r \r input::placeholder {\r color: gray;\r }\r }\r \r .list-container {\r overflow-x: hidden;\r overflow-y: auto;\r height: calc(100% - 32px);\r \r .underline {\r border-bottom: 0.5px solid rgba(255, 255, 255, 0.5);\r }\r \r .draggableLine {\r height: 30px;\r display: grid;\r align-items: center;\r justify-items: stretch;\r background: #222222;\r cursor: grab;\r text-align: center;\r margin: 0;\r box-sizing: border-box;\r \r &:hover {\r background: rgb(51, 122, 183);\r color: white;\r }\r }\r \r .nonDraggableLine {\r height: 30px;\r display: grid;\r align-items: center;\r justify-items: stretch;\r background: #222222;\r text-align: center;\r margin: 0;\r box-sizing: border-box;\r }\r \r .withButton {\r height: 30px;\r position: relative;\r .icon {\r position: absolute;\r right: 4px;\r top: 5px;\r &:hover {\r cursor: pointer;\r }\r \r .img {\r height: 17px;\r width: 17px;\r }\r }\r \r .buttonLine {\r height: 30px;\r display: grid;\r align-items: center;\r justify-items: stretch;\r padding-bottom: 5px;\r position: absolute;\r right: 0px;\r top: 2px;\r input[type="file"] {\r display: none;\r }\r \r .file-upload {\r background: transparent;\r border: transparent;\r padding: 15px 200px;\r opacity: 0.9;\r cursor: pointer;\r text-align: center;\r }\r \r .file-upload:hover {\r opacity: 1;\r }\r \r .file-upload:active {\r transform: scale(0.98);\r transform-origin: 0.5 0.5;\r }\r \r button {\r background: transparent;\r border: transparent;\r margin: 5px 10px 5px 10px;\r color: white;\r padding: 4px 5px;\r opacity: 0.9;\r }\r \r button:hover {\r opacity: 0;\r }\r \r button:active {\r background: transparent;\r }\r \r button:focus {\r border: transparent;\r outline: 0px;\r }\r }\r }\r \r .paneContainer {\r margin-top: 3px;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 100%;\r \r .paneContainer-content {\r grid-row: 1;\r grid-column: 1;\r \r .header {\r display: grid;\r grid-template-columns: 1fr auto;\r background: #555555;\r height: 30px;\r padding-right: 5px;\r cursor: pointer;\r \r .title {\r border-left: 3px solid transparent;\r padding-left: 5px;\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .collapse {\r grid-column: 2;\r display: flex;\r align-items: center;\r justify-items: center;\r transform-origin: center;\r \r &.closed {\r transform: rotate(180deg);\r }\r }\r }\r \r .paneList > div:not(:last-child) {\r border-bottom: 1px solid rgba(255, 255, 255, 0.3);\r }\r }\r }\r }\r }\r }\r }\r `],sourceRoot:""}]),p.locals={};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../tools/nodeEditor/dist/components/propertyTab/propertyTab.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.nme-right-panel #propertyTab { color: white; background: #333333; } .nme-right-panel #propertyTab #header { height: 30px; font-size: 16px; color: white; background: #222222; grid-row: 1; text-align: center; display: grid; grid-template-columns: 30px 1fr; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .nme-right-panel #propertyTab #header #logo { position: relative; grid-column: 1; width: 24px; height: 24px; left: 0; display: flex; align-self: center; justify-self: center; } .nme-right-panel #propertyTab #header #title { grid-column: 2; display: grid; align-items: center; text-align: center; } .nme-right-panel #propertyTab .range { -webkit-appearance: none; width: 120px; height: 6px; background: #d3d3d3; border-radius: 5px; outline: none; opacity: 0.7; -webkit-transition: 0.2s; transition: opacity 0.2s; } .nme-right-panel #propertyTab .range:hover { opacity: 1; } .nme-right-panel #propertyTab .range::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 14px; height: 14px; border-radius: 50%; background: rgb(51, 122, 183); cursor: pointer; } .nme-right-panel #propertyTab .range::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%; background: rgb(51, 122, 183); cursor: pointer; } .nme-right-panel #propertyTab input[type=color] { -webkit-appearance: none; border: 1px solid rgba(255, 255, 255, 0.5); padding: 0; width: 30px; height: 20px; } .nme-right-panel #propertyTab input[type=color]::-webkit-color-swatch-wrapper { padding: 0; } .nme-right-panel #propertyTab input[type=color]::-webkit-color-swatch { border: none; } .nme-right-panel #propertyTab .sliderLine { padding-left: 5px; height: 30px; display: grid; grid-template-rows: 100%; grid-template-columns: 1fr 50px auto; } .nme-right-panel #propertyTab .sliderLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .sliderLine .slider { grid-column: 3; grid-row: 1; margin-right: 5px; width: 90%; display: flex; align-items: center; } .nme-right-panel #propertyTab .sliderLine .floatLine { grid-column: 2; padding-left: 5px; } .nme-right-panel #propertyTab .sliderLine .floatLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .sliderLine .floatLine .short { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .sliderLine .floatLine .short input { width: 35px; } .nme-right-panel #propertyTab .sliderLine .floatLine .short input::-webkit-outer-spin-button, .nme-right-panel #propertyTab .sliderLine .floatLine .short input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .nme-right-panel #propertyTab .sliderLine .floatLine .short input[type=number] { -moz-appearance: textfield; } .nme-right-panel #propertyTab .textInputLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr 120px auto; } .nme-right-panel #propertyTab .textInputLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .textInputLine .value { display: flex; align-items: center; grid-column: 2; } .nme-right-panel #propertyTab .textInputLine .value input { width: calc(100% - 5px); margin-right: 5px; } .nme-right-panel #propertyTab .textInputArea { padding-left: 5px; height: 50px; display: grid; grid-template-columns: 1fr 120px; } .nme-right-panel #propertyTab .textInputArea .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .textInputArea textarea { margin-right: 5px; margin-left: -50%; height: 40px; resize: none; } .nme-right-panel #propertyTab .textInputArea .value { display: flex; align-items: center; grid-column: 2; } .nme-right-panel #propertyTab .paneContainer { margin-top: 3px; display: grid; grid-template-rows: 100%; grid-template-columns: 100%; } .nme-right-panel #propertyTab .paneContainer .paneList { border-left: 3px solid transparent; } .nme-right-panel #propertyTab .paneContainer:hover .paneList { border-left: 3px solid rgba(51, 122, 183, 0.8); } .nme-right-panel #propertyTab .paneContainer:hover .paneContainer-content .header .title { border-left: 3px solid rgb(51, 122, 183); } .nme-right-panel #propertyTab .paneContainer .paneContainer-highlight-border { grid-row: 1; grid-column: 1; opacity: 1; border: 3px solid red; transition: opacity 250ms; pointer-events: none; } .nme-right-panel #propertyTab .paneContainer .paneContainer-highlight-border.transparent { opacity: 0; } .nme-right-panel #propertyTab .paneContainer .paneContainer-content { grid-row: 1; grid-column: 1; } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .header { display: grid; grid-template-columns: 1fr auto; background: #555555; height: 30px; padding-right: 5px; cursor: pointer; } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .header .title { border-left: 3px solid transparent; padding-left: 5px; grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .header .collapse { grid-column: 2; display: flex; align-items: center; justify-items: center; transform-origin: center; } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .header .collapse.closed { transform: rotate(180deg); } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .paneList > div:not(:last-child) { border-bottom: 0.5px solid rgba(255, 255, 255, 0.1); } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .fragment > div:not(:last-child) { border-bottom: 0.5px solid rgba(255, 255, 255, 0.1); } .nme-right-panel #propertyTab .color-picker { height: calc(100% - 8px); margin: 4px; width: calc(100% - 8px); } .nme-right-panel #propertyTab .color-picker .color-rect { height: calc(100% - 4px); border: 2px white solid; cursor: pointer; min-height: 18px; } .nme-right-panel #propertyTab .color-picker .color-picker-cover { position: fixed; top: 0px; right: 0px; bottom: 0px; left: 0px; z-index: 1; } .nme-right-panel #propertyTab .color-picker .color-picker-float { z-index: 2; position: absolute; } .nme-right-panel #propertyTab .gradient-step { display: grid; grid-template-rows: 100%; grid-template-columns: 20px 30px 40px auto 20px 30px; padding-top: 5px; padding-left: 5px; padding-bottom: 5px; } .nme-right-panel #propertyTab .gradient-step .step { grid-row: 1; grid-column: 1; } .nme-right-panel #propertyTab .gradient-step .color { grid-row: 1; grid-column: 2; cursor: pointer; } .nme-right-panel #propertyTab .gradient-step .step-value { margin-left: 5px; grid-row: 1; grid-column: 3; text-align: right; margin-right: 5px; } .nme-right-panel #propertyTab .gradient-step .step-slider { grid-row: 1; grid-column: 4; display: grid; justify-content: stretch; align-content: center; margin-right: -5px; padding-left: 12px; } .nme-right-panel #propertyTab .gradient-step .step-slider input { width: 90%; } .nme-right-panel #propertyTab .gradient-step .gradient-copy { grid-row: 1; grid-column: 5; display: grid; align-content: center; justify-content: center; } .nme-right-panel #propertyTab .gradient-step .gradient-copy .img { height: 20px; width: 20px; } .nme-right-panel #propertyTab .gradient-step .gradient-copy .img:hover { cursor: pointer; } .nme-right-panel #propertyTab .gradient-step .gradient-delete { grid-row: 1; grid-column: 6; display: grid; align-content: center; justify-content: center; } .nme-right-panel #propertyTab .gradient-step .gradient-delete .img { height: 20px; width: 20px; } .nme-right-panel #propertyTab .gradient-step .gradient-delete .img:hover { cursor: pointer; } .nme-right-panel #propertyTab .floatLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr 120px; } .nme-right-panel #propertyTab .floatLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .floatLine .value { grid-column: 2; display: flex; align-items: center; } .nme-right-panel #propertyTab .floatLine .value input { width: 110px; } .nme-right-panel #propertyTab .floatLine .short { grid-column: 2; display: flex; align-items: center; } .nme-right-panel #propertyTab .floatLine .short input { width: 27px; } .nme-right-panel #propertyTab .floatLine .short input::-webkit-outer-spin-button, .nme-right-panel #propertyTab .floatLine .short input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .nme-right-panel #propertyTab .floatLine .short input[type=number] { -moz-appearance: textfield; } .nme-right-panel #propertyTab .vector3Line { padding-left: 5px; display: grid; } .nme-right-panel #propertyTab .vector3Line .firstLine { display: grid; grid-template-columns: 1fr auto 20px; height: 30px; } .nme-right-panel #propertyTab .vector3Line .firstLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .vector3Line .firstLine .vector { grid-column: 2; display: flex; align-items: center; text-align: right; opacity: 0.8; } .nme-right-panel #propertyTab .vector3Line .firstLine .expand { grid-column: 3; display: grid; align-items: center; justify-items: center; cursor: pointer; } .nme-right-panel #propertyTab .vector3Line .secondLine { display: grid; padding-right: 5px; border-left: 1px solid rgb(51, 122, 183); } .nme-right-panel #propertyTab .vector3Line .secondLine .no-right-margin { margin-right: 0; } .nme-right-panel #propertyTab .vector3Line .secondLine .numeric { display: grid; grid-template-columns: 1fr auto; } .nme-right-panel #propertyTab .vector3Line .secondLine .numeric-label { text-align: right; grid-column: 1; display: flex; align-items: center; justify-self: right; margin-right: 10px; } .nme-right-panel #propertyTab .vector3Line .secondLine .numeric-value { width: 120px; grid-column: 2; display: flex; align-items: center; border: 1px solid rgb(51, 122, 183); } .nme-right-panel #propertyTab .buttonLine { height: 30px; display: grid; align-items: center; justify-items: stretch; padding-bottom: 5px; } .nme-right-panel #propertyTab .buttonLine.disabled { opacity: 0.3; } .nme-right-panel #propertyTab .buttonLine input[type=file] { display: none; } .nme-right-panel #propertyTab .buttonLine .file-upload { background: #222222; border: 1px solid rgb(51, 122, 183); margin: 5px 10px; color: white; padding: 4px 5px; padding-top: 0px; opacity: 0.9; cursor: pointer; text-align: center; } .nme-right-panel #propertyTab .buttonLine .file-upload:hover { opacity: 1; } .nme-right-panel #propertyTab .buttonLine .file-upload:active { transform: scale(0.98); transform-origin: 0.5 0.5; } .nme-right-panel #propertyTab .buttonLine button { background: #222222; border: 1px solid rgb(51, 122, 183); margin: 5px 10px 5px 10px; color: white; padding: 4px 5px; opacity: 0.9; } .nme-right-panel #propertyTab .buttonLine button:hover { opacity: 1; } .nme-right-panel #propertyTab .buttonLine button:active { background: #282828; } .nme-right-panel #propertyTab .buttonLine button:focus { border: 1px solid rgb(51, 122, 183); outline: 0px; } .nme-right-panel #propertyTab .checkBoxLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr auto; } .nme-right-panel #propertyTab .checkBoxLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .checkBoxLine .checkBox { grid-column: 2; display: flex; align-items: center; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .lbl { position: relative; display: block; height: 14px; width: 34px; margin-right: 5px; background: #898989; border-radius: 100px; cursor: pointer; transition: all 0.3s ease; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .lbl:after { position: absolute; left: 3px; top: 2px; display: block; width: 10px; height: 10px; border-radius: 100px; background: #fff; box-shadow: 0px 3px 3px rgba(0, 0, 0, 0.05); content: ""; transition: all 0.15s ease; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .lbl:active:after { transform: scale(1.15, 0.85); } .nme-right-panel #propertyTab .checkBoxLine .checkBox .cbx:checked ~ label { background: rgb(51, 122, 183); } .nme-right-panel #propertyTab .checkBoxLine .checkBox .cbx:checked ~ label:after { left: 20px; background: rgb(22, 73, 117); } .nme-right-panel #propertyTab .checkBoxLine .checkBox .cbx:checked ~ label.disabled { background: rgb(22, 73, 117); cursor: pointer; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .cbx:checked ~ label.disabled:after { left: 20px; background: rgb(85, 85, 85); cursor: pointer; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .cbx ~ label.disabled { background: rgb(85, 85, 85); cursor: pointer; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .hidden { display: none; } .nme-right-panel #propertyTab .listLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr auto; } .nme-right-panel #propertyTab .listLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .listLine .options { grid-column: 2; display: flex; align-items: center; margin-right: 5px; } .nme-right-panel #propertyTab .listLine .options select { width: 115px; } .nme-right-panel #propertyTab .color3Line { padding-left: 5px; display: grid; } .nme-right-panel #propertyTab .color3Line .firstLine { height: 30px; display: grid; grid-template-columns: 1fr auto 0px 20px 20px; } .nme-right-panel #propertyTab .color3Line .firstLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .color3Line .firstLine .textInputLine { display: none; } .nme-right-panel #propertyTab .color3Line .firstLine .color3 { grid-column: 2; width: 50px; display: flex; align-items: center; } .nme-right-panel #propertyTab .color3Line .firstLine .color3 input { margin-right: 5px; } .nme-right-panel #propertyTab .color3Line .firstLine .copy { grid-column: 4; display: grid; align-items: center; justify-items: center; cursor: pointer; } .nme-right-panel #propertyTab .color3Line .firstLine .copy img { height: 100%; width: 24px; } .nme-right-panel #propertyTab .color3Line .firstLine .expand { grid-column: 5; display: grid; align-items: center; justify-items: center; cursor: pointer; } .nme-right-panel #propertyTab .color3Line .firstLine .expand img { height: 100%; width: 20px; } .nme-right-panel #propertyTab .color3Line .secondLine { display: grid; padding-right: 5px; border-left: 1px solid rgb(51, 122, 183); } .nme-right-panel #propertyTab .color3Line .secondLine .numeric { display: grid; grid-template-columns: 1fr auto; } .nme-right-panel #propertyTab .color3Line .secondLine .numeric-label { text-align: right; grid-column: 1; display: flex; align-items: center; justify-self: right; margin-right: 10px; } .nme-right-panel #propertyTab .color3Line .secondLine .numeric-value { width: 120px; grid-column: 2; display: flex; align-items: center; border: 1px solid rgb(51, 122, 183); } .nme-right-panel #propertyTab .textLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr auto; } .nme-right-panel #propertyTab .textLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .textLine .link-value { grid-column: 2; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; text-align: end; opacity: 0.8; margin: 5px; margin-top: 6px; max-width: 140px; text-decoration: underline; cursor: pointer; } .nme-right-panel #propertyTab .textLine .value { grid-column: 2; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; text-align: end; opacity: 0.8; margin: 5px; margin-top: 6px; max-width: 200px; -webkit-user-select: text; -moz-user-select: text; -ms-user-select: text; user-select: text; } .nme-right-panel #propertyTab .textLine .value.check { color: green; } .nme-right-panel #propertyTab .textLine .value.uncheck { color: red; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/components/propertyTab/propertyTab.scss"],names:[],mappings:"AACI;EAEI,YAAA;EACA,mBAAA;AADR;AAGQ;EACI,YAAA;EACA,eAAA;EACA,YAAA;EACA,mBAAA;EACA,WAAA;EACA,kBAAA;EACA,aAAA;EACA,+BAAA;EACA,yBAAA;EACA,sBAAA;EACA,qBAAA;EACA,iBAAA;AADZ;AAGY;EACI,kBAAA;EACA,cAAA;EACA,WAAA;EACA,YAAA;EACA,OAAA;EACA,aAAA;EACA,kBAAA;EACA,oBAAA;AADhB;AAIY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,kBAAA;AAFhB;AAMQ;EACI,wBAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,kBAAA;EACA,aAAA;EACA,YAAA;EACA,wBAAA;EACA,wBAAA;AAJZ;AAOQ;EACI,UAAA;AALZ;AAQQ;EACI,wBAAA;EACA,gBAAA;EACA,WAAA;EACA,YAAA;EACA,kBAAA;EACA,6BAAA;EACA,eAAA;AANZ;AASQ;EACI,WAAA;EACA,YAAA;EACA,kBAAA;EACA,6BAAA;EACA,eAAA;AAPZ;AAUQ;EACI,wBAAA;EACA,0CAAA;EACA,UAAA;EACA,WAAA;EACA,YAAA;AARZ;AAUQ;EACI,UAAA;AARZ;AAUQ;EACI,YAAA;AARZ;AAWQ;EACI,iBAtFgB;EAuFhB,YAAA;EACA,aAAA;EACA,wBAAA;EACA,oCAAA;AATZ;AAWY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAThB;AAYY;EACI,cAAA;EACA,WAAA;EACA,iBAAA;EACA,UAAA;EACA,aAAA;EACA,mBAAA;AAVhB;AAaY;EACI,cAAA;EACA,iBA7GY;AAkG5B;AAagB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAXpB;AAcgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAZpB;AAcoB;EACI,WAAA;AAZxB;AAeoB;;EAEI,wBAAA;EACA,SAAA;AAbxB;AAgBoB;EACI,0BAAA;AAdxB;AAoBQ;EACI,iBA5IgB;EA6IhB,YAAA;EACA,aAAA;EACA,qCAAA;AAlBZ;AAoBY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAlBhB;AAqBY;EACI,aAAA;EACA,mBAAA;EACA,cAAA;AAnBhB;AAqBgB;EACI,uBAAA;EACA,iBAAA;AAnBpB;AAwBQ;EACI,iBApKgB;EAqKhB,YAAA;EACA,aAAA;EACA,gCAAA;AAtBZ;AAwBY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAtBhB;AAyBY;EACI,iBAAA;EACA,iBAAA;EACA,YAAA;EACA,YAAA;AAvBhB;AA0BY;EACI,aAAA;EACA,mBAAA;EACA,cAAA;AAxBhB;AA4BQ;EACI,eAAA;EACA,aAAA;EACA,wBAAA;EACA,2BAAA;AA1BZ;AA4BY;EACI,kCAAA;AA1BhB;AA8BgB;EACI,8CAAA;AA5BpB;AAiCwB;EACI,wCAAA;AA/B5B;AAqCY;EACI,WAAA;EACA,cAAA;EACA,UAAA;EACA,qBAAA;EACA,yBAAA;EACA,oBAAA;AAnChB;AAqCgB;EACI,UAAA;AAnCpB;AAuCY;EACI,WAAA;EACA,cAAA;AArChB;AAuCgB;EACI,aAAA;EACA,+BAAA;EACA,mBAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;AArCpB;AAuCoB;EACI,kCAAA;EACA,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;AArCxB;AAwCoB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,wBAAA;AAtCxB;AAwCwB;EACI,yBAAA;AAtC5B;AA2CgB;EACI,mDAAA;AAzCpB;AA4CgB;EACI,mDAAA;AA1CpB;AA+CQ;EACI,wBAAA;EACA,WAAA;EACA,uBAAA;AA7CZ;AA+CY;EACI,wBAAA;EACA,uBAAA;EACA,eAAA;EACA,gBAAA;AA7ChB;AAgDY;EACI,eAAA;EACA,QAAA;EACA,UAAA;EACA,WAAA;EACA,SAAA;EACA,UAAA;AA9ChB;AAiDY;EACI,UAAA;EACA,kBAAA;AA/ChB;AAmDQ;EACI,aAAA;EACA,wBAAA;EACA,oDAAA;EACA,gBAAA;EACA,iBAAA;EACA,mBAAA;AAjDZ;AAmDY;EACI,WAAA;EACA,cAAA;AAjDhB;AAoDY;EACI,WAAA;EACA,cAAA;EACA,eAAA;AAlDhB;AAqDY;EACI,gBAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,iBAAA;AAnDhB;AAsDY;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,wBAAA;EACA,qBAAA;EACA,kBAAA;EACA,kBAAA;AApDhB;AAsDgB;EACI,UAAA;AApDpB;AAwDY;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;AAtDhB;AAwDgB;EACI,YAAA;EACA,WAAA;AAtDpB;AAwDgB;EACI,eAAA;AAtDpB;AAyDY;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;AAvDhB;AAwDgB;EACI,YAAA;EACA,WAAA;AAtDpB;AAwDgB;EACI,eAAA;AAtDpB;AA2DQ;EACI,iBAjXgB;EAkXhB,YAAA;EACA,aAAA;EACA,gCAAA;AAzDZ;AA2DY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAzDhB;AA4DY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;AA3DhB;AA6DgB;EACI,YAAA;AA3DpB;AA+DY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;AA9DhB;AAgEgB;EACI,WAAA;AA9DpB;AAiEgB;;EAEI,wBAAA;EACA,SAAA;AA/DpB;AAkEgB;EACI,0BAAA;AAhEpB;AAqEQ;EACI,iBA9ZgB;EA+ZhB,aAAA;AAnEZ;AAqEY;EACI,aAAA;EACA,oCAAA;EACA,YAAA;AAnEhB;AAqEgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAnEpB;AAsEgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,iBAAA;EACA,YAAA;AApEpB;AAuEgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AArEpB;AAyEY;EACI,aAAA;EACA,kBAAA;EACA,wCAAA;AAvEhB;AAyEgB;EACI,eAAA;AAvEpB;AA0EgB;EACI,aAAA;EACA,+BAAA;AAxEpB;AA2EgB;EACI,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mBAAA;EACA,kBAAA;AAzEpB;AA4EgB;EACI,YAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mCAAA;AA1EpB;AA+EQ;EACI,YAAA;EACA,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,mBAAA;AA7EZ;AA+EY;EACI,YAAA;AA7EhB;AAgFY;EACI,aAAA;AA9EhB;AAiFY;EACI,mBAAA;EACA,mCAAA;EACA,gBAAA;EACA,YAAA;EACA,gBAAA;EACA,gBAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;AA/EhB;AAkFY;EACI,UAAA;AAhFhB;AAmFY;EACI,sBAAA;EACA,yBAAA;AAjFhB;AAoFY;EACI,mBAAA;EACA,mCAAA;EACA,yBAAA;EACA,YAAA;EACA,gBAAA;EACA,YAAA;AAlFhB;AAqFY;EACI,UAAA;AAnFhB;AAsFY;EACI,mBAAA;AApFhB;AAuFY;EACI,mCAAA;EACA,YAAA;AArFhB;AAyFQ;EACI,iBA1hBgB;EA2hBhB,YAAA;EACA,aAAA;EACA,+BAAA;AAvFZ;AAyFY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAvFhB;AA0FY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;AAzFhB;AA2FgB;EACI,kBAAA;EACA,cAAA;EACA,YAAA;EACA,WAAA;EACA,iBAAA;EACA,mBAAA;EACA,oBAAA;EACA,eAAA;EACA,yBAAA;AAzFpB;AA4FgB;EACI,kBAAA;EACA,SAAA;EACA,QAAA;EACA,cAAA;EACA,WAAA;EACA,YAAA;EACA,oBAAA;EACA,gBAAA;EACA,2CAAA;EACA,WAAA;EACA,0BAAA;AA1FpB;AA6FgB;EACI,4BAAA;AA3FpB;AA8FgB;EACI,6BAAA;AA5FpB;AA+FgB;EACI,UAAA;EACA,4BAAA;AA7FpB;AAgGgB;EACI,4BAAA;EACA,eAAA;AA9FpB;AAiGgB;EACI,UAAA;EACA,2BAAA;EACA,eAAA;AA/FpB;AAkGgB;EACI,2BAAA;EACA,eAAA;AAhGpB;AAmGgB;EACI,aAAA;AAjGpB;AAsGQ;EACI,iBAzmBgB;EA0mBhB,YAAA;EACA,aAAA;EACA,+BAAA;AApGZ;AAsGY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AApGhB;AAuGY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;EACA,iBAAA;AAtGhB;AAwGgB;EACI,YAAA;AAtGpB;AA2GQ;EACI,iBAloBgB;EAmoBhB,aAAA;AAzGZ;AA2GY;EACI,YAAA;EACA,aAAA;EACA,6CAAA;AAzGhB;AA2GgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAzGpB;AA4GgB;EACI,aAAA;AA1GpB;AA6GgB;EACI,cAAA;EACA,WAAA;EAEA,aAAA;EACA,mBAAA;AA5GpB;AA8GoB;EACI,iBAAA;AA5GxB;AAgHgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AA9GpB;AAgHoB;EACI,YAAA;EACA,WAAA;AA9GxB;AAkHgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AAhHpB;AAkHoB;EACI,YAAA;EACA,WAAA;AAhHxB;AAqHY;EACI,aAAA;EACA,kBAAA;EACA,wCAAA;AAnHhB;AAqHgB;EACI,aAAA;EACA,+BAAA;AAnHpB;AAsHgB;EACI,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mBAAA;EACA,kBAAA;AApHpB;AAuHgB;EACI,YAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mCAAA;AArHpB;AA0HQ;EACI,iBAztBgB;EA0tBhB,YAAA;EACA,aAAA;EACA,+BAAA;AAxHZ;AA0HY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAxHhB;AA2HY;EACI,cAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;EACA,eAAA;EACA,YAAA;EACA,WAAA;EACA,eAAA;EACA,gBAAA;EACA,0BAAA;EACA,eAAA;AAzHhB;AA4HY;EACI,cAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;EACA,eAAA;EACA,YAAA;EACA,WAAA;EACA,eAAA;EACA,gBAAA;EACA,yBAAA;EACA,sBAAA;EACA,qBAAA;EACA,iBAAA;AA1HhB;AA4HgB;EACI,YAAA;AA1HpB;AA6HgB;EACI,UAAA;AA3HpB",sourcesContent:[`.nme-right-panel {\r #propertyTab {\r $line-padding-left: 5px;\r color: white;\r background: #333333;\r \r #header {\r height: 30px;\r font-size: 16px;\r color: white;\r background: #222222;\r grid-row: 1;\r text-align: center;\r display: grid;\r grid-template-columns: 30px 1fr;\r -webkit-user-select: none;\r -moz-user-select: none;\r -ms-user-select: none;\r user-select: none;\r \r #logo {\r position: relative;\r grid-column: 1;\r width: 24px;\r height: 24px;\r left: 0;\r display: flex;\r align-self: center;\r justify-self: center;\r }\r \r #title {\r grid-column: 2;\r display: grid;\r align-items: center;\r text-align: center;\r }\r }\r \r .range {\r -webkit-appearance: none;\r width: 120px;\r height: 6px;\r background: #d3d3d3;\r border-radius: 5px;\r outline: none;\r opacity: 0.7;\r -webkit-transition: 0.2s;\r transition: opacity 0.2s;\r }\r \r .range:hover {\r opacity: 1;\r }\r \r .range::-webkit-slider-thumb {\r -webkit-appearance: none;\r appearance: none;\r width: 14px;\r height: 14px;\r border-radius: 50%;\r background: rgb(51, 122, 183);\r cursor: pointer;\r }\r \r .range::-moz-range-thumb {\r width: 14px;\r height: 14px;\r border-radius: 50%;\r background: rgb(51, 122, 183);\r cursor: pointer;\r }\r \r input[type="color"] {\r -webkit-appearance: none;\r border: 1px solid rgba(255, 255, 255, 0.5);\r padding: 0;\r width: 30px;\r height: 20px;\r }\r input[type="color"]::-webkit-color-swatch-wrapper {\r padding: 0;\r }\r input[type="color"]::-webkit-color-swatch {\r border: none;\r }\r \r .sliderLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 1fr 50px auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .slider {\r grid-column: 3;\r grid-row: 1;\r margin-right: 5px;\r width: 90%;\r display: flex;\r align-items: center;\r }\r \r .floatLine {\r grid-column: 2;\r padding-left: $line-padding-left;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .short {\r grid-column: 1;\r display: flex;\r align-items: center;\r \r input {\r width: 35px;\r }\r \r input::-webkit-outer-spin-button,\r input::-webkit-inner-spin-button {\r -webkit-appearance: none;\r margin: 0;\r }\r \r input[type="number"] {\r -moz-appearance: textfield;\r }\r }\r }\r }\r \r .textInputLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr 120px auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .value {\r display: flex;\r align-items: center;\r grid-column: 2;\r \r input {\r width: calc(100% - 5px);\r margin-right: 5px;\r }\r }\r }\r \r .textInputArea {\r padding-left: $line-padding-left;\r height: 50px;\r display: grid;\r grid-template-columns: 1fr 120px;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r textarea {\r margin-right: 5px;\r margin-left: -50%;\r height: 40px;\r resize: none;\r }\r \r .value {\r display: flex;\r align-items: center;\r grid-column: 2;\r }\r }\r \r .paneContainer {\r margin-top: 3px;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 100%;\r \r .paneList {\r border-left: 3px solid transparent;\r }\r \r &:hover {\r .paneList {\r border-left: 3px solid rgba(51, 122, 183, 0.8);\r }\r \r .paneContainer-content {\r .header {\r .title {\r border-left: 3px solid rgb(51, 122, 183);\r }\r }\r }\r }\r \r .paneContainer-highlight-border {\r grid-row: 1;\r grid-column: 1;\r opacity: 1;\r border: 3px solid red;\r transition: opacity 250ms;\r pointer-events: none;\r \r &.transparent {\r opacity: 0;\r }\r }\r \r .paneContainer-content {\r grid-row: 1;\r grid-column: 1;\r \r .header {\r display: grid;\r grid-template-columns: 1fr auto;\r background: #555555;\r height: 30px;\r padding-right: 5px;\r cursor: pointer;\r \r .title {\r border-left: 3px solid transparent;\r padding-left: 5px;\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .collapse {\r grid-column: 2;\r display: flex;\r align-items: center;\r justify-items: center;\r transform-origin: center;\r \r &.closed {\r transform: rotate(180deg);\r }\r }\r }\r \r .paneList > div:not(:last-child) {\r border-bottom: 0.5px solid rgba(255, 255, 255, 0.1);\r }\r \r .fragment > div:not(:last-child) {\r border-bottom: 0.5px solid rgba(255, 255, 255, 0.1);\r }\r }\r }\r \r .color-picker {\r height: calc(100% - 8px);\r margin: 4px;\r width: calc(100% - 8px);\r \r .color-rect {\r height: calc(100% - 4px);\r border: 2px white solid;\r cursor: pointer;\r min-height: 18px;\r }\r \r .color-picker-cover {\r position: fixed;\r top: 0px;\r right: 0px;\r bottom: 0px;\r left: 0px;\r z-index: 1;\r }\r \r .color-picker-float {\r z-index: 2;\r position: absolute;\r }\r }\r \r .gradient-step {\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 20px 30px 40px auto 20px 30px;\r padding-top: 5px;\r padding-left: 5px;\r padding-bottom: 5px;\r \r .step {\r grid-row: 1;\r grid-column: 1;\r }\r \r .color {\r grid-row: 1;\r grid-column: 2;\r cursor: pointer;\r }\r \r .step-value {\r margin-left: 5px;\r grid-row: 1;\r grid-column: 3;\r text-align: right;\r margin-right: 5px;\r }\r \r .step-slider {\r grid-row: 1;\r grid-column: 4;\r display: grid;\r justify-content: stretch;\r align-content: center;\r margin-right: -5px;\r padding-left: 12px;\r \r input {\r width: 90%;\r }\r }\r \r .gradient-copy {\r grid-row: 1;\r grid-column: 5;\r display: grid;\r align-content: center;\r justify-content: center;\r \r .img {\r height: 20px;\r width: 20px;\r }\r .img:hover {\r cursor: pointer;\r }\r }\r .gradient-delete {\r grid-row: 1;\r grid-column: 6;\r display: grid;\r align-content: center;\r justify-content: center;\r .img {\r height: 20px;\r width: 20px;\r }\r .img:hover {\r cursor: pointer;\r }\r }\r }\r \r .floatLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr 120px;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .value {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r \r input {\r width: 110px;\r }\r }\r \r .short {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r \r input {\r width: 27px;\r }\r \r input::-webkit-outer-spin-button,\r input::-webkit-inner-spin-button {\r -webkit-appearance: none;\r margin: 0;\r }\r \r input[type="number"] {\r -moz-appearance: textfield;\r }\r }\r }\r \r .vector3Line {\r padding-left: $line-padding-left;\r display: grid;\r \r .firstLine {\r display: grid;\r grid-template-columns: 1fr auto 20px;\r height: 30px;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .vector {\r grid-column: 2;\r display: flex;\r align-items: center;\r text-align: right;\r opacity: 0.8;\r }\r \r .expand {\r grid-column: 3;\r display: grid;\r align-items: center;\r justify-items: center;\r cursor: pointer;\r }\r }\r \r .secondLine {\r display: grid;\r padding-right: 5px;\r border-left: 1px solid rgb(51, 122, 183);\r \r .no-right-margin {\r margin-right: 0;\r }\r \r .numeric {\r display: grid;\r grid-template-columns: 1fr auto;\r }\r \r .numeric-label {\r text-align: right;\r grid-column: 1;\r display: flex;\r align-items: center;\r justify-self: right;\r margin-right: 10px;\r }\r \r .numeric-value {\r width: 120px;\r grid-column: 2;\r display: flex;\r align-items: center;\r border: 1px solid rgb(51, 122, 183);\r }\r }\r }\r \r .buttonLine {\r height: 30px;\r display: grid;\r align-items: center;\r justify-items: stretch;\r padding-bottom: 5px;\r \r &.disabled {\r opacity: 0.3;\r }\r \r input[type="file"] {\r display: none;\r }\r \r .file-upload {\r background: #222222;\r border: 1px solid rgb(51, 122, 183);\r margin: 5px 10px;\r color: white;\r padding: 4px 5px;\r padding-top: 0px;\r opacity: 0.9;\r cursor: pointer;\r text-align: center;\r }\r \r .file-upload:hover {\r opacity: 1;\r }\r \r .file-upload:active {\r transform: scale(0.98);\r transform-origin: 0.5 0.5;\r }\r \r button {\r background: #222222;\r border: 1px solid rgb(51, 122, 183);\r margin: 5px 10px 5px 10px;\r color: white;\r padding: 4px 5px;\r opacity: 0.9;\r }\r \r button:hover {\r opacity: 1;\r }\r \r button:active {\r background: #282828;\r }\r \r button:focus {\r border: 1px solid rgb(51, 122, 183);\r outline: 0px;\r }\r }\r \r .checkBoxLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .checkBox {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r \r .lbl {\r position: relative;\r display: block;\r height: 14px;\r width: 34px;\r margin-right: 5px;\r background: #898989;\r border-radius: 100px;\r cursor: pointer;\r transition: all 0.3s ease;\r }\r \r .lbl:after {\r position: absolute;\r left: 3px;\r top: 2px;\r display: block;\r width: 10px;\r height: 10px;\r border-radius: 100px;\r background: #fff;\r box-shadow: 0px 3px 3px rgba(0, 0, 0, 0.05);\r content: "";\r transition: all 0.15s ease;\r }\r \r .lbl:active:after {\r transform: scale(1.15, 0.85);\r }\r \r .cbx:checked ~ label {\r background: rgb(51, 122, 183);\r }\r \r .cbx:checked ~ label:after {\r left: 20px;\r background: rgb(22, 73, 117);\r }\r \r .cbx:checked ~ label.disabled {\r background: rgb(22, 73, 117);\r cursor: pointer;\r }\r \r .cbx:checked ~ label.disabled:after {\r left: 20px;\r background: rgb(85, 85, 85);\r cursor: pointer;\r }\r \r .cbx ~ label.disabled {\r background: rgb(85, 85, 85);\r cursor: pointer;\r }\r \r .hidden {\r display: none;\r }\r }\r }\r \r .listLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .options {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r margin-right: 5px;\r \r select {\r width: 115px;\r }\r }\r }\r \r .color3Line {\r padding-left: $line-padding-left;\r display: grid;\r \r .firstLine {\r height: 30px;\r display: grid;\r grid-template-columns: 1fr auto 0px 20px 20px;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .textInputLine {\r display: none;\r }\r \r .color3 {\r grid-column: 2;\r width: 50px;\r \r display: flex;\r align-items: center;\r \r input {\r margin-right: 5px;\r }\r }\r \r .copy {\r grid-column: 4;\r display: grid;\r align-items: center;\r justify-items: center;\r cursor: pointer;\r \r img {\r height: 100%;\r width: 24px;\r }\r }\r \r .expand {\r grid-column: 5;\r display: grid;\r align-items: center;\r justify-items: center;\r cursor: pointer;\r \r img {\r height: 100%;\r width: 20px;\r }\r }\r }\r \r .secondLine {\r display: grid;\r padding-right: 5px;\r border-left: 1px solid rgb(51, 122, 183);\r \r .numeric {\r display: grid;\r grid-template-columns: 1fr auto;\r }\r \r .numeric-label {\r text-align: right;\r grid-column: 1;\r display: flex;\r align-items: center;\r justify-self: right;\r margin-right: 10px;\r }\r \r .numeric-value {\r width: 120px;\r grid-column: 2;\r display: flex;\r align-items: center;\r border: 1px solid rgb(51, 122, 183);\r }\r }\r }\r \r .textLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .link-value {\r grid-column: 2;\r white-space: nowrap;\r text-overflow: ellipsis;\r overflow: hidden;\r text-align: end;\r opacity: 0.8;\r margin: 5px;\r margin-top: 6px;\r max-width: 140px;\r text-decoration: underline;\r cursor: pointer;\r }\r \r .value {\r grid-column: 2;\r white-space: nowrap;\r text-overflow: ellipsis;\r overflow: hidden;\r text-align: end;\r opacity: 0.8;\r margin: 5px;\r margin-top: 6px;\r max-width: 200px;\r -webkit-user-select: text;\r -moz-user-select: text;\r -ms-user-select: text;\r user-select: text;\r \r &.check {\r color: green;\r }\r \r &.uncheck {\r color: red;\r }\r }\r }\r }\r }\r `],sourceRoot:""}]),p.locals={};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../tools/nodeEditor/dist/main.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`#node-editor-graph-root { display: grid; grid-template-rows: calc(100% - 120px) 120px; height: 100%; width: 100%; background: #464646; font: 14px "acumin-pro"; } #node-editor-graph-root.popup { grid-template-columns: 100%; overflow: hidden; } #node-editor-graph-root .wait-screen { display: grid; justify-content: center; align-content: center; height: 100%; width: 100%; background: #464646; opacity: 0.95; color: white; font: 24px "acumin-pro"; position: absolute; top: 0; left: 0; } #node-editor-graph-root .wait-screen.hidden { visibility: hidden; } #node-editor-graph-root #nmeNodeList { grid-row: 1/span 2; grid-column: 1; } #node-editor-graph-root #leftGrab { grid-row: 1/span 2; grid-column: 2; cursor: ew-resize; } #node-editor-graph-root #rightGrab { grid-row: 1/span 2; grid-column: 4; cursor: ew-resize; } #node-editor-graph-root .diagram-container { grid-row: 1; grid-column: 3; background: #5f5b60; width: 100%; height: 100%; } #node-editor-graph-root .diagram-container .diagram { display: none; width: 100%; height: 100%; } #node-editor-graph-root .nme-right-panel { grid-row: 1/span 2; grid-column: 5; display: grid; grid-template-rows: 1fr 40px auto 40px; grid-template-columns: 100%; height: 100%; overflow-y: auto; } #node-editor-graph-root #propertyTab { grid-row: 1; grid-column: 1; } #node-editor-graph-root .button { display: grid; justify-content: center; align-content: center; height: auto; width: 14.2857142857%; cursor: pointer; } #node-editor-graph-root .button:hover { background: rgb(51, 122, 183); color: white; opacity: 0.8; } #node-editor-graph-root .button.selected { background: rgb(51, 122, 183); color: white; } #node-editor-graph-root .button.align { justify-content: stretch; text-align: center; } #node-editor-graph-root #preview-mesh-bar { grid-row: 2; grid-column: 1; display: grid; grid-template-columns: auto 1fr 40px 40px 40px; align-items: center; font-size: 18px; background-color: #555555; } #node-editor-graph-root #preview-mesh-bar #file-picker { display: none; } #node-editor-graph-root #preview-mesh-bar .listLine { grid-column: 1; height: 40px; display: grid; grid-template-columns: 0px 1fr; } #node-editor-graph-root #preview-mesh-bar .listLine .label { grid-column: 1; display: flex; align-items: center; font-size: 14px; } #node-editor-graph-root #preview-mesh-bar .listLine .options { grid-column: 2; display: flex; align-items: center; margin-left: 5px; } #node-editor-graph-root #preview-mesh-bar .listLine .options select { width: 115px; } #node-editor-graph-root #preview-mesh-bar .button { color: #ffffff; width: 40px; height: 40px; transform-origin: 50% 50%; } #node-editor-graph-root #preview-mesh-bar .button:active { transform: scale(0.9); } #node-editor-graph-root #preview-mesh-bar .button:hover { background: #3f3461; } #node-editor-graph-root #preview-mesh-bar .button.selected { background: #9379e6; } #node-editor-graph-root #preview-mesh-bar .button img { height: 24px; width: 24px; } #node-editor-graph-root #preview-mesh-bar #play-button { grid-column: 3; } #node-editor-graph-root #preview-mesh-bar #color-picker-button { grid-column: 4; display: grid; grid-template-columns: 100%; grid-template-rows: 100%; } #node-editor-graph-root #preview-mesh-bar #color-picker-button img { height: 24px; width: 24px; } #node-editor-graph-root #preview-mesh-bar #color-picker-button #color-picker-image { padding-left: 7px; padding-top: 8px; } #node-editor-graph-root #preview-mesh-bar #color-picker-button #color-picker { transform: scale(0); grid-column: 1; grid-row: 1; } #node-editor-graph-root #preview-mesh-bar #color-picker-button #color-picker-label { width: 100%; background: transparent; cursor: pointer; } #node-editor-graph-root #preview-mesh-bar #preview-new-window { grid-column: 5; } #node-editor-graph-root #preview-mesh-bar select { background-color: #a3a3a3; color: #333333; } #node-editor-graph-root #preview-config-bar { grid-row: 4; grid-column: 1; display: grid; grid-template-columns: 40px 40px 40px 1fr 40px 40px; color: white; align-items: center; font-size: 18px; } #node-editor-graph-root #preview-config-bar.extended { grid-template-columns: 1fr; } #node-editor-graph-root #preview-config-bar .listLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr auto; } #node-editor-graph-root #preview-config-bar .listLine .label { grid-column: 1; display: flex; align-items: center; font-size: 14px; } #node-editor-graph-root #preview-config-bar .listLine .options { grid-column: 2; display: flex; align-items: center; margin-right: 5px; } #node-editor-graph-root #preview-config-bar .listLine .options select { width: 115px; } #node-editor-graph-root #preview-config-bar .button { width: 40px; grid-row: 1; height: 40px; transform-origin: 50% 50%; } #node-editor-graph-root #preview-config-bar .button:hover { background: #3f3461; } #node-editor-graph-root #preview-config-bar .button.selected { background: #9379e6; } #node-editor-graph-root #preview-config-bar .button:active { transform: scale(0.9); } #node-editor-graph-root #preview-config-bar .button img { height: auto; width: 100%; } #node-editor-graph-root #preview-config-bar .button.back-face { grid-column: 6; } #node-editor-graph-root #preview-config-bar .button.depth-pass { grid-column: 5/6; } #node-editor-graph-root #preview-config-bar .button.hemispheric-light { grid-column: 3/4; } #node-editor-graph-root #preview-config-bar .button.direction-light-1 { grid-column: 2/3; } #node-editor-graph-root #preview-config-bar .button.direction-light-0 { grid-column: 1/2; } #node-editor-graph-root #preview { border-top: 1px solid rgb(85, 85, 85); grid-row: 3; grid-column: 1; width: 100%; display: grid; grid-template-columns: 100%; grid-template-rows: 100%; outline: 0 !important; padding: 0 !important; user-select: none; overflow: hidden; } #node-editor-graph-root #preview #preview-canvas { width: 100%; height: 100%; outline: 0 !important; padding: 0 !important; grid-row: 1; grid-column: 1; } #node-editor-graph-root #preview .waitPanel { width: 100%; height: 100%; grid-row: 1; grid-column: 1; color: white; font-size: 18px; align-content: center; justify-content: center; background: rgba(20, 20, 20, 0.95); z-index: 10; display: grid; transition: opacity 250ms; } #node-editor-graph-root #preview .waitPanel.hidden { opacity: 0; pointer-events: none; } #node-editor-graph-root .blocker { visibility: hidden; position: absolute; width: calc(100% - 40px); height: 100%; top: 0; left: 0; background: rgba(20, 20, 20, 0.95); font-family: "acumin-pro"; color: white; font-size: 24px; display: grid; align-content: center; justify-content: center; user-select: none; padding: 20px; text-align: center; } #node-editor-graph-root #log-console { grid-row: 2; grid-column: 3; } #node-editor-graph-root .LightInformationBlock { width: 280px; } #node-editor-graph-root .InputBlock { width: 250px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/main.scss"],names:[],mappings:"AAAA;EACI,aAAA;EACA,4CAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,uBAAA;AACJ;AACI;EACI,2BAAA;EACA,gBAAA;AACR;AAEI;EACI,aAAA;EACA,uBAAA;EACA,qBAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,aAAA;EACA,YAAA;EACA,uBAAA;EACA,kBAAA;EACA,MAAA;EACA,OAAA;AAAR;AAEQ;EACI,kBAAA;AAAZ;AAII;EACI,kBAAA;EACA,cAAA;AAFR;AAKI;EACI,kBAAA;EACA,cAAA;EACA,iBAAA;AAHR;AAMI;EACI,kBAAA;EACA,cAAA;EACA,iBAAA;AAJR;AAOI;EACI,WAAA;EACA,cAAA;EACA,mBAAA;EACA,WAAA;EACA,YAAA;AALR;AAOQ;EACI,aAAA;EACA,WAAA;EACA,YAAA;AALZ;AASI;EACI,kBAAA;EACA,cAAA;EACA,aAAA;EACA,sCAAA;EACA,2BAAA;EACA,YAAA;EACA,gBAAA;AAPR;AAUI;EACI,WAAA;EACA,cAAA;AARR;AAWI;EACI,aAAA;EACA,uBAAA;EACA,qBAAA;EACA,YAAA;EACA,qBAAA;EACA,eAAA;AATR;AAWQ;EACI,6BAAA;EACA,YAAA;EACA,YAAA;AATZ;AAYQ;EACI,6BAAA;EACA,YAAA;AAVZ;AAaQ;EACI,wBAAA;EACA,kBAAA;AAXZ;AAeI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,8CAAA;EACA,mBAAA;EACA,eAAA;EACA,yBAAA;AAbR;AAeQ;EACI,aAAA;AAbZ;AAgBQ;EACI,cAAA;EACA,YAAA;EACA,aAAA;EACA,8BAAA;AAdZ;AAgBY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;AAdhB;AAiBY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;EACA,gBAAA;AAhBhB;AAkBgB;EACI,YAAA;AAhBpB;AAqBQ;EACI,cAAA;EACA,WAAA;EACA,YAAA;EACA,yBAAA;AAnBZ;AAqBY;EACI,qBAAA;AAnBhB;AAsBY;EACI,mBAAA;AApBhB;AAuBY;EACI,mBAAA;AArBhB;AAwBY;EACI,YAAA;EACA,WAAA;AAtBhB;AA0BQ;EACI,cAAA;AAxBZ;AA2BQ;EACI,cAAA;EACA,aAAA;EACA,2BAAA;EACA,wBAAA;AAzBZ;AA2BY;EACI,YAAA;EACA,WAAA;AAzBhB;AA2BY;EACI,iBAAA;EACA,gBAAA;AAzBhB;AA4BY;EACI,mBAAA;EACA,cAAA;EACA,WAAA;AA1BhB;AA6BY;EACI,WAAA;EACA,uBAAA;EACA,eAAA;AA3BhB;AA+BQ;EACI,cAAA;AA7BZ;AAgCQ;EACI,yBAAA;EACA,cAAA;AA9BZ;AAkCI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,mDAAA;EACA,YAAA;EACA,mBAAA;EACA,eAAA;AAhCR;AAkCQ;EACI,0BAAA;AAhCZ;AAmCQ;EACI,iBAAA;EACA,YAAA;EACA,aAAA;EACA,+BAAA;AAjCZ;AAmCY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;AAjChB;AAoCY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;EACA,iBAAA;AAnChB;AAqCgB;EACI,YAAA;AAnCpB;AAwCQ;EACI,WAAA;EACA,WAAA;EACA,YAAA;EACA,yBAAA;AAtCZ;AAwCY;EACI,mBAAA;AAtChB;AAyCY;EACI,mBAAA;AAvChB;AA0CY;EACI,qBAAA;AAxChB;AA2CY;EACI,YAAA;EACA,WAAA;AAzChB;AA4CY;EACI,cAAA;AA1ChB;AA6CY;EACI,gBAAA;AA3ChB;AA8CY;EACI,gBAAA;AA5ChB;AA8CY;EACI,gBAAA;AA5ChB;AA8CY;EACI,gBAAA;AA5ChB;AAiDI;EACI,qCAAA;EACA,WAAA;EACA,cAAA;EACA,WAAA;EACA,aAAA;EACA,2BAAA;EACA,wBAAA;EACA,qBAAA;EACA,qBAAA;EACA,iBAAA;EACA,gBAAA;AA/CR;AAiDQ;EACI,WAAA;EACA,YAAA;EACA,qBAAA;EACA,qBAAA;EACA,WAAA;EACA,cAAA;AA/CZ;AAkDQ;EACI,WAAA;EACA,YAAA;EACA,WAAA;EACA,cAAA;EACA,YAAA;EACA,eAAA;EACA,qBAAA;EACA,uBAAA;EACA,kCAAA;EACA,WAAA;EACA,aAAA;EACA,yBAAA;AAhDZ;AAkDY;EACI,UAAA;EACA,oBAAA;AAhDhB;AAqDI;EACI,kBAAA;EACA,kBAAA;EACA,wBAAA;EACA,YAAA;EACA,MAAA;EACA,OAAA;EAEA,kCAAA;EACA,yBAAA;EACA,YAAA;EACA,eAAA;EAEA,aAAA;EACA,qBAAA;EACA,uBAAA;EAEA,iBAAA;EAEA,aAAA;EACA,kBAAA;AAvDR;AA0DI;EACI,WAAA;EACA,cAAA;AAxDR;AA2DI;EACI,YAAA;AAzDR;AA4DI;EACI,YAAA;AA1DR",sourcesContent:[`#node-editor-graph-root {\r display: grid;\r grid-template-rows: calc(100% - 120px) 120px;\r height: 100%;\r width: 100%;\r background: #464646;\r font: 14px "acumin-pro";\r \r &.popup {\r grid-template-columns: 100%;\r overflow: hidden;\r }\r \r .wait-screen {\r display: grid;\r justify-content: center;\r align-content: center;\r height: 100%;\r width: 100%;\r background: #464646;\r opacity: 0.95;\r color: white;\r font: 24px "acumin-pro";\r position: absolute;\r top: 0;\r left: 0;\r \r &.hidden {\r visibility: hidden;\r }\r }\r \r #nmeNodeList {\r grid-row: 1 / span 2;\r grid-column: 1;\r }\r \r #leftGrab {\r grid-row: 1 / span 2;\r grid-column: 2;\r cursor: ew-resize;\r }\r \r #rightGrab {\r grid-row: 1 / span 2;\r grid-column: 4;\r cursor: ew-resize;\r }\r \r .diagram-container {\r grid-row: 1;\r grid-column: 3;\r background: #5f5b60;\r width: 100%;\r height: 100%;\r \r .diagram {\r display: none;\r width: 100%;\r height: 100%;\r }\r }\r \r .nme-right-panel {\r grid-row: 1 / span 2;\r grid-column: 5;\r display: grid;\r grid-template-rows: 1fr 40px auto 40px;\r grid-template-columns: 100%;\r height: 100%;\r overflow-y: auto;\r }\r \r #propertyTab {\r grid-row: 1;\r grid-column: 1;\r }\r \r .button {\r display: grid;\r justify-content: center;\r align-content: center;\r height: auto;\r width: calc(100% / 7);\r cursor: pointer;\r \r &:hover {\r background: rgb(51, 122, 183);\r color: white;\r opacity: 0.8;\r }\r \r &.selected {\r background: rgb(51, 122, 183);\r color: white;\r }\r \r &.align {\r justify-content: stretch;\r text-align: center;\r }\r }\r \r #preview-mesh-bar {\r grid-row: 2;\r grid-column: 1;\r display: grid;\r grid-template-columns: auto 1fr 40px 40px 40px;\r align-items: center;\r font-size: 18px;\r background-color: #555555;\r \r #file-picker {\r display: none;\r }\r \r .listLine {\r grid-column: 1;\r height: 40px;\r display: grid;\r grid-template-columns: 0px 1fr;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r font-size: 14px;\r }\r \r .options {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r margin-left: 5px;\r \r select {\r width: 115px;\r }\r }\r }\r \r .button {\r color: #ffffff;\r width: 40px;\r height: 40px;\r transform-origin: 50% 50%;\r \r &:active {\r transform: scale(0.9);\r }\r \r &:hover {\r background: #3f3461;\r }\r \r &.selected {\r background: #9379e6;\r }\r \r img {\r height: 24px;\r width: 24px;\r }\r }\r \r #play-button {\r grid-column: 3;\r }\r \r #color-picker-button {\r grid-column: 4;\r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 100%;\r \r img {\r height: 24px;\r width: 24px;\r }\r #color-picker-image {\r padding-left: 7px;\r padding-top: 8px;\r }\r \r #color-picker {\r transform: scale(0);\r grid-column: 1;\r grid-row: 1;\r }\r \r #color-picker-label {\r width: 100%;\r background: transparent;\r cursor: pointer;\r }\r }\r \r #preview-new-window {\r grid-column: 5;\r }\r \r select {\r background-color: #a3a3a3;\r color: #333333;\r }\r }\r \r #preview-config-bar {\r grid-row: 4;\r grid-column: 1;\r display: grid;\r grid-template-columns: 40px 40px 40px 1fr 40px 40px;\r color: white;\r align-items: center;\r font-size: 18px;\r \r &.extended {\r grid-template-columns: 1fr;\r }\r \r .listLine {\r padding-left: 5px;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r font-size: 14px;\r }\r \r .options {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r margin-right: 5px;\r \r select {\r width: 115px;\r }\r }\r }\r \r .button {\r width: 40px;\r grid-row: 1;\r height: 40px;\r transform-origin: 50% 50%;\r \r &:hover {\r background: #3f3461;\r }\r \r &.selected {\r background: #9379e6;\r }\r \r &:active {\r transform: scale(0.9);\r }\r \r img {\r height: auto;\r width: 100%;\r }\r \r &.back-face {\r grid-column: 6;\r }\r \r &.depth-pass {\r grid-column: 5 / 6;\r }\r \r &.hemispheric-light {\r grid-column: 3 / 4;\r }\r &.direction-light-1 {\r grid-column: 2 / 3;\r }\r &.direction-light-0 {\r grid-column: 1 / 2;\r }\r }\r }\r \r #preview {\r border-top: 1px solid rgb(85, 85, 85);\r grid-row: 3;\r grid-column: 1;\r width: 100%;\r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 100%;\r outline: 0 !important;\r padding: 0 !important;\r user-select: none;\r overflow: hidden;\r \r #preview-canvas {\r width: 100%;\r height: 100%;\r outline: 0 !important;\r padding: 0 !important;\r grid-row: 1;\r grid-column: 1;\r }\r \r .waitPanel {\r width: 100%;\r height: 100%;\r grid-row: 1;\r grid-column: 1;\r color: white;\r font-size: 18px;\r align-content: center;\r justify-content: center;\r background: rgba(20, 20, 20, 0.95);\r z-index: 10;\r display: grid;\r transition: opacity 250ms;\r \r &.hidden {\r opacity: 0;\r pointer-events: none;\r }\r }\r }\r \r .blocker {\r visibility: hidden;\r position: absolute;\r width: calc(100% - 40px);\r height: 100%;\r top: 0;\r left: 0;\r \r background: rgba(20, 20, 20, 0.95);\r font-family: "acumin-pro";\r color: white;\r font-size: 24px;\r \r display: grid;\r align-content: center;\r justify-content: center;\r \r user-select: none;\r \r padding: 20px;\r text-align: center;\r }\r \r #log-console {\r grid-row: 2;\r grid-column: 3;\r }\r \r .LightInformationBlock {\r width: 280px;\r }\r \r .InputBlock {\r width: 250px;\r }\r }\r `],sourceRoot:""}]),p.locals={};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/components/MessageDialog.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container { position: absolute; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.6); display: grid; font-family: "acumin-pro"; top: 0; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog { align-self: center; justify-self: center; min-height: 140px; max-width: 400px; border-radius: 10px; background: white; padding: 10px; display: grid; grid-template-columns: 100%; grid-template-rows: 1fr 50px; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-message { grid-row: 1; grid-column: 1; margin-top: 20px; padding: 10px; font-size: 18px; color: black; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-buttons { grid-row: 2; grid-column: 1; display: grid; grid-template-rows: 100%; grid-template-columns: 100%; color: white; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-buttons .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-button-ok { cursor: pointer; justify-self: center; background: green; min-width: 80px; justify-content: center; display: grid; align-content: center; align-self: center; height: 35px; border-radius: 10px; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-buttons .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-button-ok:hover { opacity: 0.8; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-buttons .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-button-ok.\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__error { background: red; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/components/MessageDialog.modules.scss"],names:[],mappings:"AAAA;EACI,kBAAA;EACA,WAAA;EACA,YAAA;EACA,8BAAA;EACA,aAAA;EACA,yBAAA;EACA,MAAA;AACJ;AACI;EACI,kBAAA;EACA,oBAAA;EACA,iBAAA;EACA,gBAAA;EACA,mBAAA;EACA,iBAAA;EACA,aAAA;EAEA,aAAA;EACA,2BAAA;EACA,4BAAA;AAAR;AAEQ;EACI,WAAA;EACA,cAAA;EACA,gBAAA;EACA,aAAA;EACA,eAAA;EACA,YAAA;AAAZ;AAGQ;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,wBAAA;EACA,2BAAA;EACA,YAAA;AADZ;AAGY;EACI,eAAA;EACA,oBAAA;EACA,iBAAA;EACA,eAAA;EACA,uBAAA;EACA,aAAA;EACA,qBAAA;EACA,kBAAA;EACA,YAAA;EACA,mBAAA;AADhB;AAGgB;EACI,YAAA;AADpB;AAIgB;EACI,eAAA;AAFpB",sourcesContent:[`:local .dialog-container {\r position: absolute;\r width: 100%;\r height: 100%;\r background: rgba(0.1, 0.1, 0.1, 0.6);\r display: grid;\r font-family: "acumin-pro";\r top: 0;\r \r .dialog {\r align-self: center;\r justify-self: center;\r min-height: 140px;\r max-width: 400px;\r border-radius: 10px;\r background: white;\r padding: 10px;\r \r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 1fr 50px;\r \r .dialog-message {\r grid-row: 1;\r grid-column: 1;\r margin-top: 20px;\r padding: 10px;\r font-size: 18px;\r color: black;\r }\r \r .dialog-buttons {\r grid-row: 2;\r grid-column: 1;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 100%;\r color: white;\r \r .dialog-button-ok {\r cursor: pointer;\r justify-self: center;\r background: green;\r min-width: 80px;\r justify-content: center;\r display: grid;\r align-content: center;\r align-self: center;\r height: 35px;\r border-radius: 10px;\r \r &:hover {\r opacity: 0.8;\r }\r \r &.error {\r background: red;\r }\r }\r }\r }\r }\r `],sourceRoot:""}]),p.locals={"dialog-container":"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container",dialog:"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog","dialog-message":"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-message","dialog-buttons":"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-buttons","dialog-button-ok":"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-button-ok",error:"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__error"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/common.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__hidden { display: none !important; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port { border-radius: 20px; width: 20px; height: 20px; align-self: center; display: grid; grid-template-columns: 100%; grid-template-rows: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__img { width: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port:hover, .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__selected { filter: brightness(2); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine { height: 24px; display: grid; grid-template-rows: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port-label { align-items: center; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__inputsContainer { grid-row: 1; grid-column: 1; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__inputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine { grid-template-columns: 12px calc(100% - 15px); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__inputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port-label { grid-row: 1; grid-column: 2; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__inputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port { grid-row: 1; grid-column: 1; transform: translateX(-12px); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__outputsContainer { grid-row: 1; grid-column: 2; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__outputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine { grid-template-columns: calc(100% - 10px) 12px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__outputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port-label { grid-row: 1; grid-column: 1; text-align: right; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__outputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port { grid-row: 1; grid-column: 2; transform: translateX(2px); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__frame-box { position: absolute; background: rgba(72, 72, 72, 0.7); display: grid; grid-template-rows: 40px calc(100% - 40px); grid-template-columns: 100%; box-sizing: border-box; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/common.modules.scss"],names:[],mappings:"AAAA;EACI,wBAAA;AACJ;;AAEA;EACI,mBAAA;EACA,WAAA;EACA,YAAA;EACA,kBAAA;EACA,aAAA;EACA,2BAAA;EACA,wBAAA;AACJ;AACI;EACI,WAAA;AACR;AAEI;EAEI,qBAAA;AADR;;AAKA;EACI,YAAA;EACA,aAAA;EACA,wBAAA;AAFJ;;AAKA;EACI,mBAAA;AAFJ;;AAKA;EACI,WAAA;EACA,cAAA;AAFJ;AAII;EACI,6CAAA;AAFR;AAIQ;EACI,WAAA;EACA,cAAA;AAFZ;AAKQ;EACI,WAAA;EACA,cAAA;EACA,4BAAA;AAHZ;;AAQA;EACI,WAAA;EACA,cAAA;AALJ;AAOI;EACI,6CAAA;AALR;AAOQ;EACI,WAAA;EACA,cAAA;EACA,iBAAA;AALZ;AAQQ;EACI,WAAA;EACA,cAAA;EACA,0BAAA;AANZ;;AAWA;EACI,kBAAA;EACA,iCAAA;EACA,aAAA;EACA,0CAAA;EACA,2BAAA;EACA,sBAAA;AARJ",sourcesContent:[`.hidden {\r display: none !important;\r }\r \r .port {\r border-radius: 20px;\r width: 20px;\r height: 20px;\r align-self: center;\r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 100%;\r \r .img {\r width: 100%;\r }\r \r &:hover,\r &.selected {\r filter: brightness(2);\r }\r }\r \r .portLine {\r height: 24px;\r display: grid;\r grid-template-rows: 100%;\r }\r \r .port-label {\r align-items: center;\r }\r \r .inputsContainer {\r grid-row: 1;\r grid-column: 1;\r \r .portLine {\r grid-template-columns: 12px calc(100% - 15px);\r \r .port-label {\r grid-row: 1;\r grid-column: 2;\r }\r \r .port {\r grid-row: 1;\r grid-column: 1;\r transform: translateX(-12px);\r }\r }\r }\r \r .outputsContainer {\r grid-row: 1;\r grid-column: 2;\r \r .portLine {\r grid-template-columns: calc(100% - 10px) 12px;\r \r .port-label {\r grid-row: 1;\r grid-column: 1;\r text-align: right;\r }\r \r .port {\r grid-row: 1;\r grid-column: 2;\r transform: translateX(2px);\r }\r }\r }\r \r .frame-box {\r position: absolute;\r background: rgba(72, 72, 72, 0.7);\r display: grid;\r grid-template-rows: 40px calc(100% - 40px);\r grid-template-columns: 100%;\r box-sizing: border-box;\r }\r `],sourceRoot:""}]),p.locals={hidden:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__hidden",port:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port",img:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__img",selected:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__selected",portLine:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine","port-label":"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port-label",inputsContainer:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__inputsContainer",outputsContainer:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__outputsContainer","frame-box":"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__frame-box"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphCanvas.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-canvas { width: 100%; height: 100%; margin: 0; padding: 0; font: 14px "acumin-pro"; user-select: none; overflow: hidden; cursor: move; position: relative; background-image: linear-gradient(to right, #4f4e4f 1px, transparent 1px), linear-gradient(to bottom, #4f4e4f 1px, transparent 1px); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-container { width: 100%; height: 100%; left: 0; top: 0; transform-origin: left top; display: grid; grid-template-rows: 100%; grid-template-columns: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__frame-container { overflow: visible; grid-row: 1; grid-column: 1; position: relative; width: 100%; height: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-svg-container { grid-row: 1; grid-column: 1; position: relative; width: 100%; height: 100%; overflow: visible; pointer-events: none; z-index: 2; filter: drop-shadow(7px 6px 2px rgba(0, 0, 0, 0.2)); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-canvas-container { grid-row: 1; grid-column: 1; position: relative; width: 100%; height: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__selection-container { pointer-events: none; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__selection-box { z-index: 10; position: absolute; background: rgba(72, 72, 196, 0.5); border: blue solid 2px; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphCanvas.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;EACA,SAAA;EACA,UAAA;EACA,uBAAA;EACA,iBAAA;EACA,gBAAA;EACA,YAAA;EACA,kBAAA;EACA,mIAAA;AACJ;;AAEA;EACI,WAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;EACA,0BAAA;EACA,aAAA;EACA,wBAAA;EACA,2BAAA;AACJ;;AAEA;EACI,iBAAA;EACA,WAAA;EACA,cAAA;EACA,kBAAA;EACA,WAAA;EACA,YAAA;AACJ;;AAEA;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,WAAA;EACA,YAAA;EACA,iBAAA;EACA,oBAAA;EACA,UAAA;EACA,mDAAA;AACJ;;AAEA;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,WAAA;EACA,YAAA;AACJ;;AAEA;EACI,oBAAA;AACJ;;AAEA;EACI,WAAA;EACA,kBAAA;EACA,kCAAA;EACA,sBAAA;AACJ",sourcesContent:[`.graph-canvas {\r width: 100%;\r height: 100%;\r margin: 0;\r padding: 0;\r font: 14px "acumin-pro";\r user-select: none;\r overflow: hidden;\r cursor: move;\r position: relative;\r background-image: linear-gradient(to right, #4f4e4f 1px, transparent 1px), linear-gradient(to bottom, #4f4e4f 1px, transparent 1px);\r }\r \r .graph-container {\r width: 100%;\r height: 100%;\r left: 0;\r top: 0;\r transform-origin: left top;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 100%;\r }\r \r .frame-container {\r overflow: visible;\r grid-row: 1;\r grid-column: 1;\r position: relative;\r width: 100%;\r height: 100%;\r }\r \r .graph-svg-container {\r grid-row: 1;\r grid-column: 1;\r position: relative;\r width: 100%;\r height: 100%;\r overflow: visible;\r pointer-events: none;\r z-index: 2;\r filter: drop-shadow(7px 6px 2px rgba(0, 0, 0, 0.2));\r }\r \r .graph-canvas-container {\r grid-row: 1;\r grid-column: 1;\r position: relative;\r width: 100%;\r height: 100%;\r }\r \r .selection-container {\r pointer-events: none;\r }\r \r .selection-box {\r z-index: 10;\r position: absolute;\r background: rgba(72, 72, 196, 0.5);\r border: blue solid 2px;\r }\r `],sourceRoot:""}]),p.locals={"graph-canvas":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-canvas","graph-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-container","frame-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__frame-container","graph-svg-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-svg-container","graph-canvas-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-canvas-container","selection-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__selection-container","selection-box":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__selection-box"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphFrame.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__port-container { margin-top: 6px; margin-bottom: 6px; margin-left: 4px; margin-right: 4px; color: white; grid-row: 2; grid-column: 1; display: grid; grid-template-rows: 100%; grid-template-columns: 50% 50%; z-index: 2; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-border { grid-row: 1/span 2; grid-column: 1; width: 100%; height: 100%; border: transparent solid 4px; pointer-events: none; box-sizing: border-box; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-comments { display: grid; grid-row: 2; grid-column: 1; padding: 0 10px; font-style: italic; word-wrap: break-word; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__selected.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-border { border-color: white; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header { grid-row: 1; grid-column: 1; background: rgb(72, 72, 72); color: white; text-align: center; display: grid; grid-template-rows: 100%; grid-template-columns: calc(100% - 74px) 30px 7px 30px 7px; align-content: center; overflow: hidden; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-button { cursor: pointer; align-self: center; transform-origin: 50% 50%; transform: scale(1); stroke: transparent; fill: white; display: grid; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-button.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__down { transform: scale(0.9); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-collapse { grid-column: 2; grid-row: 1; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-close { grid-column: 4; grid-row: 1; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-title { grid-column: 1; grid-row: 1; display: grid; height: 100%; width: 100%; align-self: stretch; align-items: center; margin-top: -2px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__right-handle { grid-area: 1/2/3/2; width: 4px; background-color: transparent; cursor: ew-resize; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__right-handle::after { content: ""; width: 8px; position: absolute; top: 0; bottom: 0; margin-left: -4px; cursor: ew-resize; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-right-corner-handle { background-color: transparent; height: 4px; z-index: 21; cursor: ne-resize; width: 4px; margin-left: -6px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-right-corner-handle::after { background-color: transparent; cursor: ne-resize; margin-left: unset; top: -4px; height: 10px; width: 10px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-right-corner-handle { background-color: transparent; height: 0px; z-index: 21; cursor: nw-resize; grid-area: 4/2/4/2; margin-left: -2px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-right-corner-handle::after { background-color: transparent; height: 10px; cursor: nw-resize; top: unset; bottom: -4px; width: 10px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__left-handle { grid-area: 1/1/3/1; width: 4px; background-color: transparent; cursor: ew-resize; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__left-handle::before { content: ""; width: 8px; position: absolute; top: 0; bottom: 0; margin-left: -4px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-left-corner-handle { background-color: transparent; height: 4px; z-index: 21; cursor: nw-resize; width: 4px; margin-left: -4px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-left-corner-handle::before { background-color: transparent; cursor: nw-resize; margin-left: unset; top: -4px; height: 10px; width: 10px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-left-corner-handle { background-color: transparent; height: 0px; z-index: 21; cursor: sw-resize; grid-area: 4/1/4/1; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-left-corner-handle::before { background-color: transparent; height: 10px; cursor: sw-resize; top: unset; bottom: -4px; width: 10px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-handle { grid-area: 1/1/1/1; background-color: transparent; height: 4px; cursor: ns-resize; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-handle::before { content: ""; width: 100%; position: absolute; top: -4px; bottom: 100%; right: 0; left: 0; margin-bottom: -8px; cursor: ns-resize; height: 8px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-handle { grid-area: 3/1/3/1; background-color: transparent; height: 4px; cursor: ns-resize; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-handle::after { content: ""; width: 100%; position: absolute; top: 100%; bottom: 0; right: 0; left: 0; margin-top: -8px; cursor: ns-resize; height: 12px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__expanded { font-size: 24px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__collapsed { height: auto !important; width: 200px !important; z-index: 3; font-size: 16px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__collapsedHeader { grid-template-columns: calc(100% - 37px) 30px 7px; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphFrame.modules.scss"],names:[],mappings:"AAAA;EACI,eAAA;EACA,kBAAA;EACA,gBAAA;EACA,iBAAA;EACA,YAAA;EACA,WAAA;EACA,cAAA;EACA,aAAA;EACA,wBAAA;EACA,8BAAA;EACA,UAAA;AACJ;;AAEA;EACI,kBAAA;EACA,cAAA;EACA,WAAA;EACA,YAAA;EACA,6BAAA;EACA,oBAAA;EACA,sBAAA;AACJ;;AAEA;EACI,aAAA;EACA,WAAA;EACA,cAAA;EACA,eAAA;EACA,kBAAA;EACA,qBAAA;AACJ;;AAEA;EACI,mBAAA;AACJ;;AAEA;EACI,WAAA;EACA,cAAA;EACA,2BAAA;EACA,YAAA;EACA,kBAAA;EACA,aAAA;EACA,wBAAA;EACA,0DAAA;EACA,qBAAA;EACA,gBAAA;AACJ;;AAEA;EACI,eAAA;EACA,kBAAA;EACA,yBAAA;EACA,mBAAA;EACA,mBAAA;EACA,WAAA;EACA,aAAA;AACJ;AACI;EACI,qBAAA;AACR;;AAGA;EACI,cAAA;EACA,WAAA;AAAJ;;AAGA;EACI,cAAA;EACA,WAAA;AAAJ;;AAGA;EACI,cAAA;EACA,WAAA;EACA,aAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,mBAAA;EACA,gBAAA;AAAJ;;AAGA;EACI,kBAAA;EACA,UAAA;EACA,6BAAA;EACA,iBAAA;AAAJ;AAEI;EACI,WAAA;EACA,UAAA;EACA,kBAAA;EACA,MAAA;EACA,SAAA;EACA,iBAAA;EACA,iBAAA;AAAR;;AAIA;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,UAAA;EACA,iBAAA;AADJ;AAGI;EACI,6BAAA;EACA,iBAAA;EACA,kBAAA;EACA,SAAA;EACA,YAAA;EACA,WAAA;AADR;;AAKA;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,kBAAA;EACA,iBAAA;AAFJ;AAII;EACI,6BAAA;EACA,YAAA;EACA,iBAAA;EACA,UAAA;EACA,YAAA;EACA,WAAA;AAFR;;AAMA;EACI,kBAAA;EACA,UAAA;EACA,6BAAA;EACA,iBAAA;AAHJ;AAKI;EACI,WAAA;EACA,UAAA;EACA,kBAAA;EACA,MAAA;EACA,SAAA;EACA,iBAAA;AAHR;;AAOA;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,UAAA;EACA,iBAAA;AAJJ;AAMI;EACI,6BAAA;EACA,iBAAA;EACA,kBAAA;EACA,SAAA;EACA,YAAA;EACA,WAAA;AAJR;;AAQA;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,kBAAA;AALJ;AAOI;EACI,6BAAA;EACA,YAAA;EACA,iBAAA;EACA,UAAA;EACA,YAAA;EACA,WAAA;AALR;;AASA;EACI,kBAAA;EACA,6BAAA;EACA,WAAA;EACA,iBAAA;AANJ;AAQI;EACI,WAAA;EACA,WAAA;EACA,kBAAA;EACA,SAAA;EACA,YAAA;EACA,QAAA;EACA,OAAA;EACA,mBAAA;EACA,iBAAA;EACA,WAAA;AANR;;AAUA;EACI,kBAAA;EACA,6BAAA;EACA,WAAA;EACA,iBAAA;AAPJ;AASI;EACI,WAAA;EACA,WAAA;EACA,kBAAA;EACA,SAAA;EACA,SAAA;EACA,QAAA;EACA,OAAA;EACA,gBAAA;EACA,iBAAA;EACA,YAAA;AAPR;;AAWA;EACI,eAAA;AARJ;;AAWA;EACI,uBAAA;EACA,uBAAA;EACA,UAAA;EACA,eAAA;AARJ;;AAWA;EACI,iDAAA;AARJ",sourcesContent:[`.port-container {\r margin-top: 6px;\r margin-bottom: 6px;\r margin-left: 4px;\r margin-right: 4px;\r color: white;\r grid-row: 2;\r grid-column: 1;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 50% 50%;\r z-index: 2;\r }\r \r .frame-box-border {\r grid-row: 1 / span 2;\r grid-column: 1;\r width: 100%;\r height: 100%;\r border: transparent solid 4px;\r pointer-events: none;\r box-sizing: border-box;\r }\r \r .frame-comments {\r display: grid;\r grid-row: 2;\r grid-column: 1;\r padding: 0 10px;\r font-style: italic;\r word-wrap: break-word;\r }\r \r .selected.frame-box-border {\r border-color: white;\r }\r \r .frame-box-header {\r grid-row: 1;\r grid-column: 1;\r background: rgba(72, 72, 72, 1);\r color: white;\r text-align: center;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: calc(100% - 74px) 30px 7px 30px 7px;\r align-content: center;\r overflow: hidden;\r }\r \r .frame-box-header-button {\r cursor: pointer;\r align-self: center;\r transform-origin: 50% 50%;\r transform: scale(1);\r stroke: transparent;\r fill: white;\r display: grid;\r \r &.down {\r transform: scale(0.9);\r }\r }\r \r .frame-box-header-collapse {\r grid-column: 2;\r grid-row: 1;\r }\r \r .frame-box-header-close {\r grid-column: 4;\r grid-row: 1;\r }\r \r .frame-box-header-title {\r grid-column: 1;\r grid-row: 1;\r display: grid;\r height: 100%;\r width: 100%;\r align-self: stretch;\r align-items: center;\r margin-top: -2px;\r }\r \r .right-handle {\r grid-area: 1 / 2 / 3 / 2;\r width: 4px;\r background-color: transparent;\r cursor: ew-resize;\r \r &::after {\r content: "";\r width: 8px;\r position: absolute;\r top: 0;\r bottom: 0;\r margin-left: -4px;\r cursor: ew-resize;\r }\r }\r \r .top-right-corner-handle {\r background-color: transparent;\r height: 4px;\r z-index: 21;\r cursor: ne-resize;\r width: 4px;\r margin-left: -6px;\r \r &::after {\r background-color: transparent;\r cursor: ne-resize;\r margin-left: unset;\r top: -4px;\r height: 10px;\r width: 10px;\r }\r }\r \r .bottom-right-corner-handle {\r background-color: transparent;\r height: 0px;\r z-index: 21;\r cursor: nw-resize;\r grid-area: 4 / 2 / 4 / 2;\r margin-left: -2px;\r \r &::after {\r background-color: transparent;\r height: 10px;\r cursor: nw-resize;\r top: unset;\r bottom: -4px;\r width: 10px;\r }\r }\r \r .left-handle {\r grid-area: 1 / 1 / 3 / 1;\r width: 4px;\r background-color: transparent;\r cursor: ew-resize;\r \r &::before {\r content: "";\r width: 8px;\r position: absolute;\r top: 0;\r bottom: 0;\r margin-left: -4px;\r }\r }\r \r .top-left-corner-handle {\r background-color: transparent;\r height: 4px;\r z-index: 21;\r cursor: nw-resize;\r width: 4px;\r margin-left: -4px;\r \r &::before {\r background-color: transparent;\r cursor: nw-resize;\r margin-left: unset;\r top: -4px;\r height: 10px;\r width: 10px;\r }\r }\r \r .bottom-left-corner-handle {\r background-color: transparent;\r height: 0px;\r z-index: 21;\r cursor: sw-resize;\r grid-area: 4 / 1 / 4 / 1;\r \r &::before {\r background-color: transparent;\r height: 10px;\r cursor: sw-resize;\r top: unset;\r bottom: -4px;\r width: 10px;\r }\r }\r \r .top-handle {\r grid-area: 1 / 1 / 1 / 1;\r background-color: transparent;\r height: 4px;\r cursor: ns-resize;\r \r &::before {\r content: "";\r width: 100%;\r position: absolute;\r top: -4px;\r bottom: 100%;\r right: 0;\r left: 0;\r margin-bottom: -8px;\r cursor: ns-resize;\r height: 8px;\r }\r }\r \r .bottom-handle {\r grid-area: 3 / 1 / 3 / 1;\r background-color: transparent;\r height: 4px;\r cursor: ns-resize;\r \r &::after {\r content: "";\r width: 100%;\r position: absolute;\r top: 100%;\r bottom: 0;\r right: 0;\r left: 0;\r margin-top: -8px;\r cursor: ns-resize;\r height: 12px;\r }\r }\r \r .expanded {\r font-size: 24px;\r }\r \r .collapsed {\r height: auto !important;\r width: 200px !important;\r z-index: 3;\r font-size: 16px;\r }\r \r .collapsedHeader {\r grid-template-columns: calc(100% - 37px) 30px 7px;\r }\r `],sourceRoot:""}]),p.locals={"port-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__port-container","frame-box-border":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-border","frame-comments":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-comments",selected:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__selected","frame-box-header":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header","frame-box-header-button":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-button",down:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__down","frame-box-header-collapse":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-collapse","frame-box-header-close":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-close","frame-box-header-title":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-title","right-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__right-handle","top-right-corner-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-right-corner-handle","bottom-right-corner-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-right-corner-handle","left-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__left-handle","top-left-corner-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-left-corner-handle","bottom-left-corner-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-left-corner-handle","top-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-handle","bottom-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-handle",expanded:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__expanded",collapsed:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__collapsed",collapsedHeader:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__collapsedHeader"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphNode.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__visual { z-index: 4; width: 200px; position: absolute; left: 0; top: 0; background: gray; border: 4px solid black; border-radius: 12px; display: grid; grid-template-rows: 30px auto; grid-template-columns: 100%; color: white; box-shadow: 7px 6px 2px rgba(0, 0, 0, 0.2); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__highlighted { animation: \\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__glow 0.5s infinite alternate; } @keyframes \\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__glow { to { border-color: white; } } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__header-container { grid-row: 1; grid-column: 1; position: relative; border: 4px solid black; border-top-right-radius: 7px; border-top-left-radius: 7px; background: black; color: white; transform: scaleX(1.01) translateY(-0.5px); transform-origin: center; display: grid; grid-template-columns: 1fr auto; grid-template-rows: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__headerIcon { z-index: 10; align-self: center; user-select: none; pointer-events: none; width: 20px; display: grid; margin-left: 6px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__header { font-size: 16px; text-align: center; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__headerWithIcon { margin-left: calc(20px + 6px); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__connections { grid-row: 2; grid-column: 1; display: grid; grid-template-columns: 50% 50%; transform: scale(1); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__content { min-height: 20px; grid-row: 3; grid-column: 1; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__comments { position: absolute; top: -50px; width: 200px; height: 45px; overflow: hidden; font-style: italic; opacity: 0.8; display: grid; align-items: flex-end; pointer-events: none; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__executionTime { position: absolute; bottom: 1px; width: 195px; height: 20px; overflow: hidden; font-size: 11px; opacity: 0.5; display: grid; align-items: flex-end; justify-content: end; pointer-events: none; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__selected { border-color: white !important; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphNode.modules.scss"],names:[],mappings:"AAAA;EACI,UAAA;EACA,YAAA;EACA,kBAAA;EACA,OAAA;EACA,MAAA;EACA,gBAAA;EACA,uBAAA;EACA,mBAAA;EACA,aAAA;EACA,6BAAA;EACA,2BAAA;EACA,YAAA;EACA,0CAAA;AACJ;;AAEA;EAMI,gHAAA;AAJJ;AADI;EACI;IACI,mBAAA;EAGV;AACF;;AAEA;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,uBAAA;EACA,4BAAA;EACA,2BAAA;EACA,iBAAA;EACA,YAAA;EACA,0CAAA;EACA,wBAAA;EACA,aAAA;EACA,+BAAA;EACA,wBAAA;AACJ;;AAKA;EACI,WAAA;EACA,kBAAA;EACA,iBAAA;EACA,oBAAA;EACA,WARO;EASP,aAAA;EACA,gBATS;AAOb;;AAKA;EACI,eAAA;EACA,kBAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;AAFJ;;AAKA;EACI,6BAAA;AAFJ;;AAKA;EACI,WAAA;EACA,cAAA;EAEA,aAAA;EACA,8BAAA;EACA,mBAAA;AAHJ;;AAMA;EACI,gBAAA;EACA,WAAA;EACA,cAAA;AAHJ;;AAMA;EACI,kBAAA;EACA,UAAA;EACA,YAAA;EACA,YAAA;EACA,gBAAA;EACA,kBAAA;EACA,YAAA;EACA,aAAA;EACA,qBAAA;EACA,oBAAA;AAHJ;;AAMA;EACI,kBAAA;EACA,WAAA;EACA,YAAA;EACA,YAAA;EACA,gBAAA;EACA,eAAA;EACA,YAAA;EACA,aAAA;EACA,qBAAA;EACA,oBAAA;EACA,oBAAA;AAHJ;;AAMA;EACI,8BAAA;AAHJ",sourcesContent:[`.visual {\r z-index: 4;\r width: 200px;\r position: absolute;\r left: 0;\r top: 0;\r background: gray;\r border: 4px solid black;\r border-radius: 12px;\r display: grid;\r grid-template-rows: 30px auto;\r grid-template-columns: 100%;\r color: white;\r box-shadow: 7px 6px 2px rgba(0, 0, 0, 0.2);\r }\r \r .highlighted {\r @keyframes glow {\r to {\r border-color: white;\r }\r }\r animation: glow 0.5s infinite alternate;\r }\r \r .header-container {\r grid-row: 1;\r grid-column: 1;\r position: relative;\r border: 4px solid black;\r border-top-right-radius: 7px;\r border-top-left-radius: 7px;\r background: black;\r color: white;\r transform: scaleX(1.01) translateY(-0.5px);\r transform-origin: center;\r display: grid;\r grid-template-columns: 1fr auto;\r grid-template-rows: 100%;\r }\r \r $iconSize: 20px;\r $iconMargin: 6px;\r \r .headerIcon {\r z-index: 10;\r align-self: center;\r user-select: none;\r pointer-events: none;\r width: $iconSize;\r display: grid;\r margin-left: $iconMargin;\r }\r \r .header {\r font-size: 16px;\r text-align: center;\r white-space: nowrap;\r text-overflow: ellipsis;\r overflow: hidden;\r }\r \r .headerWithIcon {\r margin-left: calc(#{$iconSize} + #{$iconMargin});\r }\r \r .connections {\r grid-row: 2;\r grid-column: 1;\r \r display: grid;\r grid-template-columns: 50% 50%;\r transform: scale(1);\r }\r \r .content {\r min-height: 20px;\r grid-row: 3;\r grid-column: 1;\r }\r \r .comments {\r position: absolute;\r top: -50px;\r width: 200px;\r height: 45px;\r overflow: hidden;\r font-style: italic;\r opacity: 0.8;\r display: grid;\r align-items: flex-end;\r pointer-events: none;\r }\r \r .executionTime {\r position: absolute;\r bottom: 1px;\r width: 195px;\r height: 20px;\r overflow: hidden;\r font-size: 11px;\r opacity: 0.5;\r display: grid;\r align-items: flex-end;\r justify-content: end;\r pointer-events: none;\r }\r \r .selected {\r border-color: white !important;\r }\r `],sourceRoot:""}]),p.locals={visual:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__visual",highlighted:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__highlighted",glow:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__glow","header-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__header-container",headerIcon:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__headerIcon",header:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__header",headerWithIcon:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__headerWithIcon",connections:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__connections",content:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__content",comments:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__comments",executionTime:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__executionTime",selected:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__selected"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/nodeLink.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__link { stroke-width: 4px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__link.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selected { stroke: white !important; stroke-dasharray: 10, 2; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__target-candidate { filter: brightness(1.5); stroke-width: 6px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selection-link { pointer-events: all; stroke-width: 16px; opacity: 0; transition: opacity 75ms; stroke: transparent; cursor: pointer; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selection-link:hover, .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selection-link.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selected { stroke: white !important; opacity: 0.4; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/nodeLink.modules.scss"],names:[],mappings:"AAAA;EACI,iBAAA;AACJ;AAAI;EACI,wBAAA;EACA,uBAAA;AAER;;AAEA;EACI,uBAAA;EACA,iBAAA;AACJ;;AAEA;EACI,mBAAA;EACA,kBAAA;EACA,UAAA;EACA,wBAAA;EACA,mBAAA;EACA,eAAA;AACJ;AACI;EAEI,wBAAA;EACA,YAAA;AAAR",sourcesContent:[`.link {\r stroke-width: 4px;\r &.selected {\r stroke: white !important;\r stroke-dasharray: 10, 2;\r }\r }\r \r .target-candidate {\r filter: brightness(1.5);\r stroke-width: 6px;\r }\r \r .selection-link {\r pointer-events: all;\r stroke-width: 16px;\r opacity: 0;\r transition: opacity 75ms;\r stroke: transparent;\r cursor: pointer;\r \r &:hover,\r &.selected {\r stroke: white !important;\r opacity: 0.4;\r }\r }\r `],sourceRoot:""}]),p.locals={link:"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__link",selected:"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selected","target-candidate":"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__target-candidate","selection-link":"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selection-link"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/nodePort.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__selected { filter: brightness(2); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__pip { background: green; width: 6px; height: 6px; grid-row: 1; grid-column: 1; align-self: center; justify-self: center; border-radius: 7px; border: 2px solid black; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__pip.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__hidden { display: none; } img { grid-row: 1; grid-column: 1; } img.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__selected { box-shadow: 0 0 0 2px; border-radius: 50%; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/nodePort.modules.scss"],names:[],mappings:"AAAA;EACI,qBAAA;AACJ;;AAEA;EACI,iBAAA;EACA,UAAA;EACA,WAAA;EACA,WAAA;EACA,cAAA;EACA,kBAAA;EACA,oBAAA;EACA,kBAAA;EACA,uBAAA;AACJ;AACI;EACI,aAAA;AACR;;AAGA;EACI,WAAA;EACA,cAAA;AAAJ;;AAGA;EACI,qBAAA;EACA,kBAAA;AAAJ",sourcesContent:[`.selected {\r filter: brightness(2);\r }\r \r .pip {\r background: green;\r width: 6px;\r height: 6px;\r grid-row: 1;\r grid-column: 1;\r align-self: center;\r justify-self: center;\r border-radius: 7px;\r border: 2px solid black;\r \r &.hidden {\r display: none;\r }\r }\r \r img {\r grid-row: 1;\r grid-column: 1;\r }\r \r img.selected {\r box-shadow: 0 0 0 2px;\r border-radius: 50%;\r }\r `],sourceRoot:""}]),p.locals={selected:"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__selected",pip:"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__pip",hidden:"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__hidden"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/blockNodeData.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-blockNodeData-modules__hidden { display: none !important; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/blockNodeData.modules.scss"],names:[],mappings:"AAAA;EACI,wBAAA;AACJ",sourcesContent:[`.hidden {\r display: none !important;\r }\r `],sourceRoot:""}]),p.locals={hidden:"---------tools-nodeEditor-dist-graphSystem-blockNodeData-modules__hidden"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/clampDisplayManager.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-clampDisplayManager-modules__clampBlock { grid-row: 2; height: 34px; text-align: center; font-size: 18px; font-weight: bold; margin: 0 10px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/clampDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,cAAA;AACJ",sourcesContent:[`.clampBlock {\r grid-row: 2;\r height: 34px;\r text-align: center;\r font-size: 18px;\r font-weight: bold;\r margin: 0 10px;\r }\r `],sourceRoot:""}]),p.locals={clampBlock:"---------tools-nodeEditor-dist-graphSystem-display-clampDisplayManager-modules__clampBlock"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/common.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-common-modules__texture-block { grid-row: 2; height: 140px; width: 140px; overflow: hidden; border-bottom-left-radius: 7px; border: black 4px solid; border-left: 0px; border-bottom: 0px; } .\\---------tools-nodeEditor-dist-graphSystem-display-common-modules__texture-block img { width: 100%; height: 100%; pointer-events: none; } .\\---------tools-nodeEditor-dist-graphSystem-display-common-modules__texture-block img.\\---------tools-nodeEditor-dist-graphSystem-display-common-modules__empty { display: none; } .\\---------tools-nodeEditor-dist-graphSystem-display-common-modules__empty { display: none; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/common.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,aAAA;EACA,YAAA;EACA,gBAAA;EACA,8BAAA;EACA,uBAAA;EACA,gBAAA;EACA,kBAAA;AACJ;AACI;EACI,WAAA;EACA,YAAA;EACA,oBAAA;AACR;AACQ;EACI,aAAA;AACZ;;AAIA;EACI,aAAA;AADJ",sourcesContent:[`.texture-block {\r grid-row: 2;\r height: 140px;\r width: 140px;\r overflow: hidden;\r border-bottom-left-radius: 7px;\r border: black 4px solid;\r border-left: 0px;\r border-bottom: 0px;\r \r img {\r width: 100%;\r height: 100%;\r pointer-events: none;\r \r &.empty {\r display: none;\r }\r }\r }\r \r .empty {\r display: none;\r }\r `],sourceRoot:""}]),p.locals={"texture-block":"---------tools-nodeEditor-dist-graphSystem-display-common-modules__texture-block",empty:"---------tools-nodeEditor-dist-graphSystem-display-common-modules__empty"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/curveDisplayManager.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-curveDisplayManager-modules__curve-block { grid-row: 2; height: 34px; text-align: center; font-size: 18px; font-weight: bold; margin: 0 10px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/curveDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,cAAA;AACJ",sourcesContent:[`.curve-block {\r grid-row: 2;\r height: 34px;\r text-align: center;\r font-size: 18px;\r font-weight: bold;\r margin: 0 10px;\r }\r `],sourceRoot:""}]),p.locals={"curve-block":"---------tools-nodeEditor-dist-graphSystem-display-curveDisplayManager-modules__curve-block"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/elbowDisplayManager.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__elbowBlock { width: 40px; grid-template-rows: 0px 40px 0px; border-radius: 40px; transform: translateY(-7px); } .\\---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__hidden { display: none; } .\\---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__translatedConnections { transform: translateY(7px); } .\\---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__roundSelectionBorder { border-radius: 40px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/elbowDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,gCAAA;EACA,mBAAA;EACA,2BAAA;AACJ;;AAEA;EACI,aAAA;AACJ;;AAEA;EACI,0BAAA;AACJ;;AAEA;EACI,mBAAA;AACJ",sourcesContent:[`.elbowBlock {\r width: 40px;\r grid-template-rows: 0px 40px 0px;\r border-radius: 40px;\r transform: translateY(-7px);\r }\r \r .hidden {\r display: none;\r }\r \r .translatedConnections {\r transform: translateY(7px);\r }\r \r .roundSelectionBorder {\r border-radius: 40px;\r }\r `],sourceRoot:""}]),p.locals={elbowBlock:"---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__elbowBlock",hidden:"---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__hidden",translatedConnections:"---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__translatedConnections",roundSelectionBorder:"---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__roundSelectionBorder"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/gradientDisplayManager.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-gradientDisplayManager-modules__gradientBlock { grid-row: 2; height: 34px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/gradientDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;AACJ",sourcesContent:[`.gradientBlock {\r grid-row: 2;\r height: 34px;\r }\r `],sourceRoot:""}]),p.locals={gradientBlock:"---------tools-nodeEditor-dist-graphSystem-display-gradientDisplayManager-modules__gradientBlock"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/imageSourceDisplayManager.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-imageSourceDisplayManager-modules__image-source-block { margin-top: 5px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/imageSourceDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,eAAA;AACJ",sourcesContent:[`.image-source-block {\r margin-top: 5px;\r }\r `],sourceRoot:""}]),p.locals={"image-source-block":"---------tools-nodeEditor-dist-graphSystem-display-imageSourceDisplayManager-modules__image-source-block"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/inputDisplayManager.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__input-block { grid-row: 2; min-height: 34px; text-align: center; font-size: 18px; font-weight: bold; margin: 0 10px 5px; display: grid; align-content: center; } .\\---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__input-block.\\---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__small-font { font-size: 17px; } .\\---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__constant { border-color: #464348; background: #464348; } .\\---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__inspector { border-color: #66491b; background: #66491b; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/inputDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,gBAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,kBAAA;EACA,aAAA;EACA,qBAAA;AACJ;AACI;EACI,eAAA;AACR;;AAGA;EACI,qBAAA;EACA,mBAAA;AAAJ;;AAGA;EACI,qBAAA;EACA,mBAAA;AAAJ",sourcesContent:[`.input-block {\r grid-row: 2;\r min-height: 34px;\r text-align: center;\r font-size: 18px;\r font-weight: bold;\r margin: 0 10px 5px;\r display: grid;\r align-content: center;\r \r &.small-font {\r font-size: 17px;\r }\r }\r \r .constant {\r border-color: #464348;\r background: #464348;\r }\r \r .inspector {\r border-color: #66491b;\r background: #66491b;\r }\r `],sourceRoot:""}]),p.locals={"input-block":"---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__input-block","small-font":"---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__small-font",constant:"---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__constant",inspector:"---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__inspector"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/remapDisplayManager.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-remapDisplayManager-modules__remap-block { height: 34px; text-align: center; font-size: 18px; font-weight: bold; margin: 0 10px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/remapDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,YAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,cAAA;AACJ",sourcesContent:[`.remap-block {\r height: 34px;\r text-align: center;\r font-size: 18px;\r font-weight: bold;\r margin: 0 10px;\r }\r `],sourceRoot:""}]),p.locals={"remap-block":"---------tools-nodeEditor-dist-graphSystem-display-remapDisplayManager-modules__remap-block"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/textureDisplayManager.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__regular-texture-block { margin-top: 80px; } .\\---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__reduced-texture-block { margin-top: 30px; } .\\---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__reflection-block { grid-row: 3 !important; } .\\---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__triplanar-texture-block { margin-top: 155px; } .\\---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__refraction-texture-block { margin-top: 80px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/textureDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,gBAAA;AACJ;;AAEA;EACI,gBAAA;AACJ;;AAEA;EACI,sBAAA;AACJ;;AAEA;EACI,iBAAA;AACJ;;AAEA;EACI,gBAAA;AACJ",sourcesContent:[`.regular-texture-block {\r margin-top: 80px;\r }\r \r .reduced-texture-block {\r margin-top: 30px;\r }\r \r .reflection-block {\r grid-row: 3 !important;\r }\r \r .triplanar-texture-block {\r margin-top: 155px;\r }\r \r .refraction-texture-block {\r margin-top: 80px;\r }\r `],sourceRoot:""}]),p.locals={"regular-texture-block":"---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__regular-texture-block","reduced-texture-block":"---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__reduced-texture-block","reflection-block":"---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__reflection-block","triplanar-texture-block":"---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__triplanar-texture-block","refraction-texture-block":"---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__refraction-texture-block"};const _=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/trigonometryDisplayManager.modules.scss":(o,c,l)=>{l.r(c),l.d(c,{default:()=>_});var h=l("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),u=l.n(h),d=l("../../../../node_modules/css-loader/dist/runtime/api.js"),f=l.n(d),p=f()(u());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-trigonometryDisplayManager-modules__trigonometry-block { grid-row: 2; height: 34px; text-align: center; font-size: 18px; font-weight: bold; margin: 0 10px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/trigonometryDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,cAAA;AACJ",sourcesContent:[`.trigonometry-block {\r grid-row: 2;\r height: 34px;\r text-align: center;\r font-size: 18px;\r font-weight: bold;\r margin: 0 10px;\r }\r `],sourceRoot:""}]),p.locals={"trigonometry-block":"---------tools-nodeEditor-dist-graphSystem-display-trigonometryDisplayManager-modules__trigonometry-block"};const _=p},"../../../../node_modules/@fortawesome/react-fontawesome/index.es.js":(o,c,l)=>{l.r(c),l.d(c,{FontAwesomeIcon:()=>k});var h=l("../../../../node_modules/@fortawesome/fontawesome-svg-core/index.mjs"),u=l("../../../../node_modules/prop-types/index.js"),d=l.n(u),f=l("../../../../node_modules/react/index.js");function p(Y,J){var re=Object.keys(Y);if(Object.getOwnPropertySymbols){var he=Object.getOwnPropertySymbols(Y);J&&(he=he.filter(function(le){return Object.getOwnPropertyDescriptor(Y,le).enumerable})),re.push.apply(re,he)}return re}function _(Y){for(var J=1;J=0)&&(re[le]=Y[le]);return re}function x(Y,J){if(Y==null)return{};var re=v(Y,J),he,le;if(Object.getOwnPropertySymbols){var ue=Object.getOwnPropertySymbols(Y);for(le=0;le=0)&&Object.prototype.propertyIsEnumerable.call(Y,he)&&(re[he]=Y[he])}return re}function y(Y){return C(Y)||b(Y)||T(Y)||N()}function C(Y){if(Array.isArray(Y))return S(Y)}function b(Y){if(typeof Symbol<"u"&&Y[Symbol.iterator]!=null||Y["@@iterator"]!=null)return Array.from(Y)}function T(Y,J){if(Y){if(typeof Y=="string")return S(Y,J);var re=Object.prototype.toString.call(Y).slice(8,-1);if(re==="Object"&&Y.constructor&&(re=Y.constructor.name),re==="Map"||re==="Set")return Array.from(Y);if(re==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(re))return S(Y,J)}}function S(Y,J){(J==null||J>Y.length)&&(J=Y.length);for(var re=0,he=new Array(J);re2&&arguments[2]!==void 0?arguments[2]:{};if(typeof J=="string")return J;var he=(J.children||[]).map(function(W){return G(Y,W)}),le=Object.keys(J.attributes||{}).reduce(function(W,te){var oe=J.attributes[te];switch(te){case"class":W.attrs.className=oe,delete J.attributes.class;break;case"style":W.attrs.style=H(oe);break;default:te.indexOf("aria-")===0||te.indexOf("data-")===0?W.attrs[te.toLowerCase()]=oe:W.attrs[I(te)]=oe}return W},{attrs:{}}),ue=re.style,L=ue===void 0?{}:ue,F=x(re,R);return le.attrs.style=_(_({},le.attrs.style),L),Y.apply(void 0,[J.tag,_(_({},le.attrs),F)].concat(y(he)))}var Q=!1;try{Q=!1}catch{}function $(){if(!Q&&console&&typeof console.error=="function"){var Y;(Y=console).error.apply(Y,arguments)}}function V(Y){if(Y&&m(Y)==="object"&&Y.prefix&&Y.iconName&&Y.icon)return Y;if(h.parse.icon)return h.parse.icon(Y);if(Y===null)return null;if(Y&&m(Y)==="object"&&Y.prefix&&Y.iconName)return Y;if(Array.isArray(Y)&&Y.length===2)return{prefix:Y[0],iconName:Y[1]};if(typeof Y=="string")return{prefix:"fas",iconName:Y}}function j(Y,J){return Array.isArray(J)&&J.length>0||!Array.isArray(J)&&J?g({},Y,J):{}}var k=f.forwardRef(function(Y,J){var re=Y.icon,he=Y.mask,le=Y.symbol,ue=Y.className,L=Y.title,F=Y.titleId,W=Y.maskId,te=V(re),oe=j("classes",[].concat(y(D(Y)),y(ue.split(" ")))),ne=j("transform",typeof Y.transform=="string"?h.parse.transform(Y.transform):Y.transform),pe=j("mask",V(he)),ye=(0,h.icon)(te,_(_(_(_({},oe),ne),pe),{},{symbol:le,title:L,titleId:F,maskId:W}));if(!ye)return $("Could not find icon",te),null;var Pe=ye.abstract,Fe={ref:J};return Object.keys(Y).forEach(function(He){k.defaultProps.hasOwnProperty(He)||(Fe[He]=Y[He])}),z(Pe[0],Fe)});k.displayName="FontAwesomeIcon",k.propTypes={beat:d().bool,border:d().bool,beatFade:d().bool,bounce:d().bool,className:d().string,fade:d().bool,flash:d().bool,mask:d().oneOfType([d().object,d().array,d().string]),maskId:d().string,fixedWidth:d().bool,inverse:d().bool,flip:d().oneOf([!0,!1,"horizontal","vertical","both"]),icon:d().oneOfType([d().object,d().array,d().string]),listItem:d().bool,pull:d().oneOf(["right","left"]),pulse:d().bool,rotation:d().oneOf([0,90,180,270]),shake:d().bool,size:d().oneOf(["2xs","xs","sm","lg","xl","2xl","1x","2x","3x","4x","5x","6x","7x","8x","9x","10x"]),spin:d().bool,spinPulse:d().bool,spinReverse:d().bool,symbol:d().oneOfType([d().bool,d().string]),title:d().string,titleId:d().string,transform:d().oneOfType([d().string,d().object]),swapOpacity:d().bool},k.defaultProps={border:!1,className:"",mask:null,maskId:null,fixedWidth:!1,inverse:!1,flip:!1,icon:null,listItem:!1,pull:null,pulse:!1,rotation:null,size:null,spin:!1,spinPulse:!1,spinReverse:!1,beat:!1,fade:!1,beatFade:!1,bounce:!1,shake:!1,symbol:!1,title:"",titleId:null,transform:null,swapOpacity:!1};var z=G.bind(null,f.createElement)},"../../../../node_modules/css-loader/dist/runtime/api.js":o=>{o.exports=function(c){var l=[];return l.toString=function(){return this.map(function(u){var d="",f=typeof u[5]<"u";return u[4]&&(d+="@supports (".concat(u[4],") {")),u[2]&&(d+="@media ".concat(u[2]," {")),f&&(d+="@layer".concat(u[5].length>0?" ".concat(u[5]):""," {")),d+=c(u),f&&(d+="}"),u[2]&&(d+="}"),u[4]&&(d+="}"),d}).join("")},l.i=function(u,d,f,p,_){typeof u=="string"&&(u=[[null,u,void 0]]);var m={};if(f)for(var g=0;g"u"||(y[1]="@layer".concat(y[5].length>0?" ".concat(y[5]):""," {").concat(y[1],"}")),y[5]=_),d&&(y[2]&&(y[1]="@media ".concat(y[2]," {").concat(y[1],"}")),y[2]=d),p&&(y[4]?(y[1]="@supports (".concat(y[4],") {").concat(y[1],"}"),y[4]=p):y[4]="".concat(p)),l.push(y))}},l}},"../../../../node_modules/css-loader/dist/runtime/sourceMaps.js":o=>{o.exports=function(c){var l=c[1],h=c[3];if(!h)return l;if(typeof btoa=="function"){var u=btoa(unescape(encodeURIComponent(JSON.stringify(h)))),d="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(u),f="/*# ".concat(d," */");return[l].concat([f]).join(` `)}return[l].join(` `)}},"../../../../node_modules/dagre/index.js":(o,c,l)=>{o.exports={graphlib:l("../../../../node_modules/dagre/lib/graphlib.js"),layout:l("../../../../node_modules/dagre/lib/layout.js"),debug:l("../../../../node_modules/dagre/lib/debug.js"),util:{time:l("../../../../node_modules/dagre/lib/util.js").time,notime:l("../../../../node_modules/dagre/lib/util.js").notime},version:l("../../../../node_modules/dagre/lib/version.js")}},"../../../../node_modules/dagre/lib/acyclic.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/greedy-fas.js");o.exports={run:d,undo:p};function d(_){var m=_.graph().acyclicer==="greedy"?u(_,g(_)):f(_);h.forEach(m,function(v){var x=_.edge(v);_.removeEdge(v),x.forwardName=v.name,x.reversed=!0,_.setEdge(v.w,v.v,x,h.uniqueId("rev"))});function g(v){return function(x){return v.edge(x).weight}}}function f(_){var m=[],g={},v={};function x(y){h.has(v,y)||(v[y]=!0,g[y]=!0,h.forEach(_.outEdges(y),function(C){h.has(g,C.w)?m.push(C):x(C.w)}),delete g[y])}return h.forEach(_.nodes(),x),m}function p(_){h.forEach(_.edges(),function(m){var g=_.edge(m);if(g.reversed){_.removeEdge(m);var v=g.forwardName;delete g.reversed,delete g.forwardName,_.setEdge(m.w,m.v,g,v)}})}},"../../../../node_modules/dagre/lib/add-border-segments.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/util.js");o.exports=d;function d(p){function _(m){var g=p.children(m),v=p.node(m);if(g.length&&h.forEach(g,_),h.has(v,"minRank")){v.borderLeft=[],v.borderRight=[];for(var x=v.minRank,y=v.maxRank+1;x{var h=l("../../../../node_modules/dagre/lib/lodash.js");o.exports={adjust:u,undo:d};function u(x){var y=x.graph().rankdir.toLowerCase();(y==="lr"||y==="rl")&&f(x)}function d(x){var y=x.graph().rankdir.toLowerCase();(y==="bt"||y==="rl")&&_(x),(y==="lr"||y==="rl")&&(g(x),f(x))}function f(x){h.forEach(x.nodes(),function(y){p(x.node(y))}),h.forEach(x.edges(),function(y){p(x.edge(y))})}function p(x){var y=x.width;x.width=x.height,x.height=y}function _(x){h.forEach(x.nodes(),function(y){m(x.node(y))}),h.forEach(x.edges(),function(y){var C=x.edge(y);h.forEach(C.points,m),h.has(C,"y")&&m(C)})}function m(x){x.y=-x.y}function g(x){h.forEach(x.nodes(),function(y){v(x.node(y))}),h.forEach(x.edges(),function(y){var C=x.edge(y);h.forEach(C.points,v),h.has(C,"x")&&v(C)})}function v(x){var y=x.x;x.x=x.y,x.y=y}},"../../../../node_modules/dagre/lib/data/list.js":o=>{o.exports=c;function c(){var u={};u._next=u._prev=u,this._sentinel=u}c.prototype.dequeue=function(){var u=this._sentinel,d=u._prev;if(d!==u)return l(d),d},c.prototype.enqueue=function(u){var d=this._sentinel;u._prev&&u._next&&l(u),u._next=d._next,d._next._prev=u,d._next=u,u._prev=d},c.prototype.toString=function(){for(var u=[],d=this._sentinel,f=d._prev;f!==d;)u.push(JSON.stringify(f,h)),f=f._prev;return"["+u.join(", ")+"]"};function l(u){u._prev._next=u._next,u._next._prev=u._prev,delete u._next,delete u._prev}function h(u,d){if(u!=="_next"&&u!=="_prev")return d}},"../../../../node_modules/dagre/lib/debug.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/util.js"),d=l("../../../../node_modules/dagre/lib/graphlib.js").Graph;o.exports={debugOrdering:f};function f(p){var _=u.buildLayerMatrix(p),m=new d({compound:!0,multigraph:!0}).setGraph({});return h.forEach(p.nodes(),function(g){m.setNode(g,{label:g}),m.setParent(g,"layer"+p.node(g).rank)}),h.forEach(p.edges(),function(g){m.setEdge(g.v,g.w,{},g.name)}),h.forEach(_,function(g,v){var x="layer"+v;m.setNode(x,{rank:"same"}),h.reduce(g,function(y,C){return m.setEdge(y,C,{style:"invis"}),C})}),m}},"../../../../node_modules/dagre/lib/graphlib.js":(o,c,l)=>{var h;try{h=l("../../../../node_modules/graphlib/index.js")}catch{}h||(h=window.graphlib),o.exports=h},"../../../../node_modules/dagre/lib/greedy-fas.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/graphlib.js").Graph,d=l("../../../../node_modules/dagre/lib/data/list.js");o.exports=p;var f=h.constant(1);function p(x,y){if(x.nodeCount()<=1)return[];var C=g(x,y||f),b=_(C.graph,C.buckets,C.zeroIdx);return h.flatten(h.map(b,function(T){return x.outEdges(T.v,T.w)}),!0)}function _(x,y,C){for(var b=[],T=y[y.length-1],S=y[0],N;x.nodeCount();){for(;N=S.dequeue();)m(x,y,C,N);for(;N=T.dequeue();)m(x,y,C,N);if(x.nodeCount()){for(var D=y.length-2;D>0;--D)if(N=y[D].dequeue(),N){b=b.concat(m(x,y,C,N,!0));break}}}return b}function m(x,y,C,b,T){var S=T?[]:void 0;return h.forEach(x.inEdges(b.v),function(N){var D=x.edge(N),M=x.node(N.v);T&&S.push({v:N.v,w:N.w}),M.out-=D,v(y,C,M)}),h.forEach(x.outEdges(b.v),function(N){var D=x.edge(N),M=N.w,I=x.node(M);I.in-=D,v(y,C,I)}),x.removeNode(b.v),S}function g(x,y){var C=new u,b=0,T=0;h.forEach(x.nodes(),function(D){C.setNode(D,{v:D,in:0,out:0})}),h.forEach(x.edges(),function(D){var M=C.edge(D.v,D.w)||0,I=y(D),R=M+I;C.setEdge(D.v,D.w,R),T=Math.max(T,C.node(D.v).out+=I),b=Math.max(b,C.node(D.w).in+=I)});var S=h.range(T+b+3).map(function(){return new d}),N=b+1;return h.forEach(C.nodes(),function(D){v(S,N,C.node(D))}),{graph:C,buckets:S,zeroIdx:N}}function v(x,y,C){C.out?C.in?x[C.out-C.in+y].enqueue(C):x[x.length-1].enqueue(C):x[0].enqueue(C)}},"../../../../node_modules/dagre/lib/layout.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/acyclic.js"),d=l("../../../../node_modules/dagre/lib/normalize.js"),f=l("../../../../node_modules/dagre/lib/rank/index.js"),p=l("../../../../node_modules/dagre/lib/util.js").normalizeRanks,_=l("../../../../node_modules/dagre/lib/parent-dummy-chains.js"),m=l("../../../../node_modules/dagre/lib/util.js").removeEmptyRanks,g=l("../../../../node_modules/dagre/lib/nesting-graph.js"),v=l("../../../../node_modules/dagre/lib/add-border-segments.js"),x=l("../../../../node_modules/dagre/lib/coordinate-system.js"),y=l("../../../../node_modules/dagre/lib/order/index.js"),C=l("../../../../node_modules/dagre/lib/position/index.js"),b=l("../../../../node_modules/dagre/lib/util.js"),T=l("../../../../node_modules/dagre/lib/graphlib.js").Graph;o.exports=S;function S(ne,pe){var ye=pe&&pe.debugTiming?b.time:b.notime;ye("layout",function(){var Pe=ye(" buildLayoutGraph",function(){return V(ne)});ye(" runLayout",function(){N(Pe,ye)}),ye(" updateInputGraph",function(){D(ne,Pe)})})}function N(ne,pe){pe(" makeSpaceForEdgeLabels",function(){j(ne)}),pe(" removeSelfEdges",function(){L(ne)}),pe(" acyclic",function(){u.run(ne)}),pe(" nestingGraph.run",function(){g.run(ne)}),pe(" rank",function(){f(b.asNonCompoundGraph(ne))}),pe(" injectEdgeLabelProxies",function(){k(ne)}),pe(" removeEmptyRanks",function(){m(ne)}),pe(" nestingGraph.cleanup",function(){g.cleanup(ne)}),pe(" normalizeRanks",function(){p(ne)}),pe(" assignRankMinMax",function(){z(ne)}),pe(" removeEdgeLabelProxies",function(){Y(ne)}),pe(" normalize.run",function(){d.run(ne)}),pe(" parentDummyChains",function(){_(ne)}),pe(" addBorderSegments",function(){v(ne)}),pe(" order",function(){y(ne)}),pe(" insertSelfEdges",function(){F(ne)}),pe(" adjustCoordinateSystem",function(){x.adjust(ne)}),pe(" position",function(){C(ne)}),pe(" positionSelfEdges",function(){W(ne)}),pe(" removeBorderNodes",function(){ue(ne)}),pe(" normalize.undo",function(){d.undo(ne)}),pe(" fixupEdgeLabelCoords",function(){he(ne)}),pe(" undoCoordinateSystem",function(){x.undo(ne)}),pe(" translateGraph",function(){J(ne)}),pe(" assignNodeIntersects",function(){re(ne)}),pe(" reversePoints",function(){le(ne)}),pe(" acyclic.undo",function(){u.undo(ne)})}function D(ne,pe){h.forEach(ne.nodes(),function(ye){var Pe=ne.node(ye),Fe=pe.node(ye);Pe&&(Pe.x=Fe.x,Pe.y=Fe.y,pe.children(ye).length&&(Pe.width=Fe.width,Pe.height=Fe.height))}),h.forEach(ne.edges(),function(ye){var Pe=ne.edge(ye),Fe=pe.edge(ye);Pe.points=Fe.points,h.has(Fe,"x")&&(Pe.x=Fe.x,Pe.y=Fe.y)}),ne.graph().width=pe.graph().width,ne.graph().height=pe.graph().height}var M=["nodesep","edgesep","ranksep","marginx","marginy"],I={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},R=["acyclicer","ranker","rankdir","align"],O=["width","height"],H={width:0,height:0},G=["minlen","weight","width","height","labeloffset"],Q={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},$=["labelpos"];function V(ne){var pe=new T({multigraph:!0,compound:!0}),ye=oe(ne.graph());return pe.setGraph(h.merge({},I,te(ye,M),h.pick(ye,R))),h.forEach(ne.nodes(),function(Pe){var Fe=oe(ne.node(Pe));pe.setNode(Pe,h.defaults(te(Fe,O),H)),pe.setParent(Pe,ne.parent(Pe))}),h.forEach(ne.edges(),function(Pe){var Fe=oe(ne.edge(Pe));pe.setEdge(Pe,h.merge({},Q,te(Fe,G),h.pick(Fe,$)))}),pe}function j(ne){var pe=ne.graph();pe.ranksep/=2,h.forEach(ne.edges(),function(ye){var Pe=ne.edge(ye);Pe.minlen*=2,Pe.labelpos.toLowerCase()!=="c"&&(pe.rankdir==="TB"||pe.rankdir==="BT"?Pe.width+=Pe.labeloffset:Pe.height+=Pe.labeloffset)})}function k(ne){h.forEach(ne.edges(),function(pe){var ye=ne.edge(pe);if(ye.width&&ye.height){var Pe=ne.node(pe.v),Fe=ne.node(pe.w),He={rank:(Fe.rank-Pe.rank)/2+Pe.rank,e:pe};b.addDummyNode(ne,"edge-proxy",He,"_ep")}})}function z(ne){var pe=0;h.forEach(ne.nodes(),function(ye){var Pe=ne.node(ye);Pe.borderTop&&(Pe.minRank=ne.node(Pe.borderTop).rank,Pe.maxRank=ne.node(Pe.borderBottom).rank,pe=h.max(pe,Pe.maxRank))}),ne.graph().maxRank=pe}function Y(ne){h.forEach(ne.nodes(),function(pe){var ye=ne.node(pe);ye.dummy==="edge-proxy"&&(ne.edge(ye.e).labelRank=ye.rank,ne.removeNode(pe))})}function J(ne){var pe=Number.POSITIVE_INFINITY,ye=0,Pe=Number.POSITIVE_INFINITY,Fe=0,He=ne.graph(),ot=He.marginx||0,Xe=He.marginy||0;function gt(rt){var ut=rt.x,Yt=rt.y,ki=rt.width,ei=rt.height;pe=Math.min(pe,ut-ki/2),ye=Math.max(ye,ut+ki/2),Pe=Math.min(Pe,Yt-ei/2),Fe=Math.max(Fe,Yt+ei/2)}h.forEach(ne.nodes(),function(rt){gt(ne.node(rt))}),h.forEach(ne.edges(),function(rt){var ut=ne.edge(rt);h.has(ut,"x")&>(ut)}),pe-=ot,Pe-=Xe,h.forEach(ne.nodes(),function(rt){var ut=ne.node(rt);ut.x-=pe,ut.y-=Pe}),h.forEach(ne.edges(),function(rt){var ut=ne.edge(rt);h.forEach(ut.points,function(Yt){Yt.x-=pe,Yt.y-=Pe}),h.has(ut,"x")&&(ut.x-=pe),h.has(ut,"y")&&(ut.y-=Pe)}),He.width=ye-pe+ot,He.height=Fe-Pe+Xe}function re(ne){h.forEach(ne.edges(),function(pe){var ye=ne.edge(pe),Pe=ne.node(pe.v),Fe=ne.node(pe.w),He,ot;ye.points?(He=ye.points[0],ot=ye.points[ye.points.length-1]):(ye.points=[],He=Fe,ot=Pe),ye.points.unshift(b.intersectRect(Pe,He)),ye.points.push(b.intersectRect(Fe,ot))})}function he(ne){h.forEach(ne.edges(),function(pe){var ye=ne.edge(pe);if(h.has(ye,"x"))switch((ye.labelpos==="l"||ye.labelpos==="r")&&(ye.width-=ye.labeloffset),ye.labelpos){case"l":ye.x-=ye.width/2+ye.labeloffset;break;case"r":ye.x+=ye.width/2+ye.labeloffset;break}})}function le(ne){h.forEach(ne.edges(),function(pe){var ye=ne.edge(pe);ye.reversed&&ye.points.reverse()})}function ue(ne){h.forEach(ne.nodes(),function(pe){if(ne.children(pe).length){var ye=ne.node(pe),Pe=ne.node(ye.borderTop),Fe=ne.node(ye.borderBottom),He=ne.node(h.last(ye.borderLeft)),ot=ne.node(h.last(ye.borderRight));ye.width=Math.abs(ot.x-He.x),ye.height=Math.abs(Fe.y-Pe.y),ye.x=He.x+ye.width/2,ye.y=Pe.y+ye.height/2}}),h.forEach(ne.nodes(),function(pe){ne.node(pe).dummy==="border"&&ne.removeNode(pe)})}function L(ne){h.forEach(ne.edges(),function(pe){if(pe.v===pe.w){var ye=ne.node(pe.v);ye.selfEdges||(ye.selfEdges=[]),ye.selfEdges.push({e:pe,label:ne.edge(pe)}),ne.removeEdge(pe)}})}function F(ne){var pe=b.buildLayerMatrix(ne);h.forEach(pe,function(ye){var Pe=0;h.forEach(ye,function(Fe,He){var ot=ne.node(Fe);ot.order=He+Pe,h.forEach(ot.selfEdges,function(Xe){b.addDummyNode(ne,"selfedge",{width:Xe.label.width,height:Xe.label.height,rank:ot.rank,order:He+ ++Pe,e:Xe.e,label:Xe.label},"_se")}),delete ot.selfEdges})})}function W(ne){h.forEach(ne.nodes(),function(pe){var ye=ne.node(pe);if(ye.dummy==="selfedge"){var Pe=ne.node(ye.e.v),Fe=Pe.x+Pe.width/2,He=Pe.y,ot=ye.x-Fe,Xe=Pe.height/2;ne.setEdge(ye.e,ye.label),ne.removeNode(pe),ye.label.points=[{x:Fe+2*ot/3,y:He-Xe},{x:Fe+5*ot/6,y:He-Xe},{x:Fe+ot,y:He},{x:Fe+5*ot/6,y:He+Xe},{x:Fe+2*ot/3,y:He+Xe}],ye.label.x=ye.x,ye.label.y=ye.y}})}function te(ne,pe){return h.mapValues(h.pick(ne,pe),Number)}function oe(ne){var pe={};return h.forEach(ne,function(ye,Pe){pe[Pe.toLowerCase()]=ye}),pe}},"../../../../node_modules/dagre/lib/lodash.js":(o,c,l)=>{var h;try{h={cloneDeep:l("../../../../node_modules/lodash/cloneDeep.js"),constant:l("../../../../node_modules/lodash/constant.js"),defaults:l("../../../../node_modules/lodash/defaults.js"),each:l("../../../../node_modules/lodash/each.js"),filter:l("../../../../node_modules/lodash/filter.js"),find:l("../../../../node_modules/lodash/find.js"),flatten:l("../../../../node_modules/lodash/flatten.js"),forEach:l("../../../../node_modules/lodash/forEach.js"),forIn:l("../../../../node_modules/lodash/forIn.js"),has:l("../../../../node_modules/lodash/has.js"),isUndefined:l("../../../../node_modules/lodash/isUndefined.js"),last:l("../../../../node_modules/lodash/last.js"),map:l("../../../../node_modules/lodash/map.js"),mapValues:l("../../../../node_modules/lodash/mapValues.js"),max:l("../../../../node_modules/lodash/max.js"),merge:l("../../../../node_modules/lodash/merge.js"),min:l("../../../../node_modules/lodash/min.js"),minBy:l("../../../../node_modules/lodash/minBy.js"),now:l("../../../../node_modules/lodash/now.js"),pick:l("../../../../node_modules/lodash/pick.js"),range:l("../../../../node_modules/lodash/range.js"),reduce:l("../../../../node_modules/lodash/reduce.js"),sortBy:l("../../../../node_modules/lodash/sortBy.js"),uniqueId:l("../../../../node_modules/lodash/uniqueId.js"),values:l("../../../../node_modules/lodash/values.js"),zipObject:l("../../../../node_modules/lodash/zipObject.js")}}catch{}h||(h=window._),o.exports=h},"../../../../node_modules/dagre/lib/nesting-graph.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/util.js");o.exports={run:d,cleanup:m};function d(g){var v=u.addDummyNode(g,"root",{},"_root"),x=p(g),y=h.max(h.values(x))-1,C=2*y+1;g.graph().nestingRoot=v,h.forEach(g.edges(),function(T){g.edge(T).minlen*=C});var b=_(g)+1;h.forEach(g.children(),function(T){f(g,v,C,b,y,x,T)}),g.graph().nodeRankFactor=C}function f(g,v,x,y,C,b,T){var S=g.children(T);if(!S.length){T!==v&&g.setEdge(v,T,{weight:0,minlen:x});return}var N=u.addBorderNode(g,"_bt"),D=u.addBorderNode(g,"_bb"),M=g.node(T);g.setParent(N,T),M.borderTop=N,g.setParent(D,T),M.borderBottom=D,h.forEach(S,function(I){f(g,v,x,y,C,b,I);var R=g.node(I),O=R.borderTop?R.borderTop:I,H=R.borderBottom?R.borderBottom:I,G=R.borderTop?y:2*y,Q=O!==H?1:C-b[T]+1;g.setEdge(N,O,{weight:G,minlen:Q,nestingEdge:!0}),g.setEdge(H,D,{weight:G,minlen:Q,nestingEdge:!0})}),g.parent(T)||g.setEdge(v,N,{weight:0,minlen:C+b[T]})}function p(g){var v={};function x(y,C){var b=g.children(y);b&&b.length&&h.forEach(b,function(T){x(T,C+1)}),v[y]=C}return h.forEach(g.children(),function(y){x(y,1)}),v}function _(g){return h.reduce(g.edges(),function(v,x){return v+g.edge(x).weight},0)}function m(g){var v=g.graph();g.removeNode(v.nestingRoot),delete v.nestingRoot,h.forEach(g.edges(),function(x){var y=g.edge(x);y.nestingEdge&&g.removeEdge(x)})}},"../../../../node_modules/dagre/lib/normalize.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/util.js");o.exports={run:d,undo:p};function d(_){_.graph().dummyChains=[],h.forEach(_.edges(),function(m){f(_,m)})}function f(_,m){var g=m.v,v=_.node(g).rank,x=m.w,y=_.node(x).rank,C=m.name,b=_.edge(m),T=b.labelRank;if(y!==v+1){_.removeEdge(m);var S,N,D;for(D=0,++v;v{var h=l("../../../../node_modules/dagre/lib/lodash.js");o.exports=u;function u(d,f,p){var _={},m;h.forEach(p,function(g){for(var v=d.parent(g),x,y;v;){if(x=d.parent(v),x?(y=_[x],_[x]=v):(y=m,m=v),y&&y!==v){f.setEdge(y,v);return}v=x}})}},"../../../../node_modules/dagre/lib/order/barycenter.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js");o.exports=u;function u(d,f){return h.map(f,function(p){var _=d.inEdges(p);if(_.length){var m=h.reduce(_,function(g,v){var x=d.edge(v),y=d.node(v.v);return{sum:g.sum+x.weight*y.order,weight:g.weight+x.weight}},{sum:0,weight:0});return{v:p,barycenter:m.sum/m.weight,weight:m.weight}}else return{v:p}})}},"../../../../node_modules/dagre/lib/order/build-layer-graph.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/graphlib.js").Graph;o.exports=d;function d(p,_,m){var g=f(p),v=new u({compound:!0}).setGraph({root:g}).setDefaultNodeLabel(function(x){return p.node(x)});return h.forEach(p.nodes(),function(x){var y=p.node(x),C=p.parent(x);(y.rank===_||y.minRank<=_&&_<=y.maxRank)&&(v.setNode(x),v.setParent(x,C||g),h.forEach(p[m](x),function(b){var T=b.v===x?b.w:b.v,S=v.edge(T,x),N=h.isUndefined(S)?0:S.weight;v.setEdge(T,x,{weight:p.edge(b).weight+N})}),h.has(y,"minRank")&&v.setNode(x,{borderLeft:y.borderLeft[_],borderRight:y.borderRight[_]}))}),v}function f(p){for(var _;p.hasNode(_=h.uniqueId("_root")););return _}},"../../../../node_modules/dagre/lib/order/cross-count.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js");o.exports=u;function u(f,p){for(var _=0,m=1;m0;)T%2&&(S+=y[T+1]),T=T-1>>1,y[T]+=b.weight;C+=b.weight*S})),C}},"../../../../node_modules/dagre/lib/order/index.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/order/init-order.js"),d=l("../../../../node_modules/dagre/lib/order/cross-count.js"),f=l("../../../../node_modules/dagre/lib/order/sort-subgraph.js"),p=l("../../../../node_modules/dagre/lib/order/build-layer-graph.js"),_=l("../../../../node_modules/dagre/lib/order/add-subgraph-constraints.js"),m=l("../../../../node_modules/dagre/lib/graphlib.js").Graph,g=l("../../../../node_modules/dagre/lib/util.js");o.exports=v;function v(b){var T=g.maxRank(b),S=x(b,h.range(1,T+1),"inEdges"),N=x(b,h.range(T-1,-1,-1),"outEdges"),D=u(b);C(b,D);for(var M=Number.POSITIVE_INFINITY,I,R=0,O=0;O<4;++R,++O){y(R%2?S:N,R%4>=2),D=g.buildLayerMatrix(b);var H=d(b,D);H{var h=l("../../../../node_modules/dagre/lib/lodash.js");o.exports=u;function u(d){var f={},p=h.filter(d.nodes(),function(x){return!d.children(x).length}),_=h.max(h.map(p,function(x){return d.node(x).rank})),m=h.map(h.range(_+1),function(){return[]});function g(x){if(!h.has(f,x)){f[x]=!0;var y=d.node(x);m[y.rank].push(x),h.forEach(d.successors(x),g)}}var v=h.sortBy(p,function(x){return d.node(x).rank});return h.forEach(v,g),m}},"../../../../node_modules/dagre/lib/order/resolve-conflicts.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js");o.exports=u;function u(p,_){var m={};h.forEach(p,function(v,x){var y=m[v.v]={indegree:0,in:[],out:[],vs:[v.v],i:x};h.isUndefined(v.barycenter)||(y.barycenter=v.barycenter,y.weight=v.weight)}),h.forEach(_.edges(),function(v){var x=m[v.v],y=m[v.w];!h.isUndefined(x)&&!h.isUndefined(y)&&(y.indegree++,x.out.push(m[v.w]))});var g=h.filter(m,function(v){return!v.indegree});return d(g)}function d(p){var _=[];function m(x){return function(y){y.merged||(h.isUndefined(y.barycenter)||h.isUndefined(x.barycenter)||y.barycenter>=x.barycenter)&&f(x,y)}}function g(x){return function(y){y.in.push(x),--y.indegree===0&&p.push(y)}}for(;p.length;){var v=p.pop();_.push(v),h.forEach(v.in.reverse(),m(v)),h.forEach(v.out,g(v))}return h.map(h.filter(_,function(x){return!x.merged}),function(x){return h.pick(x,["vs","i","barycenter","weight"])})}function f(p,_){var m=0,g=0;p.weight&&(m+=p.barycenter*p.weight,g+=p.weight),_.weight&&(m+=_.barycenter*_.weight,g+=_.weight),p.vs=_.vs.concat(p.vs),p.barycenter=m/g,p.weight=g,p.i=Math.min(_.i,p.i),_.merged=!0}},"../../../../node_modules/dagre/lib/order/sort-subgraph.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/order/barycenter.js"),d=l("../../../../node_modules/dagre/lib/order/resolve-conflicts.js"),f=l("../../../../node_modules/dagre/lib/order/sort.js");o.exports=p;function p(g,v,x,y){var C=g.children(v),b=g.node(v),T=b?b.borderLeft:void 0,S=b?b.borderRight:void 0,N={};T&&(C=h.filter(C,function(H){return H!==T&&H!==S}));var D=u(g,C);h.forEach(D,function(H){if(g.children(H.v).length){var G=p(g,H.v,x,y);N[H.v]=G,h.has(G,"barycenter")&&m(H,G)}});var M=d(D,x);_(M,N);var I=f(M,y);if(T&&(I.vs=h.flatten([T,I.vs,S],!0),g.predecessors(T).length)){var R=g.node(g.predecessors(T)[0]),O=g.node(g.predecessors(S)[0]);h.has(I,"barycenter")||(I.barycenter=0,I.weight=0),I.barycenter=(I.barycenter*I.weight+R.order+O.order)/(I.weight+2),I.weight+=2}return I}function _(g,v){h.forEach(g,function(x){x.vs=h.flatten(x.vs.map(function(y){return v[y]?v[y].vs:y}),!0)})}function m(g,v){h.isUndefined(g.barycenter)?(g.barycenter=v.barycenter,g.weight=v.weight):(g.barycenter=(g.barycenter*g.weight+v.barycenter*v.weight)/(g.weight+v.weight),g.weight+=v.weight)}},"../../../../node_modules/dagre/lib/order/sort.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/util.js");o.exports=d;function d(_,m){var g=u.partition(_,function(N){return h.has(N,"barycenter")}),v=g.lhs,x=h.sortBy(g.rhs,function(N){return-N.i}),y=[],C=0,b=0,T=0;v.sort(p(!!m)),T=f(y,x,T),h.forEach(v,function(N){T+=N.vs.length,y.push(N.vs),C+=N.barycenter*N.weight,b+=N.weight,T=f(y,x,T)});var S={vs:h.flatten(y,!0)};return b&&(S.barycenter=C/b,S.weight=b),S}function f(_,m,g){for(var v;m.length&&(v=h.last(m)).i<=g;)m.pop(),_.push(v.vs),g++;return g}function p(_){return function(m,g){return m.barycenterg.barycenter?1:_?g.i-m.i:m.i-g.i}}},"../../../../node_modules/dagre/lib/parent-dummy-chains.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js");o.exports=u;function u(p){var _=f(p);h.forEach(p.graph().dummyChains,function(m){for(var g=p.node(m),v=g.edgeObj,x=d(p,_,v.v,v.w),y=x.path,C=x.lca,b=0,T=y[b],S=!0;m!==v.w;){if(g=p.node(m),S){for(;(T=y[b])!==C&&p.node(T).maxRanky||C>_[b].lim));for(T=b,b=g;(b=p.parent(b))!==T;)x.push(b);return{path:v.concat(x.reverse()),lca:T}}function f(p){var _={},m=0;function g(v){var x=m;h.forEach(p.children(v),g),_[v]={low:x,lim:m++}}return h.forEach(p.children(),g),_}},"../../../../node_modules/dagre/lib/position/bk.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/graphlib.js").Graph,d=l("../../../../node_modules/dagre/lib/util.js");o.exports={positionX:S,findType1Conflicts:f,findType2Conflicts:p,addConflict:m,hasConflict:g,verticalAlignment:v,horizontalCompaction:x,alignCoordinates:b,findSmallestWidthAlignment:C,balance:T};function f(M,I){var R={};function O(H,G){var Q=0,$=0,V=H.length,j=h.last(G);return h.forEach(G,function(k,z){var Y=_(M,k),J=Y?M.node(Y).order:V;(Y||k===j)&&(h.forEach(G.slice($,z+1),function(re){h.forEach(M.predecessors(re),function(he){var le=M.node(he),ue=le.order;(uej)&&m(R,Y,k)})})}function H(G,Q){var $=-1,V,j=0;return h.forEach(Q,function(k,z){if(M.node(k).dummy==="border"){var Y=M.predecessors(k);Y.length&&(V=M.node(Y[0]).order,O(Q,j,z,$,V),j=z,$=V)}O(Q,j,Q.length,V,G.length)}),Q}return h.reduce(I,H),R}function _(M,I){if(M.node(I).dummy)return h.find(M.predecessors(I),function(R){return M.node(R).dummy})}function m(M,I,R){if(I>R){var O=I;I=R,R=O}var H=M[I];H||(M[I]=H={}),H[R]=!0}function g(M,I,R){if(I>R){var O=I;I=R,R=O}return h.has(M[I],R)}function v(M,I,R,O){var H={},G={},Q={};return h.forEach(I,function($){h.forEach($,function(V,j){H[V]=V,G[V]=V,Q[V]=j})}),h.forEach(I,function($){var V=-1;h.forEach($,function(j){var k=O(j);if(k.length){k=h.sortBy(k,function(he){return Q[he]});for(var z=(k.length-1)/2,Y=Math.floor(z),J=Math.ceil(z);Y<=J;++Y){var re=k[Y];G[j]===j&&V{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/util.js"),d=l("../../../../node_modules/dagre/lib/position/bk.js").positionX;o.exports=f;function f(_){_=u.asNonCompoundGraph(_),p(_),h.forEach(d(_),function(m,g){_.node(g).x=m})}function p(_){var m=u.buildLayerMatrix(_),g=_.graph().ranksep,v=0;h.forEach(m,function(x){var y=h.max(h.map(x,function(C){return _.node(C).height}));h.forEach(x,function(C){_.node(C).y=v+y/2}),v+=y+g})}},"../../../../node_modules/dagre/lib/rank/feasible-tree.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/graphlib.js").Graph,d=l("../../../../node_modules/dagre/lib/rank/util.js").slack;o.exports=f;function f(g){var v=new u({directed:!1}),x=g.nodes()[0],y=g.nodeCount();v.setNode(x,{});for(var C,b;p(v,g){var h=l("../../../../node_modules/dagre/lib/rank/util.js"),u=h.longestPath,d=l("../../../../node_modules/dagre/lib/rank/feasible-tree.js"),f=l("../../../../node_modules/dagre/lib/rank/network-simplex.js");o.exports=p;function p(v){switch(v.graph().ranker){case"network-simplex":g(v);break;case"tight-tree":m(v);break;case"longest-path":_(v);break;default:g(v)}}var _=u;function m(v){u(v),d(v)}function g(v){f(v)}},"../../../../node_modules/dagre/lib/rank/network-simplex.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/rank/feasible-tree.js"),d=l("../../../../node_modules/dagre/lib/rank/util.js").slack,f=l("../../../../node_modules/dagre/lib/rank/util.js").longestPath,p=l("../../../../node_modules/dagre/lib/graphlib.js").alg.preorder,_=l("../../../../node_modules/dagre/lib/graphlib.js").alg.postorder,m=l("../../../../node_modules/dagre/lib/util.js").simplify;o.exports=g,g.initLowLimValues=C,g.initCutValues=v,g.calcCutValue=y,g.leaveEdge=T,g.enterEdge=S,g.exchangeEdges=N;function g(R){R=m(R),f(R);var O=u(R);C(O),v(O,R);for(var H,G;H=T(O);)G=S(O,R,H),N(O,R,H,G)}function v(R,O){var H=_(R,R.nodes());H=H.slice(0,H.length-1),h.forEach(H,function(G){x(R,O,G)})}function x(R,O,H){var G=R.node(H),Q=G.parent;R.edge(H,Q).cutvalue=y(R,O,H)}function y(R,O,H){var G=R.node(H),Q=G.parent,$=!0,V=O.edge(H,Q),j=0;return V||($=!1,V=O.edge(Q,H)),j=V.weight,h.forEach(O.nodeEdges(H),function(k){var z=k.v===H,Y=z?k.w:k.v;if(Y!==Q){var J=z===$,re=O.edge(k).weight;if(j+=J?re:-re,M(R,H,Y)){var he=R.edge(H,Y).cutvalue;j+=J?-he:he}}}),j}function C(R,O){arguments.length<2&&(O=R.nodes()[0]),b(R,{},1,O)}function b(R,O,H,G,Q){var $=H,V=R.node(G);return O[G]=!0,h.forEach(R.neighbors(G),function(j){h.has(O,j)||(H=b(R,O,H,j,G))}),V.low=$,V.lim=H++,Q?V.parent=Q:delete V.parent,H}function T(R){return h.find(R.edges(),function(O){return R.edge(O).cutvalue<0})}function S(R,O,H){var G=H.v,Q=H.w;O.hasEdge(G,Q)||(G=H.w,Q=H.v);var $=R.node(G),V=R.node(Q),j=$,k=!1;$.lim>V.lim&&(j=V,k=!0);var z=h.filter(O.edges(),function(Y){return k===I(R,R.node(Y.v),j)&&k!==I(R,R.node(Y.w),j)});return h.minBy(z,function(Y){return d(O,Y)})}function N(R,O,H,G){var Q=H.v,$=H.w;R.removeEdge(Q,$),R.setEdge(G.v,G.w,{}),C(R),v(R,O),D(R,O)}function D(R,O){var H=h.find(R.nodes(),function(Q){return!O.node(Q).parent}),G=p(R,H);G=G.slice(1),h.forEach(G,function(Q){var $=R.node(Q).parent,V=O.edge(Q,$),j=!1;V||(V=O.edge($,Q),j=!0),O.node(Q).rank=O.node($).rank+(j?V.minlen:-V.minlen)})}function M(R,O,H){return R.hasEdge(O,H)}function I(R,O,H){return H.low<=O.lim&&O.lim<=H.lim}},"../../../../node_modules/dagre/lib/rank/util.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js");o.exports={longestPath:u,slack:d};function u(f){var p={};function _(m){var g=f.node(m);if(h.has(p,m))return g.rank;p[m]=!0;var v=h.min(h.map(f.outEdges(m),function(x){return _(x.w)-f.edge(x).minlen}));return(v===Number.POSITIVE_INFINITY||v===void 0||v===null)&&(v=0),g.rank=v}h.forEach(f.sources(),_)}function d(f,p){return f.node(p.w).rank-f.node(p.v).rank-f.edge(p).minlen}},"../../../../node_modules/dagre/lib/util.js":(o,c,l)=>{var h=l("../../../../node_modules/dagre/lib/lodash.js"),u=l("../../../../node_modules/dagre/lib/graphlib.js").Graph;o.exports={addDummyNode:d,simplify:f,asNonCompoundGraph:p,successorWeights:_,predecessorWeights:m,intersectRect:g,buildLayerMatrix:v,normalizeRanks:x,removeEmptyRanks:y,addBorderNode:C,maxRank:b,partition:T,time:S,notime:N};function d(D,M,I,R){var O;do O=h.uniqueId(R);while(D.hasNode(O));return I.dummy=M,D.setNode(O,I),O}function f(D){var M=new u().setGraph(D.graph());return h.forEach(D.nodes(),function(I){M.setNode(I,D.node(I))}),h.forEach(D.edges(),function(I){var R=M.edge(I.v,I.w)||{weight:0,minlen:1},O=D.edge(I);M.setEdge(I.v,I.w,{weight:R.weight+O.weight,minlen:Math.max(R.minlen,O.minlen)})}),M}function p(D){var M=new u({multigraph:D.isMultigraph()}).setGraph(D.graph());return h.forEach(D.nodes(),function(I){D.children(I).length||M.setNode(I,D.node(I))}),h.forEach(D.edges(),function(I){M.setEdge(I,D.edge(I))}),M}function _(D){var M=h.map(D.nodes(),function(I){var R={};return h.forEach(D.outEdges(I),function(O){R[O.w]=(R[O.w]||0)+D.edge(O).weight}),R});return h.zipObject(D.nodes(),M)}function m(D){var M=h.map(D.nodes(),function(I){var R={};return h.forEach(D.inEdges(I),function(O){R[O.v]=(R[O.v]||0)+D.edge(O).weight}),R});return h.zipObject(D.nodes(),M)}function g(D,M){var I=D.x,R=D.y,O=M.x-I,H=M.y-R,G=D.width/2,Q=D.height/2;if(!O&&!H)throw new Error("Not possible to find intersection inside of the rectangle");var $,V;return Math.abs(H)*G>Math.abs(O)*Q?(H<0&&(Q=-Q),$=Q*O/H,V=Q):(O<0&&(G=-G),$=G,V=G*H/O),{x:I+$,y:R+V}}function v(D){var M=h.map(h.range(b(D)+1),function(){return[]});return h.forEach(D.nodes(),function(I){var R=D.node(I),O=R.rank;h.isUndefined(O)||(M[O][R.order]=I)}),M}function x(D){var M=h.min(h.map(D.nodes(),function(I){return D.node(I).rank}));h.forEach(D.nodes(),function(I){var R=D.node(I);h.has(R,"rank")&&(R.rank-=M)})}function y(D){var M=h.min(h.map(D.nodes(),function(H){return D.node(H).rank})),I=[];h.forEach(D.nodes(),function(H){var G=D.node(H).rank-M;I[G]||(I[G]=[]),I[G].push(H)});var R=0,O=D.graph().nodeRankFactor;h.forEach(I,function(H,G){h.isUndefined(H)&&G%O!==0?--R:R&&h.forEach(H,function(Q){D.node(Q).rank+=R})})}function C(D,M,I,R){var O={width:0,height:0};return arguments.length>=4&&(O.rank=I,O.order=R),d(D,"border",O,M)}function b(D){return h.max(h.map(D.nodes(),function(M){var I=D.node(M).rank;if(!h.isUndefined(I))return I}))}function T(D,M){var I={lhs:[],rhs:[]};return h.forEach(D,function(R){M(R)?I.lhs.push(R):I.rhs.push(R)}),I}function S(D,M){var I=h.now();try{return M()}finally{console.log(D+" time: "+(h.now()-I)+"ms")}}function N(D,M){return M()}},"../../../../node_modules/dagre/lib/version.js":o=>{o.exports="0.8.5"},"../../../../node_modules/graphlib/index.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/index.js");o.exports={Graph:h.Graph,json:l("../../../../node_modules/graphlib/lib/json.js"),alg:l("../../../../node_modules/graphlib/lib/alg/index.js"),version:h.version}},"../../../../node_modules/graphlib/lib/alg/components.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/lodash.js");o.exports=u;function u(d){var f={},p=[],_;function m(g){h.has(f,g)||(f[g]=!0,_.push(g),h.each(d.successors(g),m),h.each(d.predecessors(g),m))}return h.each(d.nodes(),function(g){_=[],m(g),_.length&&p.push(_)}),p}},"../../../../node_modules/graphlib/lib/alg/dfs.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/lodash.js");o.exports=u;function u(f,p,_){h.isArray(p)||(p=[p]);var m=(f.isDirected()?f.successors:f.neighbors).bind(f),g=[],v={};return h.each(p,function(x){if(!f.hasNode(x))throw new Error("Graph does not have node: "+x);d(f,x,_==="post",v,m,g)}),g}function d(f,p,_,m,g,v){h.has(m,p)||(m[p]=!0,_||v.push(p),h.each(g(p),function(x){d(f,x,_,m,g,v)}),_&&v.push(p))}},"../../../../node_modules/graphlib/lib/alg/dijkstra-all.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/alg/dijkstra.js"),u=l("../../../../node_modules/graphlib/lib/lodash.js");o.exports=d;function d(f,p,_){return u.transform(f.nodes(),function(m,g){m[g]=h(f,g,p,_)},{})}},"../../../../node_modules/graphlib/lib/alg/dijkstra.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/lodash.js"),u=l("../../../../node_modules/graphlib/lib/data/priority-queue.js");o.exports=f;var d=h.constant(1);function f(_,m,g,v){return p(_,String(m),g||d,v||function(x){return _.outEdges(x)})}function p(_,m,g,v){var x={},y=new u,C,b,T=function(S){var N=S.v!==C?S.v:S.w,D=x[N],M=g(S),I=b.distance+M;if(M<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+S+" Weight: "+M);I0&&(C=y.removeMin(),b=x[C],b.distance!==Number.POSITIVE_INFINITY);)v(C).forEach(T);return x}},"../../../../node_modules/graphlib/lib/alg/find-cycles.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/lodash.js"),u=l("../../../../node_modules/graphlib/lib/alg/tarjan.js");o.exports=d;function d(f){return h.filter(u(f),function(p){return p.length>1||p.length===1&&f.hasEdge(p[0],p[0])})}},"../../../../node_modules/graphlib/lib/alg/floyd-warshall.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/lodash.js");o.exports=d;var u=h.constant(1);function d(p,_,m){return f(p,_||u,m||function(g){return p.outEdges(g)})}function f(p,_,m){var g={},v=p.nodes();return v.forEach(function(x){g[x]={},g[x][x]={distance:0},v.forEach(function(y){x!==y&&(g[x][y]={distance:Number.POSITIVE_INFINITY})}),m(x).forEach(function(y){var C=y.v===x?y.w:y.v,b=_(y);g[x][C]={distance:b,predecessor:x}})}),v.forEach(function(x){var y=g[x];v.forEach(function(C){var b=g[C];v.forEach(function(T){var S=b[x],N=y[T],D=b[T],M=S.distance+N.distance;M{o.exports={components:l("../../../../node_modules/graphlib/lib/alg/components.js"),dijkstra:l("../../../../node_modules/graphlib/lib/alg/dijkstra.js"),dijkstraAll:l("../../../../node_modules/graphlib/lib/alg/dijkstra-all.js"),findCycles:l("../../../../node_modules/graphlib/lib/alg/find-cycles.js"),floydWarshall:l("../../../../node_modules/graphlib/lib/alg/floyd-warshall.js"),isAcyclic:l("../../../../node_modules/graphlib/lib/alg/is-acyclic.js"),postorder:l("../../../../node_modules/graphlib/lib/alg/postorder.js"),preorder:l("../../../../node_modules/graphlib/lib/alg/preorder.js"),prim:l("../../../../node_modules/graphlib/lib/alg/prim.js"),tarjan:l("../../../../node_modules/graphlib/lib/alg/tarjan.js"),topsort:l("../../../../node_modules/graphlib/lib/alg/topsort.js")}},"../../../../node_modules/graphlib/lib/alg/is-acyclic.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/alg/topsort.js");o.exports=u;function u(d){try{h(d)}catch(f){if(f instanceof h.CycleException)return!1;throw f}return!0}},"../../../../node_modules/graphlib/lib/alg/postorder.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/alg/dfs.js");o.exports=u;function u(d,f){return h(d,f,"post")}},"../../../../node_modules/graphlib/lib/alg/preorder.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/alg/dfs.js");o.exports=u;function u(d,f){return h(d,f,"pre")}},"../../../../node_modules/graphlib/lib/alg/prim.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/lodash.js"),u=l("../../../../node_modules/graphlib/lib/graph.js"),d=l("../../../../node_modules/graphlib/lib/data/priority-queue.js");o.exports=f;function f(p,_){var m=new u,g={},v=new d,x;function y(b){var T=b.v===x?b.w:b.v,S=v.priority(T);if(S!==void 0){var N=_(b);N0;){if(x=v.removeMin(),h.has(g,x))m.setEdge(x,g[x]);else{if(C)throw new Error("Input graph is not connected: "+p);C=!0}p.nodeEdges(x).forEach(y)}return m}},"../../../../node_modules/graphlib/lib/alg/tarjan.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/lodash.js");o.exports=u;function u(d){var f=0,p=[],_={},m=[];function g(v){var x=_[v]={onStack:!0,lowlink:f,index:f++};if(p.push(v),d.successors(v).forEach(function(b){h.has(_,b)?_[b].onStack&&(x.lowlink=Math.min(x.lowlink,_[b].index)):(g(b),x.lowlink=Math.min(x.lowlink,_[b].lowlink))}),x.lowlink===x.index){var y=[],C;do C=p.pop(),_[C].onStack=!1,y.push(C);while(v!==C);m.push(y)}}return d.nodes().forEach(function(v){h.has(_,v)||g(v)}),m}},"../../../../node_modules/graphlib/lib/alg/topsort.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/lodash.js");o.exports=u,u.CycleException=d;function u(f){var p={},_={},m=[];function g(v){if(h.has(_,v))throw new d;h.has(p,v)||(_[v]=!0,p[v]=!0,h.each(f.predecessors(v),g),delete _[v],m.push(v))}if(h.each(f.sinks(),g),h.size(p)!==f.nodeCount())throw new d;return m}function d(){}d.prototype=new Error},"../../../../node_modules/graphlib/lib/data/priority-queue.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/lodash.js");o.exports=u;function u(){this._arr=[],this._keyIndices={}}u.prototype.size=function(){return this._arr.length},u.prototype.keys=function(){return this._arr.map(function(d){return d.key})},u.prototype.has=function(d){return h.has(this._keyIndices,d)},u.prototype.priority=function(d){var f=this._keyIndices[d];if(f!==void 0)return this._arr[f].priority},u.prototype.min=function(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key},u.prototype.add=function(d,f){var p=this._keyIndices;if(d=String(d),!h.has(p,d)){var _=this._arr,m=_.length;return p[d]=m,_.push({key:d,priority:f}),this._decrease(m),!0}return!1},u.prototype.removeMin=function(){this._swap(0,this._arr.length-1);var d=this._arr.pop();return delete this._keyIndices[d.key],this._heapify(0),d.key},u.prototype.decrease=function(d,f){var p=this._keyIndices[d];if(f>this._arr[p].priority)throw new Error("New priority is greater than current priority. Key: "+d+" Old: "+this._arr[p].priority+" New: "+f);this._arr[p].priority=f,this._decrease(p)},u.prototype._heapify=function(d){var f=this._arr,p=2*d,_=p+1,m=d;p>1,!(f[_].priority{var h=l("../../../../node_modules/graphlib/lib/lodash.js");o.exports=p;var u="\0",d="\0",f="";function p(y){this._isDirected=h.has(y,"directed")?y.directed:!0,this._isMultigraph=h.has(y,"multigraph")?y.multigraph:!1,this._isCompound=h.has(y,"compound")?y.compound:!1,this._label=void 0,this._defaultNodeLabelFn=h.constant(void 0),this._defaultEdgeLabelFn=h.constant(void 0),this._nodes={},this._isCompound&&(this._parent={},this._children={},this._children[d]={}),this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={}}p.prototype._nodeCount=0,p.prototype._edgeCount=0,p.prototype.isDirected=function(){return this._isDirected},p.prototype.isMultigraph=function(){return this._isMultigraph},p.prototype.isCompound=function(){return this._isCompound},p.prototype.setGraph=function(y){return this._label=y,this},p.prototype.graph=function(){return this._label},p.prototype.setDefaultNodeLabel=function(y){return h.isFunction(y)||(y=h.constant(y)),this._defaultNodeLabelFn=y,this},p.prototype.nodeCount=function(){return this._nodeCount},p.prototype.nodes=function(){return h.keys(this._nodes)},p.prototype.sources=function(){var y=this;return h.filter(this.nodes(),function(C){return h.isEmpty(y._in[C])})},p.prototype.sinks=function(){var y=this;return h.filter(this.nodes(),function(C){return h.isEmpty(y._out[C])})},p.prototype.setNodes=function(y,C){var b=arguments,T=this;return h.each(y,function(S){b.length>1?T.setNode(S,C):T.setNode(S)}),this},p.prototype.setNode=function(y,C){return h.has(this._nodes,y)?(arguments.length>1&&(this._nodes[y]=C),this):(this._nodes[y]=arguments.length>1?C:this._defaultNodeLabelFn(y),this._isCompound&&(this._parent[y]=d,this._children[y]={},this._children[d][y]=!0),this._in[y]={},this._preds[y]={},this._out[y]={},this._sucs[y]={},++this._nodeCount,this)},p.prototype.node=function(y){return this._nodes[y]},p.prototype.hasNode=function(y){return h.has(this._nodes,y)},p.prototype.removeNode=function(y){var C=this;if(h.has(this._nodes,y)){var b=function(T){C.removeEdge(C._edgeObjs[T])};delete this._nodes[y],this._isCompound&&(this._removeFromParentsChildList(y),delete this._parent[y],h.each(this.children(y),function(T){C.setParent(T)}),delete this._children[y]),h.each(h.keys(this._in[y]),b),delete this._in[y],delete this._preds[y],h.each(h.keys(this._out[y]),b),delete this._out[y],delete this._sucs[y],--this._nodeCount}return this},p.prototype.setParent=function(y,C){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(h.isUndefined(C))C=d;else{C+="";for(var b=C;!h.isUndefined(b);b=this.parent(b))if(b===y)throw new Error("Setting "+C+" as parent of "+y+" would create a cycle");this.setNode(C)}return this.setNode(y),this._removeFromParentsChildList(y),this._parent[y]=C,this._children[C][y]=!0,this},p.prototype._removeFromParentsChildList=function(y){delete this._children[this._parent[y]][y]},p.prototype.parent=function(y){if(this._isCompound){var C=this._parent[y];if(C!==d)return C}},p.prototype.children=function(y){if(h.isUndefined(y)&&(y=d),this._isCompound){var C=this._children[y];if(C)return h.keys(C)}else{if(y===d)return this.nodes();if(this.hasNode(y))return[]}},p.prototype.predecessors=function(y){var C=this._preds[y];if(C)return h.keys(C)},p.prototype.successors=function(y){var C=this._sucs[y];if(C)return h.keys(C)},p.prototype.neighbors=function(y){var C=this.predecessors(y);if(C)return h.union(C,this.successors(y))},p.prototype.isLeaf=function(y){var C;return this.isDirected()?C=this.successors(y):C=this.neighbors(y),C.length===0},p.prototype.filterNodes=function(y){var C=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});C.setGraph(this.graph());var b=this;h.each(this._nodes,function(N,D){y(D)&&C.setNode(D,N)}),h.each(this._edgeObjs,function(N){C.hasNode(N.v)&&C.hasNode(N.w)&&C.setEdge(N,b.edge(N))});var T={};function S(N){var D=b.parent(N);return D===void 0||C.hasNode(D)?(T[N]=D,D):D in T?T[D]:S(D)}return this._isCompound&&h.each(C.nodes(),function(N){C.setParent(N,S(N))}),C},p.prototype.setDefaultEdgeLabel=function(y){return h.isFunction(y)||(y=h.constant(y)),this._defaultEdgeLabelFn=y,this},p.prototype.edgeCount=function(){return this._edgeCount},p.prototype.edges=function(){return h.values(this._edgeObjs)},p.prototype.setPath=function(y,C){var b=this,T=arguments;return h.reduce(y,function(S,N){return T.length>1?b.setEdge(S,N,C):b.setEdge(S,N),N}),this},p.prototype.setEdge=function(){var y,C,b,T,S=!1,N=arguments[0];typeof N=="object"&&N!==null&&"v"in N?(y=N.v,C=N.w,b=N.name,arguments.length===2&&(T=arguments[1],S=!0)):(y=N,C=arguments[1],b=arguments[3],arguments.length>2&&(T=arguments[2],S=!0)),y=""+y,C=""+C,h.isUndefined(b)||(b=""+b);var D=g(this._isDirected,y,C,b);if(h.has(this._edgeLabels,D))return S&&(this._edgeLabels[D]=T),this;if(!h.isUndefined(b)&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(y),this.setNode(C),this._edgeLabels[D]=S?T:this._defaultEdgeLabelFn(y,C,b);var M=v(this._isDirected,y,C,b);return y=M.v,C=M.w,Object.freeze(M),this._edgeObjs[D]=M,_(this._preds[C],y),_(this._sucs[y],C),this._in[C][D]=M,this._out[y][D]=M,this._edgeCount++,this},p.prototype.edge=function(y,C,b){var T=arguments.length===1?x(this._isDirected,arguments[0]):g(this._isDirected,y,C,b);return this._edgeLabels[T]},p.prototype.hasEdge=function(y,C,b){var T=arguments.length===1?x(this._isDirected,arguments[0]):g(this._isDirected,y,C,b);return h.has(this._edgeLabels,T)},p.prototype.removeEdge=function(y,C,b){var T=arguments.length===1?x(this._isDirected,arguments[0]):g(this._isDirected,y,C,b),S=this._edgeObjs[T];return S&&(y=S.v,C=S.w,delete this._edgeLabels[T],delete this._edgeObjs[T],m(this._preds[C],y),m(this._sucs[y],C),delete this._in[C][T],delete this._out[y][T],this._edgeCount--),this},p.prototype.inEdges=function(y,C){var b=this._in[y];if(b){var T=h.values(b);return C?h.filter(T,function(S){return S.v===C}):T}},p.prototype.outEdges=function(y,C){var b=this._out[y];if(b){var T=h.values(b);return C?h.filter(T,function(S){return S.w===C}):T}},p.prototype.nodeEdges=function(y,C){var b=this.inEdges(y,C);if(b)return b.concat(this.outEdges(y,C))};function _(y,C){y[C]?y[C]++:y[C]=1}function m(y,C){--y[C]||delete y[C]}function g(y,C,b,T){var S=""+C,N=""+b;if(!y&&S>N){var D=S;S=N,N=D}return S+f+N+f+(h.isUndefined(T)?u:T)}function v(y,C,b,T){var S=""+C,N=""+b;if(!y&&S>N){var D=S;S=N,N=D}var M={v:S,w:N};return T&&(M.name=T),M}function x(y,C){return g(y,C.v,C.w,C.name)}},"../../../../node_modules/graphlib/lib/index.js":(o,c,l)=>{o.exports={Graph:l("../../../../node_modules/graphlib/lib/graph.js"),version:l("../../../../node_modules/graphlib/lib/version.js")}},"../../../../node_modules/graphlib/lib/json.js":(o,c,l)=>{var h=l("../../../../node_modules/graphlib/lib/lodash.js"),u=l("../../../../node_modules/graphlib/lib/graph.js");o.exports={write:d,read:_};function d(m){var g={options:{directed:m.isDirected(),multigraph:m.isMultigraph(),compound:m.isCompound()},nodes:f(m),edges:p(m)};return h.isUndefined(m.graph())||(g.value=h.clone(m.graph())),g}function f(m){return h.map(m.nodes(),function(g){var v=m.node(g),x=m.parent(g),y={v:g};return h.isUndefined(v)||(y.value=v),h.isUndefined(x)||(y.parent=x),y})}function p(m){return h.map(m.edges(),function(g){var v=m.edge(g),x={v:g.v,w:g.w};return h.isUndefined(g.name)||(x.name=g.name),h.isUndefined(v)||(x.value=v),x})}function _(m){var g=new u(m.options).setGraph(m.value);return h.each(m.nodes,function(v){g.setNode(v.v,v.value),v.parent&&g.setParent(v.v,v.parent)}),h.each(m.edges,function(v){g.setEdge({v:v.v,w:v.w,name:v.name},v.value)}),g}},"../../../../node_modules/graphlib/lib/lodash.js":(o,c,l)=>{var h;try{h={clone:l("../../../../node_modules/lodash/clone.js"),constant:l("../../../../node_modules/lodash/constant.js"),each:l("../../../../node_modules/lodash/each.js"),filter:l("../../../../node_modules/lodash/filter.js"),has:l("../../../../node_modules/lodash/has.js"),isArray:l("../../../../node_modules/lodash/isArray.js"),isEmpty:l("../../../../node_modules/lodash/isEmpty.js"),isFunction:l("../../../../node_modules/lodash/isFunction.js"),isUndefined:l("../../../../node_modules/lodash/isUndefined.js"),keys:l("../../../../node_modules/lodash/keys.js"),map:l("../../../../node_modules/lodash/map.js"),reduce:l("../../../../node_modules/lodash/reduce.js"),size:l("../../../../node_modules/lodash/size.js"),transform:l("../../../../node_modules/lodash/transform.js"),union:l("../../../../node_modules/lodash/union.js"),values:l("../../../../node_modules/lodash/values.js")}}catch{}h||(h=window._),o.exports=h},"../../../../node_modules/graphlib/lib/version.js":o=>{o.exports="2.1.8"},"../../../../node_modules/lodash/_DataView.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getNative.js"),u=l("../../../../node_modules/lodash/_root.js"),d=h(u,"DataView");o.exports=d},"../../../../node_modules/lodash/_Hash.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_hashClear.js"),u=l("../../../../node_modules/lodash/_hashDelete.js"),d=l("../../../../node_modules/lodash/_hashGet.js"),f=l("../../../../node_modules/lodash/_hashHas.js"),p=l("../../../../node_modules/lodash/_hashSet.js");function _(m){var g=-1,v=m==null?0:m.length;for(this.clear();++g{var h=l("../../../../node_modules/lodash/_listCacheClear.js"),u=l("../../../../node_modules/lodash/_listCacheDelete.js"),d=l("../../../../node_modules/lodash/_listCacheGet.js"),f=l("../../../../node_modules/lodash/_listCacheHas.js"),p=l("../../../../node_modules/lodash/_listCacheSet.js");function _(m){var g=-1,v=m==null?0:m.length;for(this.clear();++g{var h=l("../../../../node_modules/lodash/_getNative.js"),u=l("../../../../node_modules/lodash/_root.js"),d=h(u,"Map");o.exports=d},"../../../../node_modules/lodash/_MapCache.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_mapCacheClear.js"),u=l("../../../../node_modules/lodash/_mapCacheDelete.js"),d=l("../../../../node_modules/lodash/_mapCacheGet.js"),f=l("../../../../node_modules/lodash/_mapCacheHas.js"),p=l("../../../../node_modules/lodash/_mapCacheSet.js");function _(m){var g=-1,v=m==null?0:m.length;for(this.clear();++g{var h=l("../../../../node_modules/lodash/_getNative.js"),u=l("../../../../node_modules/lodash/_root.js"),d=h(u,"Promise");o.exports=d},"../../../../node_modules/lodash/_Set.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getNative.js"),u=l("../../../../node_modules/lodash/_root.js"),d=h(u,"Set");o.exports=d},"../../../../node_modules/lodash/_SetCache.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_MapCache.js"),u=l("../../../../node_modules/lodash/_setCacheAdd.js"),d=l("../../../../node_modules/lodash/_setCacheHas.js");function f(p){var _=-1,m=p==null?0:p.length;for(this.__data__=new h;++_{var h=l("../../../../node_modules/lodash/_ListCache.js"),u=l("../../../../node_modules/lodash/_stackClear.js"),d=l("../../../../node_modules/lodash/_stackDelete.js"),f=l("../../../../node_modules/lodash/_stackGet.js"),p=l("../../../../node_modules/lodash/_stackHas.js"),_=l("../../../../node_modules/lodash/_stackSet.js");function m(g){var v=this.__data__=new h(g);this.size=v.size}m.prototype.clear=u,m.prototype.delete=d,m.prototype.get=f,m.prototype.has=p,m.prototype.set=_,o.exports=m},"../../../../node_modules/lodash/_Symbol.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_root.js"),u=h.Symbol;o.exports=u},"../../../../node_modules/lodash/_Uint8Array.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_root.js"),u=h.Uint8Array;o.exports=u},"../../../../node_modules/lodash/_WeakMap.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getNative.js"),u=l("../../../../node_modules/lodash/_root.js"),d=h(u,"WeakMap");o.exports=d},"../../../../node_modules/lodash/_apply.js":o=>{function c(l,h,u){switch(u.length){case 0:return l.call(h);case 1:return l.call(h,u[0]);case 2:return l.call(h,u[0],u[1]);case 3:return l.call(h,u[0],u[1],u[2])}return l.apply(h,u)}o.exports=c},"../../../../node_modules/lodash/_arrayEach.js":o=>{function c(l,h){for(var u=-1,d=l==null?0:l.length;++u{function c(l,h){for(var u=-1,d=l==null?0:l.length,f=0,p=[];++u{var h=l("../../../../node_modules/lodash/_baseIndexOf.js");function u(d,f){var p=d==null?0:d.length;return!!p&&h(d,f,0)>-1}o.exports=u},"../../../../node_modules/lodash/_arrayIncludesWith.js":o=>{function c(l,h,u){for(var d=-1,f=l==null?0:l.length;++d{var h=l("../../../../node_modules/lodash/_baseTimes.js"),u=l("../../../../node_modules/lodash/isArguments.js"),d=l("../../../../node_modules/lodash/isArray.js"),f=l("../../../../node_modules/lodash/isBuffer.js"),p=l("../../../../node_modules/lodash/_isIndex.js"),_=l("../../../../node_modules/lodash/isTypedArray.js"),m=Object.prototype,g=m.hasOwnProperty;function v(x,y){var C=d(x),b=!C&&u(x),T=!C&&!b&&f(x),S=!C&&!b&&!T&&_(x),N=C||b||T||S,D=N?h(x.length,String):[],M=D.length;for(var I in x)(y||g.call(x,I))&&!(N&&(I=="length"||T&&(I=="offset"||I=="parent")||S&&(I=="buffer"||I=="byteLength"||I=="byteOffset")||p(I,M)))&&D.push(I);return D}o.exports=v},"../../../../node_modules/lodash/_arrayMap.js":o=>{function c(l,h){for(var u=-1,d=l==null?0:l.length,f=Array(d);++u{function c(l,h){for(var u=-1,d=h.length,f=l.length;++u{function c(l,h,u,d){var f=-1,p=l==null?0:l.length;for(d&&p&&(u=l[++f]);++f{function c(l,h){for(var u=-1,d=l==null?0:l.length;++u{var h=l("../../../../node_modules/lodash/_baseProperty.js"),u=h("length");o.exports=u},"../../../../node_modules/lodash/_assignMergeValue.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseAssignValue.js"),u=l("../../../../node_modules/lodash/eq.js");function d(f,p,_){(_!==void 0&&!u(f[p],_)||_===void 0&&!(p in f))&&h(f,p,_)}o.exports=d},"../../../../node_modules/lodash/_assignValue.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseAssignValue.js"),u=l("../../../../node_modules/lodash/eq.js"),d=Object.prototype,f=d.hasOwnProperty;function p(_,m,g){var v=_[m];(!(f.call(_,m)&&u(v,g))||g===void 0&&!(m in _))&&h(_,m,g)}o.exports=p},"../../../../node_modules/lodash/_assocIndexOf.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/eq.js");function u(d,f){for(var p=d.length;p--;)if(h(d[p][0],f))return p;return-1}o.exports=u},"../../../../node_modules/lodash/_baseAssign.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_copyObject.js"),u=l("../../../../node_modules/lodash/keys.js");function d(f,p){return f&&h(p,u(p),f)}o.exports=d},"../../../../node_modules/lodash/_baseAssignIn.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_copyObject.js"),u=l("../../../../node_modules/lodash/keysIn.js");function d(f,p){return f&&h(p,u(p),f)}o.exports=d},"../../../../node_modules/lodash/_baseAssignValue.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_defineProperty.js");function u(d,f,p){f=="__proto__"&&h?h(d,f,{configurable:!0,enumerable:!0,value:p,writable:!0}):d[f]=p}o.exports=u},"../../../../node_modules/lodash/_baseClone.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_Stack.js"),u=l("../../../../node_modules/lodash/_arrayEach.js"),d=l("../../../../node_modules/lodash/_assignValue.js"),f=l("../../../../node_modules/lodash/_baseAssign.js"),p=l("../../../../node_modules/lodash/_baseAssignIn.js"),_=l("../../../../node_modules/lodash/_cloneBuffer.js"),m=l("../../../../node_modules/lodash/_copyArray.js"),g=l("../../../../node_modules/lodash/_copySymbols.js"),v=l("../../../../node_modules/lodash/_copySymbolsIn.js"),x=l("../../../../node_modules/lodash/_getAllKeys.js"),y=l("../../../../node_modules/lodash/_getAllKeysIn.js"),C=l("../../../../node_modules/lodash/_getTag.js"),b=l("../../../../node_modules/lodash/_initCloneArray.js"),T=l("../../../../node_modules/lodash/_initCloneByTag.js"),S=l("../../../../node_modules/lodash/_initCloneObject.js"),N=l("../../../../node_modules/lodash/isArray.js"),D=l("../../../../node_modules/lodash/isBuffer.js"),M=l("../../../../node_modules/lodash/isMap.js"),I=l("../../../../node_modules/lodash/isObject.js"),R=l("../../../../node_modules/lodash/isSet.js"),O=l("../../../../node_modules/lodash/keys.js"),H=l("../../../../node_modules/lodash/keysIn.js"),G=1,Q=2,$=4,V="[object Arguments]",j="[object Array]",k="[object Boolean]",z="[object Date]",Y="[object Error]",J="[object Function]",re="[object GeneratorFunction]",he="[object Map]",le="[object Number]",ue="[object Object]",L="[object RegExp]",F="[object Set]",W="[object String]",te="[object Symbol]",oe="[object WeakMap]",ne="[object ArrayBuffer]",pe="[object DataView]",ye="[object Float32Array]",Pe="[object Float64Array]",Fe="[object Int8Array]",He="[object Int16Array]",ot="[object Int32Array]",Xe="[object Uint8Array]",gt="[object Uint8ClampedArray]",rt="[object Uint16Array]",ut="[object Uint32Array]",Yt={};Yt[V]=Yt[j]=Yt[ne]=Yt[pe]=Yt[k]=Yt[z]=Yt[ye]=Yt[Pe]=Yt[Fe]=Yt[He]=Yt[ot]=Yt[he]=Yt[le]=Yt[ue]=Yt[L]=Yt[F]=Yt[W]=Yt[te]=Yt[Xe]=Yt[gt]=Yt[rt]=Yt[ut]=!0,Yt[Y]=Yt[J]=Yt[oe]=!1;function ki(ei,Xi,Li,Yr,xi,Wi){var Ti,zi=Xi&G,ji=Xi&Q,Ei=Xi&$;if(Li&&(Ti=xi?Li(ei,Yr,xi,Wi):Li(ei)),Ti!==void 0)return Ti;if(!I(ei))return ei;var Si=N(ei);if(Si){if(Ti=b(ei),!zi)return m(ei,Ti)}else{var ir=C(ei),Ot=ir==J||ir==re;if(D(ei))return _(ei,zi);if(ir==ue||ir==V||Ot&&!xi){if(Ti=ji||Ot?{}:S(ei),!zi)return ji?v(ei,p(Ti,ei)):g(ei,f(Ti,ei))}else{if(!Yt[ir])return xi?ei:{};Ti=T(ei,ir,zi)}}Wi||(Wi=new h);var qt=Wi.get(ei);if(qt)return qt;Wi.set(ei,Ti),R(ei)?ei.forEach(function(er){Ti.add(ki(er,Xi,Li,er,ei,Wi))}):M(ei)&&ei.forEach(function(er,lr){Ti.set(lr,ki(er,Xi,Li,lr,ei,Wi))});var Vt=Ei?ji?y:x:ji?H:O,Mi=Si?void 0:Vt(ei);return u(Mi||ei,function(er,lr){Mi&&(lr=er,er=ei[lr]),d(Ti,lr,ki(er,Xi,Li,lr,ei,Wi))}),Ti}o.exports=ki},"../../../../node_modules/lodash/_baseCreate.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isObject.js"),u=Object.create,d=function(){function f(){}return function(p){if(!h(p))return{};if(u)return u(p);f.prototype=p;var _=new f;return f.prototype=void 0,_}}();o.exports=d},"../../../../node_modules/lodash/_baseEach.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseForOwn.js"),u=l("../../../../node_modules/lodash/_createBaseEach.js"),d=u(h);o.exports=d},"../../../../node_modules/lodash/_baseExtremum.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isSymbol.js");function u(d,f,p){for(var _=-1,m=d.length;++_{var h=l("../../../../node_modules/lodash/_baseEach.js");function u(d,f){var p=[];return h(d,function(_,m,g){f(_,m,g)&&p.push(_)}),p}o.exports=u},"../../../../node_modules/lodash/_baseFindIndex.js":o=>{function c(l,h,u,d){for(var f=l.length,p=u+(d?1:-1);d?p--:++p{var h=l("../../../../node_modules/lodash/_arrayPush.js"),u=l("../../../../node_modules/lodash/_isFlattenable.js");function d(f,p,_,m,g){var v=-1,x=f.length;for(_||(_=u),g||(g=[]);++v0&&_(y)?p>1?d(y,p-1,_,m,g):h(g,y):m||(g[g.length]=y)}return g}o.exports=d},"../../../../node_modules/lodash/_baseFor.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_createBaseFor.js"),u=h();o.exports=u},"../../../../node_modules/lodash/_baseForOwn.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseFor.js"),u=l("../../../../node_modules/lodash/keys.js");function d(f,p){return f&&h(f,p,u)}o.exports=d},"../../../../node_modules/lodash/_baseGet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_castPath.js"),u=l("../../../../node_modules/lodash/_toKey.js");function d(f,p){p=h(p,f);for(var _=0,m=p.length;f!=null&&_{var h=l("../../../../node_modules/lodash/_arrayPush.js"),u=l("../../../../node_modules/lodash/isArray.js");function d(f,p,_){var m=p(f);return u(f)?m:h(m,_(f))}o.exports=d},"../../../../node_modules/lodash/_baseGetTag.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_Symbol.js"),u=l("../../../../node_modules/lodash/_getRawTag.js"),d=l("../../../../node_modules/lodash/_objectToString.js"),f="[object Null]",p="[object Undefined]",_=h?h.toStringTag:void 0;function m(g){return g==null?g===void 0?p:f:_&&_ in Object(g)?u(g):d(g)}o.exports=m},"../../../../node_modules/lodash/_baseGt.js":o=>{function c(l,h){return l>h}o.exports=c},"../../../../node_modules/lodash/_baseHas.js":o=>{var c=Object.prototype,l=c.hasOwnProperty;function h(u,d){return u!=null&&l.call(u,d)}o.exports=h},"../../../../node_modules/lodash/_baseHasIn.js":o=>{function c(l,h){return l!=null&&h in Object(l)}o.exports=c},"../../../../node_modules/lodash/_baseIndexOf.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseFindIndex.js"),u=l("../../../../node_modules/lodash/_baseIsNaN.js"),d=l("../../../../node_modules/lodash/_strictIndexOf.js");function f(p,_,m){return _===_?d(p,_,m):h(p,u,m)}o.exports=f},"../../../../node_modules/lodash/_baseIsArguments.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGetTag.js"),u=l("../../../../node_modules/lodash/isObjectLike.js"),d="[object Arguments]";function f(p){return u(p)&&h(p)==d}o.exports=f},"../../../../node_modules/lodash/_baseIsEqual.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseIsEqualDeep.js"),u=l("../../../../node_modules/lodash/isObjectLike.js");function d(f,p,_,m,g){return f===p?!0:f==null||p==null||!u(f)&&!u(p)?f!==f&&p!==p:h(f,p,_,m,d,g)}o.exports=d},"../../../../node_modules/lodash/_baseIsEqualDeep.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_Stack.js"),u=l("../../../../node_modules/lodash/_equalArrays.js"),d=l("../../../../node_modules/lodash/_equalByTag.js"),f=l("../../../../node_modules/lodash/_equalObjects.js"),p=l("../../../../node_modules/lodash/_getTag.js"),_=l("../../../../node_modules/lodash/isArray.js"),m=l("../../../../node_modules/lodash/isBuffer.js"),g=l("../../../../node_modules/lodash/isTypedArray.js"),v=1,x="[object Arguments]",y="[object Array]",C="[object Object]",b=Object.prototype,T=b.hasOwnProperty;function S(N,D,M,I,R,O){var H=_(N),G=_(D),Q=H?y:p(N),$=G?y:p(D);Q=Q==x?C:Q,$=$==x?C:$;var V=Q==C,j=$==C,k=Q==$;if(k&&m(N)){if(!m(D))return!1;H=!0,V=!1}if(k&&!V)return O||(O=new h),H||g(N)?u(N,D,M,I,R,O):d(N,D,Q,M,I,R,O);if(!(M&v)){var z=V&&T.call(N,"__wrapped__"),Y=j&&T.call(D,"__wrapped__");if(z||Y){var J=z?N.value():N,re=Y?D.value():D;return O||(O=new h),R(J,re,M,I,O)}}return k?(O||(O=new h),f(N,D,M,I,R,O)):!1}o.exports=S},"../../../../node_modules/lodash/_baseIsMap.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getTag.js"),u=l("../../../../node_modules/lodash/isObjectLike.js"),d="[object Map]";function f(p){return u(p)&&h(p)==d}o.exports=f},"../../../../node_modules/lodash/_baseIsMatch.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_Stack.js"),u=l("../../../../node_modules/lodash/_baseIsEqual.js"),d=1,f=2;function p(_,m,g,v){var x=g.length,y=x,C=!v;if(_==null)return!y;for(_=Object(_);x--;){var b=g[x];if(C&&b[2]?b[1]!==_[b[0]]:!(b[0]in _))return!1}for(;++x{function c(l){return l!==l}o.exports=c},"../../../../node_modules/lodash/_baseIsNative.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isFunction.js"),u=l("../../../../node_modules/lodash/_isMasked.js"),d=l("../../../../node_modules/lodash/isObject.js"),f=l("../../../../node_modules/lodash/_toSource.js"),p=/[\\^$.*+?()[\]{}|]/g,_=/^\[object .+?Constructor\]$/,m=Function.prototype,g=Object.prototype,v=m.toString,x=g.hasOwnProperty,y=RegExp("^"+v.call(x).replace(p,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function C(b){if(!d(b)||u(b))return!1;var T=h(b)?y:_;return T.test(f(b))}o.exports=C},"../../../../node_modules/lodash/_baseIsSet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getTag.js"),u=l("../../../../node_modules/lodash/isObjectLike.js"),d="[object Set]";function f(p){return u(p)&&h(p)==d}o.exports=f},"../../../../node_modules/lodash/_baseIsTypedArray.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGetTag.js"),u=l("../../../../node_modules/lodash/isLength.js"),d=l("../../../../node_modules/lodash/isObjectLike.js"),f="[object Arguments]",p="[object Array]",_="[object Boolean]",m="[object Date]",g="[object Error]",v="[object Function]",x="[object Map]",y="[object Number]",C="[object Object]",b="[object RegExp]",T="[object Set]",S="[object String]",N="[object WeakMap]",D="[object ArrayBuffer]",M="[object DataView]",I="[object Float32Array]",R="[object Float64Array]",O="[object Int8Array]",H="[object Int16Array]",G="[object Int32Array]",Q="[object Uint8Array]",$="[object Uint8ClampedArray]",V="[object Uint16Array]",j="[object Uint32Array]",k={};k[I]=k[R]=k[O]=k[H]=k[G]=k[Q]=k[$]=k[V]=k[j]=!0,k[f]=k[p]=k[D]=k[_]=k[M]=k[m]=k[g]=k[v]=k[x]=k[y]=k[C]=k[b]=k[T]=k[S]=k[N]=!1;function z(Y){return d(Y)&&u(Y.length)&&!!k[h(Y)]}o.exports=z},"../../../../node_modules/lodash/_baseIteratee.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseMatches.js"),u=l("../../../../node_modules/lodash/_baseMatchesProperty.js"),d=l("../../../../node_modules/lodash/identity.js"),f=l("../../../../node_modules/lodash/isArray.js"),p=l("../../../../node_modules/lodash/property.js");function _(m){return typeof m=="function"?m:m==null?d:typeof m=="object"?f(m)?u(m[0],m[1]):h(m):p(m)}o.exports=_},"../../../../node_modules/lodash/_baseKeys.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_isPrototype.js"),u=l("../../../../node_modules/lodash/_nativeKeys.js"),d=Object.prototype,f=d.hasOwnProperty;function p(_){if(!h(_))return u(_);var m=[];for(var g in Object(_))f.call(_,g)&&g!="constructor"&&m.push(g);return m}o.exports=p},"../../../../node_modules/lodash/_baseKeysIn.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isObject.js"),u=l("../../../../node_modules/lodash/_isPrototype.js"),d=l("../../../../node_modules/lodash/_nativeKeysIn.js"),f=Object.prototype,p=f.hasOwnProperty;function _(m){if(!h(m))return d(m);var g=u(m),v=[];for(var x in m)x=="constructor"&&(g||!p.call(m,x))||v.push(x);return v}o.exports=_},"../../../../node_modules/lodash/_baseLt.js":o=>{function c(l,h){return l{var h=l("../../../../node_modules/lodash/_baseEach.js"),u=l("../../../../node_modules/lodash/isArrayLike.js");function d(f,p){var _=-1,m=u(f)?Array(f.length):[];return h(f,function(g,v,x){m[++_]=p(g,v,x)}),m}o.exports=d},"../../../../node_modules/lodash/_baseMatches.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseIsMatch.js"),u=l("../../../../node_modules/lodash/_getMatchData.js"),d=l("../../../../node_modules/lodash/_matchesStrictComparable.js");function f(p){var _=u(p);return _.length==1&&_[0][2]?d(_[0][0],_[0][1]):function(m){return m===p||h(m,p,_)}}o.exports=f},"../../../../node_modules/lodash/_baseMatchesProperty.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseIsEqual.js"),u=l("../../../../node_modules/lodash/get.js"),d=l("../../../../node_modules/lodash/hasIn.js"),f=l("../../../../node_modules/lodash/_isKey.js"),p=l("../../../../node_modules/lodash/_isStrictComparable.js"),_=l("../../../../node_modules/lodash/_matchesStrictComparable.js"),m=l("../../../../node_modules/lodash/_toKey.js"),g=1,v=2;function x(y,C){return f(y)&&p(C)?_(m(y),C):function(b){var T=u(b,y);return T===void 0&&T===C?d(b,y):h(C,T,g|v)}}o.exports=x},"../../../../node_modules/lodash/_baseMerge.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_Stack.js"),u=l("../../../../node_modules/lodash/_assignMergeValue.js"),d=l("../../../../node_modules/lodash/_baseFor.js"),f=l("../../../../node_modules/lodash/_baseMergeDeep.js"),p=l("../../../../node_modules/lodash/isObject.js"),_=l("../../../../node_modules/lodash/keysIn.js"),m=l("../../../../node_modules/lodash/_safeGet.js");function g(v,x,y,C,b){v!==x&&d(x,function(T,S){if(b||(b=new h),p(T))f(v,x,S,y,g,C,b);else{var N=C?C(m(v,S),T,S+"",v,x,b):void 0;N===void 0&&(N=T),u(v,S,N)}},_)}o.exports=g},"../../../../node_modules/lodash/_baseMergeDeep.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_assignMergeValue.js"),u=l("../../../../node_modules/lodash/_cloneBuffer.js"),d=l("../../../../node_modules/lodash/_cloneTypedArray.js"),f=l("../../../../node_modules/lodash/_copyArray.js"),p=l("../../../../node_modules/lodash/_initCloneObject.js"),_=l("../../../../node_modules/lodash/isArguments.js"),m=l("../../../../node_modules/lodash/isArray.js"),g=l("../../../../node_modules/lodash/isArrayLikeObject.js"),v=l("../../../../node_modules/lodash/isBuffer.js"),x=l("../../../../node_modules/lodash/isFunction.js"),y=l("../../../../node_modules/lodash/isObject.js"),C=l("../../../../node_modules/lodash/isPlainObject.js"),b=l("../../../../node_modules/lodash/isTypedArray.js"),T=l("../../../../node_modules/lodash/_safeGet.js"),S=l("../../../../node_modules/lodash/toPlainObject.js");function N(D,M,I,R,O,H,G){var Q=T(D,I),$=T(M,I),V=G.get($);if(V){h(D,I,V);return}var j=H?H(Q,$,I+"",D,M,G):void 0,k=j===void 0;if(k){var z=m($),Y=!z&&v($),J=!z&&!Y&&b($);j=$,z||Y||J?m(Q)?j=Q:g(Q)?j=f(Q):Y?(k=!1,j=u($,!0)):J?(k=!1,j=d($,!0)):j=[]:C($)||_($)?(j=Q,_(Q)?j=S(Q):(!y(Q)||x(Q))&&(j=p($))):k=!1}k&&(G.set($,j),O(j,$,R,H,G),G.delete($)),h(D,I,j)}o.exports=N},"../../../../node_modules/lodash/_baseOrderBy.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_arrayMap.js"),u=l("../../../../node_modules/lodash/_baseGet.js"),d=l("../../../../node_modules/lodash/_baseIteratee.js"),f=l("../../../../node_modules/lodash/_baseMap.js"),p=l("../../../../node_modules/lodash/_baseSortBy.js"),_=l("../../../../node_modules/lodash/_baseUnary.js"),m=l("../../../../node_modules/lodash/_compareMultiple.js"),g=l("../../../../node_modules/lodash/identity.js"),v=l("../../../../node_modules/lodash/isArray.js");function x(y,C,b){C.length?C=h(C,function(N){return v(N)?function(D){return u(D,N.length===1?N[0]:N)}:N}):C=[g];var T=-1;C=h(C,_(d));var S=f(y,function(N,D,M){var I=h(C,function(R){return R(N)});return{criteria:I,index:++T,value:N}});return p(S,function(N,D){return m(N,D,b)})}o.exports=x},"../../../../node_modules/lodash/_basePick.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_basePickBy.js"),u=l("../../../../node_modules/lodash/hasIn.js");function d(f,p){return h(f,p,function(_,m){return u(f,m)})}o.exports=d},"../../../../node_modules/lodash/_basePickBy.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGet.js"),u=l("../../../../node_modules/lodash/_baseSet.js"),d=l("../../../../node_modules/lodash/_castPath.js");function f(p,_,m){for(var g=-1,v=_.length,x={};++g{function c(l){return function(h){return h==null?void 0:h[l]}}o.exports=c},"../../../../node_modules/lodash/_basePropertyDeep.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGet.js");function u(d){return function(f){return h(f,d)}}o.exports=u},"../../../../node_modules/lodash/_baseRange.js":o=>{var c=Math.ceil,l=Math.max;function h(u,d,f,p){for(var _=-1,m=l(c((d-u)/(f||1)),0),g=Array(m);m--;)g[p?m:++_]=u,u+=f;return g}o.exports=h},"../../../../node_modules/lodash/_baseReduce.js":o=>{function c(l,h,u,d,f){return f(l,function(p,_,m){u=d?(d=!1,p):h(u,p,_,m)}),u}o.exports=c},"../../../../node_modules/lodash/_baseRest.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/identity.js"),u=l("../../../../node_modules/lodash/_overRest.js"),d=l("../../../../node_modules/lodash/_setToString.js");function f(p,_){return d(u(p,_,h),p+"")}o.exports=f},"../../../../node_modules/lodash/_baseSet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_assignValue.js"),u=l("../../../../node_modules/lodash/_castPath.js"),d=l("../../../../node_modules/lodash/_isIndex.js"),f=l("../../../../node_modules/lodash/isObject.js"),p=l("../../../../node_modules/lodash/_toKey.js");function _(m,g,v,x){if(!f(m))return m;g=u(g,m);for(var y=-1,C=g.length,b=C-1,T=m;T!=null&&++y{var h=l("../../../../node_modules/lodash/constant.js"),u=l("../../../../node_modules/lodash/_defineProperty.js"),d=l("../../../../node_modules/lodash/identity.js"),f=u?function(p,_){return u(p,"toString",{configurable:!0,enumerable:!1,value:h(_),writable:!0})}:d;o.exports=f},"../../../../node_modules/lodash/_baseSortBy.js":o=>{function c(l,h){var u=l.length;for(l.sort(h);u--;)l[u]=l[u].value;return l}o.exports=c},"../../../../node_modules/lodash/_baseTimes.js":o=>{function c(l,h){for(var u=-1,d=Array(l);++u{var h=l("../../../../node_modules/lodash/_Symbol.js"),u=l("../../../../node_modules/lodash/_arrayMap.js"),d=l("../../../../node_modules/lodash/isArray.js"),f=l("../../../../node_modules/lodash/isSymbol.js"),p=1/0,_=h?h.prototype:void 0,m=_?_.toString:void 0;function g(v){if(typeof v=="string")return v;if(d(v))return u(v,g)+"";if(f(v))return m?m.call(v):"";var x=v+"";return x=="0"&&1/v==-p?"-0":x}o.exports=g},"../../../../node_modules/lodash/_baseTrim.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_trimmedEndIndex.js"),u=/^\s+/;function d(f){return f&&f.slice(0,h(f)+1).replace(u,"")}o.exports=d},"../../../../node_modules/lodash/_baseUnary.js":o=>{function c(l){return function(h){return l(h)}}o.exports=c},"../../../../node_modules/lodash/_baseUniq.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_SetCache.js"),u=l("../../../../node_modules/lodash/_arrayIncludes.js"),d=l("../../../../node_modules/lodash/_arrayIncludesWith.js"),f=l("../../../../node_modules/lodash/_cacheHas.js"),p=l("../../../../node_modules/lodash/_createSet.js"),_=l("../../../../node_modules/lodash/_setToArray.js"),m=200;function g(v,x,y){var C=-1,b=u,T=v.length,S=!0,N=[],D=N;if(y)S=!1,b=d;else if(T>=m){var M=x?null:p(v);if(M)return _(M);S=!1,b=f,D=new h}else D=x?[]:N;e:for(;++C{var h=l("../../../../node_modules/lodash/_arrayMap.js");function u(d,f){return h(f,function(p){return d[p]})}o.exports=u},"../../../../node_modules/lodash/_baseZipObject.js":o=>{function c(l,h,u){for(var d=-1,f=l.length,p=h.length,_={};++d{function c(l,h){return l.has(h)}o.exports=c},"../../../../node_modules/lodash/_castFunction.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/identity.js");function u(d){return typeof d=="function"?d:h}o.exports=u},"../../../../node_modules/lodash/_castPath.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isArray.js"),u=l("../../../../node_modules/lodash/_isKey.js"),d=l("../../../../node_modules/lodash/_stringToPath.js"),f=l("../../../../node_modules/lodash/toString.js");function p(_,m){return h(_)?_:u(_,m)?[_]:d(f(_))}o.exports=p},"../../../../node_modules/lodash/_cloneArrayBuffer.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_Uint8Array.js");function u(d){var f=new d.constructor(d.byteLength);return new h(f).set(new h(d)),f}o.exports=u},"../../../../node_modules/lodash/_cloneBuffer.js":(o,c,l)=>{o=l.nmd(o);var h=l("../../../../node_modules/lodash/_root.js"),u=c&&!c.nodeType&&c,d=u&&!0&&o&&!o.nodeType&&o,f=d&&d.exports===u,p=f?h.Buffer:void 0,_=p?p.allocUnsafe:void 0;function m(g,v){if(v)return g.slice();var x=g.length,y=_?_(x):new g.constructor(x);return g.copy(y),y}o.exports=m},"../../../../node_modules/lodash/_cloneDataView.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_cloneArrayBuffer.js");function u(d,f){var p=f?h(d.buffer):d.buffer;return new d.constructor(p,d.byteOffset,d.byteLength)}o.exports=u},"../../../../node_modules/lodash/_cloneRegExp.js":o=>{var c=/\w*$/;function l(h){var u=new h.constructor(h.source,c.exec(h));return u.lastIndex=h.lastIndex,u}o.exports=l},"../../../../node_modules/lodash/_cloneSymbol.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_Symbol.js"),u=h?h.prototype:void 0,d=u?u.valueOf:void 0;function f(p){return d?Object(d.call(p)):{}}o.exports=f},"../../../../node_modules/lodash/_cloneTypedArray.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_cloneArrayBuffer.js");function u(d,f){var p=f?h(d.buffer):d.buffer;return new d.constructor(p,d.byteOffset,d.length)}o.exports=u},"../../../../node_modules/lodash/_compareAscending.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isSymbol.js");function u(d,f){if(d!==f){var p=d!==void 0,_=d===null,m=d===d,g=h(d),v=f!==void 0,x=f===null,y=f===f,C=h(f);if(!x&&!C&&!g&&d>f||g&&v&&y&&!x&&!C||_&&v&&y||!p&&y||!m)return 1;if(!_&&!g&&!C&&d{var h=l("../../../../node_modules/lodash/_compareAscending.js");function u(d,f,p){for(var _=-1,m=d.criteria,g=f.criteria,v=m.length,x=p.length;++_=x)return y;var C=p[_];return y*(C=="desc"?-1:1)}}return d.index-f.index}o.exports=u},"../../../../node_modules/lodash/_copyArray.js":o=>{function c(l,h){var u=-1,d=l.length;for(h||(h=Array(d));++u{var h=l("../../../../node_modules/lodash/_assignValue.js"),u=l("../../../../node_modules/lodash/_baseAssignValue.js");function d(f,p,_,m){var g=!_;_||(_={});for(var v=-1,x=p.length;++v{var h=l("../../../../node_modules/lodash/_copyObject.js"),u=l("../../../../node_modules/lodash/_getSymbols.js");function d(f,p){return h(f,u(f),p)}o.exports=d},"../../../../node_modules/lodash/_copySymbolsIn.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_copyObject.js"),u=l("../../../../node_modules/lodash/_getSymbolsIn.js");function d(f,p){return h(f,u(f),p)}o.exports=d},"../../../../node_modules/lodash/_coreJsData.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_root.js"),u=h["__core-js_shared__"];o.exports=u},"../../../../node_modules/lodash/_createAssigner.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseRest.js"),u=l("../../../../node_modules/lodash/_isIterateeCall.js");function d(f){return h(function(p,_){var m=-1,g=_.length,v=g>1?_[g-1]:void 0,x=g>2?_[2]:void 0;for(v=f.length>3&&typeof v=="function"?(g--,v):void 0,x&&u(_[0],_[1],x)&&(v=g<3?void 0:v,g=1),p=Object(p);++m{var h=l("../../../../node_modules/lodash/isArrayLike.js");function u(d,f){return function(p,_){if(p==null)return p;if(!h(p))return d(p,_);for(var m=p.length,g=f?m:-1,v=Object(p);(f?g--:++g{function c(l){return function(h,u,d){for(var f=-1,p=Object(h),_=d(h),m=_.length;m--;){var g=_[l?m:++f];if(u(p[g],g,p)===!1)break}return h}}o.exports=c},"../../../../node_modules/lodash/_createFind.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseIteratee.js"),u=l("../../../../node_modules/lodash/isArrayLike.js"),d=l("../../../../node_modules/lodash/keys.js");function f(p){return function(_,m,g){var v=Object(_);if(!u(_)){var x=h(m,3);_=d(_),m=function(C){return x(v[C],C,v)}}var y=p(_,m,g);return y>-1?v[x?_[y]:y]:void 0}}o.exports=f},"../../../../node_modules/lodash/_createRange.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseRange.js"),u=l("../../../../node_modules/lodash/_isIterateeCall.js"),d=l("../../../../node_modules/lodash/toFinite.js");function f(p){return function(_,m,g){return g&&typeof g!="number"&&u(_,m,g)&&(m=g=void 0),_=d(_),m===void 0?(m=_,_=0):m=d(m),g=g===void 0?_{var h=l("../../../../node_modules/lodash/_Set.js"),u=l("../../../../node_modules/lodash/noop.js"),d=l("../../../../node_modules/lodash/_setToArray.js"),f=1/0,p=h&&1/d(new h([,-0]))[1]==f?function(_){return new h(_)}:u;o.exports=p},"../../../../node_modules/lodash/_defineProperty.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getNative.js"),u=function(){try{var d=h(Object,"defineProperty");return d({},"",{}),d}catch{}}();o.exports=u},"../../../../node_modules/lodash/_equalArrays.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_SetCache.js"),u=l("../../../../node_modules/lodash/_arraySome.js"),d=l("../../../../node_modules/lodash/_cacheHas.js"),f=1,p=2;function _(m,g,v,x,y,C){var b=v&f,T=m.length,S=g.length;if(T!=S&&!(b&&S>T))return!1;var N=C.get(m),D=C.get(g);if(N&&D)return N==g&&D==m;var M=-1,I=!0,R=v&p?new h:void 0;for(C.set(m,g),C.set(g,m);++M{var h=l("../../../../node_modules/lodash/_Symbol.js"),u=l("../../../../node_modules/lodash/_Uint8Array.js"),d=l("../../../../node_modules/lodash/eq.js"),f=l("../../../../node_modules/lodash/_equalArrays.js"),p=l("../../../../node_modules/lodash/_mapToArray.js"),_=l("../../../../node_modules/lodash/_setToArray.js"),m=1,g=2,v="[object Boolean]",x="[object Date]",y="[object Error]",C="[object Map]",b="[object Number]",T="[object RegExp]",S="[object Set]",N="[object String]",D="[object Symbol]",M="[object ArrayBuffer]",I="[object DataView]",R=h?h.prototype:void 0,O=R?R.valueOf:void 0;function H(G,Q,$,V,j,k,z){switch($){case I:if(G.byteLength!=Q.byteLength||G.byteOffset!=Q.byteOffset)return!1;G=G.buffer,Q=Q.buffer;case M:return!(G.byteLength!=Q.byteLength||!k(new u(G),new u(Q)));case v:case x:case b:return d(+G,+Q);case y:return G.name==Q.name&&G.message==Q.message;case T:case N:return G==Q+"";case C:var Y=p;case S:var J=V&m;if(Y||(Y=_),G.size!=Q.size&&!J)return!1;var re=z.get(G);if(re)return re==Q;V|=g,z.set(G,Q);var he=f(Y(G),Y(Q),V,j,k,z);return z.delete(G),he;case D:if(O)return O.call(G)==O.call(Q)}return!1}o.exports=H},"../../../../node_modules/lodash/_equalObjects.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getAllKeys.js"),u=1,d=Object.prototype,f=d.hasOwnProperty;function p(_,m,g,v,x,y){var C=g&u,b=h(_),T=b.length,S=h(m),N=S.length;if(T!=N&&!C)return!1;for(var D=T;D--;){var M=b[D];if(!(C?M in m:f.call(m,M)))return!1}var I=y.get(_),R=y.get(m);if(I&&R)return I==m&&R==_;var O=!0;y.set(_,m),y.set(m,_);for(var H=C;++D{var h=l("../../../../node_modules/lodash/flatten.js"),u=l("../../../../node_modules/lodash/_overRest.js"),d=l("../../../../node_modules/lodash/_setToString.js");function f(p){return d(u(p,void 0,h),p+"")}o.exports=f},"../../../../node_modules/lodash/_freeGlobal.js":(o,c,l)=>{var h=typeof l.g=="object"&&l.g&&l.g.Object===Object&&l.g;o.exports=h},"../../../../node_modules/lodash/_getAllKeys.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGetAllKeys.js"),u=l("../../../../node_modules/lodash/_getSymbols.js"),d=l("../../../../node_modules/lodash/keys.js");function f(p){return h(p,d,u)}o.exports=f},"../../../../node_modules/lodash/_getAllKeysIn.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGetAllKeys.js"),u=l("../../../../node_modules/lodash/_getSymbolsIn.js"),d=l("../../../../node_modules/lodash/keysIn.js");function f(p){return h(p,d,u)}o.exports=f},"../../../../node_modules/lodash/_getMapData.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_isKeyable.js");function u(d,f){var p=d.__data__;return h(f)?p[typeof f=="string"?"string":"hash"]:p.map}o.exports=u},"../../../../node_modules/lodash/_getMatchData.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_isStrictComparable.js"),u=l("../../../../node_modules/lodash/keys.js");function d(f){for(var p=u(f),_=p.length;_--;){var m=p[_],g=f[m];p[_]=[m,g,h(g)]}return p}o.exports=d},"../../../../node_modules/lodash/_getNative.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseIsNative.js"),u=l("../../../../node_modules/lodash/_getValue.js");function d(f,p){var _=u(f,p);return h(_)?_:void 0}o.exports=d},"../../../../node_modules/lodash/_getPrototype.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_overArg.js"),u=h(Object.getPrototypeOf,Object);o.exports=u},"../../../../node_modules/lodash/_getRawTag.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_Symbol.js"),u=Object.prototype,d=u.hasOwnProperty,f=u.toString,p=h?h.toStringTag:void 0;function _(m){var g=d.call(m,p),v=m[p];try{m[p]=void 0;var x=!0}catch{}var y=f.call(m);return x&&(g?m[p]=v:delete m[p]),y}o.exports=_},"../../../../node_modules/lodash/_getSymbols.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_arrayFilter.js"),u=l("../../../../node_modules/lodash/stubArray.js"),d=Object.prototype,f=d.propertyIsEnumerable,p=Object.getOwnPropertySymbols,_=p?function(m){return m==null?[]:(m=Object(m),h(p(m),function(g){return f.call(m,g)}))}:u;o.exports=_},"../../../../node_modules/lodash/_getSymbolsIn.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_arrayPush.js"),u=l("../../../../node_modules/lodash/_getPrototype.js"),d=l("../../../../node_modules/lodash/_getSymbols.js"),f=l("../../../../node_modules/lodash/stubArray.js"),p=Object.getOwnPropertySymbols,_=p?function(m){for(var g=[];m;)h(g,d(m)),m=u(m);return g}:f;o.exports=_},"../../../../node_modules/lodash/_getTag.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_DataView.js"),u=l("../../../../node_modules/lodash/_Map.js"),d=l("../../../../node_modules/lodash/_Promise.js"),f=l("../../../../node_modules/lodash/_Set.js"),p=l("../../../../node_modules/lodash/_WeakMap.js"),_=l("../../../../node_modules/lodash/_baseGetTag.js"),m=l("../../../../node_modules/lodash/_toSource.js"),g="[object Map]",v="[object Object]",x="[object Promise]",y="[object Set]",C="[object WeakMap]",b="[object DataView]",T=m(h),S=m(u),N=m(d),D=m(f),M=m(p),I=_;(h&&I(new h(new ArrayBuffer(1)))!=b||u&&I(new u)!=g||d&&I(d.resolve())!=x||f&&I(new f)!=y||p&&I(new p)!=C)&&(I=function(R){var O=_(R),H=O==v?R.constructor:void 0,G=H?m(H):"";if(G)switch(G){case T:return b;case S:return g;case N:return x;case D:return y;case M:return C}return O}),o.exports=I},"../../../../node_modules/lodash/_getValue.js":o=>{function c(l,h){return l==null?void 0:l[h]}o.exports=c},"../../../../node_modules/lodash/_hasPath.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_castPath.js"),u=l("../../../../node_modules/lodash/isArguments.js"),d=l("../../../../node_modules/lodash/isArray.js"),f=l("../../../../node_modules/lodash/_isIndex.js"),p=l("../../../../node_modules/lodash/isLength.js"),_=l("../../../../node_modules/lodash/_toKey.js");function m(g,v,x){v=h(v,g);for(var y=-1,C=v.length,b=!1;++y{var c="\\ud800-\\udfff",l="\\u0300-\\u036f",h="\\ufe20-\\ufe2f",u="\\u20d0-\\u20ff",d=l+h+u,f="\\ufe0e\\ufe0f",p="\\u200d",_=RegExp("["+p+c+d+f+"]");function m(g){return _.test(g)}o.exports=m},"../../../../node_modules/lodash/_hashClear.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_nativeCreate.js");function u(){this.__data__=h?h(null):{},this.size=0}o.exports=u},"../../../../node_modules/lodash/_hashDelete.js":o=>{function c(l){var h=this.has(l)&&delete this.__data__[l];return this.size-=h?1:0,h}o.exports=c},"../../../../node_modules/lodash/_hashGet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_nativeCreate.js"),u="__lodash_hash_undefined__",d=Object.prototype,f=d.hasOwnProperty;function p(_){var m=this.__data__;if(h){var g=m[_];return g===u?void 0:g}return f.call(m,_)?m[_]:void 0}o.exports=p},"../../../../node_modules/lodash/_hashHas.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_nativeCreate.js"),u=Object.prototype,d=u.hasOwnProperty;function f(p){var _=this.__data__;return h?_[p]!==void 0:d.call(_,p)}o.exports=f},"../../../../node_modules/lodash/_hashSet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_nativeCreate.js"),u="__lodash_hash_undefined__";function d(f,p){var _=this.__data__;return this.size+=this.has(f)?0:1,_[f]=h&&p===void 0?u:p,this}o.exports=d},"../../../../node_modules/lodash/_initCloneArray.js":o=>{var c=Object.prototype,l=c.hasOwnProperty;function h(u){var d=u.length,f=new u.constructor(d);return d&&typeof u[0]=="string"&&l.call(u,"index")&&(f.index=u.index,f.input=u.input),f}o.exports=h},"../../../../node_modules/lodash/_initCloneByTag.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_cloneArrayBuffer.js"),u=l("../../../../node_modules/lodash/_cloneDataView.js"),d=l("../../../../node_modules/lodash/_cloneRegExp.js"),f=l("../../../../node_modules/lodash/_cloneSymbol.js"),p=l("../../../../node_modules/lodash/_cloneTypedArray.js"),_="[object Boolean]",m="[object Date]",g="[object Map]",v="[object Number]",x="[object RegExp]",y="[object Set]",C="[object String]",b="[object Symbol]",T="[object ArrayBuffer]",S="[object DataView]",N="[object Float32Array]",D="[object Float64Array]",M="[object Int8Array]",I="[object Int16Array]",R="[object Int32Array]",O="[object Uint8Array]",H="[object Uint8ClampedArray]",G="[object Uint16Array]",Q="[object Uint32Array]";function $(V,j,k){var z=V.constructor;switch(j){case T:return h(V);case _:case m:return new z(+V);case S:return u(V,k);case N:case D:case M:case I:case R:case O:case H:case G:case Q:return p(V,k);case g:return new z;case v:case C:return new z(V);case x:return d(V);case y:return new z;case b:return f(V)}}o.exports=$},"../../../../node_modules/lodash/_initCloneObject.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseCreate.js"),u=l("../../../../node_modules/lodash/_getPrototype.js"),d=l("../../../../node_modules/lodash/_isPrototype.js");function f(p){return typeof p.constructor=="function"&&!d(p)?h(u(p)):{}}o.exports=f},"../../../../node_modules/lodash/_isFlattenable.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_Symbol.js"),u=l("../../../../node_modules/lodash/isArguments.js"),d=l("../../../../node_modules/lodash/isArray.js"),f=h?h.isConcatSpreadable:void 0;function p(_){return d(_)||u(_)||!!(f&&_&&_[f])}o.exports=p},"../../../../node_modules/lodash/_isIndex.js":o=>{var c=9007199254740991,l=/^(?:0|[1-9]\d*)$/;function h(u,d){var f=typeof u;return d=d??c,!!d&&(f=="number"||f!="symbol"&&l.test(u))&&u>-1&&u%1==0&&u{var h=l("../../../../node_modules/lodash/eq.js"),u=l("../../../../node_modules/lodash/isArrayLike.js"),d=l("../../../../node_modules/lodash/_isIndex.js"),f=l("../../../../node_modules/lodash/isObject.js");function p(_,m,g){if(!f(g))return!1;var v=typeof m;return(v=="number"?u(g)&&d(m,g.length):v=="string"&&m in g)?h(g[m],_):!1}o.exports=p},"../../../../node_modules/lodash/_isKey.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isArray.js"),u=l("../../../../node_modules/lodash/isSymbol.js"),d=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,f=/^\w*$/;function p(_,m){if(h(_))return!1;var g=typeof _;return g=="number"||g=="symbol"||g=="boolean"||_==null||u(_)?!0:f.test(_)||!d.test(_)||m!=null&&_ in Object(m)}o.exports=p},"../../../../node_modules/lodash/_isKeyable.js":o=>{function c(l){var h=typeof l;return h=="string"||h=="number"||h=="symbol"||h=="boolean"?l!=="__proto__":l===null}o.exports=c},"../../../../node_modules/lodash/_isMasked.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_coreJsData.js"),u=function(){var f=/[^.]+$/.exec(h&&h.keys&&h.keys.IE_PROTO||"");return f?"Symbol(src)_1."+f:""}();function d(f){return!!u&&u in f}o.exports=d},"../../../../node_modules/lodash/_isPrototype.js":o=>{var c=Object.prototype;function l(h){var u=h&&h.constructor,d=typeof u=="function"&&u.prototype||c;return h===d}o.exports=l},"../../../../node_modules/lodash/_isStrictComparable.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isObject.js");function u(d){return d===d&&!h(d)}o.exports=u},"../../../../node_modules/lodash/_listCacheClear.js":o=>{function c(){this.__data__=[],this.size=0}o.exports=c},"../../../../node_modules/lodash/_listCacheDelete.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_assocIndexOf.js"),u=Array.prototype,d=u.splice;function f(p){var _=this.__data__,m=h(_,p);if(m<0)return!1;var g=_.length-1;return m==g?_.pop():d.call(_,m,1),--this.size,!0}o.exports=f},"../../../../node_modules/lodash/_listCacheGet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_assocIndexOf.js");function u(d){var f=this.__data__,p=h(f,d);return p<0?void 0:f[p][1]}o.exports=u},"../../../../node_modules/lodash/_listCacheHas.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_assocIndexOf.js");function u(d){return h(this.__data__,d)>-1}o.exports=u},"../../../../node_modules/lodash/_listCacheSet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_assocIndexOf.js");function u(d,f){var p=this.__data__,_=h(p,d);return _<0?(++this.size,p.push([d,f])):p[_][1]=f,this}o.exports=u},"../../../../node_modules/lodash/_mapCacheClear.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_Hash.js"),u=l("../../../../node_modules/lodash/_ListCache.js"),d=l("../../../../node_modules/lodash/_Map.js");function f(){this.size=0,this.__data__={hash:new h,map:new(d||u),string:new h}}o.exports=f},"../../../../node_modules/lodash/_mapCacheDelete.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getMapData.js");function u(d){var f=h(this,d).delete(d);return this.size-=f?1:0,f}o.exports=u},"../../../../node_modules/lodash/_mapCacheGet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getMapData.js");function u(d){return h(this,d).get(d)}o.exports=u},"../../../../node_modules/lodash/_mapCacheHas.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getMapData.js");function u(d){return h(this,d).has(d)}o.exports=u},"../../../../node_modules/lodash/_mapCacheSet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getMapData.js");function u(d,f){var p=h(this,d),_=p.size;return p.set(d,f),this.size+=p.size==_?0:1,this}o.exports=u},"../../../../node_modules/lodash/_mapToArray.js":o=>{function c(l){var h=-1,u=Array(l.size);return l.forEach(function(d,f){u[++h]=[f,d]}),u}o.exports=c},"../../../../node_modules/lodash/_matchesStrictComparable.js":o=>{function c(l,h){return function(u){return u==null?!1:u[l]===h&&(h!==void 0||l in Object(u))}}o.exports=c},"../../../../node_modules/lodash/_memoizeCapped.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/memoize.js"),u=500;function d(f){var p=h(f,function(m){return _.size===u&&_.clear(),m}),_=p.cache;return p}o.exports=d},"../../../../node_modules/lodash/_nativeCreate.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_getNative.js"),u=h(Object,"create");o.exports=u},"../../../../node_modules/lodash/_nativeKeys.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_overArg.js"),u=h(Object.keys,Object);o.exports=u},"../../../../node_modules/lodash/_nativeKeysIn.js":o=>{function c(l){var h=[];if(l!=null)for(var u in Object(l))h.push(u);return h}o.exports=c},"../../../../node_modules/lodash/_nodeUtil.js":(o,c,l)=>{o=l.nmd(o);var h=l("../../../../node_modules/lodash/_freeGlobal.js"),u=c&&!c.nodeType&&c,d=u&&!0&&o&&!o.nodeType&&o,f=d&&d.exports===u,p=f&&h.process,_=function(){try{var m=d&&d.require&&d.require("util").types;return m||p&&p.binding&&p.binding("util")}catch{}}();o.exports=_},"../../../../node_modules/lodash/_objectToString.js":o=>{var c=Object.prototype,l=c.toString;function h(u){return l.call(u)}o.exports=h},"../../../../node_modules/lodash/_overArg.js":o=>{function c(l,h){return function(u){return l(h(u))}}o.exports=c},"../../../../node_modules/lodash/_overRest.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_apply.js"),u=Math.max;function d(f,p,_){return p=u(p===void 0?f.length-1:p,0),function(){for(var m=arguments,g=-1,v=u(m.length-p,0),x=Array(v);++g{var h=l("../../../../node_modules/lodash/_freeGlobal.js"),u=typeof self=="object"&&self&&self.Object===Object&&self,d=h||u||Function("return this")();o.exports=d},"../../../../node_modules/lodash/_safeGet.js":o=>{function c(l,h){if(!(h==="constructor"&&typeof l[h]=="function")&&h!="__proto__")return l[h]}o.exports=c},"../../../../node_modules/lodash/_setCacheAdd.js":o=>{var c="__lodash_hash_undefined__";function l(h){return this.__data__.set(h,c),this}o.exports=l},"../../../../node_modules/lodash/_setCacheHas.js":o=>{function c(l){return this.__data__.has(l)}o.exports=c},"../../../../node_modules/lodash/_setToArray.js":o=>{function c(l){var h=-1,u=Array(l.size);return l.forEach(function(d){u[++h]=d}),u}o.exports=c},"../../../../node_modules/lodash/_setToString.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseSetToString.js"),u=l("../../../../node_modules/lodash/_shortOut.js"),d=u(h);o.exports=d},"../../../../node_modules/lodash/_shortOut.js":o=>{var c=800,l=16,h=Date.now;function u(d){var f=0,p=0;return function(){var _=h(),m=l-(_-p);if(p=_,m>0){if(++f>=c)return arguments[0]}else f=0;return d.apply(void 0,arguments)}}o.exports=u},"../../../../node_modules/lodash/_stackClear.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_ListCache.js");function u(){this.__data__=new h,this.size=0}o.exports=u},"../../../../node_modules/lodash/_stackDelete.js":o=>{function c(l){var h=this.__data__,u=h.delete(l);return this.size=h.size,u}o.exports=c},"../../../../node_modules/lodash/_stackGet.js":o=>{function c(l){return this.__data__.get(l)}o.exports=c},"../../../../node_modules/lodash/_stackHas.js":o=>{function c(l){return this.__data__.has(l)}o.exports=c},"../../../../node_modules/lodash/_stackSet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_ListCache.js"),u=l("../../../../node_modules/lodash/_Map.js"),d=l("../../../../node_modules/lodash/_MapCache.js"),f=200;function p(_,m){var g=this.__data__;if(g instanceof h){var v=g.__data__;if(!u||v.length{function c(l,h,u){for(var d=u-1,f=l.length;++d{var h=l("../../../../node_modules/lodash/_asciiSize.js"),u=l("../../../../node_modules/lodash/_hasUnicode.js"),d=l("../../../../node_modules/lodash/_unicodeSize.js");function f(p){return u(p)?d(p):h(p)}o.exports=f},"../../../../node_modules/lodash/_stringToPath.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_memoizeCapped.js"),u=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,d=/\\(\\)?/g,f=h(function(p){var _=[];return p.charCodeAt(0)===46&&_.push(""),p.replace(u,function(m,g,v,x){_.push(v?x.replace(d,"$1"):g||m)}),_});o.exports=f},"../../../../node_modules/lodash/_toKey.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isSymbol.js"),u=1/0;function d(f){if(typeof f=="string"||h(f))return f;var p=f+"";return p=="0"&&1/f==-u?"-0":p}o.exports=d},"../../../../node_modules/lodash/_toSource.js":o=>{var c=Function.prototype,l=c.toString;function h(u){if(u!=null){try{return l.call(u)}catch{}try{return u+""}catch{}}return""}o.exports=h},"../../../../node_modules/lodash/_trimmedEndIndex.js":o=>{var c=/\s/;function l(h){for(var u=h.length;u--&&c.test(h.charAt(u)););return u}o.exports=l},"../../../../node_modules/lodash/_unicodeSize.js":o=>{var c="\\ud800-\\udfff",l="\\u0300-\\u036f",h="\\ufe20-\\ufe2f",u="\\u20d0-\\u20ff",d=l+h+u,f="\\ufe0e\\ufe0f",p="["+c+"]",_="["+d+"]",m="\\ud83c[\\udffb-\\udfff]",g="(?:"+_+"|"+m+")",v="[^"+c+"]",x="(?:\\ud83c[\\udde6-\\uddff]){2}",y="[\\ud800-\\udbff][\\udc00-\\udfff]",C="\\u200d",b=g+"?",T="["+f+"]?",S="(?:"+C+"(?:"+[v,x,y].join("|")+")"+T+b+")*",N=T+b+S,D="(?:"+[v+_+"?",_,x,y,p].join("|")+")",M=RegExp(m+"(?="+m+")|"+D+N,"g");function I(R){for(var O=M.lastIndex=0;M.test(R);)++O;return O}o.exports=I},"../../../../node_modules/lodash/clone.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseClone.js"),u=4;function d(f){return h(f,u)}o.exports=d},"../../../../node_modules/lodash/cloneDeep.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseClone.js"),u=1,d=4;function f(p){return h(p,u|d)}o.exports=f},"../../../../node_modules/lodash/constant.js":o=>{function c(l){return function(){return l}}o.exports=c},"../../../../node_modules/lodash/defaults.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseRest.js"),u=l("../../../../node_modules/lodash/eq.js"),d=l("../../../../node_modules/lodash/_isIterateeCall.js"),f=l("../../../../node_modules/lodash/keysIn.js"),p=Object.prototype,_=p.hasOwnProperty,m=h(function(g,v){g=Object(g);var x=-1,y=v.length,C=y>2?v[2]:void 0;for(C&&d(v[0],v[1],C)&&(y=1);++x{o.exports=l("../../../../node_modules/lodash/forEach.js")},"../../../../node_modules/lodash/eq.js":o=>{function c(l,h){return l===h||l!==l&&h!==h}o.exports=c},"../../../../node_modules/lodash/filter.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_arrayFilter.js"),u=l("../../../../node_modules/lodash/_baseFilter.js"),d=l("../../../../node_modules/lodash/_baseIteratee.js"),f=l("../../../../node_modules/lodash/isArray.js");function p(_,m){var g=f(_)?h:u;return g(_,d(m,3))}o.exports=p},"../../../../node_modules/lodash/find.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_createFind.js"),u=l("../../../../node_modules/lodash/findIndex.js"),d=h(u);o.exports=d},"../../../../node_modules/lodash/findIndex.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseFindIndex.js"),u=l("../../../../node_modules/lodash/_baseIteratee.js"),d=l("../../../../node_modules/lodash/toInteger.js"),f=Math.max;function p(_,m,g){var v=_==null?0:_.length;if(!v)return-1;var x=g==null?0:d(g);return x<0&&(x=f(v+x,0)),h(_,u(m,3),x)}o.exports=p},"../../../../node_modules/lodash/flatten.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseFlatten.js");function u(d){var f=d==null?0:d.length;return f?h(d,1):[]}o.exports=u},"../../../../node_modules/lodash/forEach.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_arrayEach.js"),u=l("../../../../node_modules/lodash/_baseEach.js"),d=l("../../../../node_modules/lodash/_castFunction.js"),f=l("../../../../node_modules/lodash/isArray.js");function p(_,m){var g=f(_)?h:u;return g(_,d(m))}o.exports=p},"../../../../node_modules/lodash/forIn.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseFor.js"),u=l("../../../../node_modules/lodash/_castFunction.js"),d=l("../../../../node_modules/lodash/keysIn.js");function f(p,_){return p==null?p:h(p,u(_),d)}o.exports=f},"../../../../node_modules/lodash/get.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGet.js");function u(d,f,p){var _=d==null?void 0:h(d,f);return _===void 0?p:_}o.exports=u},"../../../../node_modules/lodash/has.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseHas.js"),u=l("../../../../node_modules/lodash/_hasPath.js");function d(f,p){return f!=null&&u(f,p,h)}o.exports=d},"../../../../node_modules/lodash/hasIn.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseHasIn.js"),u=l("../../../../node_modules/lodash/_hasPath.js");function d(f,p){return f!=null&&u(f,p,h)}o.exports=d},"../../../../node_modules/lodash/identity.js":o=>{function c(l){return l}o.exports=c},"../../../../node_modules/lodash/isArguments.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseIsArguments.js"),u=l("../../../../node_modules/lodash/isObjectLike.js"),d=Object.prototype,f=d.hasOwnProperty,p=d.propertyIsEnumerable,_=h(function(){return arguments}())?h:function(m){return u(m)&&f.call(m,"callee")&&!p.call(m,"callee")};o.exports=_},"../../../../node_modules/lodash/isArray.js":o=>{var c=Array.isArray;o.exports=c},"../../../../node_modules/lodash/isArrayLike.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isFunction.js"),u=l("../../../../node_modules/lodash/isLength.js");function d(f){return f!=null&&u(f.length)&&!h(f)}o.exports=d},"../../../../node_modules/lodash/isArrayLikeObject.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/isArrayLike.js"),u=l("../../../../node_modules/lodash/isObjectLike.js");function d(f){return u(f)&&h(f)}o.exports=d},"../../../../node_modules/lodash/isBuffer.js":(o,c,l)=>{o=l.nmd(o);var h=l("../../../../node_modules/lodash/_root.js"),u=l("../../../../node_modules/lodash/stubFalse.js"),d=c&&!c.nodeType&&c,f=d&&!0&&o&&!o.nodeType&&o,p=f&&f.exports===d,_=p?h.Buffer:void 0,m=_?_.isBuffer:void 0,g=m||u;o.exports=g},"../../../../node_modules/lodash/isEmpty.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseKeys.js"),u=l("../../../../node_modules/lodash/_getTag.js"),d=l("../../../../node_modules/lodash/isArguments.js"),f=l("../../../../node_modules/lodash/isArray.js"),p=l("../../../../node_modules/lodash/isArrayLike.js"),_=l("../../../../node_modules/lodash/isBuffer.js"),m=l("../../../../node_modules/lodash/_isPrototype.js"),g=l("../../../../node_modules/lodash/isTypedArray.js"),v="[object Map]",x="[object Set]",y=Object.prototype,C=y.hasOwnProperty;function b(T){if(T==null)return!0;if(p(T)&&(f(T)||typeof T=="string"||typeof T.splice=="function"||_(T)||g(T)||d(T)))return!T.length;var S=u(T);if(S==v||S==x)return!T.size;if(m(T))return!h(T).length;for(var N in T)if(C.call(T,N))return!1;return!0}o.exports=b},"../../../../node_modules/lodash/isFunction.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGetTag.js"),u=l("../../../../node_modules/lodash/isObject.js"),d="[object AsyncFunction]",f="[object Function]",p="[object GeneratorFunction]",_="[object Proxy]";function m(g){if(!u(g))return!1;var v=h(g);return v==f||v==p||v==d||v==_}o.exports=m},"../../../../node_modules/lodash/isLength.js":o=>{var c=9007199254740991;function l(h){return typeof h=="number"&&h>-1&&h%1==0&&h<=c}o.exports=l},"../../../../node_modules/lodash/isMap.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseIsMap.js"),u=l("../../../../node_modules/lodash/_baseUnary.js"),d=l("../../../../node_modules/lodash/_nodeUtil.js"),f=d&&d.isMap,p=f?u(f):h;o.exports=p},"../../../../node_modules/lodash/isObject.js":o=>{function c(l){var h=typeof l;return l!=null&&(h=="object"||h=="function")}o.exports=c},"../../../../node_modules/lodash/isObjectLike.js":o=>{function c(l){return l!=null&&typeof l=="object"}o.exports=c},"../../../../node_modules/lodash/isPlainObject.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGetTag.js"),u=l("../../../../node_modules/lodash/_getPrototype.js"),d=l("../../../../node_modules/lodash/isObjectLike.js"),f="[object Object]",p=Function.prototype,_=Object.prototype,m=p.toString,g=_.hasOwnProperty,v=m.call(Object);function x(y){if(!d(y)||h(y)!=f)return!1;var C=u(y);if(C===null)return!0;var b=g.call(C,"constructor")&&C.constructor;return typeof b=="function"&&b instanceof b&&m.call(b)==v}o.exports=x},"../../../../node_modules/lodash/isSet.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseIsSet.js"),u=l("../../../../node_modules/lodash/_baseUnary.js"),d=l("../../../../node_modules/lodash/_nodeUtil.js"),f=d&&d.isSet,p=f?u(f):h;o.exports=p},"../../../../node_modules/lodash/isString.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGetTag.js"),u=l("../../../../node_modules/lodash/isArray.js"),d=l("../../../../node_modules/lodash/isObjectLike.js"),f="[object String]";function p(_){return typeof _=="string"||!u(_)&&d(_)&&h(_)==f}o.exports=p},"../../../../node_modules/lodash/isSymbol.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseGetTag.js"),u=l("../../../../node_modules/lodash/isObjectLike.js"),d="[object Symbol]";function f(p){return typeof p=="symbol"||u(p)&&h(p)==d}o.exports=f},"../../../../node_modules/lodash/isTypedArray.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseIsTypedArray.js"),u=l("../../../../node_modules/lodash/_baseUnary.js"),d=l("../../../../node_modules/lodash/_nodeUtil.js"),f=d&&d.isTypedArray,p=f?u(f):h;o.exports=p},"../../../../node_modules/lodash/isUndefined.js":o=>{function c(l){return l===void 0}o.exports=c},"../../../../node_modules/lodash/keys.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_arrayLikeKeys.js"),u=l("../../../../node_modules/lodash/_baseKeys.js"),d=l("../../../../node_modules/lodash/isArrayLike.js");function f(p){return d(p)?h(p):u(p)}o.exports=f},"../../../../node_modules/lodash/keysIn.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_arrayLikeKeys.js"),u=l("../../../../node_modules/lodash/_baseKeysIn.js"),d=l("../../../../node_modules/lodash/isArrayLike.js");function f(p){return d(p)?h(p,!0):u(p)}o.exports=f},"../../../../node_modules/lodash/last.js":o=>{function c(l){var h=l==null?0:l.length;return h?l[h-1]:void 0}o.exports=c},"../../../../node_modules/lodash/map.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_arrayMap.js"),u=l("../../../../node_modules/lodash/_baseIteratee.js"),d=l("../../../../node_modules/lodash/_baseMap.js"),f=l("../../../../node_modules/lodash/isArray.js");function p(_,m){var g=f(_)?h:d;return g(_,u(m,3))}o.exports=p},"../../../../node_modules/lodash/mapValues.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseAssignValue.js"),u=l("../../../../node_modules/lodash/_baseForOwn.js"),d=l("../../../../node_modules/lodash/_baseIteratee.js");function f(p,_){var m={};return _=d(_,3),u(p,function(g,v,x){h(m,v,_(g,v,x))}),m}o.exports=f},"../../../../node_modules/lodash/max.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseExtremum.js"),u=l("../../../../node_modules/lodash/_baseGt.js"),d=l("../../../../node_modules/lodash/identity.js");function f(p){return p&&p.length?h(p,d,u):void 0}o.exports=f},"../../../../node_modules/lodash/memoize.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_MapCache.js"),u="Expected a function";function d(f,p){if(typeof f!="function"||p!=null&&typeof p!="function")throw new TypeError(u);var _=function(){var m=arguments,g=p?p.apply(this,m):m[0],v=_.cache;if(v.has(g))return v.get(g);var x=f.apply(this,m);return _.cache=v.set(g,x)||v,x};return _.cache=new(d.Cache||h),_}d.Cache=h,o.exports=d},"../../../../node_modules/lodash/merge.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseMerge.js"),u=l("../../../../node_modules/lodash/_createAssigner.js"),d=u(function(f,p,_){h(f,p,_)});o.exports=d},"../../../../node_modules/lodash/min.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseExtremum.js"),u=l("../../../../node_modules/lodash/_baseLt.js"),d=l("../../../../node_modules/lodash/identity.js");function f(p){return p&&p.length?h(p,d,u):void 0}o.exports=f},"../../../../node_modules/lodash/minBy.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseExtremum.js"),u=l("../../../../node_modules/lodash/_baseIteratee.js"),d=l("../../../../node_modules/lodash/_baseLt.js");function f(p,_){return p&&p.length?h(p,u(_,2),d):void 0}o.exports=f},"../../../../node_modules/lodash/noop.js":o=>{function c(){}o.exports=c},"../../../../node_modules/lodash/now.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_root.js"),u=function(){return h.Date.now()};o.exports=u},"../../../../node_modules/lodash/pick.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_basePick.js"),u=l("../../../../node_modules/lodash/_flatRest.js"),d=u(function(f,p){return f==null?{}:h(f,p)});o.exports=d},"../../../../node_modules/lodash/property.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseProperty.js"),u=l("../../../../node_modules/lodash/_basePropertyDeep.js"),d=l("../../../../node_modules/lodash/_isKey.js"),f=l("../../../../node_modules/lodash/_toKey.js");function p(_){return d(_)?h(f(_)):u(_)}o.exports=p},"../../../../node_modules/lodash/range.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_createRange.js"),u=h();o.exports=u},"../../../../node_modules/lodash/reduce.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_arrayReduce.js"),u=l("../../../../node_modules/lodash/_baseEach.js"),d=l("../../../../node_modules/lodash/_baseIteratee.js"),f=l("../../../../node_modules/lodash/_baseReduce.js"),p=l("../../../../node_modules/lodash/isArray.js");function _(m,g,v){var x=p(m)?h:f,y=arguments.length<3;return x(m,d(g,4),v,y,u)}o.exports=_},"../../../../node_modules/lodash/size.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseKeys.js"),u=l("../../../../node_modules/lodash/_getTag.js"),d=l("../../../../node_modules/lodash/isArrayLike.js"),f=l("../../../../node_modules/lodash/isString.js"),p=l("../../../../node_modules/lodash/_stringSize.js"),_="[object Map]",m="[object Set]";function g(v){if(v==null)return 0;if(d(v))return f(v)?p(v):v.length;var x=u(v);return x==_||x==m?v.size:h(v).length}o.exports=g},"../../../../node_modules/lodash/sortBy.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseFlatten.js"),u=l("../../../../node_modules/lodash/_baseOrderBy.js"),d=l("../../../../node_modules/lodash/_baseRest.js"),f=l("../../../../node_modules/lodash/_isIterateeCall.js"),p=d(function(_,m){if(_==null)return[];var g=m.length;return g>1&&f(_,m[0],m[1])?m=[]:g>2&&f(m[0],m[1],m[2])&&(m=[m[0]]),u(_,h(m,1),[])});o.exports=p},"../../../../node_modules/lodash/stubArray.js":o=>{function c(){return[]}o.exports=c},"../../../../node_modules/lodash/stubFalse.js":o=>{function c(){return!1}o.exports=c},"../../../../node_modules/lodash/toFinite.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/toNumber.js"),u=1/0,d=17976931348623157e292;function f(p){if(!p)return p===0?p:0;if(p=h(p),p===u||p===-u){var _=p<0?-1:1;return _*d}return p===p?p:0}o.exports=f},"../../../../node_modules/lodash/toInteger.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/toFinite.js");function u(d){var f=h(d),p=f%1;return f===f?p?f-p:f:0}o.exports=u},"../../../../node_modules/lodash/toNumber.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseTrim.js"),u=l("../../../../node_modules/lodash/isObject.js"),d=l("../../../../node_modules/lodash/isSymbol.js"),f=NaN,p=/^[-+]0x[0-9a-f]+$/i,_=/^0b[01]+$/i,m=/^0o[0-7]+$/i,g=parseInt;function v(x){if(typeof x=="number")return x;if(d(x))return f;if(u(x)){var y=typeof x.valueOf=="function"?x.valueOf():x;x=u(y)?y+"":y}if(typeof x!="string")return x===0?x:+x;x=h(x);var C=_.test(x);return C||m.test(x)?g(x.slice(2),C?2:8):p.test(x)?f:+x}o.exports=v},"../../../../node_modules/lodash/toPlainObject.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_copyObject.js"),u=l("../../../../node_modules/lodash/keysIn.js");function d(f){return h(f,u(f))}o.exports=d},"../../../../node_modules/lodash/toString.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseToString.js");function u(d){return d==null?"":h(d)}o.exports=u},"../../../../node_modules/lodash/transform.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_arrayEach.js"),u=l("../../../../node_modules/lodash/_baseCreate.js"),d=l("../../../../node_modules/lodash/_baseForOwn.js"),f=l("../../../../node_modules/lodash/_baseIteratee.js"),p=l("../../../../node_modules/lodash/_getPrototype.js"),_=l("../../../../node_modules/lodash/isArray.js"),m=l("../../../../node_modules/lodash/isBuffer.js"),g=l("../../../../node_modules/lodash/isFunction.js"),v=l("../../../../node_modules/lodash/isObject.js"),x=l("../../../../node_modules/lodash/isTypedArray.js");function y(C,b,T){var S=_(C),N=S||m(C)||x(C);if(b=f(b,4),T==null){var D=C&&C.constructor;N?T=S?new D:[]:v(C)?T=g(D)?u(p(C)):{}:T={}}return(N?h:d)(C,function(M,I,R){return b(T,M,I,R)}),T}o.exports=y},"../../../../node_modules/lodash/union.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseFlatten.js"),u=l("../../../../node_modules/lodash/_baseRest.js"),d=l("../../../../node_modules/lodash/_baseUniq.js"),f=l("../../../../node_modules/lodash/isArrayLikeObject.js"),p=u(function(_){return d(h(_,1,f,!0))});o.exports=p},"../../../../node_modules/lodash/uniqueId.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/toString.js"),u=0;function d(f){var p=++u;return h(f)+p}o.exports=d},"../../../../node_modules/lodash/values.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_baseValues.js"),u=l("../../../../node_modules/lodash/keys.js");function d(f){return f==null?[]:h(f,u(f))}o.exports=d},"../../../../node_modules/lodash/zipObject.js":(o,c,l)=>{var h=l("../../../../node_modules/lodash/_assignValue.js"),u=l("../../../../node_modules/lodash/_baseZipObject.js");function d(f,p){return u(f||[],p||[],h)}o.exports=d},"../../../../node_modules/object-assign/index.js":o=>{/* object-assign (c) Sindre Sorhus @license MIT */var c=Object.getOwnPropertySymbols,l=Object.prototype.hasOwnProperty,h=Object.prototype.propertyIsEnumerable;function u(f){if(f==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(f)}function d(){try{if(!Object.assign)return!1;var f=new String("abc");if(f[5]="de",Object.getOwnPropertyNames(f)[0]==="5")return!1;for(var p={},_=0;_<10;_++)p["_"+String.fromCharCode(_)]=_;var m=Object.getOwnPropertyNames(p).map(function(v){return p[v]});if(m.join("")!=="0123456789")return!1;var g={};return"abcdefghijklmnopqrst".split("").forEach(function(v){g[v]=v}),Object.keys(Object.assign({},g)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}o.exports=d()?Object.assign:function(f,p){for(var _,m=u(f),g,v=1;v{var h=function(){};{var u=l("../../../../node_modules/prop-types/lib/ReactPropTypesSecret.js"),d={},f=l("../../../../node_modules/prop-types/lib/has.js");h=function(_){var m="Warning: "+_;typeof console<"u"&&console.error(m);try{throw new Error(m)}catch{}}}function p(_,m,g,v,x){for(var y in _)if(f(_,y)){var C;try{if(typeof _[y]!="function"){var b=Error((v||"React class")+": "+g+" type `"+y+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof _[y]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw b.name="Invariant Violation",b}C=_[y](m,y,v,g,null,u)}catch(S){C=S}if(C&&!(C instanceof Error)&&h((v||"React class")+": type specification of "+g+" `"+y+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof C+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."),C instanceof Error&&!(C.message in d)){d[C.message]=!0;var T=x?x():"";h("Failed "+g+" type: "+C.message+(T??""))}}}p.resetWarningCache=function(){d={}},o.exports=p},"../../../../node_modules/prop-types/factoryWithTypeCheckers.js":(o,c,l)=>{var h=l("../../../../node_modules/prop-types/node_modules/react-is/index.js"),u=l("../../../../node_modules/object-assign/index.js"),d=l("../../../../node_modules/prop-types/lib/ReactPropTypesSecret.js"),f=l("../../../../node_modules/prop-types/lib/has.js"),p=l("../../../../node_modules/prop-types/checkPropTypes.js"),_=function(){};_=function(g){var v="Warning: "+g;typeof console<"u"&&console.error(v);try{throw new Error(v)}catch{}};function m(){return null}o.exports=function(g,v){var x=typeof Symbol=="function"&&Symbol.iterator,y="@@iterator";function C(F){var W=F&&(x&&F[x]||F[y]);if(typeof W=="function")return W}var b="<>",T={array:M("array"),bigint:M("bigint"),bool:M("boolean"),func:M("function"),number:M("number"),object:M("object"),string:M("string"),symbol:M("symbol"),any:I(),arrayOf:R,element:O(),elementType:H(),instanceOf:G,node:j(),objectOf:$,oneOf:Q,oneOfType:V,shape:z,exact:Y};function S(F,W){return F===W?F!==0||1/F===1/W:F!==F&&W!==W}function N(F,W){this.message=F,this.data=W&&typeof W=="object"?W:{},this.stack=""}N.prototype=Error.prototype;function D(F){var W={},te=0;function oe(pe,ye,Pe,Fe,He,ot,Xe){if(Fe=Fe||b,ot=ot||Pe,Xe!==d){if(v){var gt=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw gt.name="Invariant Violation",gt}else if(typeof console<"u"){var rt=Fe+":"+Pe;!W[rt]&&te<3&&(_("You are manually calling a React.PropTypes validation function for the `"+ot+"` prop on `"+Fe+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),W[rt]=!0,te++)}}return ye[Pe]==null?pe?ye[Pe]===null?new N("The "+He+" `"+ot+"` is marked as required "+("in `"+Fe+"`, but its value is `null`.")):new N("The "+He+" `"+ot+"` is marked as required in "+("`"+Fe+"`, but its value is `undefined`.")):null:F(ye,Pe,Fe,He,ot)}var ne=oe.bind(null,!1);return ne.isRequired=oe.bind(null,!0),ne}function M(F){function W(te,oe,ne,pe,ye,Pe){var Fe=te[oe],He=he(Fe);if(He!==F){var ot=le(Fe);return new N("Invalid "+pe+" `"+ye+"` of type "+("`"+ot+"` supplied to `"+ne+"`, expected ")+("`"+F+"`."),{expectedType:F})}return null}return D(W)}function I(){return D(m)}function R(F){function W(te,oe,ne,pe,ye){if(typeof F!="function")return new N("Property `"+ye+"` of component `"+ne+"` has invalid PropType notation inside arrayOf.");var Pe=te[oe];if(!Array.isArray(Pe)){var Fe=he(Pe);return new N("Invalid "+pe+" `"+ye+"` of type "+("`"+Fe+"` supplied to `"+ne+"`, expected an array."))}for(var He=0;He1?_("Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."):_("Invalid argument supplied to oneOf, expected an array."),m;function W(te,oe,ne,pe,ye){for(var Pe=te[oe],Fe=0;Fe0?", expected one of type ["+He.join(", ")+"]":"";return new N("Invalid "+Pe+" `"+Fe+"` supplied to "+("`"+ye+"`"+rt+"."))}return D(oe)}function j(){function F(W,te,oe,ne,pe){return J(W[te])?null:new N("Invalid "+ne+" `"+pe+"` supplied to "+("`"+oe+"`, expected a ReactNode."))}return D(F)}function k(F,W,te,oe,ne){return new N((F||"React class")+": "+W+" type `"+te+"."+oe+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+ne+"`.")}function z(F){function W(te,oe,ne,pe,ye){var Pe=te[oe],Fe=he(Pe);if(Fe!=="object")return new N("Invalid "+pe+" `"+ye+"` of type `"+Fe+"` "+("supplied to `"+ne+"`, expected `object`."));for(var He in F){var ot=F[He];if(typeof ot!="function")return k(ne,pe,ye,He,le(ot));var Xe=ot(Pe,He,ne,pe,ye+"."+He,d);if(Xe)return Xe}return null}return D(W)}function Y(F){function W(te,oe,ne,pe,ye){var Pe=te[oe],Fe=he(Pe);if(Fe!=="object")return new N("Invalid "+pe+" `"+ye+"` of type `"+Fe+"` "+("supplied to `"+ne+"`, expected `object`."));var He=u({},te[oe],F);for(var ot in He){var Xe=F[ot];if(f(F,ot)&&typeof Xe!="function")return k(ne,pe,ye,ot,le(Xe));if(!Xe)return new N("Invalid "+pe+" `"+ye+"` key `"+ot+"` supplied to `"+ne+"`.\nBad object: "+JSON.stringify(te[oe],null," ")+` Valid keys: `+JSON.stringify(Object.keys(F),null," "));var gt=Xe(Pe,ot,ne,pe,ye+"."+ot,d);if(gt)return gt}return null}return D(W)}function J(F){switch(typeof F){case"number":case"string":case"undefined":return!0;case"boolean":return!F;case"object":if(Array.isArray(F))return F.every(J);if(F===null||g(F))return!0;var W=C(F);if(W){var te=W.call(F),oe;if(W!==F.entries){for(;!(oe=te.next()).done;)if(!J(oe.value))return!1}else for(;!(oe=te.next()).done;){var ne=oe.value;if(ne&&!J(ne[1]))return!1}}else return!1;return!0;default:return!1}}function re(F,W){return F==="symbol"?!0:W?W["@@toStringTag"]==="Symbol"||typeof Symbol=="function"&&W instanceof Symbol:!1}function he(F){var W=typeof F;return Array.isArray(F)?"array":F instanceof RegExp?"object":re(W,F)?"symbol":W}function le(F){if(typeof F>"u"||F===null)return""+F;var W=he(F);if(W==="object"){if(F instanceof Date)return"date";if(F instanceof RegExp)return"regexp"}return W}function ue(F){var W=le(F);switch(W){case"array":case"object":return"an "+W;case"boolean":case"date":case"regexp":return"a "+W;default:return W}}function L(F){return!F.constructor||!F.constructor.name?b:F.constructor.name}return T.checkPropTypes=p,T.resetWarningCache=p.resetWarningCache,T.PropTypes=T,T}},"../../../../node_modules/prop-types/index.js":(o,c,l)=>{{var h=l("../../../../node_modules/prop-types/node_modules/react-is/index.js"),u=!0;o.exports=l("../../../../node_modules/prop-types/factoryWithTypeCheckers.js")(h.isElement,u)}},"../../../../node_modules/prop-types/lib/ReactPropTypesSecret.js":o=>{var c="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";o.exports=c},"../../../../node_modules/prop-types/lib/has.js":o=>{o.exports=Function.call.bind(Object.prototype.hasOwnProperty)},"../../../../node_modules/prop-types/node_modules/react-is/cjs/react-is.development.js":(o,c)=>{/** @license React v16.13.1 * react-is.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */(function(){var l=typeof Symbol=="function"&&Symbol.for,h=l?Symbol.for("react.element"):60103,u=l?Symbol.for("react.portal"):60106,d=l?Symbol.for("react.fragment"):60107,f=l?Symbol.for("react.strict_mode"):60108,p=l?Symbol.for("react.profiler"):60114,_=l?Symbol.for("react.provider"):60109,m=l?Symbol.for("react.context"):60110,g=l?Symbol.for("react.async_mode"):60111,v=l?Symbol.for("react.concurrent_mode"):60111,x=l?Symbol.for("react.forward_ref"):60112,y=l?Symbol.for("react.suspense"):60113,C=l?Symbol.for("react.suspense_list"):60120,b=l?Symbol.for("react.memo"):60115,T=l?Symbol.for("react.lazy"):60116,S=l?Symbol.for("react.block"):60121,N=l?Symbol.for("react.fundamental"):60117,D=l?Symbol.for("react.responder"):60118,M=l?Symbol.for("react.scope"):60119;function I(Xe){return typeof Xe=="string"||typeof Xe=="function"||Xe===d||Xe===v||Xe===p||Xe===f||Xe===y||Xe===C||typeof Xe=="object"&&Xe!==null&&(Xe.$$typeof===T||Xe.$$typeof===b||Xe.$$typeof===_||Xe.$$typeof===m||Xe.$$typeof===x||Xe.$$typeof===N||Xe.$$typeof===D||Xe.$$typeof===M||Xe.$$typeof===S)}function R(Xe){if(typeof Xe=="object"&&Xe!==null){var gt=Xe.$$typeof;switch(gt){case h:var rt=Xe.type;switch(rt){case g:case v:case d:case p:case f:case y:return rt;default:var ut=rt&&rt.$$typeof;switch(ut){case m:case x:case T:case b:case _:return ut;default:return gt}}case u:return gt}}}var O=g,H=v,G=m,Q=_,$=h,V=x,j=d,k=T,z=b,Y=u,J=p,re=f,he=y,le=!1;function ue(Xe){return le||(le=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.")),L(Xe)||R(Xe)===g}function L(Xe){return R(Xe)===v}function F(Xe){return R(Xe)===m}function W(Xe){return R(Xe)===_}function te(Xe){return typeof Xe=="object"&&Xe!==null&&Xe.$$typeof===h}function oe(Xe){return R(Xe)===x}function ne(Xe){return R(Xe)===d}function pe(Xe){return R(Xe)===T}function ye(Xe){return R(Xe)===b}function Pe(Xe){return R(Xe)===u}function Fe(Xe){return R(Xe)===p}function He(Xe){return R(Xe)===f}function ot(Xe){return R(Xe)===y}c.AsyncMode=O,c.ConcurrentMode=H,c.ContextConsumer=G,c.ContextProvider=Q,c.Element=$,c.ForwardRef=V,c.Fragment=j,c.Lazy=k,c.Memo=z,c.Portal=Y,c.Profiler=J,c.StrictMode=re,c.Suspense=he,c.isAsyncMode=ue,c.isConcurrentMode=L,c.isContextConsumer=F,c.isContextProvider=W,c.isElement=te,c.isForwardRef=oe,c.isFragment=ne,c.isLazy=pe,c.isMemo=ye,c.isPortal=Pe,c.isProfiler=Fe,c.isStrictMode=He,c.isSuspense=ot,c.isValidElementType=I,c.typeOf=R})()},"../../../../node_modules/prop-types/node_modules/react-is/index.js":(o,c,l)=>{o.exports=l("../../../../node_modules/prop-types/node_modules/react-is/cjs/react-is.development.js")},"../../../../node_modules/react-dom/cjs/react-dom.development.js":(o,c,l)=>{/** @license React v17.0.2 * react-dom.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */(function(){var h=l("../../../../node_modules/react/index.js"),u=l("../../../../node_modules/object-assign/index.js"),d=l("../../../../node_modules/scheduler/index.js"),f=l("../../../../node_modules/scheduler/tracing.js"),p=h.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function _(A){{for(var E=arguments.length,w=new Array(E>1?E-1:0),U=1;U1?E-1:0),U=1;U2&&(A[0]==="o"||A[0]==="O")&&(A[1]==="n"||A[1]==="N")}function Ti(A,E,w,U){if(w!==null&&w.type===Pe)return!1;switch(typeof E){case"function":case"symbol":return!0;case"boolean":{if(U)return!1;if(w!==null)return!w.acceptsBooleans;var X=A.toLowerCase().slice(0,5);return X!=="data-"&&X!=="aria-"}default:return!1}}function zi(A,E,w,U){if(E===null||typeof E>"u"||Ti(A,E,w,U))return!0;if(U)return!1;if(w!==null)switch(w.type){case ot:return!E;case Xe:return E===!1;case gt:return isNaN(E);case rt:return isNaN(E)||E<1}return!1}function ji(A){return Si.hasOwnProperty(A)?Si[A]:null}function Ei(A,E,w,U,X,ee,ae){this.acceptsBooleans=E===He||E===ot||E===Xe,this.attributeName=U,this.attributeNamespace=X,this.mustUseProperty=w,this.propertyName=A,this.type=E,this.sanitizeURL=ee,this.removeEmptyString=ae}var Si={},ir=["children","dangerouslySetInnerHTML","defaultValue","defaultChecked","innerHTML","suppressContentEditableWarning","suppressHydrationWarning","style"];ir.forEach(function(A){Si[A]=new Ei(A,Pe,!1,A,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(A){var E=A[0],w=A[1];Si[E]=new Ei(E,Fe,!1,w,null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(A){Si[A]=new Ei(A,He,!1,A.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(A){Si[A]=new Ei(A,He,!1,A,null,!1,!1)}),["allowFullScreen","async","autoFocus","autoPlay","controls","default","defer","disabled","disablePictureInPicture","disableRemotePlayback","formNoValidate","hidden","loop","noModule","noValidate","open","playsInline","readOnly","required","reversed","scoped","seamless","itemScope"].forEach(function(A){Si[A]=new Ei(A,ot,!1,A.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(A){Si[A]=new Ei(A,ot,!0,A,null,!1,!1)}),["capture","download"].forEach(function(A){Si[A]=new Ei(A,Xe,!1,A,null,!1,!1)}),["cols","rows","size","span"].forEach(function(A){Si[A]=new Ei(A,rt,!1,A,null,!1,!1)}),["rowSpan","start"].forEach(function(A){Si[A]=new Ei(A,gt,!1,A.toLowerCase(),null,!1,!1)});var Ot=/[\-\:]([a-z])/g,qt=function(A){return A[1].toUpperCase()};["accent-height","alignment-baseline","arabic-form","baseline-shift","cap-height","clip-path","clip-rule","color-interpolation","color-interpolation-filters","color-profile","color-rendering","dominant-baseline","enable-background","fill-opacity","fill-rule","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","glyph-name","glyph-orientation-horizontal","glyph-orientation-vertical","horiz-adv-x","horiz-origin-x","image-rendering","letter-spacing","lighting-color","marker-end","marker-mid","marker-start","overline-position","overline-thickness","paint-order","panose-1","pointer-events","rendering-intent","shape-rendering","stop-color","stop-opacity","strikethrough-position","strikethrough-thickness","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-anchor","text-decoration","text-rendering","underline-position","underline-thickness","unicode-bidi","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","vector-effect","vert-adv-y","vert-origin-x","vert-origin-y","word-spacing","writing-mode","xmlns:xlink","x-height"].forEach(function(A){var E=A.replace(Ot,qt);Si[E]=new Ei(E,Fe,!1,A,null,!1,!1)}),["xlink:actuate","xlink:arcrole","xlink:role","xlink:show","xlink:title","xlink:type"].forEach(function(A){var E=A.replace(Ot,qt);Si[E]=new Ei(E,Fe,!1,A,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(A){var E=A.replace(Ot,qt);Si[E]=new Ei(E,Fe,!1,A,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(A){Si[A]=new Ei(A,Fe,!1,A.toLowerCase(),null,!1,!1)});var Vt="xlinkHref";Si[Vt]=new Ei("xlinkHref",Fe,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(A){Si[A]=new Ei(A,Fe,!1,A.toLowerCase(),null,!0,!0)});var Mi=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i,er=!1;function lr(A){!er&&Mi.test(A)&&(er=!0,m("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.",JSON.stringify(A)))}function Fr(A,E,w,U){if(U.mustUseProperty){var X=U.propertyName;return A[X]}else{U.sanitizeURL&&lr(""+w);var ee=U.attributeName,ae=null;if(U.type===Xe){if(A.hasAttribute(ee)){var _e=A.getAttribute(ee);return _e===""?!0:zi(E,w,U,!1)?_e:_e===""+w?w:_e}}else if(A.hasAttribute(ee)){if(zi(E,w,U,!1))return A.getAttribute(ee);if(U.type===ot)return w;ae=A.getAttribute(ee)}return zi(E,w,U,!1)?ae===null?w:ae:ae===""+w?w:ae}}function cs(A,E,w){{if(!xi(E))return;if(qB(w))return w;if(!A.hasAttribute(E))return w===void 0?void 0:null;var U=A.getAttribute(E);return U===""+w?w:U}}function Kt(A,E,w,U){var X=ji(E);if(!Wi(E,X,U)){if(zi(E,w,X,U)&&(w=null),U||X===null){if(xi(E)){var ee=E;w===null?A.removeAttribute(ee):A.setAttribute(ee,""+w)}return}var ae=X.mustUseProperty;if(ae){var _e=X.propertyName;if(w===null){var be=X.type;A[_e]=be===ot?!1:""}else A[_e]=w;return}var Ne=X.attributeName,Ve=X.attributeNamespace;if(w===null)A.removeAttribute(Ne);else{var st=X.type,We;st===ot||st===Xe&&w===!0?We="":(We=""+w,X.sanitizeURL&&lr(We.toString())),Ve?A.setAttributeNS(Ve,Ne,We):A.setAttribute(Ne,We)}}}var Dr=60103,hs=60106,us=60107,ws=60108,ur=60114,Tt=60109,ti=60110,Lt=60112,Gs=60113,is=60120,Ds=60115,Ra=60116,Ge=60121,Bt=60119,ri=60128,Yi=60129,Qr=60130,$r=60131;if(typeof Symbol=="function"&&Symbol.for){var Vi=Symbol.for;Dr=Vi("react.element"),hs=Vi("react.portal"),us=Vi("react.fragment"),ws=Vi("react.strict_mode"),ur=Vi("react.profiler"),Tt=Vi("react.provider"),ti=Vi("react.context"),Lt=Vi("react.forward_ref"),Gs=Vi("react.suspense"),is=Vi("react.suspense_list"),Ds=Vi("react.memo"),Ra=Vi("react.lazy"),Ge=Vi("react.block"),Vi("react.server.block"),Vi("react.fundamental"),Bt=Vi("react.scope"),ri=Vi("react.opaque.id"),Yi=Vi("react.debug_trace_mode"),Qr=Vi("react.offscreen"),$r=Vi("react.legacy_hidden")}var Ir=typeof Symbol=="function"&&Symbol.iterator,tn="@@iterator";function _r(A){if(A===null||typeof A!="object")return null;var E=Ir&&A[Ir]||A[tn];return typeof E=="function"?E:null}var Os=0,cl,$o,Hu,ja,Gd,v1,Kd;function x1(){}x1.__reactDisabledLog=!0;function wl(){{if(Os===0){cl=console.log,$o=console.info,Hu=console.warn,ja=console.error,Gd=console.group,v1=console.groupCollapsed,Kd=console.groupEnd;var A={configurable:!0,enumerable:!0,value:x1,writable:!0};Object.defineProperties(console,{info:A,log:A,warn:A,error:A,group:A,groupCollapsed:A,groupEnd:A})}Os++}}function Dl(){{if(Os--,Os===0){var A={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:u({},A,{value:cl}),info:u({},A,{value:$o}),warn:u({},A,{value:Hu}),error:u({},A,{value:ja}),group:u({},A,{value:Gd}),groupCollapsed:u({},A,{value:v1}),groupEnd:u({},A,{value:Kd})})}Os<0&&m("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Gu=p.ReactCurrentDispatcher,bh;function Zo(A,E,w){{if(bh===void 0)try{throw Error()}catch(X){var U=X.stack.trim().match(/\n( *(at )?)/);bh=U&&U[1]||""}return` `+bh+A}}var Yc=!1,Jh;{var eu=typeof WeakMap=="function"?WeakMap:Map;Jh=new eu}function Jf(A,E){if(!A||Yc)return"";{var w=Jh.get(A);if(w!==void 0)return w}var U;Yc=!0;var X=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var ee;ee=Gu.current,Gu.current=null,wl();try{if(E){var ae=function(){throw Error()};if(Object.defineProperty(ae.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ae,[])}catch(It){U=It}Reflect.construct(A,[],ae)}else{try{ae.call()}catch(It){U=It}A.call(ae.prototype)}}else{try{throw Error()}catch(It){U=It}A()}}catch(It){if(It&&U&&typeof It.stack=="string"){for(var _e=It.stack.split(` `),be=U.stack.split(` `),Ne=_e.length-1,Ve=be.length-1;Ne>=1&&Ve>=0&&_e[Ne]!==be[Ve];)Ve--;for(;Ne>=1&&Ve>=0;Ne--,Ve--)if(_e[Ne]!==be[Ve]){if(Ne!==1||Ve!==1)do if(Ne--,Ve--,Ve<0||_e[Ne]!==be[Ve]){var st=` `+_e[Ne].replace(" at new "," at ");return typeof A=="function"&&Jh.set(A,st),st}while(Ne>=1&&Ve>=0);break}}}finally{Yc=!1,Gu.current=ee,Dl(),Error.prepareStackTrace=X}var We=A?A.displayName||A.name:"",ht=We?Zo(We):"";return typeof A=="function"&&Jh.set(A,ht),ht}function h_(A,E,w){return Jf(A,!0)}function yc(A,E,w){return Jf(A,!1)}function y1(A){var E=A.prototype;return!!(E&&E.isReactComponent)}function Wd(A,E,w){if(A==null)return"";if(typeof A=="function")return Jf(A,y1(A));if(typeof A=="string")return Zo(A);switch(A){case Gs:return Zo("Suspense");case is:return Zo("SuspenseList")}if(typeof A=="object")switch(A.$$typeof){case Lt:return yc(A.render);case Ds:return Wd(A.type,E,w);case Ge:return yc(A._render);case Ra:{var U=A,X=U._payload,ee=U._init;try{return Wd(ee(X),E,w)}catch{}}}return""}function Ku(A){switch(A._debugOwner&&A._debugOwner.type,A._debugSource,A.tag){case T:return Zo(A.type);case $:return Zo("Lazy");case H:return Zo("Suspense");case k:return Zo("SuspenseList");case v:case y:case Q:return yc(A.type);case R:return yc(A.type.render);case J:return yc(A.type._render);case x:return h_(A.type);default:return""}}function A1(A){try{var E="",w=A;do E+=Ku(w),w=w.return;while(w);return E}catch(U){return` Error generating stack: `+U.message+` `+U.stack}}function tu(A,E,w){var U=E.displayName||E.name||"";return A.displayName||(U!==""?w+"("+U+")":w)}function ep(A){return A.displayName||"Context"}function hi(A){if(A==null)return null;if(typeof A.tag=="number"&&m("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."),typeof A=="function")return A.displayName||A.name||null;if(typeof A=="string")return A;switch(A){case us:return"Fragment";case hs:return"Portal";case ur:return"Profiler";case ws:return"StrictMode";case Gs:return"Suspense";case is:return"SuspenseList"}if(typeof A=="object")switch(A.$$typeof){case ti:var E=A;return ep(E)+".Consumer";case Tt:var w=A;return ep(w._context)+".Provider";case Lt:return tu(A,A.render,"ForwardRef");case Ds:return hi(A.type);case Ge:return hi(A._render);case Ra:{var U=A,X=U._payload,ee=U._init;try{return hi(ee(X))}catch{return null}}}return null}var u_=p.ReactDebugCurrentFrame,No=null,Qc=!1;function Wu(){{if(No===null)return null;var A=No._debugOwner;if(A!==null&&typeof A<"u")return hi(A.type)}return null}function Eh(){return No===null?"":A1(No)}function Ia(){u_.getCurrentStack=null,No=null,Qc=!1}function _a(A){u_.getCurrentStack=Eh,No=A,Qc=!1}function Xa(A){Qc=A}function tp(){return Qc}function Ya(A){return""+A}function $c(A){switch(typeof A){case"boolean":case"number":case"object":case"string":case"undefined":return A;default:return""}}var ip={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0};function ju(A,E){ip[E.type]||E.onChange||E.onInput||E.readOnly||E.disabled||E.value==null||m("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."),E.onChange||E.readOnly||E.disabled||E.checked==null||m("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")}function C1(A){var E=A.type,w=A.nodeName;return w&&w.toLowerCase()==="input"&&(E==="checkbox"||E==="radio")}function iu(A){return A._valueTracker}function ru(A){A._valueTracker=null}function A2(A){var E="";return A&&(C1(A)?E=A.checked?"true":"false":E=A.value),E}function Te(A){var E=C1(A)?"checked":"value",w=Object.getOwnPropertyDescriptor(A.constructor.prototype,E),U=""+A[E];if(!(A.hasOwnProperty(E)||typeof w>"u"||typeof w.get!="function"||typeof w.set!="function")){var X=w.get,ee=w.set;Object.defineProperty(A,E,{configurable:!0,get:function(){return X.call(this)},set:function(_e){U=""+_e,ee.call(this,_e)}}),Object.defineProperty(A,E,{enumerable:w.enumerable});var ae={getValue:function(){return U},setValue:function(_e){U=""+_e},stopTracking:function(){ru(A),delete A[E]}};return ae}}function je(A){iu(A)||(A._valueTracker=Te(A))}function ct(A){if(!A)return!1;var E=iu(A);if(!E)return!0;var w=E.getValue(),U=A2(A);return U!==w?(E.setValue(U),!0):!1}function mt(A){if(A=A||(typeof document<"u"?document:void 0),typeof A>"u")return null;try{return A.activeElement||A.body}catch{return A.body}}var oi=!1,cr=!1,ar=!1,tr=!1;function Ls(A){var E=A.type==="checkbox"||A.type==="radio";return E?A.checked!=null:A.value!=null}function Tr(A,E){var w=A,U=E.checked,X=u({},E,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:U??w._wrapperState.initialChecked});return X}function An(A,E){ju("input",E),E.checked!==void 0&&E.defaultChecked!==void 0&&!cr&&(m("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components",Wu()||"A component",E.type),cr=!0),E.value!==void 0&&E.defaultValue!==void 0&&!oi&&(m("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components",Wu()||"A component",E.type),oi=!0);var w=A,U=E.defaultValue==null?"":E.defaultValue;w._wrapperState={initialChecked:E.checked!=null?E.checked:E.defaultChecked,initialValue:$c(E.value!=null?E.value:U),controlled:Ls(E)}}function Cn(A,E){var w=A,U=E.checked;U!=null&&Kt(w,"checked",U,!1)}function fo(A,E){var w=A;{var U=Ls(E);!w._wrapperState.controlled&&U&&!tr&&(m("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"),tr=!0),w._wrapperState.controlled&&!U&&!ar&&(m("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"),ar=!0)}Cn(A,E);var X=$c(E.value),ee=E.type;if(X!=null)ee==="number"?(X===0&&w.value===""||w.value!=X)&&(w.value=Ya(X)):w.value!==Ya(X)&&(w.value=Ya(X));else if(ee==="submit"||ee==="reset"){w.removeAttribute("value");return}E.hasOwnProperty("value")?Xu(w,E.type,X):E.hasOwnProperty("defaultValue")&&Xu(w,E.type,$c(E.defaultValue)),E.checked==null&&E.defaultChecked!=null&&(w.defaultChecked=!!E.defaultChecked)}function Bo(A,E,w){var U=A;if(E.hasOwnProperty("value")||E.hasOwnProperty("defaultValue")){var X=E.type,ee=X==="submit"||X==="reset";if(ee&&(E.value===void 0||E.value===null))return;var ae=Ya(U._wrapperState.initialValue);w||ae!==U.value&&(U.value=ae),U.defaultValue=ae}var _e=U.name;_e!==""&&(U.name=""),U.defaultChecked=!U.defaultChecked,U.defaultChecked=!!U._wrapperState.initialChecked,_e!==""&&(U.name=_e)}function qo(A,E){var w=A;fo(w,E),jd(w,E)}function jd(A,E){var w=E.name;if(E.type==="radio"&&w!=null){for(var U=A;U.parentNode;)U=U.parentNode;for(var X=U.querySelectorAll("input[name="+JSON.stringify(""+w)+'][type="radio"]'),ee=0;ee children."))))}),E.selected!=null&&!Xd&&(m("Use the `defaultValue` or `value` props on must be a scalar value if `multiple` is false.%s",w,Qd())}}}}function Yu(A,E,w,U){var X=A.options;if(E){for(var ee=w,ae={},_e=0;_e.");var U=u({},E,{value:void 0,defaultValue:void 0,children:Ya(w._wrapperState.initialValue)});return U}function E2(A,E){var w=A;ju("textarea",E),E.value!==void 0&&E.defaultValue!==void 0&&!T4&&(m("%s contains a textarea with both value and defaultValue props. Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://reactjs.org/link/controlled-components",Wu()||"A component"),T4=!0);var U=E.value;if(U==null){var X=E.children,ee=E.defaultValue;if(X!=null){m("Use the `defaultValue` or `value` props instead of setting children on