diff --git a/anu-examples/examples/LineCharts/linechart3D.js b/anu-examples/examples/LineCharts/linechart3D.js index a6e332d..3adfc68 100644 --- a/anu-examples/examples/LineCharts/linechart3D.js +++ b/anu-examples/examples/LineCharts/linechart3D.js @@ -21,7 +21,7 @@ export function linechart3D(babylonEngine) { let CoT = new TransformNode("cot"); - d3.csv("../anu/data/yield-curve.csv", (d) => d).then((data) => { + d3.csv("/anu/public/data/yield-curve.csv", (d) => d).then((data) => { let years = ["1 Yr", "2 Yr", "3 Yr", "5 Yr", "7 Yr", "10 Yr"]; var parseTime = d3.timeParse("%m/%d/%Y"); diff --git a/docs/public/assets/index.caebcba4.js b/docs/public/assets/index.caebcba4.js new file mode 100644 index 0000000..44d0d88 --- /dev/null +++ b/docs/public/assets/index.caebcba4.js @@ -0,0 +1,36836 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&i(n)}).observe(document,{childList:!0,subtree:!0});function t(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerpolicy&&(r.referrerPolicy=s.referrerpolicy),s.crossorigin==="use-credentials"?r.credentials="include":s.crossorigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(s){if(s.ep)return;s.ep=!0;const r=t(s);fetch(s.href,r)}})();class D${constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class Foe{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 Se{static FromPromise(e,t){const i=new Se;return e.then(s=>{i.notifyObservers(s)}).catch(s=>{if(t)t.notifyObservers(s);else throw s}),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 D$(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new Foe(e,t,s);return n.unregisterOnNextCall=r,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}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,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?n.lastReturnValue=o.callback.apply(o.scope,[e,n]):n.lastReturnValue=o.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}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 Se;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}}function ql(){return typeof window<"u"}function pP(){return typeof navigator<"u"}function Zb(){return typeof document<"u"}function OG(a){let e="",t=a.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}const B0e={IsWindowObjectExist:ql,IsNavigatorAvailable:pP,IsDocumentAvailable:Zb,GetDOMTextContent:OG};class Me{static _CheckLimit(e,t){let i=Me._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},Me._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var i;const s=Me._LogLimitOutputs[e];if(!s||!Me.MessageLimitReached)return;const r=this._Levels[t];s.current===s.limit&&Me[r.name](Me.MessageLimitReached.replace(/%LIMIT%/g,""+s.limit).replace(/%TYPE%/g,(i=r.name)!==null&&i!==void 0?i:""))}static _AddLogEntry(e){Me._LogCache=e+Me._LogCache,Me.OnNewCacheEntry&&Me.OnNewCacheEntry(e)}static _FormatMessage(e){const t=s=>s<10?"0"+s:""+s,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){if(i!==void 0&&!Me._CheckLimit(t,i))return;const s=Me._FormatMessage(t),r=this._Levels[e];r.logFunc&&r.logFunc("BJS - "+s);const n=`
${s}

`;Me._AddLogEntry(n),Me._GenerateLimitMessage(t,e)}static get LogCache(){return Me._LogCache}static ClearLogCache(){Me._LogCache="",Me._LogLimitOutputs={},Me.errorsCount=0}static set LogLevels(e){Me.Log=Me._LogDisabled,Me.Warn=Me._LogDisabled,Me.Error=Me._LogDisabled,[Me.MessageLogLevel,Me.WarningLogLevel,Me.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];Me[i.name]=Me._LogEnabled.bind(Me,t)}})}}Me.NoneLogLevel=0;Me.MessageLogLevel=1;Me.WarningLogLevel=2;Me.ErrorLogLevel=4;Me.AllLogLevel=7;Me.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";Me._LogCache="";Me._LogLimitOutputs={};Me._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];Me.errorsCount=0;Me.Log=Me._LogEnabled.bind(Me,Me.MessageLogLevel);Me.Warn=Me._LogEnabled.bind(Me,Me.WarningLogLevel);Me.Error=Me._LogEnabled.bind(Me,Me.ErrorLogLevel);const yse=(a,e)=>!a||a.getClassName&&a.getClassName()==="Mesh"?null:a.getClassName&&(a.getClassName()==="SubMesh"||a.getClassName()==="PhysicsBody")?a.clone(e):a.clone?a.clone():Array.isArray(a)?a.slice():null;function F0e(a){const e=[];do Object.getOwnPropertyNames(a).forEach(function(t){e.indexOf(t)===-1&&e.push(t)});while(a=Object.getPrototypeOf(a));return e}class e2{static DeepCopy(e,t,i,s){const r=F0e(e);for(const n of r){if(n[0]==="_"&&(!s||s.indexOf(n)===-1)||n.endsWith("Observable")||i&&i.indexOf(n)!==-1)continue;const o=e[n],l=typeof o;if(l!=="function")try{if(l==="object")if(o instanceof Uint8Array)t[n]=Uint8Array.from(o);else if(o instanceof Array){if(t[n]=[],o.length>0)if(typeof o[0]=="object")for(let c=0;cs.status!==0||r>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,r)*t}}class UP extends Error{}UP._setPrototypeOf=Object.setPrototypeOf||((a,e)=>(a.__proto__=e,a));const XM={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class nC extends UP{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",UP._setPrototypeOf(this,nC.prototype)}}const zoe=(a,e)=>a.endsWith(e),Uoe=(a,e)=>a?a.startsWith(e):!1,O$=a=>{if(typeof TextDecoder<"u")return new TextDecoder().decode(a);let e="";for(let t=0;t{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,s,r,n,o,l,c,h=0;const u=ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);for(;h>2,o=(i&3)<<4|s>>4,l=(s&15)<<2|r>>6,c=r&63,isNaN(s)?l=c=64:isNaN(r)&&(c=64),t+=e.charAt(n)+e.charAt(o)+e.charAt(l)+e.charAt(c);return t},pK=a=>atob(a),NG=a=>{const e=pK(a),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let s=0;s{let t=String(a);for(;t.length{h+=u.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),h}}class H0e{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{const r=t.split(";");for(let n=0;n{h=h.trim(),h!==""&&(i.push(h),h="")},n=u=>{scc._Stack[s],l=()=>s===-1?"!!INVALID EXPRESSION!!":cc._Stack[s--];let c=0,h="";for(;c1){for(r();s!==-1&&cc._OperatorPriority[o()]>=cc._OperatorPriority[p];)i.push(l());n(p),c++}else h+=u;c++}for(r();s!==-1;)o()==="("?l():i.push(l());return cc._InfixToPostfixCache.size>=cc.InfixToPostfixCacheLimitSize&&cc.ClearCache(),cc._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(cc._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r;break}return i}}var Ao;(function(a){a[a.GLSL=0]="GLSL",a[a.WGSL=1]="WGSL"})(Ao||(Ao={}));const X0e=/defined\s*?\((.+?)\)/g,mZ=/defined\s*?\[(.+?)\]/g,K0e=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Q0e=/__decl__/,Mse=/light\{X\}.(\w*)/g,Tse=/\{X\}/g,lY=[];class rv{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,s){var r;!((r=t.processor)===null||r===void 0)&&r.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,n=>{t.processCodeAfterIncludes&&(n=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",n));const o=this._ProcessShaderConversion(n,t,s);i(o,n)})}static PreProcess(e,t,i,s){var r;!((r=t.processor)===null||r===void 0)&&r.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,n=>{t.processCodeAfterIncludes&&(n=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",n));const o=this._ApplyPreProcessing(n,t,s);i(o,n)})}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 i;if(!((i=t.processor)===null||i===void 0)&&i.noPrecision)return e;const s=t.shouldUseHighPrecisionShader;return e.indexOf("precision highp float")===-1?s?e=`precision highp float; +`+e:e=`precision mediump float; +`+e:s||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){const i=/defined\((.+)\)/.exec(e);if(i&&i.length)return new oY(i[1].trim(),e[0]==="!");const s=["==","!=",">=","<=","<",">"];let r="",n=0;for(r of s)if(n=e.indexOf(r),n>-1)break;if(n===-1)return new oY(e);const o=e.substring(0,n).trim(),l=e.substring(n+r.length).trim();return new Y0e(o,r,l)}static _BuildSubExpression(e){e=e.replace(X0e,"defined[$1]");const t=cc.infixToPostfix(e),i=[];for(const r of t)if(r!=="||"&&r!=="&&")i.push(r);else if(i.length>=2){let n=i[i.length-1],o=i[i.length-2];i.length-=2;const l=r=="&&"?new W0e:new G0e;typeof n=="string"&&(n=n.replace(mZ,"defined($1)")),typeof o=="string"&&(o=o.replace(mZ,"defined($1)")),l.leftOperand=typeof o=="string"?this._ExtractOperation(o):o,l.rightOperand=typeof n=="string"?this._ExtractOperation(n):n,i.push(l)}let s=i[i.length-1];return typeof s=="string"&&(s=s.replace(mZ,"defined($1)")),typeof s=="string"?this._ExtractOperation(s):s}static _BuildExpression(e,t){const i=new j0e,s=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),s==="#ifdef"?i.testExpression=new oY(r):s==="#ifndef"?i.testExpression=new oY(r,!0):i.testExpression=this._BuildSubExpression(r),i}static _MoveCursorWithinIf(e,t,i){let s=e.currentLine;for(;this._MoveCursor(e,i);){s=e.currentLine;const r=s.substring(0,5).toLowerCase();if(r==="#else"){const n=new pj;t.children.push(n),this._MoveCursor(e,n);return}else if(r==="#elif"){const n=this._BuildExpression(s,5);t.children.push(n),i=n}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const r=rv._MoveCursorRegex.exec(i);if(r&&r.length){switch(r[0]){case"#ifdef":{const o=new pZ;t.children.push(o);const l=this._BuildExpression(i,6);o.children.push(l),this._MoveCursorWithinIf(e,o,l);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const o=new pZ;t.children.push(o);const l=this._BuildExpression(i,7);o.children.push(l),this._MoveCursorWithinIf(e,o,l);break}case"#if":{const o=new pZ,l=this._BuildExpression(i,3);t.children.push(o),o.children.push(l),this._MoveCursorWithinIf(e,o,l);break}}continue}}const s=new pj;if(s.line=i,t.children.push(s),i[0]==="#"&&i[1]==="d"){const r=i.replace(";","").split(" ");s.additionalDefineKey=r[1],r.length===3&&(s.additionalDefineValue=r[2])}}return!1}static _EvaluatePreProcessors(e,t,i){const s=new pj,r=new H0e;return r.lineIndex=-1,r.lines=e.split(` +`),this._MoveCursor(r,s),s.process(t,i)}static _PreparePreProcessors(e,t){var i;const s=e.defines,r={};for(const n of s){const l=n.replace("#define","").replace(";","").trim().split(" ");r[l[0]]=l.length>1?l[1]:""}return((i=e.processor)===null||i===void 0?void 0:i.shaderLanguage)===Ao.GLSL&&(r.GL_ES="true"),r.__VERSION__=e.version,r[e.platformName]="true",t._getGlobalDefines(r),r}static _ProcessShaderConversion(e,t,i){let s=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===Ao.GLSL&&s.indexOf("#version 3")!==-1&&(s=s.replace("#version 300 es",""),!t.processor.parseGLES3))return s;const r=t.defines,n=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(s=t.processor.preProcessor(s,r,t.isFragment,t.processingContext)),s=this._EvaluatePreProcessors(s,n,t),t.processor.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}static _ApplyPreProcessing(e,t,i){var s,r;let n=e;const o=t.defines,l=this._PreparePreProcessors(t,i);return!((s=t.processor)===null||s===void 0)&&s.preProcessor&&(n=t.processor.preProcessor(n,o,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,l,t),!((r=t.processor)===null||r===void 0)&&r.postProcessor&&(n=t.processor.postProcessor(n,o,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ProcessIncludes(e,t,i){lY.length=0;let s;for(;(s=K0e.exec(e))!==null;)lY.push(s);let r=String(e),n=[e],o=!1;for(const l of lY){let c=l[1];if(c.indexOf("__decl__")!==-1&&(c=c.replace(Q0e,""),t.supportsUniformBuffers&&(c=c.replace("Vertex","Ubo").replace("Fragment","Ubo")),c=c+"Declaration"),t.includesShadersStore[c]){let h=t.includesShadersStore[c];if(l[2]){const p=l[3].split(",");for(let m=0;my+"{X}")),h+=d.replace(Tse,C.toString())+` +`}else t.supportsUniformBuffers||(h=h.replace(Mse,(m,_)=>_+"{X}")),h=h.replace(Tse,p)}const u=[];for(const p of n){const m=p.split(l[0]);for(let _=0;_=0||h.indexOf("#include <")>=0}else{const h=t.shadersRepository+"ShadersInclude/"+c+".fx";rv._FileToolsLoadFile(h,u=>{t.includesShadersStore[c]=u,this._ProcessIncludes(n.join(""),t,i)});return}}lY.length=0,r=n.join(""),o?this._ProcessIncludes(r.toString(),t,i):i(r)}static _FileToolsLoadFile(e,t,i,s,r,n){throw Ys("FileTools")}}rv._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;class Ue{static GetShadersRepository(e=Ao.GLSL){return e===Ao.GLSL?Ue.ShadersRepository:Ue.ShadersRepositoryWGSL}static GetShadersStore(e=Ao.GLSL){return e===Ao.GLSL?Ue.ShadersStore:Ue.ShadersStoreWGSL}static GetIncludesShadersStore(e=Ao.GLSL){return e===Ao.GLSL?Ue.IncludesShadersStore:Ue.IncludesShadersStoreWGSL}}Ue.ShadersRepository="src/Shaders/";Ue.ShadersStore={};Ue.IncludesShadersStore={};Ue.ShadersRepositoryWGSL="src/ShadersWGSL/";Ue.ShadersStoreWGSL={};Ue.IncludesShadersStoreWGSL={};class Ws{static get ShadersRepository(){return Ue.ShadersRepository}static set ShadersRepository(e){Ue.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new Se),this._onBindObservable}constructor(e,t,i,s=null,r,n=null,o=null,l=null,c=null,h,u="",p=Ao.GLSL){var m,_,f;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new Se,this.onErrorObservable=new Se,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=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.name=e,this._key=u;let d,C=null;if(t.attributes){const I=t;if(this._engine=i,this._attributesNames=I.attributes,this._uniformsNames=I.uniformsNames.concat(I.samplers),this._samplerList=I.samplers.slice(),this.defines=I.defines,this.onError=I.onError,this.onCompiled=I.onCompiled,this._fallbacks=I.fallbacks,this._indexParameters=I.indexParameters,this._transformFeedbackVaryings=I.transformFeedbackVaryings||null,this._multiTarget=!!I.multiTarget,this._shaderLanguage=(m=I.shaderLanguage)!==null&&m!==void 0?m:Ao.GLSL,I.uniformBuffersNames){this._uniformBuffersNamesList=I.uniformBuffersNames.slice();for(let D=0;D{if(E[0]&&E[1]){b.isFragment=!0;const[I,D]=E;rv.Process(D,b,(R,L)=>{this._fragmentSourceCodeBeforeMigration=L,C&&(R=C("fragment",R));const w=rv.Finalize(I,R,b);b=null,this._useFinalCode(w.vertexCode,w.fragmentCode,e)},this._engine)}};this._loadShader(v,"Vertex","",I=>{rv.Initialize(b),rv.Process(I,b,(D,R)=>{this._rawVertexSourceCode=I,this._vertexSourceCodeBeforeMigration=R,C&&(D=C("vertex",D)),E[0]=D,S()},this._engine)}),this._loadShader(y,"Fragment","Pixel",I=>{this._rawFragmentSourceCode=I,E[1]=I,S()})}_useFinalCode(e,t,i){if(i){const s=i.vertexElement||i.vertex||i.spectorName||i,r=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===Ao.WGSL?"//":"")+"#define SHADER_NAME vertex:"+s+` +`+e,this._fragmentSourceCode=(this._shaderLanguage===Ao.WGSL?"//":"")+"#define SHADER_NAME fragment:"+r+` +`+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;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}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,s){if(typeof HTMLElement<"u"&&e instanceof HTMLElement){const o=OG(e);s(o);return}if(e.substr(0,7)==="source:"){s(e.substr(7));return}if(e.substr(0,7)==="base64:"){const o=window.atob(e.substr(7));s(o);return}const r=Ue.GetShadersStore(this._shaderLanguage);if(r[e+t+"Shader"]){s(r[e+t+"Shader"]);return}if(i&&r[e+i+"Shader"]){s(r[e+i+"Shader"]);return}let n;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?n=e:n=Ue.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",s)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:(t=(e=this._pipelineContext)===null||e===void 0?void 0:e._getVertexShaderCode())!==null&&t!==void 0?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:(t=(e=this._pipelineContext)===null||e===void 0?void 0:e._getFragmentShaderCode())!==null&&t!==void 0?t: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,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(r,n)=>{s&&s(n)},this.onCompiled=()=>{const r=this.getEngine().scenes;if(r)for(let n=0;n{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,e,this._attributes),e)for(let n=0;n=o&&(r=`Offending line [${o}] in ${i?"fragment":"vertex"} code: ${l[o-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i,s,r;this._compilationError=e.message;const n=this._attributesNames,o=this._fallbacks;if(Me.Error("Unable to compile effect:"),Me.Error("Uniforms: "+this._uniformsNames.map(function(c){return" "+c})),Me.Error("Attributes: "+n.map(function(c){return" "+c})),Me.Error(`Defines: +`+this.defines),Ws.LogShaderCodeOnCompilationError){let c=null,h=null,u=null;!((i=this._pipelineContext)===null||i===void 0)&&i._getVertexShaderCode()&&([u,c]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),u&&(Me.Error("Vertex code:"),Me.Error(u))),!((s=this._pipelineContext)===null||s===void 0)&&s._getFragmentShaderCode()&&([u,h]=this._getShaderCodeAndErrorLine((r=this._pipelineContext)===null||r===void 0?void 0:r._getFragmentShaderCode(),this._compilationError,!0),u&&(Me.Error("Fragment code:"),Me.Error(u))),c&&Me.Error(c),h&&Me.Error(h)}Me.Error("Error: "+this._compilationError);const l=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,l()),o?(this._pipelineContext=null,o.hasMoreFallbacks?(this._allFallbacksProcessed=!1,Me.Error("Trying next fallback."),this.defines=o.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,l(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||l())}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 s=this._samplerList.indexOf(e);for(let n=1;n{r._swapAndDie(this,!1),this.isReady=i.isReady};i.isAsync?i.proxy.then(s):s(i.proxy);return}let t;switch(this.source){case hr.Temp:break;case hr.Url:t=this._engine.createTexture((e=this._originalUrl)!==null&&e!==void 0?e:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,i=>{i._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 hr.Raw:t=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,void 0,this._useSRGBBuffer),t._swapAndDie(this,!1),this.isReady=!0;break;case hr.Raw3D:t=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case hr.Raw2DArray:t=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case hr.Dynamic:t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),t._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case hr.Cube:t=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{t._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer);return;case hr.CubeRaw:t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),t._swapAndDie(this,!1),this.isReady=!0;break;case hr.CubeRawRGBD:return;case hr.CubePrefiltered:t=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,i=>{i&&i._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),t._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){var i;(i=this._hardwareTexture)===null||i===void 0||i.setUsage(e._source,this.generateMipMaps,this.isCube,this.width,this.height),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 s=this._engine.getLoadedTexturesCache();let r=s.indexOf(this);r!==-1&&s.splice(r,1),r=s.indexOf(e),r===-1&&s.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._references===0&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}}dn._Counter=0;class Z0e{constructor(){this.shaderLanguage=Ao.GLSL}postProcessor(e,t,i,s,r){if(!r.getCaps().drawBuffersExtension){const n=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(n,"")}return e}}const q0e=/(flat\s)?\s*varying\s*.*/;class B${constructor(){this.shaderLanguage=Ao.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return q0e.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,r=/#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(r,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){const n=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,(s||n?"":`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 qb{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=qb._Counter++}}qb._Counter=0;class OB extends qb{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class joe{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,s,r,n,o,l){const c=this.engine;if(c.supportsUniformBuffers)for(const p in t)e.bindUniformBlock(p,t[p]);this.engine.getUniforms(this,i).forEach((p,m)=>{s[i[m]]=p}),this._uniforms=s;let u;for(u=0;u{n[p]=m});for(const p of c.getAttributes(this,o))l.push(p)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||s.length!==2)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||r.length!==3)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||n.length!==4)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,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,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(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,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(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.toArray())||(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,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(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,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(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 nu{static SetMatrixPrecision(e){if(nu.MatrixTrackPrecisionChange=!1,e&&!nu.MatrixUse64Bits&&nu.MatrixTrackedMatrices)for(let t=0;t1&&!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 Oi._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,s){var r,n,o,l,c,h,u,p,m,_,f;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 Se,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._renderingQueueLaunched=!1,this._activeRenderLoops=new Array,this.onContextLostObservable=new Se,this.onContextRestoredObservable=new Se,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new w$,this._stencilStateComposer=new F$,this._stencilState=new kM,this._alphaState=new Hoe,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._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._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,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 Se,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=Zr.Now;let d=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=s??!1,this._stencilStateComposer.stencilGlobal=this._stencilState,nu.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=t??i.antialias,i.deterministicLockstep=(r=i.deterministicLockstep)!==null&&r!==void 0?r:!1,i.lockstepMaxSteps=(n=i.lockstepMaxSteps)!==null&&n!==void 0?n:4,i.timeStep=(o=i.timeStep)!==null&&o!==void 0?o:1/60,i.audioEngine=(l=i.audioEngine)!==null&&l!==void 0?l:!0,i.stencil=(c=i.stencil)!==null&&c!==void 0?c:!0,this._audioContext=(u=(h=i.audioEngineOptions)===null||h===void 0?void 0:h.audioContext)!==null&&u!==void 0?u:null,this._audioDestination=(m=(p=i.audioEngineOptions)===null||p===void 0?void 0:p.audioDestination)!==null&&m!==void 0?m:null,this.premultipliedAlpha=(_=i.premultipliedAlpha)!==null&&_!==void 0?_:!0,this.useExactSrgbConversions=(f=i.useExactSrgbConversions)!==null&&f!==void 0?f:!1,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,s=s||i.adaptToDeviceRatio||!1;const C=ql()&&window.devicePixelRatio||1,v=i.limitDeviceRatio||C;if(this._hardwareScalingLevel=s?1/Math.min(v,C):1,this._lastDevicePixelRatio=C,!e)return;if(e.getContext){if(d=e,this._renderingCanvas=d,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const M=navigator.userAgent;for(const b of Oi.ExceptionList){const E=b.key,S=b.targets;if(new RegExp(E).test(M)){if(b.capture&&b.captureConstraint){const D=b.capture,R=b.captureConstraint,w=new RegExp(D).exec(M);if(w&&w.length>0&&parseInt(w[w.length-1])>=R)continue}for(const D of S)switch(D){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=M=>{M.preventDefault(),this._contextWasLost=!0,Me.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(this._initGLContext.bind(this))},d.addEventListener("webglcontextlost",this._onContextLost,!1),d.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=d.getContext("webgl2",i)||d.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(!d)throw new Error("The provided canvas is null or undefined.");try{this._gl=d.getContext("webgl",i)||d.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 M=this._gl.getContextAttributes();M&&(i.stencil=M.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 M=0;M1?new B$:new Z0e,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const y=`Babylon.js v${Oi.Version}`;console.log(y+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",y)}_setupMobileChecks(){!(navigator&&navigator.userAgent)||(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&Zb()&&"ontouchend"in document},this._checkForMobile(),ql()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null;const i=this._depthCullingState.depthTest,s=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),(t=this._rebuildComputeEffects)===null||t===void 0||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=i,this._depthCullingState.depthFunc=s,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=n,Me.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},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._wasPreviouslyReady=!1,t._prepareEffect()}Ws.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._rebuild();for(const e of this._storageBuffers)e._rebuild()}_initGLContext(){var e;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")),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._glVersion=this._gl.getParameter(this._gl.VERSION);const t=this._gl.getExtension("WEBGL_debug_renderer_info");if(t!=null&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.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=((e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))!==null&&e!==void 0?e: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 i=this._gl.getExtension("WEBGL_draw_buffers");if(i!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=i.drawBuffersWEBGL.bind(i),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let s=0;s<16;s++)this._gl["COLOR_ATTACHMENT"+s+"_WEBGL"]=i["COLOR_ATTACHMENT"+s+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const i=this._gl.getExtension("WEBGL_depth_texture");i!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=i.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const i=this._gl.getExtension("OES_vertex_array_object");i!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=i.createVertexArrayOES.bind(i),this._gl.bindVertexArray=i.bindVertexArrayOES.bind(i),this._gl.deleteVertexArray=i.deleteVertexArrayOES.bind(i))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const i=this._gl.getExtension("ANGLE_instanced_arrays");i!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=i.drawArraysInstancedANGLE.bind(i),this._gl.drawElementsInstanced=i.drawElementsInstancedANGLE.bind(i),this._gl.vertexAttribDivisor=i.vertexAttribDivisorANGLE.bind(i)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const i=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),s=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);i&&s&&(this._caps.highPrecisionShaderSupported=i.precision!==0&&s.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const i=this._gl.getExtension("EXT_blend_minmax");i!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=i.MAX_EXT,this._gl.MIN=i.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 i=this._gl.getExtension("EXT_sRGB");i!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:i.SRGB_EXT,SRGB8:i.SRGB_ALPHA_EXT,SRGB8_ALPHA8:i.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 i=0;i=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._renderingQueueLaunched&&this._frameHandler){if(this._renderingQueueLaunched=!1,ql()){const{cancelAnimationFrame:e}=this.getHostWindow()||window;if(typeof e=="function")return e(this._frameHandler)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(this._frameHandler);return clearTimeout(this._frameHandler)}}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let t=0;t0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return ql()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}_queueNewFrame(e,t){return Oi.QueueNewFrame(e,t)}runRenderLoop(e){this._activeRenderLoops.indexOf(e)===-1&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=this._renderLoop.bind(this),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,i,s=!1){var r,n;const o=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=o;let l=0;if(t&&e){let c=!0;if(this._currentRenderTarget){const h=(r=this._currentRenderTarget.texture)===null||r===void 0?void 0:r.format;if(h===8||h===9||h===10||h===11){const u=(n=this._currentRenderTarget.texture)===null||n===void 0?void 0:n.type;u===7||u===5?(Oi._TempClearColorUint32[0]=e.r*255,Oi._TempClearColorUint32[1]=e.g*255,Oi._TempClearColorUint32[2]=e.b*255,Oi._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,Oi._TempClearColorUint32),c=!1):(Oi._TempClearColorInt32[0]=e.r*255,Oi._TempClearColorInt32[1]=e.g*255,Oi._TempClearColorInt32[2]=e.b*255,Oi._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,Oi._TempClearColorInt32),c=!1)}}c&&(this._gl.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),l|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),l|=this._gl.DEPTH_BUFFER_BIT),s&&(this._gl.clearStencil(0),l|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(l)}_viewport(e,t,i,s){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||s!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=s,this._gl.viewport(e,t,i,s))}setViewport(e,t,i){const s=t||this.getRenderWidth(),r=i||this.getRenderHeight(),n=e.x||0,o=e.y||0;this._cachedViewport=e,this._viewport(n*s,o*r,s*e.width,r*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const s=ql()&&window.devicePixelRatio||1,r=this._lastDevicePixelRatio/s;this._lastDevicePixelRatio=s,this._hardwareScalingLevel*=r}if(ql()&&Zb())if(this._renderingCanvas){const s=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||s.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||s.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){return!this._renderingCanvas||(e=e|0,t=t|0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t)?!1:(this._renderingCanvas.width=e,this._renderingCanvas.height=t,!0)}bindFramebuffer(e,t=0,i,s,r,n=0,o=0){var l,c,h,u,p;const m=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(m._MSAAFramebuffer?m._MSAAFramebuffer:m._framebuffer);const _=this._gl;e.isMulti||(e.is2DArray?_.framebufferTextureLayer(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,(l=e.texture._hardwareTexture)===null||l===void 0?void 0:l.underlyingResource,n,o):e.isCube&&_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_CUBE_MAP_POSITIVE_X+t,(c=e.texture._hardwareTexture)===null||c===void 0?void 0:c.underlyingResource,n));const f=e._depthStencilTexture;if(f){const d=e._depthStencilTextureWithStencil?_.DEPTH_STENCIL_ATTACHMENT:_.DEPTH_ATTACHMENT;e.is2DArray?_.framebufferTextureLayer(_.FRAMEBUFFER,d,(h=f._hardwareTexture)===null||h===void 0?void 0:h.underlyingResource,n,o):e.isCube?_.framebufferTexture2D(_.FRAMEBUFFER,d,_.TEXTURE_CUBE_MAP_POSITIVE_X+t,(u=f._hardwareTexture)===null||u===void 0?void 0:u.underlyingResource,n):_.framebufferTexture2D(_.FRAMEBUFFER,d,_.TEXTURE_2D,(p=f._hardwareTexture)===null||p===void 0?void 0:p.underlyingResource,n)}this._cachedViewport&&!r?this.setViewport(this._cachedViewport,i,s):(i||(i=e.width,n&&(i=i/Math.pow(2,n))),s||(s=e.height,n&&(s=s/Math.pow(2,n))),this._viewport(0,0,i,s)),this.wipeCaches()}setState(e,t=0,i,s=!1,r,n,o=0){var l,c;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const h=!((c=(l=this.cullBackFaces)!==null&&l!==void 0?l:r)!==null&&c!==void 0)||c?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(o);const u=s?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==u||i)&&(this._depthCullingState.frontFace=u),this._stencilStateComposer.stencilMaterial=n}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){const e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){const e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return this._currentFramebuffer===null}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,i){var s;const r=e;this._currentRenderTarget=null;const n=this._gl;if(r._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}n.bindFramebuffer(n.READ_FRAMEBUFFER,r._MSAAFramebuffer),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,r._framebuffer),n.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.NEAREST)}((s=e.texture)===null||s===void 0?void 0:s.generateMipMaps)&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(r._MSAAFramebuffer&&this._bindUnboundFramebuffer(r._framebuffer),i()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");const s=new OB(i);return this.bindArrayBuffer(s),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),this._resetVertexBufferBinding(),s.references=1,s}createDynamicVertexBuffer(e){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t){const i=this._gl.createBuffer(),s=new OB(i);if(!i)throw new Error("Unable to create index buffer");this.bindIndexBuffer(s);const r=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),s.references=1,s.is32Bits=r.BYTES_PER_ELEMENT===4,s}_normalizeIndexData(e){if(e.BYTES_PER_ELEMENT===2)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let i=0;i=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 s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,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,s,r,n,o){const l=this._currentBufferPointers[t];if(!l)return;let c=!1;l.active?(l.buffer!==e&&(l.buffer=e,c=!0),l.size!==i&&(l.size=i,c=!0),l.type!==s&&(l.type=s,c=!0),l.normalized!==r&&(l.normalized=r,c=!0),l.stride!==n&&(l.stride=n,c=!0),l.offset!==o&&(l.offset=o,c=!0)):(c=!0,l.active=!0,l.index=t,l.size=i,l.type=s,l.normalized=r,l.stride=n,l.offset=o,l.buffer=e),(c||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,o):this._gl.vertexAttribPointer(t,i,s,r,n,o))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r=0){const o=s[r];let l=null;if(i&&(l=i[o]),l||(l=e[o]),!l)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const c=l.getBuffer();c&&(this._vertexAttribPointer(c,n,l.getSize(),l.type,l.normalized,l.byteStride,l.byteOffset),l.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,l.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(c))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}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,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const n=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let o=0;for(let l=0;l=0&&(this._gl.enableVertexAttribArray(c),this._vertexAttribArraysEnabled[c]=!0,this._vertexAttribPointer(e,c,i[l],this._gl.FLOAT,!1,s,o)),o+=i[l]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){!this._cachedVertexArrayObject||(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1?`#version 300 es +#define WEBGL2 +`:"",l=this._compileShader(t,"vertex",s,o),c=this._compileShader(i,"fragment",s,o);return this._createShaderProgram(e,l,c,r,n)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new joe;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");return s.attachShader(n,t),s.attachShader(n,i),s.linkProgram(n),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_finalizePipelineContext(e){const t=e.context,i=e.vertexShader,s=e.fragmentShader,r=e.program;if(!t.getProgramParameter(r,t.LINK_STATUS)){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){const l=this._gl.getShaderInfoLog(i);if(l)throw e.vertexCompilationError=l,new Error("VERTEX SHADER "+l)}if(!this._gl.getShaderParameter(s,this._gl.COMPILE_STATUS)){const l=this._gl.getShaderInfoLog(s);if(l)throw e.fragmentCompilationError=l,new Error("FRAGMENT SHADER "+l)}const o=t.getProgramInfoLog(r);if(o)throw e.programLinkError=o,new Error(o)}if(this.validateShaderPrograms&&(t.validateProgram(r),!t.getProgramParameter(r,t.VALIDATE_STATUS))){const l=t.getProgramInfoLog(r);if(l)throw e.programValidationError=l,new Error(l)}t.deleteShader(i),t.deleteShader(s),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,s,r,n,o,l,c,h){const u=e;s?u.program=this.createRawShaderProgram(u,t,i,void 0,c):u.program=this.createShaderProgram(u,t,i,l,void 0,c),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 s=i.onCompiled;s?i.onCompiled=()=>{s(),t()}:i.onCompiled=t}getUniforms(e,t){const i=new Array,s=e;for(let r=0;r1||this.isWebGPU)),(o===1&&!this._caps.textureFloatLinearFiltering||o===2&&!this._caps.textureHalfFloatLinearFiltering)&&(l=1),o===1&&!this._caps.textureFloat&&(o=0,Me.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const m=this._gl,_=new dn(this,s),f=e.width||e,d=e.height||e,C=e.layers||0,v=this._getSamplingParameters(l,n),y=C!==0?m.TEXTURE_2D_ARRAY:m.TEXTURE_2D,M=this._getRGBABufferInternalSizedFormat(o,c,h),b=this._getInternalFormat(c),E=this._getWebGLTextureType(o);return this._bindTextureDirectly(y,_),C!==0?(_.is2DArray=!0,m.texImage3D(y,0,M,f,d,C,0,b,E,null)):m.texImage2D(y,0,M,f,d,0,b,E,null),m.texParameteri(y,m.TEXTURE_MAG_FILTER,v.mag),m.texParameteri(y,m.TEXTURE_MIN_FILTER,v.min),m.texParameteri(y,m.TEXTURE_WRAP_S,m.CLAMP_TO_EDGE),m.texParameteri(y,m.TEXTURE_WRAP_T,m.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(y),this._bindTextureDirectly(y,null),_._useSRGBBuffer=h,_.baseWidth=f,_.baseHeight=d,_.width=f,_.height=d,_.depth=C,_.isReady=!0,_.samples=u,_.generateMipMaps=n,_.samplingMode=l,_.type=o,_.format=c,_.label=p,this._internalTexturesCache.push(_),_}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,s,r=3,n=null,o=null,l,c,h=null,u=null,p=null,m=null,_,f,d){e=e||"";const C=e.substr(0,5)==="data:",v=e.substr(0,5)==="blob:",y=C&&e.indexOf(";base64,")!==-1,M=u||new dn(this,hr.Url);M!==u&&(M.label=e.substring(0,60));const b=e;this._transformTextureUrl&&!y&&!u&&!h&&(e=this._transformTextureUrl(e)),b!==e&&(M._originalUrl=b);const E=e.lastIndexOf(".");let S=m||(E>-1?e.substring(E).toLowerCase():""),I=null;S.indexOf("?")>-1&&(S=S.split("?")[0]);for(const w of Oi._TextureLoaders)if(w.canLoad(S,_)){I=w;break}s&&s.addPendingData(M),M.url=e,M.generateMipMaps=!t,M.samplingMode=r,M.invertY=i,M._useSRGBBuffer=this._getUseSRGBBuffer(!!d,t),this._doNotHandleContextLost||(M._buffer=h);let R=null;n&&!u&&(R=M.onLoadedObservable.add(n)),u||this._internalTexturesCache.push(M);const L=(w,N)=>{s&&s.removePendingData(M),e===b?(R&&M.onLoadedObservable.remove(R),Ii.UseFallbackTexture&&this._createTextureBase(Ii.FallbackTexture,t,M.invertY,s,r,null,o,l,c,h,M),w=(w||"Unknown error")+(Ii.UseFallbackTexture?" - Fallback texture was used":""),M.onErrorObservable.notifyObservers({message:w,exception:N}),o&&o(w,N)):(Me.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,M.invertY,s,r,n,o,l,c,h,M,p,m,_,f,d))};if(I){const w=N=>{I.loadData(N,M,(V,W,G,ie,Z,q)=>{q?L("TextureLoader failed to load data"):l(M,S,s,{width:V,height:W},M.invertY,!G,ie,()=>(Z(),!1),r)},f)};h?h instanceof ArrayBuffer?w(new Uint8Array(h)):ArrayBuffer.isView(h)?w(h):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,N=>w(new Uint8Array(N)),void 0,s?s.offlineProvider:void 0,!0,(N,V)=>{L("Unable to load "+(N&&N.responseURL,V))})}else{const w=N=>{v&&!this._doNotHandleContextLost&&(M._buffer=N),l(M,S,s,N,M.invertY,t,!1,c,r)};!C||y?h&&(typeof h.decoding=="string"||h.close)?w(h):Oi._FileToolsLoadImage(e,w,L,s?s.offlineProvider:null,_,M.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof h=="string"||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?Oi._FileToolsLoadImage(h,w,L,s?s.offlineProvider:null,_,M.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&w(h)}return M}createTexture(e,t,i,s,r=3,n=null,o=null,l=null,c=null,h=null,u=null,p,m,_,f){return this._createTextureBase(e,t,i,s,r,n,o,this._prepareWebGLTexture.bind(this),(d,C,v,y,M,b)=>{const E=this._gl,S=v.width===d&&v.height===C,I=h?this._getInternalFormat(h,M._useSRGBBuffer):y===".jpg"&&!M._useSRGBBuffer?E.RGB:M._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:E.RGBA;let D=h?this._getInternalFormat(h):y===".jpg"&&!M._useSRGBBuffer?E.RGB:E.RGBA;if(M._useSRGBBuffer&&this.webGLVersion===1&&(D=I),S)return E.texImage2D(E.TEXTURE_2D,0,I,D,E.UNSIGNED_BYTE,v),!1;const R=this._caps.maxTextureSize;if(v.width>R||v.height>R||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=d,this._workingCanvas.height=C,this._workingContext.drawImage(v,0,0,v.width,v.height,0,0,d,C),E.texImage2D(E.TEXTURE_2D,0,I,D,E.UNSIGNED_BYTE,this._workingCanvas),M.width=d,M.height=C),!1;{const L=new dn(this,hr.Temp);this._bindTextureDirectly(E.TEXTURE_2D,L,!0),E.texImage2D(E.TEXTURE_2D,0,I,D,E.UNSIGNED_BYTE,v),this._rescaleTexture(L,M,s,I,()=>{this._releaseTexture(L),this._bindTextureDirectly(E.TEXTURE_2D,M,!0),b()})}return!0},l,c,h,u,p,m,f)}static _FileToolsLoadImage(e,t,i,s,r,n){throw Ys("FileTools")}_rescaleTexture(e,t,i,s,r){}createRawTexture(e,t,i,s,r,n,o,l=null,c=0,h=0,u=!1){throw Ys("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,r,n,o,l=null){throw Ys("Engine.RawTexture")}createRawTexture3D(e,t,i,s,r,n,o,l,c=null,h=0){throw Ys("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,r,n,o,l,c=null,h=0){throw Ys("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 s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_setupDepthStencilTexture(e,t,i,s,r,n=1){const o=t.width||t,l=t.height||t,c=t.layers||0;e.baseWidth=o,e.baseHeight=l,e.width=o,e.height=l,e.is2DArray=c>0,e.depth=c,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const h=this._gl,u=this._getTextureTarget(e),p=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(u,h.TEXTURE_MAG_FILTER,p.mag),h.texParameteri(u,h.TEXTURE_MIN_FILTER,p.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&&(r===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,r),h.texParameteri(u,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){const l=this._gl;let c=l.TEXTURE_2D;if(e.isCube&&(c=l.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}this._gl.compressedTexImage2D(c,o,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const o=this._gl,l=this._getWebGLTextureType(e.type),c=this._getInternalFormat(e.format),h=r===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let u=o.TEXTURE_2D;e.isCube&&(u=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const p=Math.round(Math.log(e.width)*Math.LOG2E),m=Math.round(Math.log(e.height)*Math.LOG2E),_=n?e.width:Math.pow(2,Math.max(p-s,0)),f=n?e.height:Math.pow(2,Math.max(m-s,0));o.texImage2D(u,s,h,_,f,0,c,l,t)}updateTextureData(e,t,i,s,r,n,o=0,l=0,c=!1){const h=this._gl,u=this._getWebGLTextureType(e.type),p=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let m=h.TEXTURE_2D,_=h.TEXTURE_2D;e.isCube&&(_=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,m=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(m,e,!0),h.texSubImage2D(_,l,i,s,r,n,p,u,t),c&&this._gl.generateMipmap(_),this._bindTextureDirectly(m,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const o=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.min),!i&&!s&&n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,o,l,c=3){const h=this.getCaps().maxTextureSize,u=Math.min(h,this.needPOTTextures?Oi.GetExponentOfTwo(s.width,h):s.width),p=Math.min(h,this.needPOTTextures?Oi.GetExponentOfTwo(s.height,h):s.height),m=this._gl;if(!!m){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(m.TEXTURE_2D,e,!0),this._unpackFlipY(r===void 0?!0:!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=p,e.isReady=!0,e.type=0,e.format=t===".jpg"&&!e._useSRGBBuffer?4:5,!l(u,p,s,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,n,o,c)})&&this._prepareWebGLTextureContinuation(e,i,n,o,c)}}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let o=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(o=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,o,o,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,o=!0){const c=this._gl.createRenderbuffer();return this._updateRenderBuffer(c,e,t,i,s,r,n,o)}_updateRenderBuffer(e,t,i,s,r,n,o,l=!0){const c=this._gl;return c.bindRenderbuffer(c.RENDERBUFFER,e),s>1&&c.renderbufferStorageMultisample?c.renderbufferStorageMultisample(c.RENDERBUFFER,s,n,t,i):c.renderbufferStorage(c.RENDERBUFFER,r,t,i),c.framebufferRenderbuffer(c.FRAMEBUFFER,o,c.RENDERBUFFER,e),l&&c.bindRenderbuffer(c.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture((t=e._hardwareTexture)===null||t===void 0?void 0:t.underlyingResource),this.unbindAllTextures();const i=this._internalTexturesCache.indexOf(e);i!==-1&&this._internalTexturesCache.splice(i,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 s=0;s-1;if(i&&l&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw console.error(e,t),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,(n=(r=t?._hardwareTexture)===null||r===void 0?void 0:r.underlyingResource)!==null&&n!==void 0?n:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(o=!0,this._activateCurrentTexture());return l&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),o}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,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,s){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,s=!1,r=""){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 c=t.getInternalTexture();c&&(c._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let n;s?n=t.depthStencilTexture:t.isReady()?n=t.getInternalTexture():t.isCube?n=this.emptyCubeTexture:t.is3D?n=this.emptyTexture3D:t.is2DArray?n=this.emptyTexture2DArray:n=this.emptyTexture,!i&&n&&(n._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),o=!1),this._activeChannel=e;const l=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(l,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const c=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=c,t.wrapV=c}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(l,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let r=0;r=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;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===void 0||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},ql()&&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,Ws.ResetCache();for(const t of this._activeRequests)t.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}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 s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),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 r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===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,l=t.UNSIGNED_BYTE,c=new Uint8Array(4);t.readPixels(0,0,1,1,o,l,c),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),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}_getRGBAMultiSampleBufferFormat(e,t=5){switch(e){case 1:switch(t){case 6:return this._gl.R32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;default:return this._gl.RGBA16F}}return this._gl.RGBA8}_loadFile(e,t,i,s,r,n){const o=Oi._FileToolsLoadFile(e,t,i,s,r,n);return this._activeRequests.push(o),o.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),o}static _FileToolsLoadFile(e,t,i,s,r,n){throw Ys("FileTools")}readPixels(e,t,i,s,r=!0,n=!0){const o=r?4:3,l=r?this._gl.RGBA:this._gl.RGB,c=new Uint8Array(s*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,l,this._gl.UNSIGNED_BYTE,c),Promise.resolve(c)}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=Oi.CeilingPOT(e),i=Oi.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let s;switch(i){case 1:s=Oi.FloorPOT(e);break;case 2:s=Oi.NearestPOT(e);break;case 3:default:s=Oi.CeilingPOT(e);break}return Math.min(s,t)}static QueueNewFrame(e,t){if(ql()){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:Zb()?document:null}}Oi._TempClearColorUint32=new Uint32Array(4);Oi._TempClearColorInt32=new Int32Array(4);Oi.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:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}];Oi._TextureLoaders=[];Oi.CollisionsEpsilon=.001;Oi._IsSupported=null;Oi._HasMajorPerformanceCaveat=null;class wB{static SetImmediate(e){ql()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const Goe=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class NB extends nC{constructor(e,t){super(e,XM.LoadFileError),this.name="LoadFileError",UP._setPrototypeOf(this,NB.prototype),t instanceof wl?this.request=t:this.file=t}}class Oj extends nC{constructor(e,t){super(e,XM.RequestFileError),this.request=t,this.name="RequestFileError",UP._setPrototypeOf(this,Oj.prototype)}}class mK extends nC{constructor(e,t){super(e,XM.ReadFileError),this.file=t,this.name="ReadFileError",UP._setPrototypeOf(this,mK.prototype)}}const Kd={DefaultRetryStrategy:Voe.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:a=>a},Woe=a=>(a=a.replace(/#/gm,"%23"),a),_K=(a,e)=>{if(!(a&&a.indexOf("data:")===0)&&Kd.CorsBehavior)if(typeof Kd.CorsBehavior=="string"||Kd.CorsBehavior instanceof String)e.crossOrigin=Kd.CorsBehavior;else{const t=Kd.CorsBehavior(a);t&&(e.crossOrigin=t)}},vF=(a,e,t,i,s="",r)=>{var n;let o,l=!1;a instanceof ArrayBuffer||ArrayBuffer.isView(a)?typeof Blob<"u"&&typeof URL<"u"?(o=URL.createObjectURL(new Blob([a],{type:s})),l=!0):o=`data:${s};base64,`+wG(a):a instanceof Blob?(o=URL.createObjectURL(a),l=!0):(o=Woe(a),o=Kd.PreprocessUrl(a));const c=Ii.LastCreatedEngine,h=E=>{if(t){const S=o||a.toString();t(`Error while trying to load image: ${S.indexOf("http")===0||S.length<=128?S:S.slice(0,128)+"..."}`,E)}};if(typeof Image>"u"||((n=c?._features.forceBitmapOverHTMLImageElement)!==null&&n!==void 0?n:!1))return CI(o,E=>{c.createImageBitmap(new Blob([E],{type:s}),Object.assign({premultiplyAlpha:"none"},r)).then(S=>{e(S),l&&URL.revokeObjectURL(o)}).catch(S=>{t&&t("Error while trying to load image: "+a,S)})},void 0,i||void 0,!0,(E,S)=>{h(S)}),null;const u=new Image;_K(o,u);const p=[],m=()=>{p.forEach(E=>{E.target.addEventListener(E.name,E.handler)})},_=()=>{p.forEach(E=>{E.target.removeEventListener(E.name,E.handler)}),p.length=0},f=()=>{_(),e(u),l&&u.src&&URL.revokeObjectURL(u.src)},d=E=>{_(),h(E),l&&u.src&&URL.revokeObjectURL(u.src)},C=E=>{if(E.blockedURI!==u.src)return;_();const S=new Error(`CSP violation of policy ${E.effectiveDirective} ${E.blockedURI}. Current policy is ${E.originalPolicy}`);Ii.UseFallbackTexture=!1,h(S),l&&u.src&&URL.revokeObjectURL(u.src),u.src=""};p.push({target:u,name:"load",handler:f}),p.push({target:u,name:"error",handler:d}),p.push({target:document,name:"securitypolicyviolation",handler:C}),m();const v=o.substring(0,5)==="blob:",y=o.substring(0,5)==="data:",M=()=>{v||y?u.src=o:CI(o,(E,S,I)=>{const D=!s&&I?I:s,R=new Blob([E],{type:D}),L=URL.createObjectURL(R);l=!0,u.src=L},void 0,i||void 0,!0,(E,S)=>{h(S)})},b=()=>{i&&i.loadImage(o,u)};if(!v&&!y&&i&&i.enableTexturesOffline)i.open(b,M);else{if(o.indexOf("file:")!==-1){const E=decodeURIComponent(o.substring(5).toLowerCase());if(MP.FilesToLoad[E]&&typeof URL<"u"){try{let S;try{S=URL.createObjectURL(MP.FilesToLoad[E])}catch{S=URL.createObjectURL(MP.FilesToLoad[E])}u.src=S,l=!0}catch{u.src=""}return u}}M()}return u},BB=(a,e,t,i,s)=>{const r=new FileReader,n={onCompleteObservable:new Se,abort:()=>r.abort()};return r.onloadend=()=>n.onCompleteObservable.notifyObservers(n),s&&(r.onerror=()=>{s(new mK(`Unable to read ${a.name}`,a))}),r.onload=o=>{e(o.target.result)},t&&(r.onprogress=t),i?r.readAsArrayBuffer(a):r.readAsText(a),n},CI=(a,e,t,i,s,r,n)=>{if(a.name)return BB(a,e,t,s,r?h=>{r(void 0,h)}:void 0);const o=a;if(o.indexOf("file:")!==-1){let h=decodeURIComponent(o.substring(5).toLowerCase());h.indexOf("./")===0&&(h=h.substring(2));const u=MP.FilesToLoad[h];if(u)return BB(u,e,t,s,r?p=>r(void 0,new NB(p.message,p.file)):void 0)}const{match:l,type:c}=Yoe(o);if(l){const h={onCompleteObservable:new Se,abort:()=>()=>{}};try{const u=s?CF(o):z$(o);e(u,void 0,c)}catch(u){r?r(void 0,u):Me.Error(u.message||"Failed to parse the Data URL")}return wB.SetImmediate(()=>{h.onCompleteObservable.notifyObservers(h)}),h}return gK(o,(h,u)=>{e(h,u?.responseURL,u?.getResponseHeader("content-type"))},t,i,s,r?h=>{r(h.request,new NB(h.message,h.request))}:void 0,n)},gK=(a,e,t,i,s,r,n)=>{a=Woe(a),a=Kd.PreprocessUrl(a);const o=Kd.BaseUrl+a;let l=!1;const c={onCompleteObservable:new Se,abort:()=>l=!0},h=()=>{let u=new wl,p=null,m;const _=()=>{!u||(t&&u.removeEventListener("progress",t),m&&u.removeEventListener("readystatechange",m),u.removeEventListener("loadend",f))};let f=()=>{_(),c.onCompleteObservable.notifyObservers(c),c.onCompleteObservable.clear(),t=void 0,m=null,f=null,r=void 0,n=void 0,e=void 0};c.abort=()=>{l=!0,f&&f(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),p!==null&&(clearTimeout(p),p=null),u=null};const d=v=>{const y=v.message||"Unknown error";r&&u?r(new Oj(y,u)):Me.Error(y)},C=v=>{if(!!u){if(u.open("GET",o),n)try{n(u)}catch(y){d(y);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),f&&u.addEventListener("loadend",f),m=()=>{if(!(l||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(m&&u.removeEventListener("readystatechange",m),u.status>=200&&u.status<300||u.status===0&&(!ql()||V$())){try{e&&e(s?u.response:u.responseText,u)}catch(b){d(b)}return}const y=Kd.DefaultRetryStrategy;if(y){const b=y(o,u,v);if(b!==-1){_(),u=new wl,p=setTimeout(()=>C(v+1),b);return}}const M=new Oj("Error status: "+u.status+" "+u.statusText+" - Unable to load "+o,u);r&&r(M)}},u.addEventListener("readystatechange",m),u.send()}};C(0)};if(i&&i.enableSceneOffline){const u=m=>{m&&m.status>400?r&&r(m):h()},p=()=>{i&&i.loadFile(Kd.BaseUrl+a,m=>{!l&&e&&e(m),c.onCompleteObservable.notifyObservers(c)},t?m=>{!l&&t&&t(m)}:void 0,u,s)};i.open(p,u)}else h();return c},V$=()=>typeof location<"u"&&location.protocol==="file:",BG=a=>Goe.test(a),Yoe=a=>{const e=Goe.exec(a);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function CF(a){return NG(a.split(",")[1])}const z$=a=>pK(a.split(",")[1]),$0e=()=>{Oi._FileToolsLoadImage=vF,Oi._FileToolsLoadFile=CI,rv._FileToolsLoadFile=CI};$0e();let SN;const Xoe=(a,e,t,i,s,r,n,o,l,c)=>{SN={DecodeBase64UrlToBinary:a,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:s,LoadFile:r,LoadImage:n,ReadFile:o,RequestFile:l,SetCorsBehavior:c},Object.defineProperty(SN,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(h){t.DefaultRetryStrategy=h}}),Object.defineProperty(SN,"BaseUrl",{get:function(){return t.BaseUrl},set:function(h){t.BaseUrl=h}}),Object.defineProperty(SN,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(h){t.PreprocessUrl=h}}),Object.defineProperty(SN,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(h){t.CorsBehavior=h}})};Xoe(CF,z$,Kd,BG,V$,CI,vF,BB,gK,_K);const Koe={};function $e(a,e){Koe[a]=e}function Bo(a){return Koe[a]}class mj{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Bo(e);if(t)return t;Me.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let r=0,n=i.length;r{const e=Math.random()*16|0;return(a==="x"?e:e&3|8).toString(16)})}const e3e={RandomId:WL};class Be{static get BaseUrl(){return Kd.BaseUrl}static set BaseUrl(e){Kd.BaseUrl=e}static get DefaultRetryStrategy(){return Kd.DefaultRetryStrategy}static set DefaultRetryStrategy(e){Kd.DefaultRetryStrategy=e}static get CorsBehavior(){return Kd.CorsBehavior}static set CorsBehavior(e){Kd.CorsBehavior=e}static get UseFallbackTexture(){return Ii.UseFallbackTexture}static set UseFallbackTexture(e){Ii.UseFallbackTexture=e}static get RegisteredExternalClasses(){return mj.RegisteredExternalClasses}static set RegisteredExternalClasses(e){mj.RegisteredExternalClasses=e}static get fallbackTexture(){return Ii.FallbackTexture}static set fallbackTexture(e){Ii.FallbackTexture=e}static FetchToRef(e,t,i,s,r,n){const o=Math.abs(e)*i%i|0,l=Math.abs(t)*s%s|0,c=(o+l*i)*4;n.r=r[c]/255,n.g=r[c+1]/255,n.b=r[c+2]/255,n.a=r[c+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return mj.Instantiate(e)}static SetImmediate(e){wB.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do t*=2;while(t{CI(e,r=>{i(r)},void 0,void 0,t,(r,n)=>{s(n)})})}static LoadScript(e,t,i,s){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(o){i?.(`Unable to load script '${e}' in worker`,o)}return}else if(!ql()){i?.(`Cannot load script '${e}' outside of a window or a worker`);return}const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=o=>{i&&i(`Unable to load script '${e}'`,o)},r.appendChild(n)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(s,r)=>{i(r||new Error(s))})})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new Se,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=n=>{t(n.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return BB(e,t,i,s,r)}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,s){e2.DeepCopy(e,t,i,s)}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 l=atob(this.toDataURL(n,o).split(",")[1]),c=l.length,h=new Uint8Array(c);for(let u=0;ut(r)):e.toBlob(function(r){t(r)},i,s)}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"}Be.Download(e,t)}else if(e&&typeof URL<"u"){const i=URL.createObjectURL(e),s=window.open("");if(!s)return;const r=s.document.createElement("img");r.onload=function(){URL.revokeObjectURL(i)},r.src=i,s.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if(typeof s=="string"||!t)this.ToBlob(e,function(n){n&&Be.DownloadBlob(n,s),t&&t("")},i,r);else if(t){if(Be._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:r}).then(o=>{const l=new FileReader;l.readAsDataURL(o),l.onloadend=()=>{const c=l.result;t(c)}});return}const n=e.toDataURL(i,r);t(n)}}static Download(e,t){if(typeof URL>"u")return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",()=>{s.parentElement&&s.parentElement.removeChild(s)}),s.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,s,r="image/png",n=!1,o){throw Ys("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw Ys("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,o=!1,l,c=!1,h=!1,u=!0,p){throw Ys("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,o,l=!1,c=!1,h=!0,u){throw Ys("ScreenshotTools")}static RandomId(){return WL()}static IsBase64(e){return BG(e)}static DecodeBase64(e){return CF(e)}static get errorsCount(){return Me.errorsCount}static Log(e){Me.Log(e)}static Warn(e){Me.Warn(e)}static Error(e){Me.Error(e)}static get LogCache(){return Me.LogCache}static ClearLogCache(){Me.ClearLogCache()}static set LogLevels(e){Me.LogLevels=e}static set PerformanceLogLevel(e){if((e&Be.PerformanceUserMarkLogLevel)===Be.PerformanceUserMarkLogLevel){Be.StartPerformanceCounter=Be._StartUserMark,Be.EndPerformanceCounter=Be._EndUserMark;return}if((e&Be.PerformanceConsoleLogLevel)===Be.PerformanceConsoleLogLevel){Be.StartPerformanceCounter=Be._StartPerformanceConsole,Be.EndPerformanceCounter=Be._EndPerformanceConsole;return}Be.StartPerformanceCounter=Be._StartPerformanceCounterDisabled,Be.EndPerformanceCounter=Be._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Be._Performance){if(!ql())return;Be._Performance=window.performance}!t||!Be._Performance.mark||Be._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!Be._Performance.mark||(Be._Performance.mark(e+"-End"),Be._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){!t||(Be._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){!t||(Be._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return Zr.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,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(s!=null?s+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return pP()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}Be.UseCustomRequestHeaders=!1;Be.CustomRequestHeaders=wl.CustomRequestHeaders;Be._TmpFloatArray=new Float32Array(1);Be.GetDOMTextContent=OG;Be.GetAbsoluteUrl=typeof document=="object"?a=>{const e=document.createElement("a");return e.href=a,e.href}:typeof URL=="function"&&typeof location=="object"?a=>new URL(a,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};Be.NoneLogLevel=Me.NoneLogLevel;Be.MessageLogLevel=Me.MessageLogLevel;Be.WarningLogLevel=Me.WarningLogLevel;Be.ErrorLogLevel=Me.ErrorLogLevel;Be.AllLogLevel=Me.AllLogLevel;Be.IsWindowObjectExist=ql;Be.PerformanceNoneLogLevel=0;Be.PerformanceUserMarkLogLevel=1;Be.PerformanceConsoleLogLevel=2;Be.StartPerformanceCounter=Be._StartPerformanceCounterDisabled;Be.EndPerformanceCounter=Be._EndPerformanceCounterDisabled;function t3e(a,e){return t=>{t.__bjsclassName__=a,t.__bjsmoduleName__=e??null}}class $6{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{r&&r()?o.breakLoop():setTimeout(()=>{for(let l=0;l=e)break;if(i(c),r&&r()){o.breakLoop();break}}o.executeNext()},n)},s)}}Ii.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 Sc{constructor(e){this.length=0,this.data=new Array(e),this._id=Sc._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}}Sc._GlobalId=0;class z9 extends Sc{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],s=e(t,i);if(s)return s}return null}}class fL{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),fL._HandleParenthesisContent(i,t))):e=fL._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:fL.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(r=>r==="true");let i;const s=e.split("||");for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r)){let n=fL._SimplifyNegation(s[r].trim());const o=n.split("&&");if(o.length>1)for(let l=0;l(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}class Nr{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Nr.HasTags(e),e.addTags=t=>Nr.AddTagsTo(e,t),e.removeTags=t=>Nr.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Nr.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 s in e._tags)Object.prototype.hasOwnProperty.call(e._tags,s)&&e._tags[s]===!0&&i.push(s);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;t.split(" ").forEach(function(s){Nr._AddTagTo(e,s)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Nr.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Nr.HasTags(e))return;const i=t.split(" ");for(const s in i)Nr._RemoveTagFrom(e,i[s])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?Nr.HasTags(e):fL.Eval(t,i=>Nr.HasTags(e)&&e._tags[i])}}class Bt{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return e=+e,e===0||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}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=Bt.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=Bt.Repeat(e,t*2);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=Bt.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return Math.abs(t-e)<=i?s=t:s=e+Bt.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=Bt.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*Bt.Clamp(i)}static InverseLerp(e,t,i){let s=0;return e!=t?s=Bt.Clamp((i-e)/(t-e)):s=0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,c=-2*o+3*n,h=o-2*n+r,u=o-n;return e*l+i*c+t*h+s*u}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return(n-r)*6*e+(3*n-4*r+1)*t+(-n+r)*6*i+(3*n-2*r)*s}static RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-=Bt.TwoPi*Math.floor((e+Math.PI)/Bt.TwoPi),e}static HCF(e,t){const i=e%t;return i===0?t:Bt.HCF(t,i)}}Bt.TwoPi=Math.PI*2;const GN=1/2.2,_j=2.2,sh=(1+Math.sqrt(5))/2,Ls=.001;class ah{static BuildArray(e,t){const i=[];for(let s=0;s{const r=s.previous;if(!r)return;const n=s.next;n?(r.next=n,n.previous=r):(r.next=void 0,a[e]=r),s.next=void 0,s.previous=void 0}}const s3e=["push","splice","pop","shift","unshift"];function Qoe(a,e){const t=s3e.map(i=>i3e(a,i,e));return()=>{t.forEach(i=>{i?.()})}}const t4=a=>parseInt(a.toString().replace(/\W/g,""));class lt{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=t4(this.x),t=t4(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 lt.FromArrayToRef(e,t,this),this}asArray(){const e=new Array;return this.toArray(e,0),e}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)}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}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.divideToRef(e,this)}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){const t=new this.constructor(0,0);return this.scaleToRef(e,t),t}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=Ls){return e&&Bt.WithinEpsilon(this.x,e.x,t)&&Bt.WithinEpsilon(this.y,e.y,t)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,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 lt.NormalizeToRef(this,this),this}clone(){return new this.constructor(this.x,this.y)}static Zero(){return new lt(0,0)}static One(){return new lt(1,1)}static Random(e=0,t=1){return new lt(Bt.RandomRange(e,t),Bt.RandomRange(e,t))}static get ZeroReadOnly(){return lt._ZeroReadOnly}static FromArray(e,t=0){return new lt(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,l=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*o),c=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*o);return new e.constructor(l,c)}static Clamp(e,t,i){let s=e.x;s=s>i.x?i.x:s,s=si.y?i.y:r,r=rt.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new e.constructor(i,s)}static Transform(e,t){const i=new e.constructor;return lt.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,l=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&l>0&&o+l<2*r*n}static Distance(e,t){return Math.sqrt(lt.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){const i=new e.constructor;return lt.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 s=lt.DistanceSquared(t,i);if(s===0)return lt.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,lt.Dot(e.subtract(t),r)/s)),o=t.add(r.multiplyByFloats(n,n));return lt.Distance(e,o)}}lt._ZeroReadOnly=lt.Zero();class O{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=t4(this._x),t=t4(this._y),i=t4(this._z);let s=e;return s=s*397^t,s=s*397^i,s}asArray(){const e=[];return this.toArray(e,0),e}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 O.FromArrayToRef(e,t,this),this}toQuaternion(){return ke.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this.addInPlaceFromFloats(e._x,e._y,e._z)}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,s){return s.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 s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(r,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,o=e._y,l=e._z,c=e._w,h=2*(o*r-l*s),u=2*(l*i-n*r),p=2*(n*s-o*i);return t._x=i+c*h+o*p-l*u,t._y=s+c*u+l*h-n*p,t._z=r+c*p+n*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 s=e.normal,r=e.d,n=Ks.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=O.Dot(n,s);if(Math.abs(o)this._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(!Bt.WithinEpsilon(t,i,e))return!0;const s=Math.abs(this._z);return!Bt.WithinEpsilon(t,s,e)||!Bt.WithinEpsilon(i,s,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}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}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._x*this._x+this._y*this._y+this._z*this._z)}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){return e=e.toLowerCase(),e==="xyz"?this:(Ks.Vector3[0].copyFrom(this),["x","y","z"].forEach((t,i)=>{this[t]=Ks.Vector3[0][e[i]]}),this)}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(Ks.Matrix[0]),O.TransformCoordinatesToRef(this,Ks.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,Ks.Vector3[0]),Ks.Vector3[0].rotateByQuaternionToRef(e,Ks.Vector3[0]),t.addToRef(Ks.Vector3[0],i),i}cross(e){const t=new this.constructor;return O.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.copyFromFloats(this._x,this._y,this._z):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,s){const r=O.Dot(e,i)-s,n=O.Dot(t,i)-s;return r/(r-n)}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(Ks.Vector3[1]),r=t.normalizeToRef(Ks.Vector3[2]);let n=O.Dot(s,r);n=Bt.Clamp(n,-1,1);const o=Math.acos(n),l=Ks.Vector3[3];return O.CrossToRef(s,r,l),O.Dot(l,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){Ks.Vector3[0].copyFrom(e);const s=Ks.Vector3[0];Ks.Vector3[1].copyFrom(t);const r=Ks.Vector3[1];Ks.Vector3[2].copyFrom(i);const n=Ks.Vector3[2],o=Ks.Vector3[3],l=Ks.Vector3[4];s.normalize(),r.normalize(),n.normalize(),O.CrossToRef(n,s,o),O.CrossToRef(o,n,l);const c=Math.atan2(O.Dot(r,o),O.Dot(r,l));return Bt.NormalizeRadians(c)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=ue.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=O.Zero();return O.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=Bt.Clamp(i,0,1);const r=Ks.Vector3[0],n=Ks.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const l=n.length();n.normalizeFromLength(l);const c=O.Dot(r,n);let h,u;if(c<1-Ls){const p=Math.acos(c),m=1/Math.sin(p);h=Math.sin((1-i)*p)*m,u=Math.sin(i*p)*m}else h=1-i,u=i;return r.scaleInPlace(h),n.scaleInPlace(u),s.copyFrom(r).addInPlace(n),s.scaleInPlace(Bt.Lerp(o,l,i)),s}static SmoothToRef(e,t,i,s,r){return O.SlerpToRef(e,t,s===0?1:i/s,r),r}static FromArray(e,t=0){return new O(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return O.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 O.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new O(0,0,0)}static One(){return new O(1,1,1)}static Up(){return new O(0,1,0)}static get UpReadOnly(){return O._UpReadOnly}static get DownReadOnly(){return O._DownReadOnly}static get RightReadOnly(){return O._RightReadOnly}static get LeftReadOnly(){return O._LeftReadOnly}static get LeftHandedForwardReadOnly(){return O._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return O._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return O._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return O._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return O._ZeroReadOnly}static get OneReadOnly(){return O._OneReadOnly}static Down(){return new O(0,-1,0)}static Forward(e=!1){return new O(0,0,e?-1:1)}static Backward(e=!1){return new O(0,0,e?1:-1)}static Right(){return new O(1,0,0)}static Left(){return new O(-1,0,0)}static Random(e=0,t=1){return new O(Bt.RandomRange(e,t),Bt.RandomRange(e,t),Bt.RandomRange(e,t))}static TransformCoordinates(e,t){const i=O.Zero();return O.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return O.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],l=e*n[1]+t*n[5]+i*n[9]+n[13],c=e*n[2]+t*n[6]+i*n[10]+n[14],h=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=o*h,r._y=l*h,r._z=c*h,r._isDirty=!0,r}static TransformNormal(e,t){const i=O.Zero();return O.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,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,l=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*o),c=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*o),h=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*o);return new e.constructor(l,c,h)}static Clamp(e,t,i){const s=new e.constructor;return O.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:o,o=o0&&R<0?(w.copyFrom(n),N=t,V=i):R>0&&L<0?(w.copyFrom(l),N=i,V=s):(w.copyFrom(o).scaleInPlace(-1),N=s,V=t);const W=Ks.Vector3[9],G=Ks.Vector3[4];if(N.subtractToRef(v,E),V.subtractToRef(v,W),O.CrossToRef(E,W,G),!(O.Dot(G,c)<0))return r.copyFrom(v),Math.abs(f*d);const Z=Ks.Vector3[5];O.CrossToRef(w,G,Z),Z.normalize();const q=Ks.Vector3[9];q.copyFrom(N).subtractInPlace(v);const K=q.length();if(Kthis.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}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}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(){const e=this.length();return e===0?this:this.scaleInPlace(1/e)}toVector3(){return new O(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,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.x=this.y=this.z=this.w=e,this}static FromArray(e,t){return t||(t=0),new Ui(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 Ui.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new Ui(0,0,0,0)}static One(){return new Ui(1,1,1,1)}static Random(e=0,t=1){return new Ui(Bt.RandomRange(e,t),Bt.RandomRange(e,t),Bt.RandomRange(e,t),Bt.RandomRange(e,t))}static get ZeroReadOnly(){return Ui._ZeroReadOnly}static Normalize(e){const t=Ui.Zero();return Ui.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return t.copyFrom(e),t.normalize(),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(Ui.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return Ui.CenterToRef(e,t,Ui.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=Ui.Zero();return Ui.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return Ui.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],l=e*n[1]+t*n[5]+i*n[9]+n[13],c=e*n[2]+t*n[6]+i*n[10]+n[14],h=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=o,r.y=l,r.z=c,r.w=h,r}static TransformNormal(e,t){const i=new e.constructor;return Ui.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],o=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const o=r.m;return n.x=e*o[0]+t*o[4]+i*o[8],n.y=e*o[1]+t*o[5]+i*o[9],n.z=e*o[2]+t*o[6]+i*o[10],n.w=s,n}static FromVector3(e,t=0){return new Ui(e._x,e._y,e._z,t)}}Ui._ZeroReadOnly=Ui.Zero();class ke{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,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){const e=t4(this._x),t=t4(this._y),i=t4(this._z),s=t4(this._w);let r=e;return r=r*397^t,r=r*397^i,r=r*397^s,r}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}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=Ls){return e&&Bt.WithinEpsilon(this._x,e._x,t)&&Bt.WithinEpsilon(this._y,e._y,t)&&Bt.WithinEpsilon(this._z,e._z,t)&&Bt.WithinEpsilon(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,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}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}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,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}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(){const e=this.length();if(e===0)return this;const t=1/e;return this.scaleInPlace(t),this}normalizeToNew(){const e=this.length();if(e===0)return this.clone();const t=1/e;return this.scale(t)}toEulerAngles(){const e=O.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,o=.4999999;if(n<-o)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const l=r*r,c=t*t,h=i*i,u=s*s;e._z=Math.atan2(2*(i*s+t*r),-c-h+u+l),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),c-h-u+l),e._isDirty=!0}return e}toRotationMatrix(e){return ge.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return ke.FromRotationMatrixToRef(e,this),this}static FromRotationMatrix(e){const t=new ke;return ke.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],p=i[10],m=s+l+p;let _;return m>0?(_=.5/Math.sqrt(m+1),t._w=.25/_,t._x=(u-c)*_,t._y=(n-h)*_,t._z=(o-r)*_,t._isDirty=!0):s>l&&s>p?(_=2*Math.sqrt(1+s-l-p),t._w=(u-c)/_,t._x=.25*_,t._y=(r+o)/_,t._z=(n+h)/_,t._isDirty=!0):l>p?(_=2*Math.sqrt(1+l-s-p),t._w=(n-h)/_,t._x=(r+o)/_,t._y=.25*_,t._z=(c+u)/_,t._isDirty=!0):(_=2*Math.sqrt(1+p-s-l),t._w=(o-r)/_,t._x=(n+h)/_,t._y=(c+u)/_,t._z=.25*_,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 s=ke.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=s===0?1:i/s;return n=Bt.Clamp(n,0,1),ke.SlerpToRef(e,t,n,r),r}static Zero(){return new ke(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 ke(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 ke.RotationAxisToRef(e,t,new ke)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new ke(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 FromEulerAngles(e,t,i){const s=new ke;return ke.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return ke.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new ke;return ke.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return ke.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=Ls){const r=O.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(O.CrossToRef(e,t,ue.Vector3[0]),i.set(ue.Vector3[0].x,ue.Vector3[0].y,ue.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new ke;return ke.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=i*.5,n=t*.5,o=e*.5,l=Math.sin(r),c=Math.cos(r),h=Math.sin(n),u=Math.cos(n),p=Math.sin(o),m=Math.cos(o);return s._x=m*h*c+p*u*l,s._y=p*u*c-m*h*l,s._z=m*u*l-p*h*c,s._w=m*u*c+p*h*l,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new ke;return ke.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=(i+e)*.5,n=(i-e)*.5,o=t*.5;return s._x=Math.cos(n)*Math.sin(o),s._y=Math.sin(n)*Math.sin(o),s._z=Math.sin(r)*Math.cos(o),s._w=Math.cos(r)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new ke(0,0,0,0);return ke.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=Ks.Matrix[0];return ge.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),ke.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new ke;return ke.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=Ks.Matrix[0];return ge.LookDirectionLHToRef(e,t,s),ke.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new ke;return ke.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=Ks.Matrix[0];return ge.LookDirectionRHToRef(e,t,s),ke.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=ke.Identity();return ke.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,l=!1;if(o<0&&(l=!0,o=-o),o>.999999)n=1-i,r=l?-i:i;else{const c=Math.acos(o),h=1/Math.sin(c);n=Math.sin((1-i)*c)*h,r=l?-Math.sin(i*c)*h:Math.sin(i*c)*h}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,c=-2*o+3*n,h=o-2*n+r,u=o-n,p=e._x*l+i._x*c+t._x*h+s._x*u,m=e._y*l+i._y*c+t._y*h+s._y*u,_=e._z*l+i._z*c+t._z*h+s._z*u,f=e._w*l+i._w*c+t._w*h+s._w*u;return new e.constructor(p,m,_,f)}static Hermite1stDerivative(e,t,i,s,r){const n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n._x=(o-r)*6*e._x+(3*o-4*r+1)*t._x+(-o+r)*6*i._x+(3*o-2*r)*s._x,n._y=(o-r)*6*e._y+(3*o-4*r+1)*t._y+(-o+r)*6*i._y+(3*o-2*r)*s._y,n._z=(o-r)*6*e._z+(3*o-4*r+1)*t._z+(-o+r)*6*i._z+(3*o-2*r)*s._z,n._w=(o-r)*6*e._w+(3*o-4*r+1)*t._w+(-o+r)*6*i._w+(3*o-2*r)*s._w,n._isDirty=!0,n}}class ge{static get Use64Bits(){return nu.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=ge._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,nu.MatrixTrackPrecisionChange&&nu.MatrixTrackedMatrices.push(this),this._m=new nu.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],s=e[2],r=e[3],n=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=e[9],p=e[10],m=e[11],_=e[12],f=e[13],d=e[14],C=e[15],v=p*C-d*m,y=u*C-f*m,M=u*d-f*p,b=h*C-_*m,E=h*d-p*_,S=h*f-_*u,I=+(o*v-l*y+c*M),D=-(n*v-l*b+c*E),R=+(n*y-o*b+c*S),L=-(n*M-o*E+l*S);return t*I+i*D+s*R+r*L}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(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return ge.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,s=t._m,r=e.m;for(let n=0;n<16;n++)s[n]=i[n]+r[n];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]+=i[s];return this.markAsUpdated(),this}invertToRef(e){if(this._isIdentity===!0)return ge.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],l=t[5],c=t[6],h=t[7],u=t[8],p=t[9],m=t[10],_=t[11],f=t[12],d=t[13],C=t[14],v=t[15],y=m*v-C*_,M=p*v-d*_,b=p*C-d*m,E=u*v-f*_,S=u*C-m*f,I=u*d-f*p,D=+(l*y-c*M+h*b),R=-(o*y-c*E+h*S),L=+(o*M-l*E+h*I),w=-(o*b-l*S+c*I),N=i*D+s*R+r*L+n*w;if(N===0)return e.copyFrom(this),e;const V=1/N,W=c*v-C*h,G=l*v-d*h,ie=l*C-d*c,Z=o*v-f*h,q=o*C-f*c,K=o*d-f*l,j=c*_-m*h,H=l*_-p*h,Y=l*m-p*c,J=o*_-u*h,te=o*m-u*c,re=o*p-u*l,ee=-(s*y-r*M+n*b),oe=+(i*y-r*E+n*S),ae=-(i*M-s*E+n*I),fe=+(i*b-s*S+r*I),de=+(s*W-r*G+n*ie),me=-(i*W-r*Z+n*q),Fe=+(i*G-s*Z+n*K),je=-(i*ie-s*q+r*K),nt=-(s*j-r*H+n*Y),we=+(i*j-r*J+n*te),Ke=-(i*H-s*J+n*re),ft=+(i*Y-s*te+r*re);return ge.FromValuesToRef(D*V,ee*V,de*V,nt*V,R*V,oe*V,me*V,we*V,L*V,ae*V,Fe*V,Ke*V,w*V,fe*V,je*V,ft*V,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 O(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 ge.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}multiply(e){const t=new this.constructor;return this.multiplyToRef(e,t),t}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}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 s=this._m,r=e.m,n=s[0],o=s[1],l=s[2],c=s[3],h=s[4],u=s[5],p=s[6],m=s[7],_=s[8],f=s[9],d=s[10],C=s[11],v=s[12],y=s[13],M=s[14],b=s[15],E=r[0],S=r[1],I=r[2],D=r[3],R=r[4],L=r[5],w=r[6],N=r[7],V=r[8],W=r[9],G=r[10],ie=r[11],Z=r[12],q=r[13],K=r[14],j=r[15];return t[i]=n*E+o*R+l*V+c*Z,t[i+1]=n*S+o*L+l*W+c*q,t[i+2]=n*I+o*w+l*G+c*K,t[i+3]=n*D+o*N+l*ie+c*j,t[i+4]=h*E+u*R+p*V+m*Z,t[i+5]=h*S+u*L+p*W+m*q,t[i+6]=h*I+u*w+p*G+m*K,t[i+7]=h*D+u*N+p*ie+m*j,t[i+8]=_*E+f*R+d*V+C*Z,t[i+9]=_*S+f*L+d*W+C*q,t[i+10]=_*I+f*w+d*G+C*K,t[i+11]=_*D+f*N+d*ie+C*j,t[i+12]=v*E+y*R+M*V+b*Z,t[i+13]=v*S+y*L+M*W+b*q,t[i+14]=v*I+y*w+M*G+b*K,t[i+15]=v*D+y*N+M*ie+b*j,this}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,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}clone(){const e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=t4(this._m[0]);for(let t=1;t<16;t++)e=e*397^t4(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new ke,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const r=this._m;if(i&&i.copyFromFloats(r[12],r[13],r[14]),e=e||Ks.Vector3[0],e.x=Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]),e.y=Math.sqrt(r[4]*r[4]+r[5]*r[5]+r[6]*r[6]),e.z=Math.sqrt(r[8]*r[8]+r[9]*r[9]+r[10]*r[10]),s){const n=s.scaling.x<0?-1:1,o=s.scaling.y<0?-1:1,l=s.scaling.z<0?-1:1;e.x*=n,e.y*=o,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 n=1/e._x,o=1/e._y,l=1/e._z;ge.FromValuesToRef(r[0]*n,r[1]*n,r[2]*n,0,r[4]*o,r[5]*o,r[6]*o,0,r[8]*l,r[9]*l,r[10]*l,0,0,0,0,1,Ks.Matrix[0]),ke.FromRotationMatrixToRef(Ks.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new Ui(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 ge.TransposeToRef(this,e),e}transposeToRef(e){return ge.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=e*4;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,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}toNormalMatrix(e){const t=Ks.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return ge.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=Ks.Vector3[0];if(!this.decompose(t))return ge.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return ge.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,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 ge;return ge.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return ge._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,o,l,c,h,u,p,m,_,f,d,C){const v=C._m;v[0]=e,v[1]=t,v[2]=i,v[3]=s,v[4]=r,v[5]=n,v[6]=o,v[7]=l,v[8]=c,v[9]=h,v[10]=u,v[11]=p,v[12]=m,v[13]=_,v[14]=f,v[15]=d,C.markAsUpdated()}static FromValues(e,t,i,s,r,n,o,l,c,h,u,p,m,_,f,d){const C=new ge,v=C._m;return v[0]=e,v[1]=t,v[2]=i,v[3]=s,v[4]=r,v[5]=n,v[6]=o,v[7]=l,v[8]=c,v[9]=h,v[10]=u,v[11]=p,v[12]=m,v[13]=_,v[14]=f,v[15]=d,C.markAsUpdated(),C}static Compose(e,t,i){const s=new ge;return ge.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,o=t._y,l=t._z,c=t._w,h=n+n,u=o+o,p=l+l,m=n*h,_=n*u,f=n*p,d=o*u,C=o*p,v=l*p,y=c*h,M=c*u,b=c*p,E=e._x,S=e._y,I=e._z;return r[0]=(1-(d+v))*E,r[1]=(_+b)*E,r[2]=(f-M)*E,r[3]=0,r[4]=(_-b)*S,r[5]=(1-(m+v))*S,r[6]=(C+y)*S,r[7]=0,r[8]=(f+M)*I,r[9]=(C-y)*I,r[10]=(1-(m+d))*I,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=ge.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 ge.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=ge.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 ge;return ge.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),s=Math.cos(e);return ge.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationY(e){const t=new ge;return ge.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return ge.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationZ(e){const t=new ge;return ge.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return ge.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationAxis(e,t){const i=new ge;return ge.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const o=i._m;return o[0]=e._x*e._x*n+r,o[1]=e._x*e._y*n-e._z*s,o[2]=e._x*e._z*n+e._y*s,o[3]=0,o[4]=e._y*e._x*n+e._z*s,o[5]=e._y*e._y*n+r,o[6]=e._y*e._z*n-e._x*s,o[7]=0,o[8]=e._z*e._x*n-e._y*s,o[9]=e._z*e._y*n+e._x*s,o[10]=e._z*e._z*n+r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=O.Dot(t,e),n=i._m;if(r<-1+Ls)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const o=O.Cross(t,e),l=1/(1+r);n[0]=o._x*o._x*l+r,n[1]=o._y*o._x*l-o._z,n[2]=o._z*o._x*l+o._y,n[3]=0,n[4]=o._x*o._y*l+o._z,n[5]=o._y*o._y*l+r,n[6]=o._z*o._y*l-o._x,n[7]=0,n[8]=o._x*o._z*l-o._y,n[9]=o._y*o._z*l+o._x,n[10]=o._z*o._z*l+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new ge;return ge.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return ke.RotationYawPitchRollToRef(e,t,i,Ks.Quaternion[0]),Ks.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new ge;return ge.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return ge.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(e===1&&t===1&&i===1),s}static Translation(e,t,i){const s=new ge;return ge.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return ge.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(e===0&&t===0&&i===0),s}static Lerp(e,t,i){const s=new e.constructor;return ge.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,o=t.m;for(let l=0;l<16;l++)r[l]=n[l]*(1-i)+o[l]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new e.constructor;return ge.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=Ks.Vector3[0],n=Ks.Quaternion[0],o=Ks.Vector3[1];e.decompose(r,n,o);const l=Ks.Vector3[2],c=Ks.Quaternion[1],h=Ks.Vector3[3];t.decompose(l,c,h);const u=Ks.Vector3[4];O.LerpToRef(r,l,i,u);const p=Ks.Quaternion[2];ke.SlerpToRef(n,c,i,p);const m=Ks.Vector3[5];return O.LerpToRef(o,h,i,m),ge.ComposeToRef(u,p,m,s),s}static LookAtLH(e,t,i){const s=new ge;return ge.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=Ks.Vector3[0],n=Ks.Vector3[1],o=Ks.Vector3[2];t.subtractToRef(e,o),o.normalize(),O.CrossToRef(i,o,r);const l=r.lengthSquared();l===0?r.x=1:r.normalizeFromLength(Math.sqrt(l)),O.CrossToRef(o,r,n),n.normalize();const c=-O.Dot(r,e),h=-O.Dot(n,e),u=-O.Dot(o,e);ge.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,c,h,u,1,s)}static LookAtRH(e,t,i){const s=new ge;return ge.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=Ks.Vector3[0],n=Ks.Vector3[1],o=Ks.Vector3[2];e.subtractToRef(t,o),o.normalize(),O.CrossToRef(i,o,r);const l=r.lengthSquared();l===0?r.x=1:r.normalizeFromLength(Math.sqrt(l)),O.CrossToRef(o,r,n),n.normalize();const c=-O.Dot(r,e),h=-O.Dot(n,e),u=-O.Dot(o,e);return ge.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,c,h,u,1,s),s}static LookDirectionLH(e,t){const i=new ge;return ge.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=Ks.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=Ks.Vector3[1];return O.CrossToRef(t,s,r),ge.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new ge;return ge.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=Ks.Vector3[2];return O.CrossToRef(t,e,s),ge.FromValuesToRef(s._x,s._y,s._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,s,r){const n=new ge;return ge.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const o=i,l=s,c=2/e,h=2/t,u=2/(l-o),p=-(l+o)/(l-o);return ge.FromValuesToRef(c,0,0,0,0,h,0,0,0,0,u,0,0,0,p,1,r),n&&r.multiplyToRef(JI,r),r._updateIdentityStatus(c===1&&h===1&&u===1&&p===0),r}static OrthoOffCenterLH(e,t,i,s,r,n,o){const l=new ge;return ge.OrthoOffCenterLHToRef(e,t,i,s,r,n,l,o),l}static OrthoOffCenterLHToRef(e,t,i,s,r,n,o,l){const c=r,h=n,u=2/(t-e),p=2/(s-i),m=2/(h-c),_=-(h+c)/(h-c),f=(e+t)/(e-t),d=(s+i)/(i-s);return ge.FromValuesToRef(u,0,0,0,0,p,0,0,0,0,m,0,f,d,_,1,o),l&&o.multiplyToRef(JI,o),o.markAsUpdated(),o}static OrthoOffCenterRH(e,t,i,s,r,n,o){const l=new ge;return ge.OrthoOffCenterRHToRef(e,t,i,s,r,n,l,o),l}static OrthoOffCenterRHToRef(e,t,i,s,r,n,o,l){return ge.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,l),o._m[10]*=-1,o}static PerspectiveLH(e,t,i,s,r,n=0){const o=new ge,l=i,c=s,h=2*l/e,u=2*l/t,p=(c+l)/(c-l),m=-2*c*l/(c-l),_=Math.tan(n);return ge.FromValuesToRef(h,0,0,0,0,u,0,_,0,0,p,1,0,0,m,0,o),r&&o.multiplyToRef(JI,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,r,n=0,o=!1){const l=new ge;return ge.PerspectiveFovLHToRef(e,t,i,s,l,!0,r,n,o),l}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,o,l=0,c=!1){const h=i,u=s,p=1/Math.tan(e*.5),m=n?p/t:p,_=n?p:p*t,f=c&&h===0?-1:u!==0?(u+h)/(u-h):1,d=c&&h===0?2*u:u!==0?-2*u*h/(u-h):-2*h,C=Math.tan(l);return ge.FromValuesToRef(m,0,0,0,0,_,0,C,0,0,f,1,0,0,d,0,r),o&&r.multiplyToRef(JI,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,o,l=0){const c=1/Math.tan(e*.5),h=n?c/t:c,u=n?c:c*t,p=Math.tan(l);return ge.FromValuesToRef(h,0,0,0,0,u,0,p,0,0,-i,1,0,0,1,0,r),o&&r.multiplyToRef(JI,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,o=!1){const l=new ge;return ge.PerspectiveFovRHToRef(e,t,i,s,l,!0,r,n,o),l}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,o,l=0,c=!1){const h=i,u=s,p=1/Math.tan(e*.5),m=n?p/t:p,_=n?p:p*t,f=c&&h===0?1:u!==0?-(u+h)/(u-h):-1,d=c&&h===0?2*u:u!==0?-2*u*h/(u-h):-2*h,C=Math.tan(l);return ge.FromValuesToRef(m,0,0,0,0,_,0,C,0,0,f,-1,0,0,d,0,r),o&&r.multiplyToRef(JI,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,o,l=0){const c=1/Math.tan(e*.5),h=n?c/t:c,u=n?c:c*t,p=Math.tan(l);return ge.FromValuesToRef(h,0,0,0,0,u,0,p,0,0,-i,-1,0,0,-1,0,r),o&&r.multiplyToRef(JI,r),r._updateIdentityStatus(!1),r}static PerspectiveFovWebVRToRef(e,t,i,s,r=!1,n,o=0){const l=r?-1:1,c=Math.tan(e.upDegrees*Math.PI/180),h=Math.tan(e.downDegrees*Math.PI/180),u=Math.tan(e.leftDegrees*Math.PI/180),p=Math.tan(e.rightDegrees*Math.PI/180),m=2/(u+p),_=2/(c+h),f=Math.tan(o),d=s._m;return d[0]=m,d[1]=d[2]=d[3]=d[4]=0,d[5]=_,d[6]=0,d[7]=f,d[8]=(u-p)*m*.5,d[9]=-((c-h)*_*.5),d[10]=-i/(t-i),d[11]=1*l,d[12]=d[13]=d[15]=0,d[14]=-(2*i*t)/(i-t),n&&s.multiplyToRef(JI,s),s.markAsUpdated(),s}static GetFinalMatrix(e,t,i,s,r,n){const o=e.width,l=e.height,c=e.x,h=e.y,u=ge.FromValues(o/2,0,0,0,0,-l/2,0,0,0,0,n-r,0,c+o/2,l/2+h,r,1),p=new t.constructor;return t.multiplyToRef(i,p),p.multiplyToRef(s,p),p.multiplyToRef(u,p)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return nu.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 nu.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return ge.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=t._m,s=e.m;return i[0]=s[0],i[1]=s[4],i[2]=s[8],i[3]=s[12],i[4]=s[1],i[5]=s[5],i[6]=s[9],i[7]=s[13],i[8]=s[2],i[9]=s[6],i[10]=s[10],i[11]=s[14],i[12]=s[3],i[13]=s[7],i[14]=s[11],i[15]=s[15],t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new ge;return ge.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,o=-2*s,l=-2*r;return ge.FromValuesToRef(n*i+1,o*i,l*i,0,n*s,o*s+1,l*s,0,n*r,o*r,l*r+1,0,n*e.d,o*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return ge.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,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,o=e._z*e._w,l=e._z*e._x,c=e._y*e._w,h=e._y*e._z,u=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+o),t._m[2]=2*(l-c),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(r+i),t._m[6]=2*(h+u),t._m[7]=0,t._m[8]=2*(l+c),t._m[9]=2*(h-u),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}ge._UpdateFlagSeed=0;ge._IdentityReadOnly=ge.Identity();class Ks{}Ks.Vector3=ah.BuildTuple(11,O.Zero);Ks.Matrix=ah.BuildTuple(2,ge.Identity);Ks.Quaternion=ah.BuildTuple(3,ke.Zero);class ue{}ue.Vector2=ah.BuildTuple(3,lt.Zero);ue.Vector3=ah.BuildTuple(13,O.Zero);ue.Vector4=ah.BuildTuple(3,Ui.Zero);ue.Quaternion=ah.BuildTuple(2,ke.Zero);ue.Matrix=ah.BuildTuple(8,ge.Identity);$e("BABYLON.Vector2",lt);$e("BABYLON.Vector3",O);$e("BABYLON.Vector4",Ui);$e("BABYLON.Matrix",ge);const JI=ge.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class pc{constructor(){this.rootNodes=new Array,this.cameras=new Array,this.lights=new Array,this.meshes=new Array,this.skeletons=new Array,this.particleSystems=new Array,this.animations=[],this.animationGroups=new Array,this.multiMaterials=new Array,this.materials=new Array,this.morphTargetManagers=new Array,this.geometries=new Array,this.transformNodes=new Array,this.actionManagers=new Array,this.textures=new Array,this._environmentTexture=null,this.postProcesses=new Array}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,s){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=new Array;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}}pc._BabylonFileParsers={};pc._IndividualBabylonFileParsers={};function z(a,e,t,i){var s=arguments.length,r=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,n;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(a,e,t,i);else for(var o=a.length-1;o>=0;o--)(n=a[o])&&(r=(s<3?n(r):s>3?n(e,t,r):n(e,t))||r);return s>3&&r&&Object.defineProperty(e,t,r),r}function WN(a){return Math.pow(a,_j)}function YN(a){return a<=.04045?.0773993808*a:Math.pow(.947867299*(a+.055),2.4)}function XN(a){return Math.pow(a,GN)}function KN(a){return a<=.0031308?12.92*a:1.055*Math.pow(a,.41666)-.055}class Ie{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 Ie.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Zt(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 Ie(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,this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}scale(e){return new Ie(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this}clampToRef(e=0,t=1,i){return i.r=Bt.Clamp(this.r,e,t),i.g=Bt.Clamp(this.g,e,t),i.b=Bt.Clamp(this.b,e,t),this}add(e){return new Ie(this.r+e.r,this.g+e.g,this.b+e.b)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this}subtract(e){return new Ie(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,this}clone(){return new Ie(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)}toHexString(){const e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+Bt.ToHex(e)+Bt.ToHex(t)+Bt.ToHex(i)}toHSV(){const e=new Ie;return this.toHSVToRef(e),e}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let o=0,l=0;const c=r,h=r-n;r!==0&&(l=h/r),r!=n&&(r==t?(o=(i-s)/h,i=0&&n<=1?(l=r,c=o):n>=1&&n<=2?(l=o,c=r):n>=2&&n<=3?(c=r,h=o):n>=3&&n<=4?(c=o,h=r):n>=4&&n<=5?(l=o,h=r):n>=5&&n<=6&&(l=r,h=o);const u=i-r;s.set(l+u,c+u,h+u)}static FromHSV(e,t,i){const s=new Ie(0,0,0);return Ie.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==7)return new Ie(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return Ie.FromInts(t,i,s)}static FromArray(e,t=0){return new Ie(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 Ie(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new Ie(0,0,0);return Ie.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,c=-2*o+3*n,h=o-2*n+r,u=o-n,p=e.r*l+i.r*c+t.r*h+s.r*u,m=e.g*l+i.g*c+t.g*h+s.g*u,_=e.b*l+i.b*c+t.b*h+s.b*u;return new Ie(p,m,_)}static Hermite1stDerivative(e,t,i,s,r){const n=Ie.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=(o-r)*6*e.r+(3*o-4*r+1)*t.r+(-o+r)*6*i.r+(3*o-2*r)*s.r,n.g=(o-r)*6*e.g+(3*o-4*r+1)*t.g+(-o+r)*6*i.g+(3*o-2*r)*s.g,n.b=(o-r)*6*e.b+(3*o-4*r+1)*t.b+(-o+r)*6*i.b+(3*o-2*r)*s.b}static Red(){return new Ie(1,0,0)}static Green(){return new Ie(0,1,0)}static Blue(){return new Ie(0,0,1)}static Black(){return new Ie(0,0,0)}static get BlackReadOnly(){return Ie._BlackReadOnly}static White(){return new Ie(1,1,1)}static Purple(){return new Ie(.5,0,.5)}static Magenta(){return new Ie(1,0,1)}static Yellow(){return new Ie(1,1,0)}static Gray(){return new Ie(.5,.5,.5)}static Teal(){return new Ie(0,1,1)}static Random(){return new Ie(Math.random(),Math.random(),Math.random())}}Ie._BlackReadOnly=Ie.Black();class Zt{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}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 Zt.FromArrayToRef(e,t,this),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 Zt(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new Zt(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,this}scale(e){return new Zt(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this}clampToRef(e=0,t=1,i){return i.r=Bt.Clamp(this.r,e,t),i.g=Bt.Clamp(this.g,e,t),i.b=Bt.Clamp(this.b,e,t),i.a=Bt.Clamp(this.a,e,t),this}multiply(e){return new Zt(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}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 Zt(this.r,this.g,this.b,this.a)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}toHexString(e=!1){const t=Math.round(this.r*255),i=Math.round(this.g*255),s=Math.round(this.b*255);if(e)return"#"+Bt.ToHex(t)+Bt.ToHex(i)+Bt.ToHex(s);const r=Math.round(this.a*255);return"#"+Bt.ToHex(t)+Bt.ToHex(i)+Bt.ToHex(s)+Bt.ToHex(r)}toLinearSpace(e=!1){const t=new Zt;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=YN(this.r),e.g=YN(this.g),e.b=YN(this.b)):(e.r=WN(this.r),e.g=WN(this.g),e.b=WN(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Zt;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=KN(this.r),e.g=KN(this.g),e.b=KN(this.b)):(e.r=XN(this.r),e.g=XN(this.g),e.b=XN(this.b)),e.a=this.a,this}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==9&&e.length!==7)return new Zt(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=e.length===9?parseInt(e.substring(7,9),16):255;return Zt.FromInts(t,i,s,r)}static Lerp(e,t,i){const s=new Zt(0,0,0,0);return Zt.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,c=-2*o+3*n,h=o-2*n+r,u=o-n,p=e.r*l+i.r*c+t.r*h+s.r*u,m=e.g*l+i.g*c+t.g*h+s.g*u,_=e.b*l+i.b*c+t.b*h+s.b*u,f=e.a*l+i.a*c+t.a*h+s.a*u;return new Zt(p,m,_,f)}static Hermite1stDerivative(e,t,i,s,r){const n=new Zt;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=(o-r)*6*e.r+(3*o-4*r+1)*t.r+(-o+r)*6*i.r+(3*o-2*r)*s.r,n.g=(o-r)*6*e.g+(3*o-4*r+1)*t.g+(-o+r)*6*i.g+(3*o-2*r)*s.g,n.b=(o-r)*6*e.b+(3*o-4*r+1)*t.b+(-o+r)*6*i.b+(3*o-2*r)*s.b,n.a=(o-r)*6*e.a+(3*o-4*r+1)*t.a+(-o+r)*6*i.a+(3*o-2*r)*s.a}static FromColor3(e,t=1){return new Zt(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Zt(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,s){return new Zt(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let s=0;snew Zt(0,0,0,0));$e("BABYLON.Color3",Ie);$e("BABYLON.Color4",Zt);const NY={},cY={},Sse=function(a,e,t,i={}){const s=a();Nr&&Nr.HasTags(e)&&Nr.AddTagsTo(s,Nr.GetTags(e,!0));const r=bq(s),n={};for(const o in r){const l=r[o],c=e[o],h=l.type;if(c!=null&&(o!=="uniqueId"||Kt.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:s[o]=c;break;case 1:i.cloneTexturesOnlyOnce&&n[c.uniqueId]?s[o]=n[c.uniqueId]:(s[o]=t||c.isRenderTarget?c:c.clone(),n[c.uniqueId]=s[o]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[o]=t?c:c.clone();break}}return s};function r3e(a){const e=a.getClassName();return NY[e]||(NY[e]={}),NY[e]}function bq(a){const e=a.getClassName();if(cY[e])return cY[e];cY[e]={};const t=cY[e];let i=a,s=e;for(;s;){const r=NY[s];for(const l in r)t[l]=r[l];let n,o=!1;do{if(n=Object.getPrototypeOf(i),!n.getClassName){o=!0;break}if(n.getClassName()!==s)break;i=n}while(n);if(o)break;s=n.getClassName(),i=n}return t}function fv(a,e){return(t,i)=>{const s=r3e(t);s[i]||(s[i]={type:a,sourceName:e})}}function n3e(a,e=null){return(t,i)=>{const s=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[s]},set:function(r){typeof this.equals=="function"&&this.equals(r)||this[s]!==r&&(this[s]=r,t[a].apply(this))},enumerable:!0,configurable:!0})}}function _t(a,e=null){return n3e(a,e)}function X(a){return fv(0,a)}function xs(a){return fv(1,a)}function Br(a){return fv(2,a)}function AF(a){return fv(3,a)}function FG(a){return fv(4,a)}function bo(a){return fv(5,a)}function xF(a){return fv(6,a)}function Zoe(a){return fv(7,a)}function bF(a){return fv(8,a)}function U$(a){return fv(9,a)}function qoe(a){return fv(10,a)}function vK(a){return fv(12,a)}function Joe(a){return fv(11,a)}class Kt{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw Ys("ImageProcessingConfiguration")};Kt._FresnelParametersParser=a=>{throw Ys("FresnelParameters")};Kt._ColorCurvesParser=a=>{throw Ys("ColorCurves")};Kt._TextureParser=(a,e,t)=>{throw Ys("Texture")};function AI(a,e,t,i){const s=t.value;t.value=(...r)=>{let n=s;if(typeof _native<"u"&&_native[e]){const o=_native[e];i?n=(...l)=>i(...l)?o(...l):s(...l):n=o}return a[e]=n,n(...r)}}AI.filter=function(a){return(e,t,i)=>AI(e,t,i,a)};class ta{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))e[0]!=="_"&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)this._keys.indexOf(e)===-1&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e))}_setDefaultValue(e){var t,i,s,r,n;const o=(s=(i=(t=this._externalProperties)===null||t===void 0?void 0:t[e])===null||i===void 0?void 0:i.type)!==null&&s!==void 0?s:typeof this[e],l=(n=(r=this._externalProperties)===null||r===void 0?void 0:r[e])===null||n===void 0?void 0:n.default;switch(o){case"number":this[e]=l??0;break;case"string":this[e]=l??"";break;default:this[e]=l??!1;break}}toString(){let e="";for(let t=0;tnew hl,this)}serialize(){return Kt.Serialize(this)}static Parse(e){return Kt.Parse(()=>new hl,e,null,null)}}z([X()],hl.prototype,"_globalHue",void 0);z([X()],hl.prototype,"_globalDensity",void 0);z([X()],hl.prototype,"_globalSaturation",void 0);z([X()],hl.prototype,"_globalExposure",void 0);z([X()],hl.prototype,"_highlightsHue",void 0);z([X()],hl.prototype,"_highlightsDensity",void 0);z([X()],hl.prototype,"_highlightsSaturation",void 0);z([X()],hl.prototype,"_highlightsExposure",void 0);z([X()],hl.prototype,"_midtonesHue",void 0);z([X()],hl.prototype,"_midtonesDensity",void 0);z([X()],hl.prototype,"_midtonesSaturation",void 0);z([X()],hl.prototype,"_midtonesExposure",void 0);Kt._ColorCurvesParser=hl.Parse;class $oe extends ta{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 Dr{constructor(){this.colorCurves=new hl,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Dr.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Zt(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Dr.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new Se}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"}static PrepareUniforms(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&hl.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}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===Dr._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType){case Dr.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&&hl.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=t??s/i;let n=Math.tan(this.vignetteCameraFov*.5),o=n*r;const l=Math.sqrt(o*n);o=Be.Mix(o,l,this.vignetteStretch),n=Be.Mix(n,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*this.vignetteCenterX,-n*this.vignetteCenterY);const c=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,c)}}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 Kt.Clone(()=>new Dr,this)}serialize(){return Kt.Serialize(this)}static Parse(e){const t=Kt.Parse(()=>new Dr,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}}Dr.TONEMAPPING_STANDARD=0;Dr.TONEMAPPING_ACES=1;Dr._VIGNETTEMODE_MULTIPLY=0;Dr._VIGNETTEMODE_OPAQUE=1;z([Zoe()],Dr.prototype,"colorCurves",void 0);z([X()],Dr.prototype,"_colorCurvesEnabled",void 0);z([xs("colorGradingTexture")],Dr.prototype,"_colorGradingTexture",void 0);z([X()],Dr.prototype,"_colorGradingEnabled",void 0);z([X()],Dr.prototype,"_colorGradingWithGreenDepth",void 0);z([X()],Dr.prototype,"_colorGradingBGR",void 0);z([X()],Dr.prototype,"_exposure",void 0);z([X()],Dr.prototype,"_toneMappingEnabled",void 0);z([X()],Dr.prototype,"_toneMappingType",void 0);z([X()],Dr.prototype,"_contrast",void 0);z([X()],Dr.prototype,"vignetteStretch",void 0);z([X()],Dr.prototype,"vignetteCenterX",void 0);z([X()],Dr.prototype,"vignetteCenterY",void 0);z([X()],Dr.prototype,"vignetteWeight",void 0);z([bF()],Dr.prototype,"vignetteColor",void 0);z([X()],Dr.prototype,"vignetteCameraFov",void 0);z([X()],Dr.prototype,"_vignetteBlendMode",void 0);z([X()],Dr.prototype,"_vignetteEnabled",void 0);z([X()],Dr.prototype,"_ditheringEnabled",void 0);z([X()],Dr.prototype,"_ditheringIntensity",void 0);z([X()],Dr.prototype,"_skipFinalColorClamp",void 0);z([X()],Dr.prototype,"_applyByPostProcess",void 0);z([X()],Dr.prototype,"_isEnabled",void 0);Kt._ImageProcessingConfigurationParser=Dr.Parse;Oi.prototype.createUniformBuffer=function(a){const e=this._gl.createBuffer();if(!e)throw new Error("Unable to create uniform buffer");const t=new OB(e);return this.bindUniformBuffer(t),a instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,a,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(a),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),t.references=1,t};Oi.prototype.createDynamicUniformBuffer=function(a){const e=this._gl.createBuffer();if(!e)throw new Error("Unable to create dynamic uniform buffer");const t=new OB(e);return this.bindUniformBuffer(t),a instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,a,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(a),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),t.references=1,t};Oi.prototype.updateUniformBuffer=function(a,e,t,i){this.bindUniformBuffer(a),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)};Oi.prototype.bindUniformBuffer=function(a){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,a?a.underlyingResource:null)};Oi.prototype.bindUniformBufferBase=function(a,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,a?a.underlyingResource:null)};Oi.prototype.bindUniformBlock=function(a,e,t){const i=a.program,s=this._gl.getUniformBlockIndex(i,e);s!==4294967295&&this._gl.uniformBlockBinding(i,s,t)};class es{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"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 s=this._uniformLocationPointer-i;for(let r=0;r0){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 n=(4-t)*i;t=t*i+n}s=[];for(let r=0;r1&&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&&(es._UpdatedUbosInFrame[this._name]||(es._UpdatedUbosInFrame[this._name]=0),es._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 s=this._uniformLocations[e];if(s===void 0){if(this._buffer){Me.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let r=0;rn[l]=o),n}if(!(i instanceof Array||i instanceof Float32Array)||this.byteOffset!==0||i.length!==r)if(i instanceof Array){const n=this.byteOffset/4;return i.slice(n,n+r)}else{if(i instanceof ArrayBuffer)return new Float32Array(i,this.byteOffset,r);{let n=i.byteOffset+this.byteOffset;if(t){const l=new Float32Array(r),c=new Float32Array(i.buffer,n,r);return l.set(c),l}const o=n%4;return o&&(n=Math.max(0,n-o)),new Float32Array(i.buffer,n,r)}}return t?i.slice():i}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/se.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/se.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*se.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e)}update(e){this._buffer.update(e)}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i)}dispose(){this._ownsBuffer&&this._buffer.dispose()}forEach(e,t){se.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}static DeduceStride(e){switch(e){case se.UVKind:case se.UV2Kind:case se.UV3Kind:case se.UV4Kind:case se.UV5Kind:case se.UV6Kind:return 2;case se.NormalKind:case se.PositionKind:return 3;case se.ColorKind:case se.MatricesIndicesKind:case se.MatricesIndicesExtraKind:case se.MatricesWeightsKind:case se.MatricesWeightsExtraKind:case se.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetTypeByteLength(e){switch(e){case se.BYTE:case se.UNSIGNED_BYTE:return 1;case se.SHORT:case se.UNSIGNED_SHORT:return 2;case se.INT:case se.UNSIGNED_INT:case se.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,o,l){if(e instanceof Array){let c=t/4;const h=i/4;for(let u=0;u{let u=c.getWorldMatrix();c.nonUniformScaling&&(ue.Matrix[0].copyFrom(u),u=ue.Matrix[0],u.setTranslationFromFloats(0,0,0),u.invert(),u.transposeToRef(ue.Matrix[1]),u=ue.Matrix[1]),O.TransformNormalToRef(h,u,h)};if(e&&l(this.pickedMesh,s),this.ray){const c=ue.Vector3[0].copyFrom(s);e||l(this.pickedMesh,c),O.Dot(c,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=se.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 s=lt.FromArray(i,t[this.faceId*3]*2),r=lt.FromArray(i,t[this.faceId*3+1]*2),n=lt.FromArray(i,t[this.faceId*3+2]*2);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new lt(s.x+r.x+n.x,s.y+r.y+n.y)}}class $o{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new $o(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new $o(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new $o(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new $o(e,t.x,t.y,null,i,s)}}class wj{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[se.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[se.PositionKind]=new se(this._scene.getEngine(),e,se.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[se.PositionKind];!e||(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!i||(t=t||i._postProcesses.filter(s=>s!=null),!t||t.length===0||!this._scene.postProcessesEnabled)?!1:(t[0].activate(i,e,t!=null),!0)}directRender(e,t=null,i=!1,s=0,r=0,n=!1){var o;const l=this._scene.getEngine();for(let c=0;cc!=null),s.length===0||!this._scene.postProcessesEnabled))return;const l=this._scene.getEngine();for(let c=0,h=s.length;ct._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(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.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=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in $3.Triggers)if(Object.prototype.hasOwnProperty.call($3.Triggers,t)&&parseInt(t)===e)return!0;return!1}}$3.Triggers={};class i7{}i7.KEYDOWN=1;i7.KEYUP=2;class oX{constructor(e,t){this.type=e,this.event=t}}class Eq extends oX{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}var Rs;(function(a){a[a.Generic=0]="Generic",a[a.Keyboard=1]="Keyboard",a[a.Mouse=2]="Mouse",a[a.Touch=3]="Touch",a[a.DualShock=4]="DualShock",a[a.Xbox=5]="Xbox",a[a.Switch=6]="Switch",a[a.DualSense=7]="DualSense"})(Rs||(Rs={}));var er;(function(a){a[a.Horizontal=0]="Horizontal",a[a.Vertical=1]="Vertical",a[a.LeftClick=2]="LeftClick",a[a.MiddleClick=3]="MiddleClick",a[a.RightClick=4]="RightClick",a[a.BrowserBack=5]="BrowserBack",a[a.BrowserForward=6]="BrowserForward",a[a.MouseWheelX=7]="MouseWheelX",a[a.MouseWheelY=8]="MouseWheelY",a[a.MouseWheelZ=9]="MouseWheelZ",a[a.Move=12]="Move"})(er||(er={}));var Nj;(function(a){a[a.Horizontal=0]="Horizontal",a[a.Vertical=1]="Vertical",a[a.LeftClick=2]="LeftClick",a[a.MiddleClick=3]="MiddleClick",a[a.RightClick=4]="RightClick",a[a.BrowserBack=5]="BrowserBack",a[a.BrowserForward=6]="BrowserForward",a[a.MouseWheelX=7]="MouseWheelX",a[a.MouseWheelY=8]="MouseWheelY",a[a.MouseWheelZ=9]="MouseWheelZ",a[a.DeltaHorizontal=10]="DeltaHorizontal",a[a.DeltaVertical=11]="DeltaVertical"})(Nj||(Nj={}));var yq;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.L2=6]="L2",a[a.R2=7]="R2",a[a.Share=8]="Share",a[a.Options=9]="Options",a[a.L3=10]="L3",a[a.R3=11]="R3",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.TouchPad=17]="TouchPad",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(yq||(yq={}));var Mq;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.L2=6]="L2",a[a.R2=7]="R2",a[a.Create=8]="Create",a[a.Options=9]="Options",a[a.L3=10]="L3",a[a.R3=11]="R3",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.TouchPad=17]="TouchPad",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(Mq||(Mq={}));var Tq;(function(a){a[a.A=0]="A",a[a.B=1]="B",a[a.X=2]="X",a[a.Y=3]="Y",a[a.LB=4]="LB",a[a.RB=5]="RB",a[a.LT=6]="LT",a[a.RT=7]="RT",a[a.Back=8]="Back",a[a.Start=9]="Start",a[a.LS=10]="LS",a[a.RS=11]="RS",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.LStickXAxis=17]="LStickXAxis",a[a.LStickYAxis=18]="LStickYAxis",a[a.RStickXAxis=19]="RStickXAxis",a[a.RStickYAxis=20]="RStickYAxis"})(Tq||(Tq={}));var Sq;(function(a){a[a.B=0]="B",a[a.A=1]="A",a[a.Y=2]="Y",a[a.X=3]="X",a[a.L=4]="L",a[a.R=5]="R",a[a.ZL=6]="ZL",a[a.ZR=7]="ZR",a[a.Minus=8]="Minus",a[a.Plus=9]="Plus",a[a.LS=10]="LS",a[a.RS=11]="RS",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.Capture=17]="Capture",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(Sq||(Sq={}));var Iq;(function(a){a[a.PointerMove=0]="PointerMove",a[a.PointerDown=1]="PointerDown",a[a.PointerUp=2]="PointerUp"})(Iq||(Iq={}));class rD{}rD.DOM_DELTA_PIXEL=0;rD.DOM_DELTA_LINE=1;rD.DOM_DELTA_PAGE=2;class lP{static CreateDeviceEvent(e,t,i,s,r,n,o){switch(e){case Rs.Keyboard:return this._CreateKeyboardEvent(i,s,r,n);case Rs.Mouse:if(i===er.MouseWheelX||i===er.MouseWheelY||i===er.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,r,n);case Rs.Touch:return this._CreatePointerEvent(e,t,i,s,r,n,o);default:throw`Unable to generate event for device ${Rs[e]}`}}static _CreatePointerEvent(e,t,i,s,r,n,o){const l=this._CreateMouseEvent(e,t,i,s,r,n);e===Rs.Mouse?(l.deviceType=Rs.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=Rs.Touch,l.pointerId=o??t,l.pointerType="touch");let c=0;return c+=r.pollInput(e,t,er.LeftClick),c+=r.pollInput(e,t,er.RightClick)*2,c+=r.pollInput(e,t,er.MiddleClick)*4,l.buttons=c,i===er.Move?l.type="pointermove":i>=er.LeftClick&&i<=er.RightClick&&(l.type=s===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,r,n){const o=this._CreateMouseEvent(e,t,i,s,r,n);switch(o.pointerId=1,o.type="wheel",o.deltaMode=rD.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case er.MouseWheelX:o.deltaX=s;break;case er.MouseWheelY:o.deltaY=s;break;case er.MouseWheelZ:o.deltaZ=s;break}return o}static _CreateMouseEvent(e,t,i,s,r,n){const o=this._CreateEvent(n),l=r.pollInput(e,t,er.Horizontal),c=r.pollInput(e,t,er.Vertical);return n?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-n.getBoundingClientRect().x,o.offsetY=o.movementY-n.getBoundingClientRect().y):(o.movementX=r.pollInput(e,t,Nj.DeltaHorizontal),o.movementY=r.pollInput(e,t,Nj.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,r),o.clientX=l,o.clientY=c,o.x=l,o.y=c,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=Rs.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=t===1?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(Rs.Keyboard),s=i&&t.pollInput(Rs.Keyboard,0,18)===1,r=i&&t.pollInput(Rs.Keyboard,0,17)===1,n=i&&(t.pollInput(Rs.Keyboard,0,91)===1||t.pollInput(Rs.Keyboard,0,92)===1||t.pollInput(Rs.Keyboard,0,93)===1),o=i&&t.pollInput(Rs.Keyboard,0,16)===1;e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=o}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class a3e{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(s,r,n,o)=>{const l=lP.CreateDeviceEvent(s,r,n,o,this);i(s,r,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Rs.Mouse||e===Rs.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const Ise=255,Lse=Object.keys(er).length/2;class o3e{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Be.IsSafari(),this._usingMacOS=pP()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=r=>{},this._keyboardUpEvent=r=>{},this._keyboardBlurEvent=r=>{},this._pointerMoveEvent=r=>{},this._pointerDownEvent=r=>{},this._pointerUpEvent=r=>{},this._pointerCancelEvent=r=>{},this._pointerWheelEvent=r=>{},this._pointerBlurEvent=r=>{},this._pointerMacOSChromeOutEvent=r=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=pP()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=pP()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=r=>{},this._gamepadDisconnectedEvent=r=>{},this._eventPrefix=Be.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,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 s=this._inputs[e][t];if(!s)throw`Unable to find device ${Rs[e]}`;e>=Rs.DualShock&&e<=Rs.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(r===void 0)throw`Unable to find input ${i} for device ${Rs[e]} in slot ${t}`;return i===er.Move&&Be.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}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||this===void 0?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 s=+i,r=t[s];if(r)for(let n=0;n{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Rs.Keyboard,0,Ise));const t=this._inputs[Rs.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(Rs.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Rs.Keyboard,0,Ise));const t=this._inputs[Rs.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 s of this._metaKeys){const r=lP.CreateDeviceEvent(Rs.Keyboard,0,s,0,this,this._elementToAttachTo);t[s]=0,this._onInputChanged(Rs.Keyboard,0,r)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Rs.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[Rs.Keyboard][0];for(let t=0;t{const s=this._getPointerType(i);let r=s===Rs.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===Rs.Touch&&r===-1){const o=this._activeTouchIds.indexOf(-1);if(o>=0)r=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(s,r);else{Be.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[s]||(this._inputs[s]={}),this._inputs[s][r]||this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const o=i;o.inputIndex=er.Move,n[er.Horizontal]=i.clientX,n[er.Vertical]=i.clientY,s===Rs.Touch&&n[er.LeftClick]===0&&(n[er.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(s,r,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,n[i.button+2]=n[i.button+2]?0:1,this._onInputChanged(s,r,o))}},this._pointerDownEvent=i=>{const s=this._getPointerType(i);let r=s===Rs.Mouse?0:i.pointerId;if(s===Rs.Touch){const o=this._activeTouchIds.indexOf(-1);if(o>=0)r=o,this._activeTouchIds[o]=i.pointerId;else{Be.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[s]||(this._inputs[s]={}),this._inputs[s][r]?s===Rs.Touch&&this._onDeviceConnected(s,r):this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const o=n[er.Horizontal],l=n[er.Vertical];if(s===Rs.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{}n[er.Horizontal]=i.clientX,n[er.Vertical]=i.clientY,n[i.button+2]=1;const c=i;c.inputIndex=i.button+2,this._onInputChanged(s,r,c),(o!==i.clientX||l!==i.clientY)&&(c.inputIndex=er.Move,this._onInputChanged(s,r,c))}},this._pointerUpEvent=i=>{var s,r,n,o,l;const c=this._getPointerType(i),h=c===Rs.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(c===Rs.Touch){if(h===-1)return;this._activeTouchIds[h]=-1}const u=(s=this._inputs[c])===null||s===void 0?void 0:s[h];if(u&&u[i.button+2]!==0){const p=u[er.Horizontal],m=u[er.Vertical];u[er.Horizontal]=i.clientX,u[er.Vertical]=i.clientY,u[i.button+2]=0;const _=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(p!==i.clientX||m!==i.clientY)&&(_.inputIndex=er.Move,this._onInputChanged(c,h,_)),_.inputIndex=i.button+2,c===Rs.Mouse&&this._mouseId>=0&&((n=(r=this._elementToAttachTo).hasPointerCapture)===null||n===void 0?void 0:n.call(r,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&((l=(o=this._elementToAttachTo).hasPointerCapture)===null||l===void 0?void 0:l.call(o,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(c,h,_),c===Rs.Touch&&this._onDeviceDisconnected(c,h)}},this._pointerCancelEvent=i=>{var s,r,n,o;if(i.pointerType==="mouse"){const l=this._inputs[Rs.Mouse][0];this._mouseId>=0&&((r=(s=this._elementToAttachTo).hasPointerCapture)===null||r===void 0?void 0:r.call(s,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let c=er.LeftClick;c<=er.BrowserForward;c++)if(l[c]===1){l[c]=0;const h=lP.CreateDeviceEvent(Rs.Mouse,0,c,0,this,this._elementToAttachTo);this._onInputChanged(Rs.Mouse,0,h)}}else{const l=this._activeTouchIds.indexOf(i.pointerId);if(l===-1)return;!((o=(n=this._elementToAttachTo).hasPointerCapture)===null||o===void 0)&&o.call(n,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[Rs.Touch][l][er.LeftClick]=0;const c=lP.CreateDeviceEvent(Rs.Touch,l,er.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(Rs.Touch,l,c),this._activeTouchIds[l]=-1,this._onDeviceDisconnected(Rs.Touch,l)}},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,s,r,n,o;if(this.isDeviceAvailable(Rs.Mouse)){const l=this._inputs[Rs.Mouse][0];this._mouseId>=0&&((s=(i=this._elementToAttachTo).hasPointerCapture)===null||s===void 0?void 0:s.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let c=er.LeftClick;c<=er.BrowserForward;c++)if(l[c]===1){l[c]=0;const h=lP.CreateDeviceEvent(Rs.Mouse,0,c,0,this,this._elementToAttachTo);this._onInputChanged(Rs.Mouse,0,h)}}if(this.isDeviceAvailable(Rs.Touch)){const l=this._inputs[Rs.Touch];for(let c=0;c{const s=Rs.Mouse,r=0;this._inputs[s]||(this._inputs[s]=[]),this._inputs[s][r]||(this._pointerActive=!0,this._registerDevice(s,r,Lse));const n=this._inputs[s][r];if(n){n[er.MouseWheelX]=i.deltaX||0,n[er.MouseWheelY]=i.deltaY||i.wheelDelta||0,n[er.MouseWheelZ]=i.deltaZ||0;const o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),n[er.MouseWheelX]!==0&&(o.inputIndex=er.MouseWheelX,this._onInputChanged(s,r,o)),n[er.MouseWheelY]!==0&&(o.inputIndex=er.MouseWheelY,this._onInputChanged(s,r,o)),n[er.MouseWheelZ]!==0&&(o.inputIndex=er.MouseWheelZ,this._onInputChanged(s,r,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(Rs.Mouse)){const i=this._inputs[Rs.Mouse][0];i[er.MouseWheelX]=0,i[er.MouseWheelY]=0,i[er.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 s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?Rs.DualSense:Rs.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?Rs.Xbox:e.indexOf("057e")!==-1?Rs.Switch:Rs.Generic}_getPointerType(e){let t=Rs.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=Rs.Touch),t}}class Lq{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new Se,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class l3e{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=n=>{for(let o=0;o{const o=this._registeredManagers.indexOf(n);o>-1&&this._registeredManagers.splice(o,1)};const t=Object.keys(Rs).length/2;this._devices=new Array(t);const i=(n,o)=>{this._devices[n]||(this._devices[n]=new Array),this._devices[n][o]||(this._devices[n][o]=o);for(const l of this._registeredManagers){const c=new Lq(this._deviceInputSystem,n,o);l._addDevice(c)}},s=(n,o)=>{var l;!((l=this._devices[n])===null||l===void 0)&&l[o]&&delete this._devices[n][o];for(const c of this._registeredManagers)c._removeDevice(n,o)},r=(n,o,l)=>{if(l)for(const c of this._registeredManagers)c._onInputChanged(n,o,l)};typeof _native<"u"?this._deviceInputSystem=new a3e(i,s,r):this._deviceInputSystem=new o3e(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class ile{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(Rs).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new l3e(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new Se(i=>{for(const s of this._devices)if(s)for(const r of s)r&&this.onDeviceConnectedObservable.notifyObserver(i,r)}),this.onDeviceDisconnectedObservable=new Se,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 i,s;const r=(i=this._devices[e])===null||i===void 0?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(r),!((s=this._devices[e])===null||s===void 0)&&s[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var s,r;(r=(s=this._devices[e])===null||s===void 0?void 0:s[t])===null||r===void 0||r.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Rs.Keyboard:case Rs.Mouse:this._firstDevice[e]=0;break;case Rs.Touch:case Rs.DualSense:case Rs.DualShock:case Rs.Xbox:case Rs.Switch:case Rs.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i=er.MouseWheelX&&t.inputIndex<=er.MouseWheelZ?mi.POINTERWHEEL:mi.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n));let o;e?(o=new J6(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new J6(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,ge.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 s=this._scene,r=new tle(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.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 r=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){const n=this._pointerOverMesh._getActionManagerForTrigger();n&&n.hasPointerTriggers&&(r.style.cursor=n.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=er.Move,!this._checkPrePointerObservable(e,i,mi.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,mi.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const n=e.pickedMesh._getActionManagerForTrigger();if(n){if(n.hasPickTriggers)switch(n.processTrigger(5,$o.CreateNew(e.pickedMesh,t,e)),t.button){case 0:n.processTrigger(2,$o.CreateNew(e.pickedMesh,t,e));break;case 1:n.processTrigger(4,$o.CreateNew(e.pickedMesh,t,e));break;case 2:n.processTrigger(3,$o.CreateNew(e.pickedMesh,t,e));break}n.hasSpecificTrigger(8)&&window.setTimeout(()=>{const o=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,l=>l.isPickable&&l.isVisible&&l.isReady()&&l.actionManager&&l.actionManager.hasSpecificTrigger(8)&&l===this._pickedDownMesh,!1,i.cameraToUseForPointers);o?.pickedMesh&&n&&this._totalPointersPressed!==0&&Date.now()-this._startingPointerTime>yc.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,$o.CreateNew(o.pickedMesh,t)))},yc.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=mi.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new J6(r,t,e),this._setRayOnPointerInfo(e,t)):s=new J6(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=er.Move;const r=new Rse;i?r.doubleClick=!0:r.singleClick=!0,!this._checkPrePointerObservable(e,s,mi.POINTERUP)&&this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const n=mi.POINTERPICK,o=new J6(n,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(o,n)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,$o.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,$o.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,$o.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const r=this._pickedDownMesh._getActionManagerForTrigger(16);r&&r.processTrigger(16,$o.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new J6(mi.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,mi.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,mi.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=mi.POINTERTAP:i.doubleClick&&(n=mi.POINTERDOUBLETAP),n){const o=new J6(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(o,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new ile(n),this._initActionManager=o=>{if(!this._meshPickProceed){const l=r.skipPointerUpPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers);this._currentPickResult=l,l&&(o=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,l,c)=>{if((Date.now()-this._previousStartingPointerTime>yc.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[o])){const h=this._delayedClicks[o].evt,u=mi.POINTERTAP,p=new J6(u,h,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(u)&&r.onPointerObservable.notifyObservers(p,u),this._delayedClicks[o]=null}},this._initClickEvent=(o,l,c,h)=>{var u,p;const m=new Rse;this._currentPickResult=null;let _=null,f=o.hasSpecificMask(mi.POINTERPICK)||l.hasSpecificMask(mi.POINTERPICK)||o.hasSpecificMask(mi.POINTERTAP)||l.hasSpecificMask(mi.POINTERTAP)||o.hasSpecificMask(mi.POINTERDOUBLETAP)||l.hasSpecificMask(mi.POINTERDOUBLETAP);!f&&$3&&(_=this._initActionManager(_,m),_&&(f=_.hasPickTriggers));let d=!1;if(f){const C=c.button;if(m.hasSwiped=this._isPointerSwiping(),!m.hasSwiped){let v=!yc.ExclusiveDoubleClickMode;if(v||(v=!o.hasSpecificMask(mi.POINTERDOUBLETAP)&&!l.hasSpecificMask(mi.POINTERDOUBLETAP),v&&!$3.HasSpecificTrigger(6)&&(_=this._initActionManager(_,m),_&&(v=!_.hasSpecificTrigger(6)))),v)(Date.now()-this._previousStartingPointerTime>yc.DoubleClickDelay||C!==this._previousButtonPressed)&&(m.singleClick=!0,h(m,this._currentPickResult),d=!0);else{const M={evt:c,clickInfo:m,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,C,m,h),yc.DoubleClickDelay)};this._delayedClicks[C]=M}let y=o.hasSpecificMask(mi.POINTERDOUBLETAP)||l.hasSpecificMask(mi.POINTERDOUBLETAP);!y&&$3.HasSpecificTrigger(6)&&(_=this._initActionManager(_,m),_&&(y=_.hasSpecificTrigger(6))),y&&(C===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>yc.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>yc.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=er.MouseWheelX&&o.inputIndex<=er.MouseWheelZ?mi.POINTERWHEEL:mi.POINTERMOVE)||!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking){this._processPointerMove(new cu,o);return}r.pointerMovePredicate||(r.pointerMovePredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(c.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||c._getActionManagerForTrigger()!==null)&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&c.layerMask)!==0));const l=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(l,o)},this._onPointerDown=o=>{var l;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,yc.ExclusiveDoubleClickMode){for(let h=0;hh.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&h.layerMask)!==0)),this._pickedDownMesh=null;let c;r.skipPointerDownPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerDown?c=new cu:c=r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers),this._processPointerDown(c,o)},this._onPointerUp=o=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),r.preventDefaultOnPointerUp&&s&&(o.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,o,(l,c)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,o,mi.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}l.hasSwiped||(l.singleClick&&r.onPrePointerObservable.hasSpecificMask(mi.POINTERTAP)&&this._checkPrePointerObservable(null,o,mi.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&r.onPrePointerObservable.hasSpecificMask(mi.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,mi.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),!(!r.cameraToUseForPointers&&!r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=h=>h.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&h.layerMask)!==0)),!this._meshPickProceed&&($3&&$3.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,l),c||(c=this._currentPickResult),this._processPointerUp(c,o,l),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{const l=i7.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const c=new Eq(l,o);if(r.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const c=new oX(l,o);r.onKeyboardObservable.notifyObservers(c,l)}r.actionManager&&r.actionManager.processTrigger(14,$o.CreateNewFromScene(r,o))},this._onKeyUp=o=>{const l=i7.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const c=new Eq(l,o);if(r.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const c=new oX(l,o);r.onKeyboardObservable.notifyObservers(c,l)}r.actionManager&&r.actionManager.processTrigger(15,$o.CreateNewFromScene(r,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===Rs.Mouse?o.onInputChangedObservable.add(l=>{l.inputIndex===er.LeftClick||l.inputIndex===er.MiddleClick||l.inputIndex===er.RightClick||l.inputIndex===er.BrowserBack||l.inputIndex===er.BrowserForward?t&&o.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&o.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===er.Move?this._onPointerMove(l):(l.inputIndex===er.MouseWheelX||l.inputIndex===er.MouseWheelY||l.inputIndex===er.MouseWheelZ)&&this._onPointerMove(l))}):o.deviceType===Rs.Touch?o.onInputChangedObservable.add(l=>{l.inputIndex===er.LeftClick&&(t&&o.getInput(l.inputIndex)===1?(this._onPointerDown(l),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&o.getInput(l.inputIndex)===0&&(this._onPointerUp(l),this._totalPointersPressed===0&&(this._isMultiTouchGesture=!1))),i&&l.inputIndex===er.Move&&this._onPointerMove(l)}):o.deviceType===Rs.Keyboard&&o.onInputChangedObservable.add(l=>{l.type==="keydown"?this._onKeyDown(l):l.type==="keyup"&&this._onKeyUp(l)})}),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,s){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,$o.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,$o.CreateNew(e,s,{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]}}yc.DragMovementThreshold=10;yc.LongPressDelay=500;yc.DoubleClickDelay=300;yc.ExclusiveDoubleClickMode=!1;class Tc{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){!Tc.Enabled||(this._current+=e,t&&this._fetchResult())}beginMonitoring(){!Tc.Enabled||(this._startMonitoringTime=Zr.Now)}endMonitoring(e=!0){if(!Tc.Enabled)return;e&&this.fetchNewFrame();const t=Zr.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=Zr.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}Tc.Enabled=!0;class Zd{constructor(e,t,i,s){this.normal=new O(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Zd(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=Zd._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,o=this.d,l=s*i[0]+r*i[1]+n*i[2]+o*i[3],c=s*i[4]+r*i[5]+n*i[6]+o*i[7],h=s*i[8]+r*i[9]+n*i[10]+o*i[11],u=s*i[12]+r*i[13]+n*i[14]+o*i[15];return new Zd(l,c,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 s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,o=i.x-e.x,l=i.y-e.y,c=i.z-e.z,h=r*c-n*l,u=n*o-s*c,p=s*l-r*o,m=Math.sqrt(h*h+u*u+p*p);let _;return m!==0?_=1/m:_=0,this.normal.x=h*_,this.normal.y=u*_,this.normal.z=p*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return O.Dot(this.normal,e)<=t}signedDistanceTo(e){return O.Dot(e,this.normal)+this.d}static FromArray(e){return new Zd(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Zd(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Zd(0,0,0,0);return t.normalize(),i.normal=t,i.d=-(t.x*e.x+t.y*e.y+t.z*e.z),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return O.Dot(i,t)+s}}Zd._TmpMatrix=ge.Identity();class p_{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new Zd(0,0,0,0));return p_.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){p_.GetNearPlaneToRef(e,t[0]),p_.GetFarPlaneToRef(e,t[1]),p_.GetLeftPlaneToRef(e,t[2]),p_.GetRightPlaneToRef(e,t[3]),p_.GetTopPlaneToRef(e,t[4]),p_.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 VG{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}VG._UniqueIdCounter=1;class ea{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}ea.FALLOFF_DEFAULT=0;ea.FALLOFF_PHYSICAL=1;ea.FALLOFF_GLTF=2;ea.FALLOFF_STANDARD=3;ea.LIGHTMAP_DEFAULT=0;ea.LIGHTMAP_SPECULAR=1;ea.LIGHTMAP_SHADOWSONLY=2;ea.INTENSITYMODE_AUTOMATIC=0;ea.INTENSITYMODE_LUMINOUSPOWER=1;ea.INTENSITYMODE_LUMINOUSINTENSITY=2;ea.INTENSITYMODE_ILLUMINANCE=3;ea.INTENSITYMODE_LUMINANCE=4;ea.LIGHTTYPEID_POINTLIGHT=0;ea.LIGHTTYPEID_DIRECTIONALLIGHT=1;ea.LIGHTTYPEID_SPOTLIGHT=2;ea.LIGHTTYPEID_HEMISPHERICLIGHT=3;class c3e{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Kb;(function(a){a[a.BackwardCompatible=0]="BackwardCompatible",a[a.Intermediate=1]="Intermediate",a[a.Aggressive=2]="Aggressive"})(Kb||(Kb={}));class oi extends pc{static DefaultMaterialFactory(e){throw Ys("StandardMaterial")}static CollisionCoordinatorFactory(){throw Ys("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 Kb.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case Kb.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case Kb.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 yc.DragMovementThreshold}static set DragMovementThreshold(e){yc.DragMovementThreshold=e}static get LongPressDelay(){return yc.LongPressDelay}static set LongPressDelay(e){yc.LongPressDelay=e}static get DoubleClickDelay(){return yc.DoubleClickDelay}static set DoubleClickDelay(e){yc.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return yc.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){yc.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){var s;const r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:(s=this.activeCamera.globalPosition)!==null&&s!==void 0?s:this.activeCamera.devicePosition,n=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return ue.Vector4[0].set(r.x,r.y,r.z,n?-1:1),e&&(i?e.setFloat3(t,ue.Vector4[0].x,ue.Vector4[0].y,ue.Vector4[0].z):e.setVector4(t,ue.Vector4[0])),ue.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=Qoe(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=oi.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=oi.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 yc(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new Zt(.2,.2,.3,1),this.ambientColor=new Ie(0,0,0),this.environmentIntensity=1,this._performancePriority=Kb.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new Se,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=new Array,this.onDisposeObservable=new Se,this._onDisposeObserver=null,this.onBeforeRenderObservable=new Se,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new Se,this.onAfterRenderCameraObservable=new Se,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new Se,this.onAfterAnimationsObservable=new Se,this.onBeforeDrawPhaseObservable=new Se,this.onAfterDrawPhaseObservable=new Se,this.onReadyObservable=new Se,this.onBeforeCameraRenderObservable=new Se,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new Se,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new Se,this.onAfterActiveMeshesEvaluationObservable=new Se,this.onBeforeParticlesRenderingObservable=new Se,this.onAfterParticlesRenderingObservable=new Se,this.onDataLoadedObservable=new Se,this.onNewCameraAddedObservable=new Se,this.onCameraRemovedObservable=new Se,this.onNewLightAddedObservable=new Se,this.onLightRemovedObservable=new Se,this.onNewGeometryAddedObservable=new Se,this.onGeometryRemovedObservable=new Se,this.onNewTransformNodeAddedObservable=new Se,this.onTransformNodeRemovedObservable=new Se,this.onNewMeshAddedObservable=new Se,this.onMeshRemovedObservable=new Se,this.onNewSkeletonAddedObservable=new Se,this.onSkeletonRemovedObservable=new Se,this.onNewMaterialAddedObservable=new Se,this.onNewMultiMaterialAddedObservable=new Se,this.onMaterialRemovedObservable=new Se,this.onMultiMaterialRemovedObservable=new Se,this.onNewTextureAddedObservable=new Se,this.onTextureRemovedObservable=new Se,this.onBeforeRenderTargetsRenderObservable=new Se,this.onAfterRenderTargetsRenderObservable=new Se,this.onBeforeStepObservable=new Se,this.onAfterStepObservable=new Se,this.onActiveCameraChanged=new Se,this.onActiveCamerasChanged=new Se,this.onBeforeRenderingGroupObservable=new Se,this.onAfterRenderingGroupObservable=new Se,this.onMeshImportedObservable=new Se,this.onAnimationFileImportedObservable=new Se,this._registeredForLateAnimationBindings=new z9(256),this._pointerPickingConfiguration=new c3e,this.onPrePointerObservable=new Se,this.onPointerObservable=new Se,this.onPreKeyboardObservable=new Se,this.onKeyboardObservable=new Se,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=oi.FOGMODE_NONE,this.fogColor=new Ie(.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 O(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=new Array,this.importedMeshesFiles=new Array,this.probesEnabled=!0,this._meshesForIntersections=new z9(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Tc,this._activeIndices=new Tc,this._activeParticles=new Tc,this._activeBones=new Tc,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 Sc(256),this._processedMaterials=new Sc(256),this._renderTargets=new z9(256),this._materialsRenderTargets=new z9(256),this._activeParticleSystems=new Sc(256),this._activeSkeletons=new z9(32),this._softwareSkinnedMeshes=new z9(32),this._activeAnimatables=new Array,this._transformMatrix=ge.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=ac.Create(),this._beforeClearStage=ac.Create(),this._beforeRenderTargetClearStage=ac.Create(),this._gatherRenderTargetsStage=ac.Create(),this._gatherActiveCameraRenderTargetsStage=ac.Create(),this._isReadyForMeshStage=ac.Create(),this._beforeEvaluateActiveMeshStage=ac.Create(),this._evaluateSubMeshStage=ac.Create(),this._preActiveMeshStage=ac.Create(),this._cameraDrawRenderTargetStage=ac.Create(),this._beforeCameraDrawStage=ac.Create(),this._beforeRenderTargetDrawStage=ac.Create(),this._beforeRenderingGroupDrawStage=ac.Create(),this._beforeRenderingMeshStage=ac.Create(),this._afterRenderingMeshStage=ac.Create(),this._afterRenderingGroupDrawStage=ac.Create(),this._afterCameraDrawStage=ac.Create(),this._afterCameraPostProcessStage=ac.Create(),this._afterRenderTargetDrawStage=ac.Create(),this._afterRenderTargetPostProcessStage=ac.Create(),this._afterRenderStage=ac.Create(),this._pointerMoveStage=ac.Create(),this._pointerDownStage=ac.Create(),this._pointerUpStage=ac.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=new Array;const i=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);this._engine=e||Ii.LastCreatedEngine,i.virtual?this._engine._virtualScenes.push(this):(Ii._LastCreatedScene=this,this._engine.scenes.push(this)),this._uid=null,this._renderingManager=new pd(this),wj&&(this.postProcessManager=new wj(this)),ql()&&this.attachControl(),this._createUbo(),Dr&&(this._imageProcessingConfiguration=new Dr),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&this._engine.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.bind(this),this.getActiveSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getIntersectingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getCollidingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this)}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 t,i,s;if(this._isDisposed)return!1;let r;const n=this.getEngine(),o=n.currentRenderPassId;n.currentRenderPassId=(i=(t=this.activeCamera)===null||t===void 0?void 0:t.renderPassId)!==null&&i!==void 0?i:o;let l=!0;for(this._pendingData.length>0&&(l=!1),(s=this.prePassRenderer)===null||s===void 0||s.update(),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),r=0;r0;for(const p of this._isReadyForMeshStage)p.action(c,h)||(l=!1);if(!e)continue;const u=c.material||this.defaultMaterial;if(u)if(u._storeEffectOnSubMeshes)for(const p of c.subMeshes){const m=p.getMaterial();m&&m.hasRenderTargetTextures&&m.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(m)===-1&&(this._processedMaterials.push(m),this._materialsRenderTargets.concatWithNoDuplicate(m.getRenderTargetTextures()))}else u.hasRenderTargetTextures&&u.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(u)===-1&&(this._processedMaterials.push(u),this._materialsRenderTargets.concatWithNoDuplicate(u.getRenderTargetTextures()))}if(e)for(r=0;r0)for(const c of this.activeCameras)c.isReady(!0)||(l=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(l=!1));for(const c of this.particleSystems)c.isReady()||(l=!1);if(this.layers)for(const c of this.layers)c.isReady()||(l=!1);return n.areAllEffectsReady()||(l=!1),n.currentRenderPassId=o,l}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=Zr.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){!i&&!s&&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?p_.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=p_.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):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 es(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 VG.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(s=>{this.removeMesh(s)}),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 s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;const n=this.getBoneById(e);return n||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;const n=this.getBoneByName(e);return n||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=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let n=0;ne.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((e=this.activeCamera)===null||e===void 0||e._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 s=this._activeMeshes.length;for(let r=0;r0&&(r.layerMask&this.activeCamera.layerMask)!==0&&(this._skipFrustumClipping||r.alwaysSelectAsActiveMesh||r.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(r),this.activeCamera._activeMeshes.push(r),n!==r&&n._activate(this._renderId,!1);for(const o of this._preActiveMeshStage)o.action(r);r._activate(this._renderId,!1)&&(r.isAnInstance?r._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=r):n._internalAbstractMeshDataInfo._onlyForInstances=!1,n._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(r,n)),r._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let s=0;s0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||r===1;for(let n=0;n0&&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 c of this._gatherActiveCameraRenderTargetsStage)c.action(this._renderTargets);let l=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Be.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let c=0;c0),this._renderId++}for(const c of this._cameraDrawRenderTargetStage)l=c.action(this.activeCamera)||l;this._intermediateRendering=!1}this._engine.currentRenderPassId=(n=(r=(s=e.outputRenderTarget)===null||s===void 0?void 0:s.renderPassId)!==null&&r!==void 0?r:e.renderPassId)!==null&&n!==void 0?n:0,l&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(const c of this._beforeCameraDrawStage)c.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),o.snapshotRendering&&o.snapshotRenderingMode===1&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const c of this._afterCameraDrawStage)c.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const c=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,c)}for(const c of this._afterCameraPostProcessStage)c.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&&(s.trigger===13&&s._executeCurrent($o.CreateNew(t,void 0,n)),(!t.actionManager.hasSpecificTrigger(13,c=>{const h=c.mesh?c.mesh:c;return n===h})||s.trigger===13)&&t._intersectionsInProgress.splice(l,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(oi.MinDeltaTime,Math.min(this._engine.getDeltaTime(),oi.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let l=0;l0),this._intermediateRendering=!0;for(let l=0;l0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(r=o?.renderPassId)!==null&&r!==void 0?r:0,this.activeCamera=o,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const l of this._beforeClearStage)l.action();this._clearFrameBuffer(this.activeCamera);for(const l of this._gatherRenderTargetsStage)l.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let l=0;l0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const l of this._afterRenderStage)l.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let l=0;l{r.onAnimationEndObservable.clear(),r.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 r of e)r.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(r){console.error("An error occurred while calling onDisposeObservable!",r)}if(this.detachControl(),this._engine.getInputElement())for(let r=0;rr.dispose(!0)),this._disposeList(this.transformNodes,r=>r.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 s=this._engine.scenes.indexOf(this);s>-1&&this._engine.scenes.splice(s,1),Ii._LastCreatedScene===this&&(this._engine.scenes.length>0?Ii._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:Ii._LastCreatedScene=null),s=this._engine._virtualScenes.indexOf(this),s>-1&&this._engine._virtualScenes.splice(s,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??(s=>s.dispose());for(const s of i)t(s);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach(s=>{if(s.computeWorldMatrix(!0),!s.subMeshes||s.subMeshes.length===0||s.infiniteDistance)return;const r=s.getBoundingInfo(),n=r.boundingBox.minimumWorld,o=r.boundingBox.maximumWorld;O.CheckExtends(n,t,i),O.CheckExtends(o,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw Ys("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,o=!1){throw Ys("Ray")}createPickingRayInCameraSpace(e,t,i){throw Ys("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw Ys("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){return new cu}pickWithBoundingInfo(e,t,i,s,r){return new cu}pickWithRay(e,t,i,s){throw Ys("Ray")}multiPick(e,t,i,s,r){throw Ys("Ray")}multiPickWithRay(e,t,i){throw Ys("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();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;const s=[];i=i||(r=>{});for(const r in e){const n=e[r];Nr&&Nr.MatchesQuery(n,t)&&(s.push(n),i(n))}return s}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,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(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,s,r,n,o){const l=CI(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}_loadFileAsync(e,t,i,s,r){return new Promise((n,o)=>{this._loadFile(e,l=>{n(l)},t,i,s,(l,c)=>{o(c)},r)})}_requestFile(e,t,i,s,r,n,o){const l=gK(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}_requestFileAsync(e,t,i,s,r){return new Promise((n,o)=>{this._requestFile(e,l=>{n(l)},t,i,s,l=>{o(l)},r)})}_readFile(e,t,i,s,r){const n=BB(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),n}_readFileAsync(e,t,i){return new Promise((s,r)=>{this._readFile(e,n=>{s(n)},t,i,n=>{r(n)})})}getPerfCollector(){throw Ys("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)}}oi.FOGMODE_NONE=0;oi.FOGMODE_EXP=1;oi.FOGMODE_EXP2=2;oi.FOGMODE_LINEAR=3;oi.MinDeltaTime=1;oi.MaxDeltaTime=1e3;class sle{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new rle(e)}sampleFrame(e=Zr.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 rle{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}}Oi.prototype.setAlphaConstants=function(a,e,t,i){this._alphaState.setAlphaBlendConstants(a,e,t,i)};Oi.prototype.setAlphaMode=function(a,e=!1){if(this._alphaMode===a){if(!e){const t=a===0;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(a){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=a===0),this._alphaMode=a};Oi.prototype.getAlphaMode=function(){return this._alphaMode};Oi.prototype.setAlphaEquation=function(a){if(this._alphaEquation!==a){switch(a){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=a}};Oi.prototype.getAlphaEquation=function(){return this._alphaEquation};function lX(a,e,t=!1,i){switch(a){case 3:{const r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e);return i&&r.set(new Int8Array(i)),r}case 0:{const r=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&r.set(new Uint8Array(i)),r}case 4:{const r=e instanceof ArrayBuffer?new Int16Array(e):new Int16Array(t?e/2:e);return i&&r.set(new Int16Array(i)),r}case 5:case 8:case 9:case 10:case 2:{const r=e instanceof ArrayBuffer?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&r.set(new Uint16Array(i)),r}case 6:{const r=e instanceof ArrayBuffer?new Int32Array(e):new Int32Array(t?e/4:e);return i&&r.set(new Int32Array(i)),r}case 7:case 11:case 12:case 13:case 14:case 15:{const r=e instanceof ArrayBuffer?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&r.set(new Uint32Array(i)),r}case 1:{const r=e instanceof ArrayBuffer?new Float32Array(e):new Float32Array(t?e/4:e);return i&&r.set(new Float32Array(i)),r}}const s=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}Oi.prototype._readTexturePixelsSync=function(a,e,t,i=-1,s=0,r=null,n=!0,o=!1,l=0,c=0){var h,u;const p=this._gl;if(!p)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const _=p.createFramebuffer();if(!_)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=_}p.bindFramebuffer(p.FRAMEBUFFER,this._dummyFramebuffer),i>-1?p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_CUBE_MAP_POSITIVE_X+i,(h=a._hardwareTexture)===null||h===void 0?void 0:h.underlyingResource,s):p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,(u=a._hardwareTexture)===null||u===void 0?void 0:u.underlyingResource,s);let m=a.type!==void 0?this._getWebGLTextureType(a.type):p.UNSIGNED_BYTE;if(o)r||(r=lX(a.type,4*e*t));else switch(m){case p.UNSIGNED_BYTE:r||(r=new Uint8Array(4*e*t)),m=p.UNSIGNED_BYTE;break;default:r||(r=new Float32Array(4*e*t)),m=p.FLOAT;break}return n&&this.flushFramebuffer(),p.readPixels(l,c,e,t,p.RGBA,m,r),p.bindFramebuffer(p.FRAMEBUFFER,this._currentFramebuffer),r};Oi.prototype._readTexturePixels=function(a,e,t,i=-1,s=0,r=null,n=!0,o=!1,l=0,c=0){return Promise.resolve(this._readTexturePixelsSync(a,e,t,i,s,r,n,o,l,c))};Oi.prototype.updateDynamicIndexBuffer=function(a,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(a);let i;a.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()};Oi.prototype.updateDynamicVertexBuffer=function(a,e,t,i){this.bindArrayBuffer(a),t===void 0&&(t=0);const s=e.byteLength||e.length;i===void 0||i>=s&&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 He extends Oi{static get NpmPackage(){return Oi.NpmPackage}static get Version(){return Oi.Version}static get Instances(){return Ii.Instances}static get LastCreatedEngine(){return Ii.LastCreatedEngine}static get LastCreatedScene(){return Ii.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{this.createImageBitmap(n,t).then(o=>{s(o)})})},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=e})}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const r=this.createCanvas(t,i).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(e,0,0),r.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(),!He.audioEngine&&this._creationOptions.audioEngine&&He.AudioEngineFactory&&(He.audioEngine=He.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),Zb()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&He._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=He.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===void 0||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,s){const r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),r}scissorClear(e,t,i,s,r){this.enableScissor(e,t,i,s),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,s)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}initWebVR(){throw Ys("WebVRCamera")}_prepareVRComponent(){}_connectVREvents(e,t){}_submitVRFrame(){}disableVR(){}isVRPresenting(){return!1}_requestVRFrame(){}_loadFileAsync(e,t,i){return new Promise((s,r)=>{this._loadFile(e,n=>{s(n)},void 0,t,i,(n,o)=>{r(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,s){e!==void 0&&(t&&(this._boundUniforms[e]=t),!i||!i.depthStencilTexture?this._setTexture(e,null,void 0,void 0,s):this._setTexture(e,i,!1,!0,s))}setTextureFromPostProcess(e,t,i){var s;let r=null;t&&(t._forcedOutputTexture?r=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(r=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,(s=r?.texture)!==null&&s!==void 0?s:null,i)}setTextureFromPostProcessOutput(e,t,i){var s,r;this._bindTexture(e,(r=(s=t?._outputTexture)===null||s===void 0?void 0:s.texture)!==null&&r!==void 0?r:null,i)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this.isVRPresenting()?this._requestVRFrame():this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&He._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&He._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&He._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){He._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this._submitVRFrame(),this.onEndFrameObservable.notifyObservers(this)}resize(e=!1){this.isVRPresenting()||super.resize(e)}setSize(e,t,i=!1){if(!this._renderingCanvas||!super.setSize(e,t,i))return!1;if(this.scenes){for(let s=0;s1&&r){const o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=o}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_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(s=>{s&&s._outputTexture===e&&(s._outputTexture=null)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++He._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(l){l._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()}))}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){const s=new gF(e,this._gl),r=new dn(this,hr.Unknown,!0);return r._hardwareTexture=s,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,o),c=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(c,e,!0),this._unpackFlipY(e.invertY);let h=r.TEXTURE_2D;e.isCube&&(h=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(h,s,l,o,n,t),this._bindTextureDirectly(c,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){Me.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 OB(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 s=this._gl;return new Promise((r,n)=>{const o=()=>{const l=s.clientWaitSync(e,t,0);if(l==s.WAIT_FAILED){n();return}if(l==s.TIMEOUT_EXPIRED){setTimeout(o,i);return}r()};o()})}_readPixelsAsync(e,t,i,s,r,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const l=this._gl,c=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,c),l.bufferData(l.PIXEL_PACK_BUFFER,o.byteLength,l.STREAM_READ),l.readPixels(e,t,i,s,r,n,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null);const h=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(l.flush(),this._clientWaitAsync(h,0,10).then(()=>(l.deleteSync(h),l.bindBuffer(l.PIXEL_PACK_BUFFER,c),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,o),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(c),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();Ii.Instances.length===1&&He.audioEngine&&(He.audioEngine.dispose(),He.audioEngine=null),this.disableVR();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)),Zb()&&(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=Ii.Instances.indexOf(this);t>=0&&Ii.Instances.splice(t,1),He.Instances.length||Ii.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(!ql())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!ql())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=He.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 s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let r=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:r,height:n,descent:n-r}}}He.ALPHA_DISABLE=0;He.ALPHA_ADD=1;He.ALPHA_COMBINE=2;He.ALPHA_SUBTRACT=3;He.ALPHA_MULTIPLY=4;He.ALPHA_MAXIMIZED=5;He.ALPHA_ONEONE=6;He.ALPHA_PREMULTIPLIED=7;He.ALPHA_PREMULTIPLIED_PORTERDUFF=8;He.ALPHA_INTERPOLATE=9;He.ALPHA_SCREENMODE=10;He.DELAYLOADSTATE_NONE=0;He.DELAYLOADSTATE_LOADED=1;He.DELAYLOADSTATE_LOADING=2;He.DELAYLOADSTATE_NOTLOADED=4;He.NEVER=512;He.ALWAYS=519;He.LESS=513;He.EQUAL=514;He.LEQUAL=515;He.GREATER=516;He.GEQUAL=518;He.NOTEQUAL=517;He.KEEP=7680;He.REPLACE=7681;He.INCR=7682;He.DECR=7683;He.INVERT=5386;He.INCR_WRAP=34055;He.DECR_WRAP=34056;He.TEXTURE_CLAMP_ADDRESSMODE=0;He.TEXTURE_WRAP_ADDRESSMODE=1;He.TEXTURE_MIRROR_ADDRESSMODE=2;He.TEXTUREFORMAT_ALPHA=0;He.TEXTUREFORMAT_LUMINANCE=1;He.TEXTUREFORMAT_LUMINANCE_ALPHA=2;He.TEXTUREFORMAT_RGB=4;He.TEXTUREFORMAT_RGBA=5;He.TEXTUREFORMAT_RED=6;He.TEXTUREFORMAT_R=6;He.TEXTUREFORMAT_RG=7;He.TEXTUREFORMAT_RED_INTEGER=8;He.TEXTUREFORMAT_R_INTEGER=8;He.TEXTUREFORMAT_RG_INTEGER=9;He.TEXTUREFORMAT_RGB_INTEGER=10;He.TEXTUREFORMAT_RGBA_INTEGER=11;He.TEXTURETYPE_UNSIGNED_BYTE=0;He.TEXTURETYPE_UNSIGNED_INT=0;He.TEXTURETYPE_FLOAT=1;He.TEXTURETYPE_HALF_FLOAT=2;He.TEXTURETYPE_BYTE=3;He.TEXTURETYPE_SHORT=4;He.TEXTURETYPE_UNSIGNED_SHORT=5;He.TEXTURETYPE_INT=6;He.TEXTURETYPE_UNSIGNED_INTEGER=7;He.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;He.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;He.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;He.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;He.TEXTURETYPE_UNSIGNED_INT_24_8=12;He.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;He.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;He.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;He.TEXTURE_NEAREST_SAMPLINGMODE=1;He.TEXTURE_BILINEAR_SAMPLINGMODE=2;He.TEXTURE_TRILINEAR_SAMPLINGMODE=3;He.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;He.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;He.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;He.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;He.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;He.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;He.TEXTURE_NEAREST_LINEAR=7;He.TEXTURE_NEAREST_NEAREST=1;He.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;He.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;He.TEXTURE_LINEAR_LINEAR=2;He.TEXTURE_LINEAR_NEAREST=12;He.TEXTURE_EXPLICIT_MODE=0;He.TEXTURE_SPHERICAL_MODE=1;He.TEXTURE_PLANAR_MODE=2;He.TEXTURE_CUBIC_MODE=3;He.TEXTURE_PROJECTION_MODE=4;He.TEXTURE_SKYBOX_MODE=5;He.TEXTURE_INVCUBIC_MODE=6;He.TEXTURE_EQUIRECTANGULAR_MODE=7;He.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;He.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;He.SCALEMODE_FLOOR=1;He.SCALEMODE_NEAREST=2;He.SCALEMODE_CEILING=3;He._RescalePostProcessFactory=null;He._RenderPassIdCounter=0;Object.defineProperty(oi.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new zG(this)),this._debugLayer},enumerable:!0,configurable:!0});var Rq;(function(a){a[a.Properties=0]="Properties",a[a.Debug=1]="Debug",a[a.Statistics=2]="Statistics",a[a.Tools=3]="Tools",a[a.Settings=4]="Settings"})(Rq||(Rq={}));class zG{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new Se),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new Se),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||Ii.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=Object.assign({overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0},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:zG.InspectorURL;Be.LoadScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}zG.InspectorURL=`https://unpkg.com/babylonjs-inspector@${He.Version}/babylon.inspector.bundle.js`;var QN=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function UG(a){var e=a.default;if(typeof e=="function"){var t=function(){return e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(a).forEach(function(i){var s=Object.getOwnPropertyDescriptor(a,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return a[i]}})}),t}var EF={exports:{}};class Da{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new Se,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){}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const s=this._condition.serialize();return s.children.push(i),t&&t.children.push(s),s}return t&&t.children.push(i),i}}Da._SerializeValueAsString=a=>typeof a=="number"?a.toString():typeof a=="boolean"?a?"true":"false":a instanceof lt?a.x+", "+a.y:a instanceof O?a.x+", "+a.y+", "+a.z:a instanceof Ie?a.r+", "+a.g+", "+a.b:a instanceof Zt?a.r+", "+a.g+", "+a.b+", "+a.a:a;Da._GetTargetProperty=a=>({name:"target",targetType:a._isMesh?"MeshProperties":a._isLight?"LightProperties":a._isCamera?"CameraProperties":a._isMaterial?"MaterialProperties":"SceneProperties",value:a._isScene?"Scene":a.name});$e("BABYLON.Action",Da);class FB{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 tu extends FB{static get IsEqual(){return tu._IsEqual}static get IsDifferent(){return tu._IsDifferent}static get IsGreater(){return tu._IsGreater}static get IsLesser(){return tu._IsLesser}constructor(e,t,i,s,r=tu.IsEqual){super(e),this.propertyPath=i,this.value=s,this.operator=r,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case tu.IsGreater:return this._effectiveTarget[this._property]>this.value;case tu.IsLesser:return this._effectiveTarget[this._property]-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=mn.OnPickTrigger&&t.trigger<=mn.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=mn.OnPickTrigger&&t.trigger<=mn.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===mn.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(Me.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,mn.Triggers[e.trigger]?mn.Triggers[e.trigger]++:mn.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),mn.Triggers[e.trigger]-=1,mn.Triggers[e.trigger]===0&&delete mn.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0):!1}processTrigger(e,t){for(let i=0;i{const h=Bo("BABYLON."+l);return h&&new h(...c)},n=(l,c,h,u)=>{if(u===null){const f=parseFloat(c);return c==="true"||c==="false"?c==="true":isNaN(f)?c:f}const p=u.split("."),m=c.split(",");for(let f=0;f{if(l.detached)return;const m=new Array;let _=null,f=null;const d=l.combine&&l.combine.length>0;if(l.type===2?m.push(s):m.push(c),d){const v=new Array;for(let y=0;y0){const u=h.properties[0].value,p=h.properties[0].targetType===null?u:i.getMeshByName(u);p._meshId&&(p.mesh=i.getMeshById(p._meshId)),c={trigger:mn[h.name],parameter:p}}else c=mn[h.name];for(let u=0;u{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 s=0;s(!t||t(s))&&s.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 pn(e,this.getScene()),this);if(t&&(s.parent=t),!i){const r=this.getDescendants(!0);for(let n=0;n{throw Ys("AnimationRange")};pn._NodeConstructors={};z([X()],pn.prototype,"name",void 0);z([X()],pn.prototype,"id",void 0);z([X()],pn.prototype,"uniqueId",void 0);z([X()],pn.prototype,"state",void 0);z([X()],pn.prototype,"metadata",void 0);class __{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 __(this.width*e,this.height*t)}clone(){return new __(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 __(0,0)}add(e){return new __(this.width+e.width,this.height+e.height)}subtract(e){return new __(this.width-e.width,this.height-e.height)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new __(s,r)}}class u3e{}const Tb={key:0,repeatCount:0,loopMode:2};class at{static _PrepareAnimation(e,t,i,s,r,n,o,l){let c;if(!isNaN(parseFloat(r))&&isFinite(r)?c=at.ANIMATIONTYPE_FLOAT:r instanceof ke?c=at.ANIMATIONTYPE_QUATERNION:r instanceof O?c=at.ANIMATIONTYPE_VECTOR3:r instanceof lt?c=at.ANIMATIONTYPE_VECTOR2:r instanceof Ie?c=at.ANIMATIONTYPE_COLOR3:r instanceof Zt?c=at.ANIMATIONTYPE_COLOR4:r instanceof __&&(c=at.ANIMATIONTYPE_SIZE),c==null)return null;const h=new at(e,t,i,c,o),u=[{frame:0,value:r},{frame:s,value:n}];return h.setKeys(u),l!==void 0&&h.setEasingFunction(l),h}static CreateAnimation(e,t,i,s){const r=new at(e+"Animation",e,i,t,at.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,o,l,c,h,u){const p=at._PrepareAnimation(e,i,s,r,n,o,l,c);return!p||(t.getScene&&(u=t.getScene()),!u)?null:u.beginDirectAnimation(t,[p],0,r,p.loopMode===1,1,h)}static CreateAndStartHierarchyAnimation(e,t,i,s,r,n,o,l,c,h,u){const p=at._PrepareAnimation(e,s,r,n,o,l,c,h);return p?t.getScene().beginDirectHierarchyAnimation(t,i,[p],0,n,p.loopMode===1,1,u):null}static CreateMergeAndStartAnimation(e,t,i,s,r,n,o,l,c,h){const u=at._PrepareAnimation(e,i,s,r,n,o,l,c);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,r,u.loopMode===1,1,h)):null}static MakeAnimationAdditive(e,t,i,s=!1,r){var n,o;let l;typeof t=="object"?l=t:l={referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let c=e;if(l.cloneOriginalAnimation&&(c=e.clone(),c.name=l.clonedAnimationName||c.name),!c._keys.length)return c;const h=l.referenceFrame&&l.referenceFrame>=0?l.referenceFrame:0;let u=0;const p=c._keys[0];let m=c._keys.length-1;const _=c._keys[m],f={referenceValue:p.value,referencePosition:ue.Vector3[0],referenceQuaternion:ue.Quaternion[0],referenceScaling:ue.Vector3[1],keyPosition:ue.Vector3[2],keyQuaternion:ue.Quaternion[1],keyScaling:ue.Vector3[3]};let d=p.frame,C=_.frame;if(l.range){const M=c.getRange(l.range);M&&(d=M.from,C=M.to)}else d=(n=l.fromFrame)!==null&&n!==void 0?n:d,C=(o=l.toFrame)!==null&&o!==void 0?o:C;if(d!==p.frame&&(u=c.createKeyForFrame(d)),C!==_.frame&&(m=c.createKeyForFrame(C)),c._keys.length===1){const M=c._getKeyValue(c._keys[0]);f.referenceValue=M.clone?M.clone():M}else if(h<=p.frame){const M=c._getKeyValue(p.value);f.referenceValue=M.clone?M.clone():M}else if(h>=_.frame){const M=c._getKeyValue(_.value);f.referenceValue=M.clone?M.clone():M}else{Tb.key=0;const M=c._interpolate(h,Tb);f.referenceValue=M.clone?M.clone():M}c.dataType===at.ANIMATIONTYPE_QUATERNION?f.referenceValue.normalize().conjugateInPlace():c.dataType===at.ANIMATIONTYPE_MATRIX&&(f.referenceValue.decompose(f.referenceScaling,f.referenceQuaternion,f.referencePosition),f.referenceQuaternion.normalize().conjugateInPlace());let v=Number.MAX_VALUE;const y=l.clipKeys?[]:null;for(let M=u;M<=m;M++){let b=c._keys[M];if(y&&(b={frame:b.frame,value:b.value.clone?b.value.clone():b.value,inTangent:b.inTangent,outTangent:b.outTangent,interpolation:b.interpolation,lockedTangent:b.lockedTangent},v===Number.MAX_VALUE&&(v=b.frame),b.frame-=v,y.push(b)),!(M&&c.dataType!==at.ANIMATIONTYPE_FLOAT&&b.value===p.value))switch(c.dataType){case at.ANIMATIONTYPE_MATRIX:b.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),ge.ComposeToRef(f.keyScaling,f.keyQuaternion,f.keyPosition,b.value);break;case at.ANIMATIONTYPE_QUATERNION:f.referenceValue.multiplyToRef(b.value,b.value);break;case at.ANIMATIONTYPE_VECTOR2:case at.ANIMATIONTYPE_VECTOR3:case at.ANIMATIONTYPE_COLOR3:case at.ANIMATIONTYPE_COLOR4:b.value.subtractToRef(f.referenceValue,b.value);break;case at.ANIMATIONTYPE_SIZE:b.value.width-=f.referenceValue.width,b.value.height-=f.referenceValue.height;break;default:b.value-=f.referenceValue}}return y&&c.setKeys(y,!0),c}static TransitionTo(e,t,i,s,r,n,o,l=null){if(o<=0)return i[e]=t,l&&l(),null;const c=r*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:c,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const h=s.beginAnimation(i,0,c,!1);return h.onAnimationEnd=l,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,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=r===void 0?at.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=at._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 s in this._ranges)i&&(t+=", ",i=!1),t+=s;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;n--)this._keys[n].frame>=s&&this._keys[n].frame<=r&&this._keys.splice(n,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 s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const o=s[n],l=s[n+1];if(i&&(e===o.frame||e===l.frame))return;const c=this._getKeyValue(o.value),h=this._getKeyValue(l.value);if(o.interpolation===kP.STEP)return l.frame>e?c:h;const u=o.outTangent!==void 0&&l.inTangent!==void 0,p=l.frame-o.frame;let m=(e-o.frame)/p;const _=this.getEasingFunction();switch(_!==null&&(m=_.ease(m)),this.dataType){case at.ANIMATIONTYPE_FLOAT:{const f=u?this.floatInterpolateFunctionWithTangents(c,o.outTangent*p,h,l.inTangent*p,m):this.floatInterpolateFunction(c,h,m);switch(t.loopMode){case at.ANIMATIONLOOPMODE_CYCLE:case at.ANIMATIONLOOPMODE_CONSTANT:case at.ANIMATIONLOOPMODE_YOYO:return f;case at.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+f}break}case at.ANIMATIONTYPE_QUATERNION:{const f=u?this.quaternionInterpolateFunctionWithTangents(c,o.outTangent.scale(p),h,l.inTangent.scale(p),m):this.quaternionInterpolateFunction(c,h,m);switch(t.loopMode){case at.ANIMATIONLOOPMODE_CYCLE:case at.ANIMATIONLOOPMODE_CONSTANT:case at.ANIMATIONLOOPMODE_YOYO:return f;case at.ANIMATIONLOOPMODE_RELATIVE:return f.addInPlace(t.offsetValue.scale(t.repeatCount))}return f}case at.ANIMATIONTYPE_VECTOR3:{const f=u?this.vector3InterpolateFunctionWithTangents(c,o.outTangent.scale(p),h,l.inTangent.scale(p),m):this.vector3InterpolateFunction(c,h,m);switch(t.loopMode){case at.ANIMATIONLOOPMODE_CYCLE:case at.ANIMATIONLOOPMODE_CONSTANT:case at.ANIMATIONLOOPMODE_YOYO:return f;case at.ANIMATIONLOOPMODE_RELATIVE:return f.add(t.offsetValue.scale(t.repeatCount))}break}case at.ANIMATIONTYPE_VECTOR2:{const f=u?this.vector2InterpolateFunctionWithTangents(c,o.outTangent.scale(p),h,l.inTangent.scale(p),m):this.vector2InterpolateFunction(c,h,m);switch(t.loopMode){case at.ANIMATIONLOOPMODE_CYCLE:case at.ANIMATIONLOOPMODE_CONSTANT:case at.ANIMATIONLOOPMODE_YOYO:return f;case at.ANIMATIONLOOPMODE_RELATIVE:return f.add(t.offsetValue.scale(t.repeatCount))}break}case at.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case at.ANIMATIONLOOPMODE_CYCLE:case at.ANIMATIONLOOPMODE_CONSTANT:case at.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(c,h,m);case at.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(c,h,m).add(t.offsetValue.scale(t.repeatCount))}break}case at.ANIMATIONTYPE_COLOR3:{const f=u?this.color3InterpolateFunctionWithTangents(c,o.outTangent.scale(p),h,l.inTangent.scale(p),m):this.color3InterpolateFunction(c,h,m);switch(t.loopMode){case at.ANIMATIONLOOPMODE_CYCLE:case at.ANIMATIONLOOPMODE_CONSTANT:case at.ANIMATIONLOOPMODE_YOYO:return f;case at.ANIMATIONLOOPMODE_RELATIVE:return f.add(t.offsetValue.scale(t.repeatCount))}break}case at.ANIMATIONTYPE_COLOR4:{const f=u?this.color4InterpolateFunctionWithTangents(c,o.outTangent.scale(p),h,l.inTangent.scale(p),m):this.color4InterpolateFunction(c,h,m);switch(t.loopMode){case at.ANIMATIONLOOPMODE_CYCLE:case at.ANIMATIONLOOPMODE_CONSTANT:case at.ANIMATIONLOOPMODE_YOYO:return f;case at.ANIMATIONLOOPMODE_RELATIVE:return f.add(t.offsetValue.scale(t.repeatCount))}break}case at.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case at.ANIMATIONLOOPMODE_CYCLE:case at.ANIMATIONLOOPMODE_CONSTANT:case at.ANIMATIONLOOPMODE_YOYO:return at.AllowMatricesInterpolation?this.matrixInterpolateFunction(c,h,m,t.workValue):c;case at.ANIMATIONLOOPMODE_RELATIVE:return c}break}}return 0}matrixInterpolateFunction(e,t,i,s){return at.AllowMatrixDecomposeForInterpolation?s?(ge.DecomposeLerpToRef(e,t,i,s),s):ge.DecomposeLerp(e,t,i):s?(ge.LerpToRef(e,t,i,s),s):ge.Lerp(e,t,i)}clone(){const e=new at(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){Tb.key=0;const t=this._interpolate(e,Tb,!0);if(!t)return Tb.key===e?Tb.key:Tb.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Tb.key+1,0,i),Tb.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 s=0;s=2&&(l=o.values[1]),o.values.length>=3&&(c=o.values[2]),o.values.length>=4&&(h=o.values[3]);break;case at.ANIMATIONTYPE_QUATERNION:if(r=ke.FromArray(o.values),o.values.length>=8){const p=ke.FromArray(o.values.slice(4,8));p.equals(ke.Zero())||(l=p)}if(o.values.length>=12){const p=ke.FromArray(o.values.slice(8,12));p.equals(ke.Zero())||(c=p)}o.values.length>=13&&(h=o.values[12]);break;case at.ANIMATIONTYPE_MATRIX:r=ge.FromArray(o.values),o.values.length>=17&&(h=o.values[16]);break;case at.ANIMATIONTYPE_COLOR3:r=Ie.FromArray(o.values),o.values[3]&&(l=Ie.FromArray(o.values[3])),o.values[4]&&(c=Ie.FromArray(o.values[4])),o.values[5]&&(h=o.values[5]);break;case at.ANIMATIONTYPE_COLOR4:r=Zt.FromArray(o.values),o.values[4]&&(l=Zt.FromArray(o.values[4])),o.values[5]&&(c=Zt.FromArray(o.values[5])),o.values[6]&&(h=Zt.FromArray(o.values[6]));break;case at.ANIMATIONTYPE_VECTOR3:default:r=O.FromArray(o.values),o.values[3]&&(l=O.FromArray(o.values[3])),o.values[4]&&(c=O.FromArray(o.values[4])),o.values[5]&&(h=o.values[5]);break}const u={};u.frame=o.frame,u.value=r,l!=null&&(u.inTangent=l),c!=null&&(u.outTangent=c),h!=null&&(u.interpolation=h),s.push(u)}if(t.setKeys(s),e.ranges)for(n=0;n{const r=new wl;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){let n=JSON.parse(r.responseText);if(n.animations&&(n=n.animations),n.length){const o=new Array;for(const l of n)o.push(this.Parse(l));i(o)}else{const o=this.Parse(n);e&&(o.name=e),i(o)}}else s("Unable to load the animation")}),r.open("GET",t),r.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{const s=new wl;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){const r=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(r.animations){const n=JSON.parse(r.animations),o=new Array;for(const l of n.animations){const c=this.Parse(l);c.snippetId=e,o.push(c)}t(o)}else{const n=JSON.parse(r.animation),o=this.Parse(n);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()})}}at._UniqueIdGenerator=0;at.AllowMatricesInterpolation=!1;at.AllowMatrixDecomposeForInterpolation=!0;at.SnippetUrl="https://snippet.babylonjs.com";at.ANIMATIONTYPE_FLOAT=0;at.ANIMATIONTYPE_VECTOR3=1;at.ANIMATIONTYPE_QUATERNION=2;at.ANIMATIONTYPE_MATRIX=3;at.ANIMATIONTYPE_COLOR3=4;at.ANIMATIONTYPE_COLOR4=7;at.ANIMATIONTYPE_VECTOR2=5;at.ANIMATIONTYPE_SIZE=6;at.ANIMATIONLOOPMODE_RELATIVE=0;at.ANIMATIONLOOPMODE_CYCLE=1;at.ANIMATIONLOOPMODE_CONSTANT=2;at.ANIMATIONLOOPMODE_YOYO=4;at.CreateFromSnippetAsync=at.ParseFromSnippetAsync;$e("BABYLON.Animation",at);pn._AnimationRangeFactory=(a,e,t)=>new HP(a,e,t);class cX extends Da{constructor(e,t,i,s,r=1e3,n,o,l){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new Se,this.propertyPath=i,this.value=s,this.duration=r,this.stopOtherAnimations=o,this.onInterpolationDone=l,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=at.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Ie)i=at.ANIMATIONTYPE_COLOR3;else if(this.value instanceof O)i=at.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof ge)i=at.ANIMATIONTYPE_MATRIX;else if(this.value instanceof ke)i=at.ANIMATIONTYPE_QUATERNION;else{Me.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}const s=new at("InterpolateValueAction",this._property,100*(1e3/this.duration),i,at.ANIMATIONLOOPMODE_CONSTANT);s.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget);const r=()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()};e.beginDirectAnimation(this._effectiveTarget,[s],0,100,!1,1,r)}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Da._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Da._SerializeValueAsString(this.value)},{name:"duration",value:Da._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Da._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}$e("BABYLON.InterpolateValueAction",cX);const d3e=Object.freeze(new ke(0,0,0,0)),f3e=Object.freeze(O.Zero()),p3e=Object.freeze(lt.Zero()),m3e=Object.freeze(__.Zero()),_3e=Object.freeze(Ie.Black());class gle{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,s){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=s,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===at.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=ge.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 n={frame:0,value:this._minValue};this._keys.splice(0,0,n)}if(this._target instanceof Array){let n=0;for(const o of this._target)this._preparePath(o,n),this._getOriginalValues(n),n++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach(n=>{this._events.push(n._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 s=e[i[0]];for(let r=1;r-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 r=0;rthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let u,p=e*(o.framePerSecond*r)/1e3+this._absoluteFrameOffset,m=0;if(s&&this._animationState.loopMode===at.ANIMATIONLOOPMODE_YOYO){const C=(p-t)/h;p=Math.abs(Math.sin(C*Math.PI))*h+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=p,!s&&i>=t&&p>=h)c=!1,m=o._getKeyValue(this._maxValue);else if(!s&&t>=i&&p<=h)c=!1,m=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==at.ANIMATIONLOOPMODE_CYCLE){const C=i.toString()+t.toString();if(!this._offsetsCache[C]){this._animationState.repeatCount=0,this._animationState.loopMode=at.ANIMATIONLOOPMODE_CYCLE;const v=o._interpolate(t,this._animationState),y=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case at.ANIMATIONTYPE_FLOAT:this._offsetsCache[C]=y-v;break;case at.ANIMATIONTYPE_QUATERNION:this._offsetsCache[C]=y.subtract(v);break;case at.ANIMATIONTYPE_VECTOR3:this._offsetsCache[C]=y.subtract(v);break;case at.ANIMATIONTYPE_VECTOR2:this._offsetsCache[C]=y.subtract(v);break;case at.ANIMATIONTYPE_SIZE:this._offsetsCache[C]=y.subtract(v);break;case at.ANIMATIONTYPE_COLOR3:this._offsetsCache[C]=y.subtract(v);break}this._highLimitsCache[C]=y}m=this._highLimitsCache[C],u=this._offsetsCache[C]}if(u===void 0)switch(o.dataType){case at.ANIMATIONTYPE_FLOAT:u=0;break;case at.ANIMATIONTYPE_QUATERNION:u=d3e;break;case at.ANIMATIONTYPE_VECTOR3:u=f3e;break;case at.ANIMATIONTYPE_VECTOR2:u=p3e;break;case at.ANIMATIONTYPE_SIZE:u=m3e;break;case at.ANIMATIONTYPE_COLOR3:u=_3e}let _;if(this._host&&this._host.syncRoot){const C=this._host.syncRoot,v=(C.masterFrame-C.fromFrame)/(C.toFrame-C.fromFrame);_=t+h*v}else p>0&&t>i||p<0&&t0&&this.currentFrame>_||r<0&&this.currentFrame<_){this._onLoop();for(let C=0;C0?0:o.getKeys().length-1}this._currentFrame=_,this._animationState.repeatCount=h===0?0:p/h>>0,this._animationState.highLimitValue=m,this._animationState.offsetValue=u;const d=o._interpolate(_,this._animationState);if(this.setValue(d,n),f.length){for(let C=0;C0&&_>=f[C].frame&&f[C].frame>=t||h<0&&_<=f[C].frame&&f[C].frame<=t){const v=f[C];v.isDone||(v.onlyOnce&&(f.splice(C,1),C--),v.isDone=!0,v.action(_))}}return c||(this._stopped=!0),c}}var sr;(function(a){a[a.LOCAL=0]="LOCAL",a[a.WORLD=1]="WORLD",a[a.BONE=2]="BONE"})(sr||(sr={}));class Fo{}Fo.X=new O(1,0,0);Fo.Y=new O(0,1,0);Fo.Z=new O(0,0,1);var pL;(function(a){a[a.X=0]="X",a[a.Y=1]="Y",a[a.Z=2]="Z"})(pL||(pL={}));class ca extends pn{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,s=null,r=null,n=null,o=null){var l;super(e,t.getScene()),this.name=e,this.children=new Array,this.animations=new Array,this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=(l=s?.clone())!==null&&l!==void 0?l:ge.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new ge,this._absoluteBindMatrix=new ge,this._absoluteInverseBindMatrix=new ge,this._finalMatrix=new ge,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(){var e;if(this._linkedTransformNode){const t=ue.Vector3[0],i=ue.Quaternion[0],s=ue.Vector3[1];this.getRestMatrix().decompose(t,i,s),this._linkedTransformNode.position.copyFrom(s),this._linkedTransformNode.rotationQuaternion=(e=this._linkedTransformNode.rotationQuaternion)!==null&&e!==void 0?e:ke.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}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=O.Zero(),this._localRotation=ke.Zero(),this._localPosition=O.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(!!this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,ge.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(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const r=this._runtimeAnimations;for(let n=r.length-1;n>=0;n--){const o=r[n];e&&o.animation.name!=e||t&&!t(o.target)||(o.dispose(),r.splice(n,1))}r.length==0&&(i||this._scene._activeAnimatables.splice(s,1),this._raiseOnAnimationEnd())}}else{const s=this._scene._activeAnimatables.indexOf(this);if(s>-1){i||this._scene._activeAnimatables.splice(s,1);const r=this._runtimeAnimations;for(let n=0;n{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 s;for(s=0;s0)return;this._animationTimeLast=a}this.deltaTime=this.useConstantAnimationDeltaTime?16:(a-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=a;const e=this._activeAnimatables;if(e.length===0)return;this._animationTime+=this.deltaTime;const t=this._animationTime;for(let i=0;ia.playOrder-e.playOrder)};oi.prototype.beginWeightedAnimation=function(a,e,t,i=1,s,r=1,n,o,l,c,h=!1){const u=this.beginAnimation(a,e,t,s,r,n,o,!1,l,c,h);return u.weight=i,u};oi.prototype.beginAnimation=function(a,e,t,i,s=1,r,n,o=!0,l,c,h=!1){e>t&&s>0&&(s*=-1),o&&this.stopAnimation(a,void 0,l),n||(n=new G$(this,a,e,t,i,s,r,void 0,c,h));const u=l?l(a):!0;if(a.animations&&u&&n.appendAnimations(a,a.animations),a.getAnimatables){const p=a.getAnimatables();for(let m=0;mi&&r>0)r*=-1;else if(i>t&&r<0){const h=i;i=t,t=h}return new G$(this,a,t,i,s,r,n,e,o,l)};oi.prototype.beginDirectHierarchyAnimation=function(a,e,t,i,s,r,n,o,l,c=!1){const h=a.getDescendants(e),u=[];u.push(this.beginDirectAnimation(a,t,i,s,r,n,o,l,c));for(const p of h)u.push(this.beginDirectAnimation(p,t,i,s,r,n,o,l,c));return u};oi.prototype.getAnimatableByTarget=function(a){for(let e=0;e0?l:-l,s),m.scaleAndAddToRef(l,t)}s.normalize()}for(let u=0;u0)s.copyFrom(i);else if(a.animations.length===1){if(ke.SlerpToRef(i,t.currentValue,Math.min(1,a.totalWeight),s),a.totalAdditiveWeight===0)return s}else if(a.animations.length>1){let r=1,n,o;if(a.totalWeight<1){const c=1-a.totalWeight;n=[],o=[],n.push(i),o.push(c)}else{if(a.animations.length===2&&(ke.SlerpToRef(a.animations[0].currentValue,a.animations[1].currentValue,a.animations[1].weight/a.totalWeight,e),a.totalAdditiveWeight===0))return e;n=[],o=[],r=a.totalWeight}for(let c=0;c=n&&d.frame<=o&&(i?(v=d.value.clone(),p?(C=v.getTranslation(),v.setTranslation(C.scaleInPlace(m))):_&&s?(C=v.getTranslation(),v.setTranslation(C.multiplyInPlace(s))):v=d.value):v=d.value,f.push({frame:d.frame+t,value:v}));return this.animations[0].createRange(e,n+t,o+t),!0};class g3e{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=at.ANIMATIONLOOPMODE_CYCLE}}var TP;(function(a){a[a.CW=0]="CW",a[a.CCW=1]="CCW"})(TP||(TP={}));class vle{static Interpolate(e,t,i,s,r){const n=1-3*s+3*t,o=3*s-6*t,l=3*t;let c=e;for(let h=0;h<5;h++){const u=c*c,p=u*c,m=n*p+o*u+l*c,_=1/(3*n*u+2*o*c+l);c-=(m-e)*_,c=Math.min(1,Math.max(0,c))}return 3*Math.pow(1-c,2)*c*i+3*(1-c)*Math.pow(c,2)*r+Math.pow(c,3)}}class $9{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),s=Math.atan2(i.y,i.x);return new $9(s)}static FromRadians(e){return new $9(e)}static FromDegrees(e){return new $9(e*Math.PI/180)}}class Cle{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,n=(s-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 lt((r*(t.y-i.y)-n*(e.y-t.y))/o,((e.x-t.x)*n-(t.x-i.x)*r)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=$9.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let c=$9.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=$9.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-l>180&&(c-=360),c-l<-180&&(c+=360),h-c>180&&(h-=360),h-c<-180&&(h+=360),this.orientation=c-l<0?TP.CW:TP.CCW,this.angle=$9.FromDegrees(this.orientation===TP.CW?l-h:h-l)}}class yF{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new lt(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new lt(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,r=36){if(this.closed)return this;const n=this._points[this._points.length-1],o=new lt(e,t),l=new lt(i,s),c=new Cle(n,o,l);let h=c.angle.radians()/r;c.orientation===TP.CW&&(h*=-1);let u=c.startAngle.radians()+h;for(let p=0;p(1-l)*(1-l)*c+2*l*(1-l)*h+l*l*u,o=this._points[this._points.length-1];for(let l=0;l<=r;l++){const c=l/r,h=n(c,o.x,e,i),u=n(c,o.y,t,s);this.addLineTo(h,u)}return this}addBezierCurveTo(e,t,i,s,r,n,o=36){if(this.closed)return this;const l=(h,u,p,m,_)=>(1-h)*(1-h)*(1-h)*u+3*h*(1-h)*(1-h)*p+3*h*h*(1-h)*m+h*h*h*_,c=this._points[this._points.length-1];for(let h=0;h<=o;h++){const u=h/o,p=l(u,c.x,e,i,r),m=l(u,c.y,t,s,n);this.addLineTo(p,m)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,r=0;rNumber.EPSILON){if(c<0&&(n=this._points[r],l=-l,o=this._points[s],c=-c),e.yo.y)continue;if(e.y===n.y&&e.x===n.x)return!0;{const h=c*(e.x-n.x)-l*(e.y-n.y);if(h===0)return!0;if(h<0)continue;t=!t}}else{if(e.y!==n.y)continue;if(o.x<=e.x&&e.x<=n.x||n.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,s=0;s1)return lt.Zero();const t=e*this.length();let i=0;for(let s=0;s=i&&t<=c){const h=l.normalize(),u=t-i;return new lt(n.x+h.x*u,n.y+h.y*u)}i=c}return lt.Zero()}static StartingAt(e,t){return new yF(e,t)}}class VB{constructor(e,t=null,i,s=!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:O.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:ge.Identity()};for(let r=0;rt){const c=e;e=t,t=c}const i=this.getCurve(),s=this.getPointAt(e);let r=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(r++,l.push(s)),l.push(...i.slice(r,o)),(t!==1||e===1)&&l.push(n),new VB(l,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let s=0;st+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(s===0&&(s=1),t==null){let r;Bt.WithinEpsilon(Math.abs(e.y)/s,1,Ls)?Bt.WithinEpsilon(Math.abs(e.x)/s,1,Ls)?Bt.WithinEpsilon(Math.abs(e.z)/s,1,Ls)?r=O.Zero():r=new O(0,0,1):r=new O(1,0,0):r=new O(0,-1,0),i=O.Cross(e,r)}else i=O.Cross(e,t),O.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 s=i[0],r,n=0;const o=e*this.length();for(let l=1;lo){const u=(n-o)/c,p=s.subtract(r),m=r.add(p.scaleInPlace(u));return this._setPointAtData(e,1-u,m,l-1,t)}s=r}return this._pointAtData}_setPointAtData(e,t,i,s,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=ge.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),r=this._binormals[e].clone(),n=this._tangents[t].clone(),o=this._normals[t].clone(),l=this._binormals[t].clone(),c=ke.RotationQuaternionFromAxis(s,r,i),h=ke.RotationQuaternionFromAxis(o,l,n);ke.Slerp(c,h,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class Ob{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=new Array,n=(o,l,c,h)=>(1-o)*(1-o)*l+2*o*(1-o)*c+o*o*h;for(let o=0;o<=s;o++)r.push(new O(n(o/s,e.x,t.x,i.x),n(o/s,e.y,t.y,i.y),n(o/s,e.z,t.z,i.z)));return new Ob(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=new Array,o=(l,c,h,u,p)=>(1-l)*(1-l)*(1-l)*c+3*l*(1-l)*(1-l)*h+3*l*l*(1-l)*u+l*l*l*p;for(let l=0;l<=r;l++)n.push(new O(o(l/r,e.x,t.x,i.x,s.x),o(l/r,e.y,t.y,i.y,s.y),o(l/r,e.z,t.z,i.z,s.z)));return new Ob(n)}static CreateHermiteSpline(e,t,i,s,r){const n=new Array,o=1/r;for(let l=0;l<=r;l++)n.push(O.Hermite(e,t,i,s,l*o));return new Ob(n)}static CreateCatmullRomSpline(e,t,i){const s=new Array,r=1/t;let n=0;if(i){const o=e.length;for(let l=0;l=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}}Pc.EASINGMODE_EASEIN=0;Pc.EASINGMODE_EASEOUT=1;Pc.EASINGMODE_EASEINOUT=2;class Ale extends Pc{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class xle extends Pc{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 v3e extends Pc{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 s=Math.pow(i,t),r=1-i,n=(1-s)/r+s*.5,o=e*n,l=Math.log(-o*(1-i)+1)/Math.log(i),c=Math.floor(l),h=c+1,u=(1-Math.pow(i,c))/(r*n),p=(1-Math.pow(i,h))/(r*n),m=(u+p)*.5,_=e-m,f=m-u;return-Math.pow(1/i,t-c)/(f*f)*(_-f)*(_+f)}}class C3e extends Pc{easeInCore(e){return e*e*e}}class A3e extends Pc{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),s=Math.max(0,this.springiness);return s==0?t=e:t=(Math.exp(s*e)-1)/(Math.exp(s)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class ble extends Pc{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 x3e extends Pc{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class Ele extends Pc{easeInCore(e){return e*e}}class b3e extends Pc{easeInCore(e){return e*e*e*e}}class E3e extends Pc{easeInCore(e){return e*e*e*e*e}}class W$ extends Pc{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class ZN extends Pc{constructor(e=0,t=0,i=1,s=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=s}easeInCore(e){return vle.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}class CK{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new CK(this.frame,this.action,this.onlyOnce)}}class yle{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class ev{syncWithMask(){if(!!this.mask)for(let e=0;e0)){for(let t=0;tn&&(n=l.to);const o=new ev(e[0].name+"_merged",e[0]._scene,s);for(const l of e){i&&l.normalize(r,n);for(const c of l.targetedAnimations)o.addTargetedAnimation(c.animation,c.target);t&&l.dispose()}return o}constructor(e,t=null,i=-1,s=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._parentContainer=null,this.onAnimationEndObservable=new Se,this.onAnimationLoopObservable=new Se,this.onAnimationGroupLoopObservable=new Se,this.onAnimationGroupEndObservable=new Se,this.onAnimationGroupPauseObservable=new Se,this.onAnimationGroupPlayObservable=new Se,this.metadata=null,this._animationLoopFlags=[],this._scene=t||Ii.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new yle;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[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 l={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};r.splice(0,0,l)}if(o.frame{this.onAnimationLoopObservable.notifyObservers(t),!this._animationLoopFlags[i]&&(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._targetedAnimations.length&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,r){if(this._isStarted||this._targetedAnimations.length===0)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(l)},this._processLoop(l,o,n),this._animatables.push(l)}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++]=s)}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 s=new ev(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(const r of this._targetedAnimations)s.addTargetedAnimation(i?r.animation.clone():r.animation,t?t(r.target):r.target);return s}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;tf[0].frame&&(c=f[0].frame),h=t&&f<=i||r&&d.frame>=t&&d.frame<=i){const C={frame:d.frame,value:d.value.clone?d.value.clone():d.value,inTangent:d.inTangent,outTangent:d.outTangent,interpolation:d.interpolation,lockedTangent:d.lockedTangent};_===Number.MAX_VALUE&&(_=C.frame),C.frame-=_,m.push(C)}}if(m.length===0){l.splice(c,1),c--;continue}n>m[0].frame&&(n=m[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 Bj;(function(a){a[a.Include=0]="Include",a[a.Exclude=1]="Exclude"})(Bj||(Bj={}));class M3e{constructor(e,t=Bj.Include){this.mode=t,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===Bj.Include)}}function Fj(a,e,t){try{const i=a.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function Mle(a=25){let e;return(t,i,s)=>{const r=performance.now();e===void 0||r-e>a?(e=r,setTimeout(()=>{Fj(t,i,s)},0)):Fj(t,i,s)}}function Y$(a,e,t,i,s){const r=()=>{let n;const o=l=>{l.done?t(l.value):n===void 0?n=!0:r()};do n=void 0,!s||!s.aborted?e(a,o,i):i(new Error("Aborted")),n===void 0&&(n=!1);while(n)};r()}function AK(a,e){let t;return Y$(a,Fj,i=>t=i,i=>{throw i},e),t}function xK(a,e,t){return new Promise((i,s)=>{Y$(a,e,i,s,t)})}function Tle(a,e){return(...t)=>AK(a(...t),e)}function T3e(a,e,t){return(...i)=>xK(a(...i),e,t)}class hu{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new hu(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 hu(this.x,this.y,this.width,this.height)}}class Pi extends pn{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,s;let r=0,n=0;if(this.mode===Pi.PERSPECTIVE_CAMERA)this.fovMode===Pi.FOVMODE_VERTICAL_FIXED?(n=this.minZ*2*Math.tan(this.fov/2),r=this.getEngine().getAspectRatio(this)*n):(r=this.minZ*2*Math.tan(this.fov/2),n=r/this.getEngine().getAspectRatio(this));else{const o=this.getEngine().getRenderWidth()/2,l=this.getEngine().getRenderHeight()/2;r=((e=this.orthoRight)!==null&&e!==void 0?e:o)-((t=this.orthoLeft)!==null&&t!==void 0?t:-o),n=((i=this.orthoTop)!==null&&i!==void 0?i:l)-((s=this.orthoBottom)!==null&&s!==void 0?s:-l)}return r*n}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}constructor(e,t,i,s=!0){super(e,i),this._position=O.Zero(),this._upVector=O.Up(),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=Pi.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new hu(0,0,1,1),this.layerMask=268435455,this.fovMode=Pi.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=Pi.RIG_MODE_NONE,this.customRenderTargets=new Array,this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new Se,this.onProjectionMatrixChangedObservable=new Se,this.onAfterCheckInputsObservable=new Se,this.onRestoreStateObservable=new Se,this.isRigCamera=!1,this._rigCameras=new Array,this._webvrViewMatrix=ge.Identity(),this._skipRendering=!1,this._projectionMatrix=new ge,this._postProcesses=new Array,this._activeMeshes=new Sc(256),this._globalPosition=O.Zero(),this._computedViewMatrix=ge.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=ge.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=ke.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!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?(Me.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 ge.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(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 t,i,s,r,n,o,l,c;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 h=this.getEngine(),u=this.getScene(),p=h.useReverseDepthBuffer;if(this.mode===Pi.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=h.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let m;u.useRightHandedSystem?m=ge.PerspectiveFovRHToRef:m=ge.PerspectiveFovLHToRef,m(this.fov,h.getAspectRatio(this),p?this.maxZ:this.minZ,p?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===Pi.FOVMODE_VERTICAL_FIXED,h.isNDCHalfZRange,this.projectionPlaneTilt,p)}else{const m=h.getRenderWidth()/2,_=h.getRenderHeight()/2;u.useRightHandedSystem?ge.OrthoOffCenterRHToRef((t=this.orthoLeft)!==null&&t!==void 0?t:-m,(i=this.orthoRight)!==null&&i!==void 0?i:m,(s=this.orthoBottom)!==null&&s!==void 0?s:-_,(r=this.orthoTop)!==null&&r!==void 0?r:_,p?this.maxZ:this.minZ,p?this.minZ:this.maxZ,this._projectionMatrix,h.isNDCHalfZRange):ge.OrthoOffCenterLHToRef((n=this.orthoLeft)!==null&&n!==void 0?n:-m,(o=this.orthoRight)!==null&&o!==void 0?o:m,(l=this.orthoBottom)!==null&&l!==void 0?l:-_,(c=this.orthoTop)!==null&&c!==void 0?c:_,p?this.maxZ:this.minZ,p?this.minZ:this.maxZ,this._projectionMatrix,h.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=h.getRenderWidth(),this._cache.renderHeight=h.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_updateFrustumPlanes(){!this._refreshFrustumPlanes||(this.getTransformationMatrix(),this._frustumPlanes?p_.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=p_.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(s=>{s._updateFrustumPlanes(),i=i||e.isInFrustum(s._frustumPlanes)}),i}else return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw Ys("Ray")}getForwardRayToRef(e,t=100,i,s){throw Ys("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 s=this._rigCameras.pop();s&&s.dispose()}if(this._parentContainer){const s=this._parentContainer.cameras.indexOf(this);s>-1&&this._parentContainer.cameras.splice(s,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==Pi.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let s=this._postProcesses.length;for(;--s>=0;){const r=this._postProcesses[s];r&&r.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=Be.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==Pi.RIG_MODE_NONE){const i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);const s=this.createRigCamera(this.name+"_R",1);s&&(s._isRightCamera=!0),i&&s&&(this._rigCameras.push(i),this._rigCameras.push(s))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return ge.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}_updateCameraRotationMatrix(){}_updateWebVRCameraRotationMatrix(){}_getWebVRProjectionMatrix(){return ge.Identity()}_getWebVRViewMatrix(){return ge.Identity()}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=Be.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;ePi._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=Pi.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=Kt.Parse(s,e,t);if(e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=O.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(O.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(O.FromArray(e.target)),e.cameraRigMode){const n=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,n)}if(e.animations){for(let n=0;n{throw Ys("UniversalCamera")};Pi.PERSPECTIVE_CAMERA=0;Pi.ORTHOGRAPHIC_CAMERA=1;Pi.FOVMODE_VERTICAL_FIXED=0;Pi.FOVMODE_HORIZONTAL_FIXED=1;Pi.RIG_MODE_NONE=0;Pi.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;Pi.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;Pi.RIG_MODE_STEREOSCOPIC_INTERLACED=14;Pi.RIG_MODE_VR=20;Pi.RIG_MODE_WEBVR=21;Pi.RIG_MODE_CUSTOM=22;Pi.ForceAttachControlToAlwaysPreventDefault=!1;z([bo("position")],Pi.prototype,"_position",void 0);z([bo("upVector")],Pi.prototype,"_upVector",void 0);z([X()],Pi.prototype,"orthoLeft",null);z([X()],Pi.prototype,"orthoRight",null);z([X()],Pi.prototype,"orthoBottom",null);z([X()],Pi.prototype,"orthoTop",null);z([X()],Pi.prototype,"fov",void 0);z([X()],Pi.prototype,"projectionPlaneTilt",void 0);z([X()],Pi.prototype,"minZ",void 0);z([X()],Pi.prototype,"maxZ",void 0);z([X()],Pi.prototype,"inertia",void 0);z([X()],Pi.prototype,"mode",null);z([X()],Pi.prototype,"layerMask",void 0);z([X()],Pi.prototype,"fovMode",void 0);z([X()],Pi.prototype,"cameraRigMode",void 0);z([X()],Pi.prototype,"interaxialDistance",void 0);z([X()],Pi.prototype,"isStereoscopicSideBySide",void 0);class hX{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class sv{constructor(e,t,i){this.vectors=ah.BuildArray(8,O.Zero),this.center=O.Zero(),this.centerWorld=O.Zero(),this.extendSize=O.Zero(),this.extendSizeWorld=O.Zero(),this.directions=ah.BuildArray(3,O.Zero),this.vectorsWorld=ah.BuildArray(8,O.Zero),this.minimumWorld=O.Zero(),this.maximumWorld=O.Zero(),this.minimum=O.Zero(),this.maximum=O.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,o=t.x,l=t.y,c=t.z,h=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(o,l,c),h[0].copyFromFloats(s,r,n),h[1].copyFromFloats(o,l,c),h[2].copyFromFloats(o,r,n),h[3].copyFromFloats(s,l,n),h[4].copyFromFloats(s,r,c),h[5].copyFromFloats(o,l,n),h[6].copyFromFloats(s,l,c),h[7].copyFromFloats(o,r,c),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||ge.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=sv._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(r*.5),o=this.center.subtractToRef(n,t[1]),l=this.center.addToRef(n,t[2]);return this.reConstruct(o,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)r[o].copyFrom(n[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 l=r[o];O.TransformCoordinatesToRef(n[o],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}O.FromArrayToRef(e.m,0,s[0]),O.FromArrayToRef(e.m,4,s[1]),O.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return sv.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return sv.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,l=i.y,c=i.z,h=e.x,u=e.y,p=e.z,m=-Ls;return!(o-hh-s||l-uu-r||c-pp-n)}intersectsSphere(e){return sv.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,o=i.z,l=s.x,c=s.y,h=s.z,u=e.x,p=e.y,m=e.z,_=t.x,f=t.y,d=t.z;return!(l_||cf||hd)}dispose(){var e,t;(e=this._drawWrapperFront)===null||e===void 0||e.dispose(),(t=this._drawWrapperBack)===null||t===void 0||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=sv._TmpVector3[0];return O.ClampToRef(i,e,t,r),O.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let r=0;r<8;++r)if(s.dotCoordinate(e[r])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let n=0;n<8;++n)if(r.dotCoordinate(e[n])>=0){s=!1;break}if(s)return!1}return!0}}sv._TmpVector3=ah.BuildArray(3,O.Zero);class Jb{constructor(e,t,i){this.center=O.Zero(),this.centerWorld=O.Zero(),this.minimum=O.Zero(),this.maximum=O.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=O.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=s*.5,this._update(i||ge.IdentityReadOnly)}scale(e){const t=this.radius*e,i=Jb._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{O.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=Jb._TmpVector3[0];O.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 s=0;s<6;s++)if(e[s].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=O.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const i=O.Dot(e.centerWorld,a),s=Math.abs(O.Dot(e.directions[0],a))*e.extendSize.x,r=Math.abs(O.Dot(e.directions[1],a))*e.extendSize.y,n=Math.abs(O.Dot(e.directions[2],a))*e.extendSize.z,o=s+r+n;t.min=i-o,t.max=i+o},H3=(a,e,t)=>(Pse(a,e,_Z),Pse(a,t,gZ),!(_Z.min>gZ.max||gZ.min>_Z.max));class dc{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new sv(e,t,i),this.boundingSphere=new Jb(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=dc._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=dc._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=O.Minimize(this.minimum,e),i=O.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=ue.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=ue.Vector3[0];return O.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),O.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,dc._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(!Jb.Intersects(this.boundingSphere,e.boundingSphere)||!sv.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!(!H3(i.directions[0],i,s)||!H3(i.directions[1],i,s)||!H3(i.directions[2],i,s)||!H3(s.directions[0],i,s)||!H3(s.directions[1],i,s)||!H3(s.directions[2],i,s)||!H3(O.Cross(i.directions[0],s.directions[0]),i,s)||!H3(O.Cross(i.directions[0],s.directions[1]),i,s)||!H3(O.Cross(i.directions[0],s.directions[2]),i,s)||!H3(O.Cross(i.directions[1],s.directions[0]),i,s)||!H3(O.Cross(i.directions[1],s.directions[1]),i,s)||!H3(O.Cross(i.directions[1],s.directions[2]),i,s)||!H3(O.Cross(i.directions[2],s.directions[0]),i,s)||!H3(O.Cross(i.directions[2],s.directions[1]),i,s)||!H3(O.Cross(i.directions[2],s.directions[2]),i,s))}}dc._TmpVector3=ah.BuildArray(2,O.Zero);class bK{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let o=i;o!Array.isArray(a)&&!Array.isArray(e))],bK,"extractMinAndMaxIndexed",null);z([AI.filter((...[a])=>!Array.isArray(a))],bK,"extractMinAndMax",null);function Sle(a,e,t,i,s=null){const r=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new O(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return bK.extractMinAndMaxIndexed(a,e,t,i,r,n),s&&(r.x-=r.x*s.x+s.y,r.y-=r.y*s.x+s.y,r.z-=r.z*s.x+s.y,n.x+=n.x*s.x+s.y,n.y+=n.y*s.x+s.y,n.z+=n.z*s.x+s.y),{minimum:r,maximum:n}}function zB(a,e,t,i=null,s){const r=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new O(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),bK.extractMinAndMax(a,e,t,s,r,n),i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,r.z-=r.z*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y,n.z+=n.z*i.x+i.y),{minimum:r,maximum:n}}class _d{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(e=this._getDrawWrapper())===null||e===void 0?void 0:e.defines}set materialDefines(e){var t;const i=(t=this._mainDrawWrapperOverride)!==null&&t!==void 0?t:this._getDrawWrapper(void 0,!0);i.defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new ml(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&((i=this._drawWrappers[e])===null||i===void 0||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:(t=(e=this._getDrawWrapper())===null||e===void 0?void 0:e.effect)!==null&&t!==void 0?t:null}get _drawWrapper(){var e;return(e=this._mainDrawWrapperOverride)!==null&&e!==void 0?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),i!==void 0&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e);return}else for(const t of this._drawWrappers)t?.dispose();this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,o,l=!0){return new _d(e,t,i,s,r,n,o,l)}constructor(e,t,i,s,r,n,o,l=!0,c=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,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=n,this._renderingMesh=o||n,c&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,l&&(this.refreshBoundingInfo(),n.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){var t;const i=(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))!==null&&t!==void 0?t:this._renderingMesh.material;if(i){if(this._isMultiMaterial(i)){const s=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==s&&(this._currentMaterial=s,this.resetDrawCache()),s}}else return e?this._mesh.getScene().defaultMaterial:null;return i}_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(se.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 s=this._renderingMesh.getBoundingInfo();i={minimum:s.minimum.clone(),maximum:s.maximum.clone()}}else i=Sle(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new dc(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 s=this.indexStart;sl&&(l=p)}return new _d(e,o,l-o+1,t,i,s,r,n)}}class gj{}class Jt{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=Tle(this._applyToCoroutine.bind(this)),this.uniqueId=Jt._UniqueIDGenerator,Jt._UniqueIDGenerator++}set(e,t){switch(e.length||Me.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case se.PositionKind:this.positions=e;break;case se.NormalKind:this.normals=e;break;case se.TangentKind:this.tangents=e;break;case se.UVKind:this.uvs=e;break;case se.UV2Kind:this.uvs2=e;break;case se.UV3Kind:this.uvs3=e;break;case se.UV4Kind:this.uvs4=e;break;case se.UV5Kind:this.uvs5=e;break;case se.UV6Kind:this.uvs6=e;break;case se.ColorKind:this.colors=e;break;case se.MatricesIndicesKind:this.matricesIndices=e;break;case se.MatricesWeightsKind:this.matricesWeights=e;break;case se.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case se.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(se.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(se.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(se.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(se.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(se.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(se.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(se.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(se.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(se.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(se.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(se.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(se.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(se.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(se.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 s=e;s.subMeshes=[];for(const r of this.materialInfos)new _d(r.materialIndex,r.verticesStart,r.verticesCount,r.indexStart,r.indexCount,s)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(se.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(se.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(se.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(se.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(se.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(se.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(se.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(se.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(se.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(se.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(se.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(se.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(se.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(se.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=ue.Vector3[0],n=ue.Vector3[1];for(let o=i;o({vertexData:o})):[{vertexData:e}];return AK(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,o=!1){var l,c,h,u;this._validate();let p=t.map(C=>C.vertexData),m=this;for(const C of p)if(!!C){if(C._validate(),o)!this.normals!=!C.normals&&(this.normals?C.normals=new Float32Array(C.positions.length):this.normals=new Float32Array(this.positions.length)),!this.tangents!=!C.tangents&&(this.tangents?C.tangents=new Float32Array(C.positions.length/3*4):this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs!=!C.uvs&&(this.uvs?C.uvs=new Float32Array(C.positions.length/3*2):this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2!=!C.uvs2&&(this.uvs2?C.uvs2=new Float32Array(C.positions.length/3*2):this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3!=!C.uvs3&&(this.uvs3?C.uvs3=new Float32Array(C.positions.length/3*2):this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4!=!C.uvs4&&(this.uvs4?C.uvs4=new Float32Array(C.positions.length/3*2):this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5!=!C.uvs5&&(this.uvs5?C.uvs5=new Float32Array(C.positions.length/3*2):this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6!=!C.uvs6&&(this.uvs6?C.uvs6=new Float32Array(C.positions.length/3*2):this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors!=!C.colors&&(this.colors?(C.colors=new Float32Array(C.positions.length/3*4),C.colors.fill(1)):(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1))),!this.matricesIndices!=!C.matricesIndices&&(this.matricesIndices?C.matricesIndices=new Float32Array(C.positions.length/3*4):this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights!=!C.matricesWeights&&(this.matricesWeights?C.matricesWeights=new Float32Array(C.positions.length/3*4):this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra!=!C.matricesIndicesExtra&&(this.matricesIndicesExtra?C.matricesIndicesExtra=new Float32Array(C.positions.length/3*4):this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra!=!C.matricesWeightsExtra&&(this.matricesWeightsExtra?C.matricesWeightsExtra=new Float32Array(C.positions.length/3*4):this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4));else if(!this.normals!=!C.normals||!this.tangents!=!C.tangents||!this.uvs!=!C.uvs||!this.uvs2!=!C.uvs2||!this.uvs3!=!C.uvs3||!this.uvs4!=!C.uvs4||!this.uvs5!=!C.uvs5||!this.uvs6!=!C.uvs6||!this.colors!=!C.colors||!this.matricesIndices!=!C.matricesIndices||!this.matricesWeights!=!C.matricesWeights||!this.matricesIndicesExtra!=!C.matricesIndicesExtra||!this.matricesWeightsExtra!=!C.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(n){let C=0,v=0,y=0;const M=[];let b=null;const E=[];for(const I of this.splitBasedOnMaterialID())E.push({vertexData:I,transform:e});for(const I of t)if(!!I.vertexData)for(const D of I.vertexData.splitBasedOnMaterialID())E.push({vertexData:D,transform:I.transform});E.sort((I,D)=>{const R=I.vertexData.materialInfos?I.vertexData.materialInfos[0].materialIndex:0,L=D.vertexData.materialInfos?D.vertexData.materialInfos[0].materialIndex:0;return R>L?1:R===L?0:-1});for(const I of E){const D=I.vertexData;if(D.materialInfos?C=D.materialInfos[0].materialIndex:C=0,b&&b.materialIndex===C)b.indexCount+=D.indices.length,b.verticesCount+=D.positions.length/3;else{const R=new gj;R.materialIndex=C,R.indexStart=v,R.indexCount=D.indices.length,R.verticesStart=y,R.verticesCount=D.positions.length/3,M.push(R),b=R}v+=D.indices.length,y+=D.positions.length/3}const S=E.splice(0,1)[0];m=S.vertexData,e=S.transform,p=E.map(I=>I.vertexData),t=E,this.materialInfos=M}const _=p.reduce((C,v)=>{var y,M;return C+((M=(y=v.indices)===null||y===void 0?void 0:y.length)!==null&&M!==void 0?M:0)},(c=(l=m.indices)===null||l===void 0?void 0:l.length)!==null&&c!==void 0?c:0);let d=r||p.some(C=>C.indices===m.indices)?(h=m.indices)===null||h===void 0?void 0:h.slice():m.indices;if(_>0){let C=(u=d?.length)!==null&&u!==void 0?u:0;if(d||(d=new Array(_)),d.length!==_){if(Array.isArray(d))d.length=_;else{const y=i||d instanceof Uint32Array?new Uint32Array(_):new Uint16Array(_);y.set(d),d=y}e&&e.determinant()<0&&Jt._FlipFaces(d,0,C)}let v=m.positions?m.positions.length/3:0;for(const{vertexData:y,transform:M}of t)if(y.indices){for(let b=0;b[C.vertexData.positions,C.transform])),s&&(yield),m.normals&&(this.normals=Jt._MergeElement(se.NormalKind,m.normals,e,t.map(C=>[C.vertexData.normals,C.transform])),s&&(yield)),m.tangents&&(this.tangents=Jt._MergeElement(se.TangentKind,m.tangents,e,t.map(C=>[C.vertexData.tangents,C.transform])),s&&(yield)),m.uvs&&(this.uvs=Jt._MergeElement(se.UVKind,m.uvs,e,t.map(C=>[C.vertexData.uvs,C.transform])),s&&(yield)),m.uvs2&&(this.uvs2=Jt._MergeElement(se.UV2Kind,m.uvs2,e,t.map(C=>[C.vertexData.uvs2,C.transform])),s&&(yield)),m.uvs3&&(this.uvs3=Jt._MergeElement(se.UV3Kind,m.uvs3,e,t.map(C=>[C.vertexData.uvs3,C.transform])),s&&(yield)),m.uvs4&&(this.uvs4=Jt._MergeElement(se.UV4Kind,m.uvs4,e,t.map(C=>[C.vertexData.uvs4,C.transform])),s&&(yield)),m.uvs5&&(this.uvs5=Jt._MergeElement(se.UV5Kind,m.uvs5,e,t.map(C=>[C.vertexData.uvs5,C.transform])),s&&(yield)),m.uvs6&&(this.uvs6=Jt._MergeElement(se.UV6Kind,m.uvs6,e,t.map(C=>[C.vertexData.uvs6,C.transform])),s&&(yield)),m.colors&&(this.colors=Jt._MergeElement(se.ColorKind,m.colors,e,t.map(C=>[C.vertexData.colors,C.transform])),s&&(yield)),m.matricesIndices&&(this.matricesIndices=Jt._MergeElement(se.MatricesIndicesKind,m.matricesIndices,e,t.map(C=>[C.vertexData.matricesIndices,C.transform])),s&&(yield)),m.matricesWeights&&(this.matricesWeights=Jt._MergeElement(se.MatricesWeightsKind,m.matricesWeights,e,t.map(C=>[C.vertexData.matricesWeights,C.transform])),s&&(yield)),m.matricesIndicesExtra&&(this.matricesIndicesExtra=Jt._MergeElement(se.MatricesIndicesExtraKind,m.matricesIndicesExtra,e,t.map(C=>[C.vertexData.matricesIndicesExtra,C.transform])),s&&(yield)),m.matricesWeightsExtra&&(this.matricesWeightsExtra=Jt._MergeElement(se.MatricesWeightsExtraKind,m.matricesWeightsExtra,e,t.map(C=>[C.vertexData.matricesWeightsExtra,C.transform]))),this}static _MergeElement(e,t,i,s){const r=s.filter(l=>l[0]!==null&&l[0]!==void 0);if(!t&&r.length==0)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce((l,c)=>l+c[0].length,t.length),o=e===se.PositionKind?Jt._TransformVector3Coordinates:e===se.NormalKind?Jt._TransformVector3Normals:e===se.TangentKind?Jt._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const l=new Float32Array(n);l.set(t),i&&o(l,i,0,t.length);let c=t.length;for(const[h,u]of r)l.set(h,c),u&&o(l,u,c,h.length),c+=h.length;return l}else{const l=new Array(n);for(let h=0;h{const n=se.DeduceStride(s);if(r.length%n!==0)throw new Error("The "+s+"s array count must be a multiple of "+n);return r.length/n},t=e(se.PositionKind,this.positions),i=(s,r)=>{const n=e(s,r);if(n!==t)throw new Error("The "+s+"s element count ("+n+") does not match the positions count ("+t+")")};this.normals&&i(se.NormalKind,this.normals),this.tangents&&i(se.TangentKind,this.tangents),this.uvs&&i(se.UVKind,this.uvs),this.uvs2&&i(se.UV2Kind,this.uvs2),this.uvs3&&i(se.UV3Kind,this.uvs3),this.uvs4&&i(se.UV4Kind,this.uvs4),this.uvs5&&i(se.UV5Kind,this.uvs5),this.uvs6&&i(se.UV6Kind,this.uvs6),this.colors&&i(se.ColorKind,this.colors),this.matricesIndices&&i(se.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(se.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(se.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(se.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Jt.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)),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 Jt._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Jt._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new Jt;return e.isVerticesDataPresent(se.PositionKind)&&(s.positions=e.getVerticesData(se.PositionKind,t,i)),e.isVerticesDataPresent(se.NormalKind)&&(s.normals=e.getVerticesData(se.NormalKind,t,i)),e.isVerticesDataPresent(se.TangentKind)&&(s.tangents=e.getVerticesData(se.TangentKind,t,i)),e.isVerticesDataPresent(se.UVKind)&&(s.uvs=e.getVerticesData(se.UVKind,t,i)),e.isVerticesDataPresent(se.UV2Kind)&&(s.uvs2=e.getVerticesData(se.UV2Kind,t,i)),e.isVerticesDataPresent(se.UV3Kind)&&(s.uvs3=e.getVerticesData(se.UV3Kind,t,i)),e.isVerticesDataPresent(se.UV4Kind)&&(s.uvs4=e.getVerticesData(se.UV4Kind,t,i)),e.isVerticesDataPresent(se.UV5Kind)&&(s.uvs5=e.getVerticesData(se.UV5Kind,t,i)),e.isVerticesDataPresent(se.UV6Kind)&&(s.uvs6=e.getVerticesData(se.UV6Kind,t,i)),e.isVerticesDataPresent(se.ColorKind)&&(s.colors=e.getVerticesData(se.ColorKind,t,i)),e.isVerticesDataPresent(se.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(se.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(se.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(se.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(se.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(se.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(se.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(se.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw Ys("ribbonBuilder")}static CreateBox(e){throw Ys("boxBuilder")}static CreateTiledBox(e){throw Ys("tiledBoxBuilder")}static CreateTiledPlane(e){throw Ys("tiledPlaneBuilder")}static CreateSphere(e){throw Ys("sphereBuilder")}static CreateCylinder(e){throw Ys("cylinderBuilder")}static CreateTorus(e){throw Ys("torusBuilder")}static CreateLineSystem(e){throw Ys("linesBuilder")}static CreateDashedLines(e){throw Ys("linesBuilder")}static CreateGround(e){throw Ys("groundBuilder")}static CreateTiledGround(e){throw Ys("groundBuilder")}static CreateGroundFromHeightMap(e){throw Ys("groundBuilder")}static CreatePlane(e){throw Ys("planeBuilder")}static CreateDisc(e){throw Ys("discBuilder")}static CreatePolygon(e,t,i,s,r,n,o){throw Ys("polygonBuilder")}static CreateIcoSphere(e){throw Ys("icoSphereBuilder")}static CreatePolyhedron(e){throw Ys("polyhedronBuilder")}static CreateCapsule(e={orientation:O.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw Ys("capsuleBuilder")}static CreateTorusKnot(e){throw Ys("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,o=0,l=0,c=0,h=0,u=0,p=0,m=0,_=0,f=0,d=0,C=0,v=0,y=0,M=0,b=0,E=0,S=0,I=0,D=!1,R=!1,L=!1,w=!1,N=1,V=0,W=null;s&&(D=!!s.facetNormals,R=!!s.facetPositions,L=!!s.facetPartitioning,N=s.useRightHandedSystem===!0?-1:1,V=s.ratio||0,w=!!s.depthSort,W=s.distanceTo,w&&W===void 0&&(W=O.Zero()));let G=0,ie=0,Z=0,q=0;for(L&&s&&s.bbSize&&(G=s.subDiv.X*V/s.bbSize.x,ie=s.subDiv.Y*V/s.bbSize.y,Z=s.subDiv.Z*V/s.bbSize.z,q=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(a))],Jt,"_TransformVector3Coordinates",null);z([AI.filter((...[a])=>!Array.isArray(a))],Jt,"_TransformVector3Normals",null);z([AI.filter((...[a])=>!Array.isArray(a))],Jt,"_TransformVector4Normals",null);z([AI.filter((...[a])=>!Array.isArray(a))],Jt,"_FlipFaces",null);class Lh{static get ForceFullSceneLoadingForIncremental(){return Lh._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Lh._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Lh._ShowLoadingScreen}static set ShowLoadingScreen(e){Lh._ShowLoadingScreen=e}static get loggingLevel(){return Lh._LoggingLevel}static set loggingLevel(e){Lh._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Lh._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Lh._CleanBoneMatrixWeights=e}}Lh._ForceFullSceneLoadingForIncremental=!1;Lh._ShowLoadingScreen=!0;Lh._CleanBoneMatrixWeights=!1;Lh._LoggingLevel=0;class fn{}fn.UseOpenGLOrientationForUV=!1;class au{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 au(au.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||Ii.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.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;e0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),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 s=this._meshes,r=s.length;for(let n=0;n0){for(let s=0;s0){for(let s=0;s0){for(let s=0;s-1&&this._parentContainer.geometries.splice(s,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Jt;t.indices=[];const i=this.getIndices();if(i)for(let l=0;l0){const o=new Float32Array(e,n.positionsAttrDesc.offset,n.positionsAttrDesc.count);t.setVerticesData(se.PositionKind,o,!1)}if(n.normalsAttrDesc&&n.normalsAttrDesc.count>0){const o=new Float32Array(e,n.normalsAttrDesc.offset,n.normalsAttrDesc.count);t.setVerticesData(se.NormalKind,o,!1)}if(n.tangetsAttrDesc&&n.tangetsAttrDesc.count>0){const o=new Float32Array(e,n.tangetsAttrDesc.offset,n.tangetsAttrDesc.count);t.setVerticesData(se.TangentKind,o,!1)}if(n.uvsAttrDesc&&n.uvsAttrDesc.count>0){const o=new Float32Array(e,n.uvsAttrDesc.offset,n.uvsAttrDesc.count);if(fn.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.uvs2AttrDesc.offset,n.uvs2AttrDesc.count);if(fn.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.uvs3AttrDesc.offset,n.uvs3AttrDesc.count);if(fn.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.uvs4AttrDesc.offset,n.uvs4AttrDesc.count);if(fn.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.uvs5AttrDesc.offset,n.uvs5AttrDesc.count);if(fn.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.uvs6AttrDesc.offset,n.uvs6AttrDesc.count);if(fn.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.colorsAttrDesc.offset,n.colorsAttrDesc.count);t.setVerticesData(se.ColorKind,o,!1,n.colorsAttrDesc.stride)}if(n.matricesIndicesAttrDesc&&n.matricesIndicesAttrDesc.count>0){const o=new Int32Array(e,n.matricesIndicesAttrDesc.offset,n.matricesIndicesAttrDesc.count),l=[];for(let c=0;c>8),l.push((h&16711680)>>16),l.push(h>>24&255)}t.setVerticesData(se.MatricesIndicesKind,l,!1)}if(n.matricesIndicesExtraAttrDesc&&n.matricesIndicesExtraAttrDesc.count>0){const o=new Int32Array(e,n.matricesIndicesExtraAttrDesc.offset,n.matricesIndicesExtraAttrDesc.count),l=[];for(let c=0;c>8),l.push((h&16711680)>>16),l.push(h>>24&255)}t.setVerticesData(se.MatricesIndicesExtraKind,l,!1)}if(n.matricesWeightsAttrDesc&&n.matricesWeightsAttrDesc.count>0){const o=new Float32Array(e,n.matricesWeightsAttrDesc.offset,n.matricesWeightsAttrDesc.count);t.setVerticesData(se.MatricesWeightsKind,o,!1)}if(n.indicesAttrDesc&&n.indicesAttrDesc.count>0){const o=new Int32Array(e,n.indicesAttrDesc.offset,n.indicesAttrDesc.count);t.setIndices(o,null)}if(n.subMeshesAttrDesc&&n.subMeshesAttrDesc.count>0){const o=new Int32Array(e,n.subMeshesAttrDesc.offset,n.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l>8),n.push((l&16711680)>>16),n.push(l>>24&255)}t.setVerticesData(se.MatricesIndicesKind,n,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(se.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const n=[];for(let o=0;o>8),n.push((l&16711680)>>16),n.push(l>>24&255)}t.setVerticesData(se.MatricesIndicesExtraKind,n,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(au._CleanMatricesWeights(e,t),t.setVerticesData(se.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(se.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let n=0;n-1){const u=t.getScene().getLastSkeletonById(e.skeletonId);if(!u)return;s=u.bones.length}else return;const r=t.getVerticesData(se.MatricesIndicesKind),n=t.getVerticesData(se.MatricesIndicesExtraKind),o=e.matricesWeights,l=e.matricesWeightsExtra,c=e.numBoneInfluencer,h=o.length;for(let u=0;uc-1)&&(m=c-1),p>.001){const _=1/p;for(let f=0;f<4;f++)o[u+f]*=_;if(l)for(let f=0;f<4;f++)l[u+f]*=_}else m>=4?(l[u+m-4]=1-p,n[u+m-4]=s):(o[u+m]=1-p,r[u+m]=s)}t.setVerticesData(se.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(se.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new au(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,Nr&&Nr.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new dc(O.FromArray(e.boundingBoxMinimum),O.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(se.UVKind),e.hasUVs2&&s._delayInfo.push(se.UV2Kind),e.hasUVs3&&s._delayInfo.push(se.UV3Kind),e.hasUVs4&&s._delayInfo.push(se.UV4Kind),e.hasUVs5&&s._delayInfo.push(se.UV5Kind),e.hasUVs6&&s._delayInfo.push(se.UV6Kind),e.hasColors&&s._delayInfo.push(se.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(se.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(se.MatricesWeightsKind),s._delayLoadingFunction=Jt.ImportVertexData):Jt.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}const S3e=ge.Compose(O.One(),ke.FromEulerAngles(0,Math.PI,0),O.Zero());class Ki extends pn{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&Ki.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!==Ki.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 O(0,0,1),this._up=new O(0,1,0),this._right=new O(1,0,0),this._position=O.Zero(),this._rotation=O.Zero(),this._rotationQuaternion=null,this._scaling=O.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Ki.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=ge.Zero(),this._usePivotMatrix=!1,this._absolutePosition=O.Zero(),this._absoluteScaling=O.Zero(),this._absoluteRotationQuaternion=ke.Identity(),this._pivotMatrix=ge.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new Se,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}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 O.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return O.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return O.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=ge.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Ki.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=ge.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const r of this.getChildTransformNodes(!0))r.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||ke.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,s;if(e.x===void 0){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const r=ue.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),O.TransformCoordinatesFromFloatsToRef(t,i,s,r,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=O.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=ue.Matrix[0];return this._localMatrix.invertToRef(e),O.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=O.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=sr.LOCAL){const n=Ki._LookAtVectorCache,o=r===sr.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,s),r===sr.WORLD&&this.parent)if(this.rotationQuaternion){const l=ue.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);const c=ue.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),l.multiplyToRef(c,l),this.rotationQuaternion.fromRotationMatrix(l)}else{const l=ue.Quaternion[0];ke.FromEulerVectorToRef(this.rotation,l);const c=ue.Matrix[0];l.toRotationMatrix(c);const h=ue.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),c.multiplyToRef(h,c),l.fromRotationMatrix(c),l.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=O.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return O.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?ke.RotationYawPitchRollToRef(r+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=sr.LOCAL){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==sr.WORLD){const s=ue.Matrix[0];i.invertToRef(s),e=O.TransformCoordinates(e,s)}return this.setPivotMatrix(ge.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=O.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=O.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),O.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 s=ue.Quaternion[0],r=ue.Vector3[0],n=ue.Vector3[1],o=ue.Matrix[1];ge.IdentityToRef(o);const l=ue.Matrix[0];this.computeWorldMatrix(!0);let c=this.rotationQuaternion;return c||(c=Ki._TmpRotation,ke.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,c)),ge.ComposeToRef(this.scaling,c,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(ge.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 s;if(!i||i===sr.LOCAL)s=ke.RotationAxisToRef(e,t,Ki._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);else{if(this.parent){const r=ue.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),e=O.TransformNormal(e,r)}s=ke.RotationAxisToRef(e,t,Ki._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=ke.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=ue.Vector3[0],r=ue.Vector3[1],n=ue.Vector3[2],o=ue.Quaternion[0],l=ue.Matrix[0],c=ue.Matrix[1],h=ue.Matrix[2],u=ue.Matrix[3];return e.subtractToRef(this.position,s),ge.TranslationToRef(s.x,s.y,s.z,l),ge.TranslationToRef(-s.x,-s.y,-s.z,c),ge.RotationAxisToRef(t,i,h),c.multiplyToRef(h,u),u.multiplyToRef(l,u),u.decompose(r,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(!i||i===sr.LOCAL){const r=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(r)}else this.setAbsolutePosition(this.getAbsolutePosition().add(s));return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=ue.Quaternion[1],ke.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=ue.Quaternion[0];return ke.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Ki.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 s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.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 r=this._getEffectiveParent(),n=Ki._TmpScaling;let o=this._position;if(this._infiniteDistance&&!this.parent&&t){const c=t.getWorldMatrix(),h=new O(c.m[12],c.m[13],c.m[14]);o=Ki._TmpTranslation,o.copyFromFloats(this._position.x+h.x,this._position.y+h.y,this._position.z+h.z)}n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let l;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,l=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(ke.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=Ki._TmpRotation,ke.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){const c=ue.Matrix[1];ge.ScalingToRef(n.x,n.y,n.z,c);const h=ue.Matrix[0];l.toRotationMatrix(h),this._pivotMatrix.multiplyToRef(c,ue.Matrix[4]),ue.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 ge.ComposeToRef(n,l,o,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const p=this.parent;p.getSkeleton().prepare(),p.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),ue.Matrix[7])}else ue.Matrix[7].copyFrom(r.getWorldMatrix());const c=ue.Vector3[5],h=ue.Vector3[6],u=ue.Quaternion[0];ue.Matrix[7].decompose(h,u,c),ge.ScalingToRef(h.x,h.y,h.z,ue.Matrix[7]),ue.Matrix[7].setTranslation(c),Ki.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,c),this._localMatrix.setTranslation(c)),this._localMatrix.multiplyToRef(ue.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const c=this.parent;c.getSkeleton().prepare(),this._localMatrix.multiplyToRef(c.getFinalMatrix(),ue.Matrix[6]),ue.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const c=ue.Vector3[0];if(this._worldMatrix.getTranslationToRef(c),ue.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&ue.Matrix[1].multiplyToRef(S3e,ue.Matrix[1]),ue.Matrix[1].setTranslationFromFloats(0,0,0),ue.Matrix[1].invertToRef(ue.Matrix[0]),(this.billboardMode&Ki.BILLBOARDMODE_ALL)!==Ki.BILLBOARDMODE_ALL){ue.Matrix[0].decompose(void 0,ue.Quaternion[0],void 0);const h=ue.Vector3[1];ue.Quaternion[0].toEulerAnglesToRef(h),(this.billboardMode&Ki.BILLBOARDMODE_X)!==Ki.BILLBOARDMODE_X&&(h.x=0),(this.billboardMode&Ki.BILLBOARDMODE_Y)!==Ki.BILLBOARDMODE_Y&&(h.y=0),(this.billboardMode&Ki.BILLBOARDMODE_Z)!==Ki.BILLBOARDMODE_Z&&(h.z=0),ge.RotationYawPitchRollToRef(h.y,h.x,h.z,ue.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ue.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ue.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const c=ue.Vector3[0];this._worldMatrix.getTranslationToRef(c);const h=t.globalPosition;this._worldMatrix.invertToRef(ue.Matrix[1]);const u=ue.Vector3[1];O.TransformCoordinatesToRef(h,ue.Matrix[1],u),u.normalize();const p=-Math.atan2(u.z,u.x)+Math.PI/2,m=Math.sqrt(u.x*u.x+u.z*u.z),_=-Math.atan2(u.y,m);if(ke.RotationYawPitchRollToRef(p,_,0,ue.Quaternion[0]),(this.billboardMode&Ki.BILLBOARDMODE_ALL)!==Ki.BILLBOARDMODE_ALL){const f=ue.Vector3[1];ue.Quaternion[0].toEulerAnglesToRef(f),(this.billboardMode&Ki.BILLBOARDMODE_X)!==Ki.BILLBOARDMODE_X&&(f.x=0),(this.billboardMode&Ki.BILLBOARDMODE_Y)!==Ki.BILLBOARDMODE_Y&&(f.y=0),(this.billboardMode&Ki.BILLBOARDMODE_Z)!==Ki.BILLBOARDMODE_Z&&(f.z=0),ge.RotationYawPitchRollToRef(f.y,f.x,f.z,ue.Matrix[0])}else ge.FromQuaternionToRef(ue.Quaternion[0],ue.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ue.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ue.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._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=ge.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;inew Ki(e,this.getScene()),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const r=this.getDescendants(!0);for(let n=0;nnew Ki(e.name,t),e,t,i);return e.localMatrix?s.setPreTransformMatrix(ge.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(ge.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,s=>(!t||t(s))&&s instanceof Ki),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 s of i)s.parent=null,s.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),o=n.max.subtract(n.min),l=Math.max(o.x,o.y,o.z);if(l===0)return this;const c=1/l;return this.scaling.scaleInPlace(c),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}Ki.BILLBOARDMODE_NONE=0;Ki.BILLBOARDMODE_X=1;Ki.BILLBOARDMODE_Y=2;Ki.BILLBOARDMODE_Z=4;Ki.BILLBOARDMODE_ALL=7;Ki.BILLBOARDMODE_USE_POSITION=128;Ki.BillboardUseParentOrientation=!1;Ki._TmpRotation=ke.Zero();Ki._TmpScaling=O.Zero();Ki._TmpTranslation=O.Zero();Ki._LookAtVectorCache=new O(0,0,0);Ki._RotationAxisCache=new ke;z([bo("position")],Ki.prototype,"_position",void 0);z([bo("rotation")],Ki.prototype,"_rotation",void 0);z([qoe("rotationQuaternion")],Ki.prototype,"_rotationQuaternion",void 0);z([bo("scaling")],Ki.prototype,"_scaling",void 0);z([X("billboardMode")],Ki.prototype,"_billboardMode",void 0);z([X()],Ki.prototype,"scalingDeterminant",void 0);z([X("infiniteDistance")],Ki.prototype,"_infiniteDistance",void 0);z([X()],Ki.prototype,"ignoreNonUniformScaling",void 0);z([X()],Ki.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Ile{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new O(0,0,0),this._diffPositionForCollisions=new O(0,0,0),this._collisionResponse=!0}}class I3e{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=O.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class L3e{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new I3e,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 Ile,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class Ir extends Ki{static get BILLBOARDMODE_NONE(){return Ki.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Ki.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Ki.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Ki.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Ki.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Ki.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||t===void 0?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 L3e,this._waitingMaterialId=null,this.cullingStrategy=Ir.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new Se,this.onCollisionPositionChangeObservable=new Se,this.onMaterialChangedObservable=new Se,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=Ie.Red(),this.outlineWidth=.02,this.overlayColor=Ie.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 O(.5,1,.5),this.ellipsoidOffset=new O(0,0,0),this.edgesWidth=1,this.edgesColor=new Zt(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 Se,this._onCollisionPositionChange=(i,s,r=null)=>{s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>He.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),r&&this.onCollideObservable.notifyObservers(r),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new es(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case Kb.Aggressive:this.doNotSyncBoundingInfo=!0;case Kb.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!==Ki.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()}_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 s=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_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,s){return this}updateVerticesData(e,t,i,s){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(){var e;return(e=this.rawBoundingInfo)!==null&&e!==void 0?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new dc(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(se.MatricesIndicesKind)&&this.isVerticesDataPresent(se.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Ki.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 s=new ge;(this.rotationQuaternion?this.rotationQuaternion:ke.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const n=O.Zero(),o=this.definedFacingForward?-1:1;return O.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,s,n),n}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new O(e*s,t,i*s)}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=zB(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new dc(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i0){const u=c.getPositions();u&&(i[o]+=(u[o]-i[o])*h)}}if(r++,s===se.PositionKind&&this._positions&&r===3){r=0;const l=n*3;this._positions[n++].copyFromFloats(i[l],i[l+1],i[l+2])}}}if(i&&e&&this.skeleton){const r=this.getVerticesData(se.MatricesIndicesKind),n=this.getVerticesData(se.MatricesWeightsKind);if(n&&r){const o=this.numBoneInfluencers>4,l=o?this.getVerticesData(se.MatricesIndicesExtraKind):null,c=o?this.getVerticesData(se.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this),u=ue.Vector3[0],p=ue.Matrix[0],m=ue.Matrix[1];let _=0;for(let f=0;f0&&(ge.FromFloat32ArrayToRefScaled(h,Math.floor(r[_+d]*16),C,m),p.addToSelf(m));if(o)for(d=0;d<4;d++)C=c[_+d],C>0&&(ge.FromFloat32ArrayToRefScaled(h,Math.floor(l[_+d]*16),C,m),p.addToSelf(m));s===se.NormalKind?O.TransformNormalFromFloatsToRef(i[f],i[f+1],i[f+2],p,u):O.TransformCoordinatesFromFloatsToRef(i[f],i[f+1],i[f+2],p,u),u.toArray(i,f),s===se.PositionKind&&this._positions&&this._positions[f/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,se.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,se.PositionKind)}_getPositionData(e,t){var i;let s=this.getVerticesData(se.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),s&&(e&&this.skeleton||t&&this.morphTargetManager)){if(s=s.slice(),this._generatePointsArray(),this._positions){const r=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(r.length);for(let n=0;n1||!s.IsGlobal)&&s.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 s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i){for(const n of this.getChildMeshes())if(n.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 s;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const r=e.verticesStart,n=e.verticesStart+e.verticesCount;for(let o=r;o1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=ue.Matrix[0],i=ue.Matrix[1];return ge.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,s=!1,r,n=!1){const o=new cu,l=this.getClassName(),c=l==="InstancedLinesMesh"||l==="LinesMesh"||l==="GreasedLineMesh"?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes||!n&&(!e.intersectsSphere(h.boundingSphere,c)||!e.intersectsBox(h.boundingBox,c)))return o;if(s)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:O.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let u=null;const p=this._scene.getIntersectingSubMeshCandidates(this,e),m=p.length;let _=!1;for(let f=0;f1&&!d.canIntersects(e))continue;const C=d.intersects(e,this._positions,this.getIndices(),t,i);if(C&&(t||!u||C.distancen!==this&&n.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 o=n.includedOnlyMeshes.indexOf(this);o!==-1&&n.includedOnlyMeshes.splice(o,1),o=n.excludedMeshes.indexOf(this),o!==-1&&n.excludedMeshes.splice(o,1);const l=n.getShadowGenerators();if(l){const c=l.values();for(let h=c.next();h.done!==!0;h=c.next()){const p=h.value.getShadowMap();p&&p.renderList&&(o=p.renderList.indexOf(this),o!==-1&&p.renderList.splice(o,1))}}}),(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes();const r=this.getScene().getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),this.getScene().removeMesh(this),this._parentContainer){const n=this._parentContainer.meshes.indexOf(this);n>-1&&this._parentContainer.meshes.splice(n,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,l){return l.sqDistance-o.sqDistance},!e.facetDepthSortFrom){const o=this.getScene().activeCamera;e.facetDepthSortFrom=o?o.position:O.Zero()}e.depthSortedFacets=[];for(let o=0;oLs?r.maximum.x-r.minimum.x:Ls,e.bbSize.y=r.maximum.y-r.minimum.y>Ls?r.maximum.y-r.minimum.y:Ls,e.bbSize.z=r.maximum.z-r.minimum.z>Ls?r.maximum.z-r.minimum.z:Ls;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),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=r,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),O.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&Jt.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const o=e.depthSortedIndices.length/3|0;for(let l=0;lr.subDiv.max||o<0||o>r.subDiv.max||l<0||l>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*o+r.subDiv.max*r.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const o=this.getWorldMatrix(),l=ue.Matrix[5];o.invertToRef(l);const c=ue.Vector3[8];O.TransformCoordinatesFromFloatsToRef(e,t,i,l,c);const h=this.getClosestFacetAtLocalCoordinates(c.x,c.y,c.z,s,r,n);return s&&O.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),h}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let o=null,l=0,c=0,h=0,u=0,p=0,m=0,_=0,f=0;const d=this.getFacetLocalPositions(),C=this.getFacetLocalNormals(),v=this.getFacetsAtLocalCoordinates(e,t,i);if(!v)return null;let y=Number.MAX_VALUE,M=y,b,E,S;for(let I=0;I=0||r&&!n&&u<=0)&&(u=E.x*S.x+E.y*S.y+E.z*S.z,p=-(E.x*e+E.y*t+E.z*i-u)/(E.x*E.x+E.y*E.y+E.z*E.z),m=e+E.x*p,_=t+E.y*p,f=i+E.z*p,l=m-e,c=_-t,h=f-i,M=l*l+c*c+h*h,Me.emitter===this)}}Ir.OCCLUSION_TYPE_NONE=0;Ir.OCCLUSION_TYPE_OPTIMISTIC=1;Ir.OCCLUSION_TYPE_STRICT=2;Ir.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;Ir.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;Ir.CULLINGSTRATEGY_STANDARD=0;Ir.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;Ir.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;Ir.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;$e("BABYLON.AbstractMesh",Ir);function lh(a){a.indexOf("vClipPlane")===-1&&a.push("vClipPlane"),a.indexOf("vClipPlane2")===-1&&a.push("vClipPlane2"),a.indexOf("vClipPlane3")===-1&&a.push("vClipPlane3"),a.indexOf("vClipPlane4")===-1&&a.push("vClipPlane4"),a.indexOf("vClipPlane5")===-1&&a.push("vClipPlane5"),a.indexOf("vClipPlane6")===-1&&a.push("vClipPlane6")}function PI(a,e,t){var i,s,r,n,o,l;const c=!!((i=a.clipPlane)!==null&&i!==void 0?i:e.clipPlane),h=!!((s=a.clipPlane2)!==null&&s!==void 0?s:e.clipPlane2),u=!!((r=a.clipPlane3)!==null&&r!==void 0?r:e.clipPlane3),p=!!((n=a.clipPlane4)!==null&&n!==void 0?n:e.clipPlane4),m=!!((o=a.clipPlane5)!==null&&o!==void 0?o:e.clipPlane5),_=!!((l=a.clipPlane6)!==null&&l!==void 0?l:e.clipPlane6);c&&t.push("#define CLIPPLANE"),h&&t.push("#define CLIPPLANE2"),u&&t.push("#define CLIPPLANE3"),p&&t.push("#define CLIPPLANE4"),m&&t.push("#define CLIPPLANE5"),_&&t.push("#define CLIPPLANE6")}function Lle(a,e,t){var i,s,r,n,o,l;let c=!1;const h=!!((i=a.clipPlane)!==null&&i!==void 0?i:e.clipPlane),u=!!((s=a.clipPlane2)!==null&&s!==void 0?s:e.clipPlane2),p=!!((r=a.clipPlane3)!==null&&r!==void 0?r:e.clipPlane3),m=!!((n=a.clipPlane4)!==null&&n!==void 0?n:e.clipPlane4),_=!!((o=a.clipPlane5)!==null&&o!==void 0?o:e.clipPlane5),f=!!((l=a.clipPlane6)!==null&&l!==void 0?l:e.clipPlane6);return t.CLIPPLANE!==h&&(t.CLIPPLANE=h,c=!0),t.CLIPPLANE2!==u&&(t.CLIPPLANE2=u,c=!0),t.CLIPPLANE3!==p&&(t.CLIPPLANE3=p,c=!0),t.CLIPPLANE4!==m&&(t.CLIPPLANE4=m,c=!0),t.CLIPPLANE5!==_&&(t.CLIPPLANE5=_,c=!0),t.CLIPPLANE6!==f&&(t.CLIPPLANE6=f,c=!0),c}function wc(a,e,t){var i,s,r,n,o,l;let c=(i=e.clipPlane)!==null&&i!==void 0?i:t.clipPlane;hN(a,"vClipPlane",c),c=(s=e.clipPlane2)!==null&&s!==void 0?s:t.clipPlane2,hN(a,"vClipPlane2",c),c=(r=e.clipPlane3)!==null&&r!==void 0?r:t.clipPlane3,hN(a,"vClipPlane3",c),c=(n=e.clipPlane4)!==null&&n!==void 0?n:t.clipPlane4,hN(a,"vClipPlane4",c),c=(o=e.clipPlane5)!==null&&o!==void 0?o:t.clipPlane5,hN(a,"vClipPlane5",c),c=(l=e.clipPlane6)!==null&&l!==void 0?l:t.clipPlane6,hN(a,"vClipPlane6",c)}function hN(a,e,t){t&&a.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}class ze{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}static BindTextureMatrix(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==oi.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,s,r,n,o,l=!1){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=s,o.FOG=r&&this.GetFogState(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=n,o.DECAL_AFTER_DETAIL=l)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){const s=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,n=e.activeCamera.mode===Pi.ORTHOGRAPHIC_CAMERA?1:0,o=e.activeCamera.mode===Pi.PERSPECTIVE_CAMERA?1:0;(s^n||r^o)&&(t.CAMERA_ORTHOGRAPHIC=n===1,t.CAMERA_PERSPECTIVE=o===1,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,s,r,n=null,o=!1){let l=ze.PrepareDefinesForCamera(e,s);n!==!1&&(l=Lle(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,l=!0),s.INSTANCES!==r&&(s.INSTANCES=r,l=!0),s.THIN_INSTANCES!==o&&(s.THIN_INSTANCES=o,l=!0),l&&s.markAsUnprocessed()}static PrepareDefinesForBones(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=t.BONETEXTURE!==void 0;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=i?!1:void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const r=s.excludedSkinnedMesh.indexOf(e)===-1;t.BONES_VELOCITY_ENABLED=r}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.BONETEXTURE!==void 0&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}static PrepareDefinesForBakedVertexAnimation(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!(i&&i.isEnabled)}static PrepareDefinesForAttributes(e,t,i,s,r=!1,n=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(se.NormalKind),t._needNormals&&e.isVerticesDataPresent(se.TangentKind)&&(t.TANGENT=!0);for(let l=1;l<=6;++l)t["UV"+l]=t._needUVs?e.isVerticesDataPresent(`uv${l===1?"":l}`):!1;if(i){const l=e.useVertexColors&&e.isVerticesDataPresent(se.ColorKind);t.VERTEXCOLOR=l,t.VERTEXALPHA=e.hasVertexAlpha&&l&&n}return e.isVerticesDataPresent(se.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&this.PrepareDefinesForBones(e,t),r&&this.PrepareDefinesForMorphTargets(e,t),o&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=e.activeCamera.outputRenderTarget!==null&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(s!==t.ORDER_INDEPENDENT_TRANSPARENCY||r!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){const s=t.PREPASS;if(!t._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(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let n=0;n0&&(o.shadowEnabled=!0,c.prepareDefines(r,s))}}i.lightmapMode!=ea.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==ea.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}static PrepareDefinesForLights(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const l={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n){for(const h of t.lightSources)if(this.PrepareDefinesForLight(e,t,h,o,i,s,l),o++,o===r)break}i.SPECULARTERM=l.specularEnabled,i.SHADOWS=l.shadowEnabled;for(let h=o;h0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));return r++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&Ii.LastCreatedEngine){const r=Ii.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n?.isUsingTextureForTargets)return;const o=n&&n.supportsNormals&&i.NORMAL,l=n&&n.supportsTangents&&i.TANGENT,c=n&&n.supportsUVs&&i.UV1;for(let h=0;hr&&Me.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,s){i.NUM_BONE_INFLUENCERS>0&&(s.addCPUSkinningFallback(0,t),e.push(se.MatricesIndicesKind),e.push(se.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(se.MatricesIndicesExtraKind),e.push(se.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(se.ColorInstanceKind)}static PushAttributesForInstances(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}static BindLights(e,t,i,s,r=4){const n=Math.min(t.lightSources.length,r);for(let o=0;o-1){const r=s.getTransformMatrixTexture(e);t.setTexture("boneSampler",r),t.setFloat("boneTextureWidth",4*(s.bones.length+1))}else{const r=s.getTransformMatrices(e);r&&(t.setMatrices("mBones",r),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=r.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),ze._CopyBonesTransformationMatrices(r,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){const i=e.morphTargetManager;!e||!i||t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const s=i.activeCamera;s.mode===Pi.ORTHOGRAPHIC_CAMERA&&Me.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(s.maxZ+1)/Math.LN2))}}}ze._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0};ze._TempFogColor=Ie.Black();class DI{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){Kt.Clone(()=>e,this)}serialize(){return Kt.Serialize(this)}parse(e,t,i){Kt.Parse(()=>this,e,t,i)}}z([X()],DI.prototype,"func",null);z([X()],DI.prototype,"funcRef",null);z([X()],DI.prototype,"funcMask",null);z([X()],DI.prototype,"opStencilFail",null);z([X()],DI.prototype,"opDepthFail",null);z([X()],DI.prototype,"opStencilDepthPass",null);z([X()],DI.prototype,"mask",null);z([X()],DI.prototype,"enabled",null);var zu;(function(a){a[a.Created=1]="Created",a[a.Disposed=2]="Disposed",a[a.GetDefineNames=4]="GetDefineNames",a[a.PrepareUniformBuffer=8]="PrepareUniformBuffer",a[a.IsReadyForSubMesh=16]="IsReadyForSubMesh",a[a.PrepareDefines=32]="PrepareDefines",a[a.BindForSubMesh=64]="BindForSubMesh",a[a.PrepareEffect=128]="PrepareEffect",a[a.GetAnimatables=256]="GetAnimatables",a[a.GetActiveTextures=512]="GetActiveTextures",a[a.HasTexture=1024]="HasTexture",a[a.FillRenderTargetTextures=2048]="FillRenderTargetTextures",a[a.HasRenderTargetTextures=4096]="HasRenderTargetTextures",a[a.HardBindForSubMesh=8192]="HardBindForSubMesh"})(zu||(zu={}));class Lt{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;const t=this._alpha;this._alpha=e,(t===1||e===1)&&this.markAsDirty(Lt.MiscDirtyFlag+Lt.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Lt.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Lt.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new Se),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new Se),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new Se),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Lt.TextureDirtyFlag))}get alphaMode(){return this._alphaMode}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(Lt.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Lt.WireFrameFillMode:case Lt.LineListDrawMode:case Lt.LineLoopDrawMode:case Lt.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Lt.WireFrameFillMode:Lt.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Lt.PointFillMode:case Lt.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Lt.PointFillMode:Lt.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Lt.MiscDirtyFlag))}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new Se,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new DI,this._useUBO=!1,this._fillMode=Lt.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||Ii.LastCreatedScene;!s||(this._scene=s,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||Be.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new ml(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=Lt.ClockWiseSideOrientation:this.sideOrientation=Lt.CounterClockWiseSideOrientation,this._uniformBuffer=new es(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Lt.OnEventObservable.notifyObservers(this,zu.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 s=t.materialDefines;return s?(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,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===Lt.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Lt.MATERIAL_OPAQUE||this._transparencyMode===Lt.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 s of i.subMeshes)s.getMaterial()===this&&(!s.effect||(s.effect._wasPreviouslyReady=!1,s.effect._wasPreviouslyUsingInstances=null,s.effect._forceRebindOnNextCall=e));e&&this.markAsDirty(Lt.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),r=(t??this.sideOrientation)===Lt.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,r,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),r}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(zu.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i.effect;!s||(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._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){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,ze.BindSceneUniformBuffer(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 i=this._scene.getEngine();this._cachedDepthWriteState=i.getDepthWrite(),i.setDepthWrite(!1)}if(this.disableColorWrite){const i=this._scene.getEngine();this._cachedColorWriteState=i.getColorWrite(),i.setColorWrite(!1)}if(this.depthFunction!==0){const i=this._scene.getEngine();this._cachedDepthFunctionState=i.getDepthFunction()||0,i.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(zu.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(zu.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(zu.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Lt._parsePlugins(i,e,this._scene,t),this.pluginManager)for(const s of this.pluginManager._plugins){const r=e.pluginManager.getPlugin(s.name);s.copyTo(r)}}getBindedMeshes(){if(this.meshMap){const e=new Array;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,s){const r=Object.assign({clipPlane:!1,useInstances:!1},i),n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const l=()=>{if(!this._scene||!this._scene.getEngine())return;const c=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new Zd(0,0,0,1)),this._storeEffectOnSubMeshes){let h=!0,u=null;if(e.subMeshes){const p=new _d(0,0,0,0,0,e,void 0,!1,!1);p.materialDefines&&(p.materialDefines._renderId=-1),this.isReadyForSubMesh(e,p,r.useInstances)||(p.effect&&p.effect.getCompilationError()&&p.effect.allFallbacksProcessed()?u=p.effect.getCompilationError():(h=!1,setTimeout(l,16)))}h&&(this.allowShaderHotSwapping=o,u&&s&&s(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(l,16);r.clipPlane&&(n.clipPlane=c)};l()}forceCompilationAsync(e,t){return new Promise((i,s)=>{this.forceCompilation(e,()=>{i()},t,r=>{s(r)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Lt._DirtyCallbackArray.length=0,e&Lt.TextureDirtyFlag&&Lt._DirtyCallbackArray.push(Lt._TextureDirtyCallBack),e&Lt.LightDirtyFlag&&Lt._DirtyCallbackArray.push(Lt._LightsDirtyCallBack),e&Lt.FresnelDirtyFlag&&Lt._DirtyCallbackArray.push(Lt._FresnelDirtyCallBack),e&Lt.AttributesDirtyFlag&&Lt._DirtyCallbackArray.push(Lt._AttributeDirtyCallBack),e&Lt.MiscDirtyFlag&&Lt._DirtyCallbackArray.push(Lt._MiscDirtyCallBack),e&Lt.PrePassDirtyFlag&&Lt._DirtyCallbackArray.push(Lt._PrePassDirtyCallBack),Lt._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Lt._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 s of i.subMeshes)if(s.getMaterial(!1)===this)for(const r of s._drawWrappers)!r||!r.defines||!r.defines.markAllAsDirty||this._materialContext===r.materialContext&&e(r.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Lt._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Lt._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Lt._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Lt._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Lt._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Lt._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Lt._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Lt._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Lt._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Lt._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==Kb.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 s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(zu.Disposed,this._eventInfo),this._parentContainer){const r=this._parentContainer.materials.indexOf(this);r>-1&&this._parentContainer.materials.splice(r,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(const r in this.meshMap){const n=this.meshMap[r];n&&(n.material=null,this.releaseVertexArrayObject(n,e))}else{const r=s.meshes;for(const n of r)n.material===this&&!n.sourceMesh&&(n.material=null,this.releaseVertexArrayObject(n,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){if(e.geometry){const i=e.geometry;if(this._storeEffectOnSubMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose();else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){const e=Kt.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 Me.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const r=Be.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,r}static _parsePlugins(e,t,i,s){var r;if(!!e.plugins)for(const n in e.plugins){const o=e.plugins[n];let l=(r=t.pluginManager)===null||r===void 0?void 0:r.getPlugin(o.name);if(!l){const c=Be.Instantiate("BABYLON."+n);c&&(l=new c(t))}l?.parse(o,i,s)}}}Lt.TriangleFillMode=0;Lt.WireFrameFillMode=1;Lt.PointFillMode=2;Lt.PointListDrawMode=3;Lt.LineListDrawMode=4;Lt.LineLoopDrawMode=5;Lt.LineStripDrawMode=6;Lt.TriangleStripDrawMode=7;Lt.TriangleFanDrawMode=8;Lt.ClockWiseSideOrientation=0;Lt.CounterClockWiseSideOrientation=1;Lt.TextureDirtyFlag=1;Lt.LightDirtyFlag=2;Lt.FresnelDirtyFlag=4;Lt.AttributesDirtyFlag=8;Lt.MiscDirtyFlag=16;Lt.PrePassDirtyFlag=32;Lt.AllDirtyFlag=63;Lt.MATERIAL_OPAQUE=0;Lt.MATERIAL_ALPHATEST=1;Lt.MATERIAL_ALPHABLEND=2;Lt.MATERIAL_ALPHATESTANDBLEND=3;Lt.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;Lt.MATERIAL_NORMALBLENDMETHOD_RNM=1;Lt.OnEventObservable=new Se;Lt._AllDirtyCallBack=a=>a.markAllAsDirty();Lt._ImageProcessingDirtyCallBack=a=>a.markAsImageProcessingDirty();Lt._TextureDirtyCallBack=a=>a.markAsTexturesDirty();Lt._FresnelDirtyCallBack=a=>a.markAsFresnelDirty();Lt._MiscDirtyCallBack=a=>a.markAsMiscDirty();Lt._PrePassDirtyCallBack=a=>a.markAsPrePassDirty();Lt._LightsDirtyCallBack=a=>a.markAsLightDirty();Lt._AttributeDirtyCallBack=a=>a.markAsAttributesDirty();Lt._FresnelAndMiscDirtyCallBack=a=>{Lt._FresnelDirtyCallBack(a),Lt._MiscDirtyCallBack(a)};Lt._TextureAndMiscDirtyCallBack=a=>{Lt._TextureDirtyCallBack(a),Lt._MiscDirtyCallBack(a)};Lt._DirtyCallbackArray=[];Lt._RunDirtyCallBacks=a=>{for(const e of Lt._DirtyCallbackArray)e(a)};z([X()],Lt.prototype,"id",void 0);z([X()],Lt.prototype,"uniqueId",void 0);z([X()],Lt.prototype,"name",void 0);z([X()],Lt.prototype,"metadata",void 0);z([X()],Lt.prototype,"checkReadyOnEveryCall",void 0);z([X()],Lt.prototype,"checkReadyOnlyOnce",void 0);z([X()],Lt.prototype,"state",void 0);z([X("alpha")],Lt.prototype,"_alpha",void 0);z([X("backFaceCulling")],Lt.prototype,"_backFaceCulling",void 0);z([X("cullBackFaces")],Lt.prototype,"_cullBackFaces",void 0);z([X()],Lt.prototype,"sideOrientation",void 0);z([X("alphaMode")],Lt.prototype,"_alphaMode",void 0);z([X()],Lt.prototype,"_needDepthPrePass",void 0);z([X()],Lt.prototype,"disableDepthWrite",void 0);z([X()],Lt.prototype,"disableColorWrite",void 0);z([X()],Lt.prototype,"forceDepthWrite",void 0);z([X()],Lt.prototype,"depthFunction",void 0);z([X()],Lt.prototype,"separateCullingPass",void 0);z([X("fogEnabled")],Lt.prototype,"_fogEnabled",void 0);z([X()],Lt.prototype,"pointSize",void 0);z([X()],Lt.prototype,"zOffset",void 0);z([X()],Lt.prototype,"zOffsetUnits",void 0);z([X()],Lt.prototype,"pointsCloud",null);z([X()],Lt.prototype,"fillMode",null);z([X()],Lt.prototype,"transparencyMode",null);class g0 extends Lt{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=new Array,this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...s)=>{const r=t.apply(e,s);return this._markAllSubMeshesAsTexturesDirty(),r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);return this._markAllSubMeshesAsTexturesDirty(),n}}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&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new g0(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Nr&&Nr.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(s=>i.subMaterials.push(t.getLastMaterialById(s))),i}}$e("BABYLON.MultiMaterial",g0);class Rle{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class X${}class R3e{constructor(){this.visibleInstances={},this.batchCache=new Pq,this.batchCacheReplacementModeInFrozenMode=new Pq,this.instancesBufferSize=32*16*4}}class Pq{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array,this.hardwareInstancedRendering=new Array}}class P3e{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class D3e{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 Oe extends Ir{static _GetDefaultSideOrientation(e){return e||Oe.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(se.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(se.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 Se),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new Se),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new Se),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new Se),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new Se),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(){var e;return((e=this._thinInstanceDataStorage.instancesCount)!==null&&e!==void 0?e: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,s=null,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new D3e,this.delayLoadState=0,this.instances=new Array,this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new R3e,this._thinInstanceDataStorage=new P3e,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=Oe.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(o,l,c)=>{o&&c&&(this._uniformBuffer?this.transferToEffect(l):c.bindOnlyWorldMatrix(l))},s){if(s._geometry&&s._geometry.applyToMesh(this),e2.DeepCopy(s,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=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const o=s._ranges;for(const l in o)!Object.prototype.hasOwnProperty.call(o,l)||!o[l]||this.createAnimationRange(l,o[l].from,o[l].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,Nr&&Nr.HasTags(s)&&Nr.AddTagsTo(this,Nr.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix()),this.id=e+"."+s.id,this.material=s.material,!r){const o=s.getDescendants(!0);for(let l=0;l{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 Se(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=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));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const r of this.getChildTransformNodes(!0))r.getClassName()==="InstancedMesh"&&s.getClassName()==="Mesh"&&r.sourceMesh===this?r.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):r.instantiateHierarchy(s,t,i);return s}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 Me.Warn("You cannot use a mesh as LOD level twice"),this;const i=new Rle(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*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let l=0;l0||this.hasThinInstances);this.computeWorldMatrix();const m=this.material||u.defaultMaterial;if(m){if(m._storeEffectOnSubMeshes)for(const f of this.subMeshes){const d=f.getMaterial();if(d){if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,f,p))return!1}else if(!d.isReady(this,p))return!1}}else if(!m.isReady(this,p))return!1}const _=h.currentRenderPassId;for(const f of this.lightSources){const d=f.getShadowGenerators();if(!d)continue;const C=d.values();for(let v=C.next();v.done!==!0;v=C.next()){const y=v.value;if(y&&(!(!((i=y.getShadowMap())===null||i===void 0)&&i.renderList)||((s=y.getShadowMap())===null||s===void 0?void 0:s.renderList)&&((n=(r=y.getShadowMap())===null||r===void 0?void 0:r.renderList)===null||n===void 0?void 0:n.indexOf(this))!==-1)){const b=(o=y.getShadowMap().renderPassIds)!==null&&o!==void 0?o:[h.currentRenderPassId];for(let E=0;E0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const n of this.subMeshes){if(n.indexStart+n.indexCount>s){r=!0;break}if(n.verticesStart+n.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new _d(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!==0;)i++;this.releaseSubMeshes();for(let r=0;r=t);r++)_d.CreateFromIndices(0,s,r===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const r=new Jt;r.set(t,e);const n=this.getScene();new au(au.RandomId(),n,r,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=au.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(se.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(se.PositionKind,i,!1,!1),t){const s=this.getIndices(),r=this.getVerticesData(se.NormalKind);if(!r)return this;Jt.ComputeNormals(i,s,r),this.updateVerticesData(se.NormalKind,r,!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(au.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const s=new Jt;s.indices=e;const r=this.getScene();new au(au.RandomId(),r,s,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,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t);let n;if(this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case Lt.PointFillMode:n=null;break;case Lt.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case Lt.TriangleFillMode:n=this._geometry.getIndexBuffer();break}return!s||!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,n):this._geometry._bind(t,n,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 r=this.getScene().getEngine();return this._unIndexed||t==Lt.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Lt.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):r.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(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const o=this._instanceDataStorage.visibleInstances,l=i.getRenderId(),c=s?o.intermediateDefaultRenderId:o.defaultRenderId;n.visibleInstances[e]=o[l],!n.visibleInstances[e]&&c&&(n.visibleInstances[e]=o[c])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&n.visibleInstances[e]!==null&&n.visibleInstances[e]!==void 0,this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){var n;const o=i.visibleInstances[e._id],l=o?o.length:0,c=this._instanceDataStorage,h=c.instancesBufferSize;let u=c.instancesBuffer,p=c.instancesPreviousBuffer;const _=(l+1)*16*4;for(;c.instancesBufferSize<_;)c.instancesBufferSize*=2;(!c.instancesData||h!=c.instancesBufferSize)&&(c.instancesData=new Float32Array(c.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!c.instancesPreviousData||h!=c.instancesBufferSize)&&(c.instancesPreviousData=new Float32Array(c.instancesBufferSize/4));let f=0,d=0;const C=i.renderSelf[e._id],v=!u||h!==c.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!c.instancesPreviousBuffer;if(!this._instanceDataStorage.manualUpdate&&(!c.isFrozen||v)){const y=this.getWorldMatrix();if(C&&(this._scene.needsPreviousWorldMatrices&&(c.masterMeshPreviousWorldMatrix?(c.masterMeshPreviousWorldMatrix.copyToArray(c.instancesPreviousData,f),c.masterMeshPreviousWorldMatrix.copyFrom(y)):(c.masterMeshPreviousWorldMatrix=y.clone(),c.masterMeshPreviousWorldMatrix.copyToArray(c.instancesPreviousData,f))),y.copyToArray(c.instancesData,f),f+=16,d++),o){if(Oe.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&((n=e.getMaterial())===null||n===void 0?void 0:n.needAlphaBlendingForMesh(e.getRenderingMesh()))){const M=this._scene.activeCamera.globalPosition;for(let b=0;bb._distanceToCamera>E._distanceToCamera?-1:b._distanceToCamera1&&c.activeCamera===c.activeCameras[0]||h<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const p=this._getInstancesRenderList(e._id,!!i);if(p.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const m=c.getEngine();let _=0,f=null;this.ignoreCameraMaxZ&&c.activeCamera&&!c._isInIntermediateRendering()&&(_=c.activeCamera.maxZ,f=c.activeCamera,c.activeCamera.maxZ=0,c.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const d=e.getRenderingMesh(),C=p.hardwareInstancedRendering[e._id]||d.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,v=this._instanceDataStorage,y=e.getMaterial();if(!y)return f&&(f.maxZ=_,c.updateTransformMatrix(!0)),this;if(!v.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==y){if(y._storeEffectOnSubMeshes){if(!y.isReadyForSubMesh(this,e,C))return f&&(f.maxZ=_,c.updateTransformMatrix(!0)),this}else if(!y.isReady(this,C))return f&&(f.maxZ=_,c.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=y}else if(y._storeEffectOnSubMeshes&&!(!((n=e.effect)===null||n===void 0)&&n._wasPreviouslyReady)||!y._storeEffectOnSubMeshes&&!(!((o=y.getEffect())===null||o===void 0)&&o._wasPreviouslyReady))return f&&(f.maxZ=_,c.updateTransformMatrix(!0)),this;t&&m.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let M;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?M=e._drawWrapper:M=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const b=(l=M?.effect)!==null&&l!==void 0?l:null;for(const w of c._beforeRenderingMeshStage)w.action(this,e,p,b);if(!M||!b)return f&&(f.maxZ=_,c.updateTransformMatrix(!0)),this;const E=i||this;let S;if(!v.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this.overrideMaterialSideOrientation!==null)){const w=E._getWorldMatrixDeterminant();S=this.overrideMaterialSideOrientation,S==null&&(S=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),w<0&&(S=S===Lt.ClockWiseSideOrientation?Lt.CounterClockWiseSideOrientation:Lt.ClockWiseSideOrientation),v.sideOrientation=S}else S=v.sideOrientation;const I=this._internalMeshDataInfo._effectiveMaterial._preBind(M,S);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&m.setDepthWrite(!0);const D=this._internalMeshDataInfo._effectiveMaterial,R=D.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),C||this._bind(e,b,R,!1);const L=E.getWorldMatrix();D._storeEffectOnSubMeshes?D.bindForSubMesh(L,this,e):D.bind(L,this),!D.backFaceCulling&&D.separateCullingPass&&(m.setState(!0,D.zOffset,!1,!I,D.cullBackFaces,D.stencil,D.zOffsetUnits),this._processRendering(this,e,b,R,p,C,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),m.setState(!0,D.zOffset,!1,I,D.cullBackFaces,D.stencil,D.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,b,R,p,C,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const w of c._afterRenderingMeshStage)w.action(this,e,p,b);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),f&&(f.maxZ=_,c.updateTransformMatrix(!0)),c.performancePriority===Kb.Aggressive&&!v.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(se.MatricesWeightsKind)&&(this.isVerticesDataPresent(se.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(se.MatricesWeightsKind),t=e.length;for(let i=0;iC&&s++,b!==0&&y++,v+=b,C=b}if(c[y]++,y>n&&(n=y),v===0)r++;else{const M=1/v;let b=0;for(let E=0;Eh&&o++}}const u=this.skeleton.bones.length,p=this.getVerticesData(se.MatricesIndicesKind),m=this.getVerticesData(se.MatricesIndicesExtraKind);let _=0;for(let d=0;d=u||v<0)&&_++}const f="Number of Weights = "+i/4+` +Maximum influences = `+n+` +Missing Weights = `+r+` +Not Sorted = `+s+` +Not Normalized = `+o+` +WeightCounts = [`+c+`] +Number of bones = `+u+` +Bad Bone Indices = `+_;return{skinned:!0,valid:r===0&&o===0&&_===0,report:f}}_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 Be.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this),this.instances.forEach(s=>{s.refreshBoundingInfo(),s._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 s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],this;return this}getAnimatables(){const e=new Array;return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(se.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(se.PositionKind);const s=O.Zero();let r;for(r=0;r{const u=h.width,p=h.height,_=this.getEngine().createCanvas(u,p).getContext("2d");_.drawImage(h,0,0);const f=_.getImageData(0,0,u,p).data;this.applyDisplacementMapFromBuffer(f,u,p,t,i,r,n,o),s&&s(this)};return Be.LoadImage(e,c,()=>{},l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,o,l=!1){if(!this.isVerticesDataPresent(se.PositionKind)||!this.isVerticesDataPresent(se.NormalKind)||!this.isVerticesDataPresent(se.UVKind))return Me.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const c=this.getVerticesData(se.PositionKind,!0,!0),h=this.getVerticesData(se.NormalKind),u=this.getVerticesData(se.UVKind);let p=O.Zero();const m=O.Zero(),_=lt.Zero();n=n||lt.Zero(),o=o||new lt(1,1);for(let f=0;f{const c=new Float32Array(i.length*l);let h=0;for(let u=0;u{const o=s.length-1-n,l=s[o];for(let c=0;c{for(let o=0;o-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),e.skeletonId!==void 0&&e.skeletonId!==null&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let r=0;r4,c=l?this.getVerticesData(se.MatricesIndicesExtraKind):null,h=l?this.getVerticesData(se.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),p=O.Zero(),m=new ge,_=new ge;let f=0,d;for(let C=0;C0&&(ge.FromFloat32ArrayToRefScaled(u,Math.floor(n[f+d]*16),v,_),m.addToSelf(_));if(l)for(d=0;d<4;d++)v=h[f+d],v>0&&(ge.FromFloat32ArrayToRefScaled(u,Math.floor(c[f+d]*16),v,_),m.addToSelf(_));O.TransformCoordinatesFromFloatsToRef(i._sourcePositions[C],i._sourcePositions[C+1],i._sourcePositions[C+2],m,p),p.toArray(s,C),t&&(O.TransformNormalFromFloatsToRef(i._sourceNormals[C],i._sourceNormals[C+1],i._sourceNormals[C+2],m,p),p.toArray(r,C)),m.reset()}return this.updateVerticesData(se.PositionKind,s),t&&this.updateVerticesData(se.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach(function(s){const n=s.getBoundingInfo().boundingBox;!t||!i?(t=n.minimumWorld,i=n.maximumWorld):(t.minimizeInPlace(n.minimumWorld),i.maximizeInPlace(n.maximumWorld))}),!t||!i?{min:O.Zero(),max:O.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?Oe.MinMax(e):e;return O.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return AK(Oe._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return xK(Oe._MergeMeshesCoroutine(e,t,i,s,r,n,!0),Mle())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,o){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let S=0;for(l=0;l=65536)return Me.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const c=new Array,h=new Array,u=new Array,p=e[0].overrideMaterialSideOrientation;for(l=0;l{const I=S.computeWorldMatrix(!0);return{vertexData:Jt.ExtractFromMesh(S,!1,!1),transform:I}},{vertexData:f,transform:d}=_(m);o&&(yield);const C=new Array(e.length-1);for(let S=1;S{throw Ys("GroundMesh")};Oe._GoldbergMeshParser=(a,e)=>{throw Ys("GoldbergMesh")};Oe._LinesMeshParser=(a,e)=>{throw Ys("LinesMesh")};Oe._GreasedLineMeshParser=(a,e)=>{throw Ys("GreasedLineMesh")};Oe._TrailMeshParser=(a,e)=>{throw Ys("TrailMesh")};$e("BABYLON.Mesh",Oe);Oe._instancedMeshFactory=(a,e)=>{const t=new ov(a,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class ov extends Ir{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||t===void 0?void 0:t.receiveShadows)!==e&&Be.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||t===void 0?void 0:t.material)!==e&&Be.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||t===void 0?void 0:t.visibility)!==e&&Be.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||t===void 0?void 0:t.skeleton)!==e&&Be.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||Me.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,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),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||Me.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!==Ki.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new ge);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,ue.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(ue.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)===0||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0}dispose(e,t=!1){if(this._shadowGenerators){const i=this._shadowGenerators.values();for(let s=i.next();s.done!==!0;s=i.next())s.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=pr.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=Kt.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=Kt.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)})),Kt.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const s=pn.Construct("Light_Type_"+e,t,i);return s||null}static Parse(e,t){const i=pr.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=Kt.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(s.falloffType=e.falloffType),e.lightmapMode!==void 0&&(s.lightmapMode=e.lightmapMode),e.animations){for(let r=0;r{const r=t.apply(e,s);for(const n of s)n._resyncLightSource(this);return r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);for(const o of n)o._resyncLightSource(this);return n};for(const s of e)s._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...s)=>{const r=t.apply(e,s);return this._resyncMeshes(),r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);return this._resyncMeshes(),n},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===pr.INTENSITYMODE_AUTOMATIC&&(t===pr.LIGHTTYPEID_DIRECTIONALLIGHT?i=pr.INTENSITYMODE_ILLUMINANCE:i=pr.INTENSITYMODE_LUMINOUSINTENSITY),t){case pr.LIGHTTYPEID_POINTLIGHT:case pr.LIGHTTYPEID_SPOTLIGHT:switch(i){case pr.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case pr.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case pr.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case pr.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case pr.INTENSITYMODE_ILLUMINANCE:e=1;break;case pr.INTENSITYMODE_LUMINANCE:{let s=this.radius;s=Math.max(s,.001),e=2*Math.PI*(1-Math.cos(s));break}}break;case pr.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}pr.FALLOFF_DEFAULT=ea.FALLOFF_DEFAULT;pr.FALLOFF_PHYSICAL=ea.FALLOFF_PHYSICAL;pr.FALLOFF_GLTF=ea.FALLOFF_GLTF;pr.FALLOFF_STANDARD=ea.FALLOFF_STANDARD;pr.LIGHTMAP_DEFAULT=ea.LIGHTMAP_DEFAULT;pr.LIGHTMAP_SPECULAR=ea.LIGHTMAP_SPECULAR;pr.LIGHTMAP_SHADOWSONLY=ea.LIGHTMAP_SHADOWSONLY;pr.INTENSITYMODE_AUTOMATIC=ea.INTENSITYMODE_AUTOMATIC;pr.INTENSITYMODE_LUMINOUSPOWER=ea.INTENSITYMODE_LUMINOUSPOWER;pr.INTENSITYMODE_LUMINOUSINTENSITY=ea.INTENSITYMODE_LUMINOUSINTENSITY;pr.INTENSITYMODE_ILLUMINANCE=ea.INTENSITYMODE_ILLUMINANCE;pr.INTENSITYMODE_LUMINANCE=ea.INTENSITYMODE_LUMINANCE;pr.LIGHTTYPEID_POINTLIGHT=ea.LIGHTTYPEID_POINTLIGHT;pr.LIGHTTYPEID_DIRECTIONALLIGHT=ea.LIGHTTYPEID_DIRECTIONALLIGHT;pr.LIGHTTYPEID_SPOTLIGHT=ea.LIGHTTYPEID_SPOTLIGHT;pr.LIGHTTYPEID_HEMISPHERICLIGHT=ea.LIGHTTYPEID_HEMISPHERICLIGHT;z([Br()],pr.prototype,"diffuse",void 0);z([Br()],pr.prototype,"specular",void 0);z([X()],pr.prototype,"falloffType",void 0);z([X()],pr.prototype,"intensity",void 0);z([X()],pr.prototype,"range",null);z([X()],pr.prototype,"intensityMode",null);z([X()],pr.prototype,"radius",null);z([X()],pr.prototype,"_renderPriority",void 0);z([_t("_reorderLightsInScene")],pr.prototype,"renderPriority",void 0);z([X("shadowEnabled")],pr.prototype,"_shadowEnabled",void 0);z([X("excludeWithLayerMask")],pr.prototype,"_excludeWithLayerMask",void 0);z([X("includeOnlyWithLayerMask")],pr.prototype,"_includeOnlyWithLayerMask",void 0);z([X("lightmapMode")],pr.prototype,"_lightmapMode",void 0);class Ple extends pc{}class Dle{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 kG extends pc{constructor(e){super(),this._wasAddedToScene=!1,e=e||Ii.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 l=o.uniqueId;i.dependsOn.set(l,new Set),i.dependedBy.set(l,new Set)}for(const o of e){const l=o.uniqueId,c=i.dependsOn.get(l);if(o instanceof ov){const u=o.sourceMesh;t.has(u.uniqueId)&&(c.add(u.uniqueId),i.dependedBy.get(u.uniqueId).add(l))}const h=i.dependedBy.get(l);for(const u of o.getDescendants()){const p=u.uniqueId;t.has(p)&&(h.add(p),i.dependsOn.get(p).add(l))}}const s=[],r=[];for(const o of e){const l=o.uniqueId;i.dependsOn.get(l).size===0&&(r.push(o),t.delete(l))}const n=r;for(;n.length>0;){const o=n.shift();s.push(o);const l=i.dependedBy.get(o.uniqueId);for(const c of Array.from(l.values())){const h=i.dependsOn.get(c);h.delete(o.uniqueId),h.size===0&&t.get(c)&&(n.push(t.get(c)),t.delete(c))}}return t.size>0&&(console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>console.error(o.name))),s}_addNodeAndDescendantsToList(e,t,i,s){if(!(!i||s&&!s(i)||t.has(i.uniqueId))){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof Oe&&this.meshes.indexOf(e)!==-1||e instanceof Ki&&this.transformNodes.indexOf(e)!==-1||e instanceof pr&&this.lights.indexOf(e)!==-1||e instanceof Pi&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return Me.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 Me.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 Me.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 Me.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Be.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new Dle,o=[],l=[],c=Object.assign({doNotInstantiate:!0},i),h=(f,d)=>{if(s[f.uniqueId]=d.uniqueId,r[d.uniqueId]=d,e&&(d.name=e(f.name)),d instanceof Oe){const C=d;if(C.morphTargetManager){const v=f.morphTargetManager;C.morphTargetManager=v.clone();for(let y=0;y{if(h(f,d),f.parent){const C=s[f.parent.uniqueId],v=r[C];v?d.parent=v:d.parent=f.parent}if(d.position&&f.position&&d.position.copyFrom(f.position),d.rotationQuaternion&&f.rotationQuaternion&&d.rotationQuaternion.copyFrom(f.rotationQuaternion),d.rotation&&f.rotation&&d.rotation.copyFrom(f.rotation),d.scaling&&f.scaling&&d.scaling.copyFrom(f.scaling),d.material){const C=d;if(C.material)if(t){const v=f.material;if(l.indexOf(v)===-1){let y=v.clone(e?e(v.name):"Clone of "+v.name);if(l.push(v),s[v.uniqueId]=y.uniqueId,r[y.uniqueId]=y,v.getClassName()==="MultiMaterial"){const M=v;for(const b of M.subMaterials)!b||(y=b.clone(e?e(b.name):"Clone of "+b.name),l.push(b),s[b.uniqueId]=y.uniqueId,r[y.uniqueId]=y);M.subMaterials=M.subMaterials.map(b=>b&&r[s[b.uniqueId]])}}C.getClassName()!=="InstancedMesh"&&(C.material=r[s[v.uniqueId]])}else C.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(C.material)===-1&&this.scene.addMultiMaterial(C.material):this.scene.materials.indexOf(C.material)===-1&&this.scene.addMaterial(C.material)}d.parent===null&&n.rootNodes.push(d)};return m.forEach(f=>{if(f.getClassName()==="InstancedMesh"){const d=f,C=d.sourceMesh,v=s[C.uniqueId],M=(typeof v=="number"?r[v]:C).createInstance(d.name);_(d,M)}else{let d=!0;f.getClassName()==="TransformNode"||f.getClassName()==="Node"||f.skeleton||!f.getTotalVertices||f.getTotalVertices()===0?d=!1:c.doNotInstantiate&&(typeof c.doNotInstantiate=="function"?d=!c.doNotInstantiate(f):d=!c.doNotInstantiate);const C=d?f.createInstance(`instance of ${f.name}`):f.clone(`Clone of ${f.name}`,null,!0);if(!C)throw new Error(`Could not clone or instantiate node on Asset Container ${f.name}`);_(f,C)}}),this.skeletons.forEach(f=>{if(c.predicate&&!c.predicate(f))return;const d=f.clone(e?e(f.name):"Clone of "+f.name);for(const C of this.meshes)if(C.skeleton===f&&!C.isAnInstance){const v=r[s[C.uniqueId]];if(!v||v.isAnInstance||(v.skeleton=d,o.indexOf(d)!==-1))continue;o.push(d);for(const y of d.bones)y._linkedTransformNode&&(y._linkedTransformNode=r[s[y._linkedTransformNode.uniqueId]])}n.skeletons.push(d)}),this.animationGroups.forEach(f=>{if(c.predicate&&!c.predicate(f))return;const d=f.clone(e?e(f.name):"Clone of "+f.name,C=>r[s[C.uniqueId]]||C);n.animationGroups.push(d)}),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Be.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()||Be.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)}),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 s of e){let r=!0;if(i){for(const n of i)if(s===n){r=!1;break}}r&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new Ple);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 Oe("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=Ii.LastCreatedScene,t,i=null){if(!e)return Me.Error("No scene available to merge animations to"),[];const s=i||(o=>{let l=null;const c=o.animations.length?o.animations[0].targetProperty:"",h=o.name.split(".").join("").split("_primitive")[0];switch(c){case"position":case"rotationQuaternion":l=e.getTransformNodeByName(o.name)||e.getTransformNodeByName(h);break;case"influence":l=e.getMorphTargetByName(o.name)||e.getMorphTargetByName(h);break;default:l=e.getNodeByName(o.name)||e.getNodeByName(h)}return l});this.getNodes().forEach(o=>{const l=s(o);if(l!==null){for(const c of o.animations){const h=l.animations.filter(u=>u.targetProperty===c.targetProperty);for(const u of h){const p=l.animations.indexOf(u,0);p>-1&&l.animations.splice(p,1)}}l.animations=l.animations.concat(o.animations)}});const n=new Array;return this.animationGroups.slice().forEach(o=>{n.push(o.clone(o.name,s)),o.animatables.forEach(l=>{l.stop()})}),t.forEach(o=>{const l=s(o.target);l&&(e.beginAnimation(l,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))}),n}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)})}}class O3e{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||Ii.LastCreatedScene,!!e){if(this._scene=e,!He.audioEngine){Be.Warn("No audio engine initialized, failed to create an audio analyser");return}this._audioEngine=He.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 Ole(a,e,t);class Ole{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 Se,this.onAudioLockedObservable=new Se,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!ql())return;typeof window.AudioContext<"u"&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&!!s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch{}try{s&&!!s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch{}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if(((e=this._audioContext)===null||e===void 0?void 0:e.state)==="running"){this._hideMuteButton();return}this._tryToRun?(t=this._audioContext)===null||t===void 0||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return!((e=this._audioContext)===null||e===void 0)&&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,Me.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 J5{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=He.audioEngine)===null||e===void 0?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){const t=this.isPaused?0:He.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,s=null,r){var n,o,l,c,h;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 Se,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=O.Zero(),this._localDirection=new O(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||Ii.LastCreatedScene,!!i)if(this._scene=i,J5._SceneComponentInitialization(i),this._readyToPlayCallback=s,this._customAttenuationFunction=(u,p,m,_,f)=>p0&&(m=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":p.push(t);case"Array":p.length===0&&(p=t);for(let _=0;_{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(f,d=>{this._soundLoaded(d)},void 0,!0,!0,d=>{d&&Me.Error("XHR "+d.status+" error on: "+f+"."),Me.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:u=!1;break}u?m||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):Me.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch{Me.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),He.audioEngine&&!He.audioEngine.WarnedWebAudioUnsupported&&(Me.Error("Web Audio is not supported by your browser."),He.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;!((e=He.audioEngine)===null||e===void 0)&&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=He.audioEngine)===null||t===void 0)&&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=He.audioEngine)===null||t===void 0)&&t.audioContext)||He.audioEngine.audioContext.decodeAudioData(e,i=>{this._audioBufferLoaded(i)},i=>{Me.Error("Error while decoding audio data for: "+this.name+" / Error: "+i)})}setAudioBuffer(e){var t;!((t=He.audioEngine)===null||t===void 0)&&t.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,s,r,n,o,l,c,h,u,p;e&&(this.loop=(t=e.loop)!==null&&t!==void 0?t:this.loop,this.maxDistance=(i=e.maxDistance)!==null&&i!==void 0?i:this.maxDistance,this.useCustomAttenuation=(s=e.useCustomAttenuation)!==null&&s!==void 0?s:this.useCustomAttenuation,this.rolloffFactor=(r=e.rolloffFactor)!==null&&r!==void 0?r:this.rolloffFactor,this.refDistance=(n=e.refDistance)!==null&&n!==void 0?n:this.refDistance,this.distanceModel=(o=e.distanceModel)!==null&&o!==void 0?o:this.distanceModel,this._playbackRate=(l=e.playbackRate)!==null&&l!==void 0?l:this._playbackRate,this._length=(c=e.length)!==null&&c!==void 0?c:void 0,this.spatialSound=(h=e.spatialSound)!==null&&h!==void 0?h:this._spatialSound,this._setOffset((u=e.offset)!==null&&u!==void 0?u:void 0),this.setVolume((p=e.volume)!==null&&p!==void 0?p: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,t;((e=He.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&He.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=(t=this._soundPanner)!==null&&t!==void 0?t:He.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===void 0||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=He.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;((t=He.audioEngine)===null||t===void 0?void 0: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 c=()=>{var h,u;if(!((h=He.audioEngine)===null||h===void 0)&&h.unlocked){const p=this._htmlAudioElement.play();p!==void 0&&p.catch(()=>{var m,_;(m=He.audioEngine)===null||m===void 0||m.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(_=He.audioEngine)===null||_===void 0?void 0:_.onAudioUnlockedObservable.addOnce(()=>{c()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(u=He.audioEngine)===null||u===void 0?void 0:u.onAudioUnlockedObservable.addOnce(()=>{c()}))};c()}}else{const c=()=>{var h,u,p,m;if(!((h=He.audioEngine)===null||h===void 0)&&h.audioContext){if(i=i||this._length,t!==void 0&&this._setOffset(t),this._soundSource){const _=this._soundSource;_.onended=()=>{_.disconnect()}}if(this._soundSource=(u=He.audioEngine)===null||u===void 0?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()},l=e?((p=He.audioEngine)===null||p===void 0?void 0:p.audioContext.currentTime)+e:He.audioEngine.audioContext.currentTime;const _=((this.isPaused?this.currentTime:0)+((m=this._offset)!==null&&m!==void 0?m:0))%this._soundSource.buffer.duration;this._soundSource.start(l,_,this.loop?void 0:i)}}};((o=He.audioEngine)===null||o===void 0?void 0:o.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var h;((h=He.audioEngine)===null||h===void 0?void 0:h.audioContext.state)==="suspended"?(He.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=He.audioEngine.onAudioUnlockedObservable.addOnce(()=>{c()}))):c()},500):c()}this._startTime=l,this.isPlaying=!0,this.isPaused=!1}catch(l){Me.Error("Error while trying to play audio: "+this.name+", "+l.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=He.audioEngine)===null||t===void 0?void 0:t.audioContext)&&this._soundSource){const i=e?He.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=He.audioEngine)===null||e===void 0?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=He.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;((i=He.audioEngine)===null||i===void 0?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&He.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(He.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,He.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,He.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 s=e.getBoundingInfo();this.setPosition(s.boundingSphere.centerWorld)}((t=He.audioEngine)===null||t===void 0?void 0: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 J5(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,s){const r=e.name;let n;e.url?n=i+e.url:n=i+r;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 l;if(!s)l=new J5(r,n,t,()=>{t.removePendingData(l)},o),t.addPendingData(l);else{const c=()=>{s._isReadyToPlay?(l._audioBuffer=s.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play(0,l._offset,l._length)):setTimeout(c,300)};l=new J5(r,new ArrayBuffer(0),t,null,o),c()}if(e.position){const c=O.FromArray(e.position);l.setPosition(c)}if(e.isDirectional&&(l.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const c=O.FromArray(e.localDirectionToMesh);l.setLocalDirectionToMesh(c)}if(e.connectedMeshId){const c=t.getMeshById(e.connectedMeshId);c&&l.attachToMesh(c)}return e.metadata&&(l.metadata=e.metadata),l}_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=He.audioEngine)===null||e===void 0||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}J5._SceneComponentInitialization=a=>{throw Ys("AudioSceneComponent")};class wle{constructor(e,t={}){this.id=-1,this._isInitialized=!1,e=e||Ii.LastCreatedScene,e&&(this._scene=e,this.soundCollection=new Array,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=He.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&He.audioEngine.audioContext&&(this._outputAudioNode=He.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(He.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(He.audioEngine&&He.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=He.audioEngine)===null||t===void 0?void 0: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=He.audioEngine)===null||t===void 0?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(!((e=He.audioEngine)===null||e===void 0)&&e.canUseWebAudio)for(let t=0;t{var s;let r=[],n;if(t.sounds=t.sounds||[],a.sounds!==void 0&&a.sounds!==null)for(let o=0,l=a.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&&(s=t.activeCameras[0]),this.audioListenerPositionProvider){const n=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(n.x||0,n.y||0,n.z||0)}else s?this._cachedCameraPosition.equals(s.globalPosition)||(this._cachedCameraPosition.copyFrom(s.globalPosition),i.audioContext.listener.setPosition(s.globalPosition.x,s.globalPosition.y,s.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const n=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(n.x||0,n.y||0,n.z||0,0,1,0)}else s?(s.rigCameras&&s.rigCameras.length>0&&(s=s.rigCameras[0]),s.getViewMatrix().invertToRef(this._invertMatrixTemp),O.TransformNormalToRef(v0._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 r;for(r=0;r{let e=a._getComponent(ai.NAME_AUDIO);e||(e=new v0(a),a._addComponent(e))};class Nle{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 s=0;for(const n of i)s+=n;const r=s>0?1/s:0;for(let n=0;n{this._onended()})}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee,this)}serialize(){return Kt.Serialize(this)}parse(e,t,i){Kt.Parse(()=>this,e,t,i)}}z([xs(),_t("_markSubMeshesAsAttributesDirty")],nD.prototype,"texture",void 0);z([X(),_t("_markSubMeshesAsAttributesDirty")],nD.prototype,"isEnabled",void 0);z([X()],nD.prototype,"animationParameters",void 0);z([X()],nD.prototype,"time",void 0);class eI{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?._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=__.Zero(),this._cachedBaseSize=__.Zero(),this._initialSamplingMode=2,this._texture=eI._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 Sn extends eI{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){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this._markAllSubMeshesAsTexturesDirty()}get isRGBD(){return this._texture!=null&&this._texture._isRGBD}set isRGBD(e){this._texture&&(this._texture._isRGBD=e)}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=WL()),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=Sn.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=new Array,this.onDisposeObservable=new Se,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Sn._IsScene(e)?this._scene=e:this._engine=e:this._scene=Ii.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 ge.IdentityReadOnly}getReflectionTextureMatrix(){return ge.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const o=this._getEngine();if(!o)return null;const l=o._getUseSRGBBuffer(!!r,t),c=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=Kt.Serialize(this);return Kt.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let s=0;s{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}}Sn.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;z([X()],Sn.prototype,"uniqueId",void 0);z([X()],Sn.prototype,"name",void 0);z([X()],Sn.prototype,"metadata",void 0);z([X("hasAlpha")],Sn.prototype,"_hasAlpha",void 0);z([X("getAlphaFromRGB")],Sn.prototype,"_getAlphaFromRGB",void 0);z([X()],Sn.prototype,"level",void 0);z([X("coordinatesIndex")],Sn.prototype,"_coordinatesIndex",void 0);z([X()],Sn.prototype,"optimizeUVAllocation",void 0);z([X("coordinatesMode")],Sn.prototype,"_coordinatesMode",void 0);z([X()],Sn.prototype,"wrapU",null);z([X()],Sn.prototype,"wrapV",null);z([X()],Sn.prototype,"wrapR",void 0);z([X()],Sn.prototype,"anisotropicFilteringLevel",void 0);z([X()],Sn.prototype,"isCube",null);z([X()],Sn.prototype,"is3D",null);z([X()],Sn.prototype,"is2DArray",null);z([X()],Sn.prototype,"gammaSpace",null);z([X()],Sn.prototype,"invertZ",void 0);z([X()],Sn.prototype,"lodLevelInAlpha",void 0);z([X()],Sn.prototype,"lodGenerationOffset",null);z([X()],Sn.prototype,"lodGenerationScale",null);z([X()],Sn.prototype,"linearSpecularLOD",null);z([xs()],Sn.prototype,"irradianceTexture",null);z([X()],Sn.prototype,"isRenderTarget",void 0);function EK(a,e,t=!1){const i=e.width,s=e.height;if(a instanceof Float32Array){let c=a.byteLength/a.BYTES_PER_ELEMENT;const h=new Uint8Array(c);for(;--c>=0;){let u=a[c];u<0?u=0:u>1&&(u=1),h[c]=u*255}a=h}const r=document.createElement("canvas");r.width=i,r.height=s;const n=r.getContext("2d");if(!n)return null;const o=n.createImageData(i,s);if(o.data.set(a),n.putImageData(o,0,0),t){const c=document.createElement("canvas");c.width=i,c.height=s;const h=c.getContext("2d");return h?(h.translate(0,s),h.scale(1,-1),h.drawImage(r,0,0),c.toDataURL("image/png")):null}return r.toDataURL("image/png")}function K$(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=a._readPixelsSync(e,t);return s?EK(s,a.getSize(),i.invertY):null}async function Q$(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=await a.readPixels(e,t);return s?EK(s,a.getSize(),i.invertY):null}const w3e={GenerateBase64StringFromPixelData:EK,GenerateBase64StringFromTexture:K$,GenerateBase64StringFromTextureAsync:Q$};class Te extends Sn{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,s,r=Te.TRILINEAR_SAMPLINGMODE,n=null,o=null,l=null,c=!1,h,u,p,m,_){var f,d,C,v,y,M,b,E,S;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 Se,this._isBlocking=!0,this.name=e||"",this.url=e;let I,D=!1,R=null;typeof i=="object"&&i!==null?(I=(f=i.noMipmap)!==null&&f!==void 0?f:!1,s=(d=i.invertY)!==null&&d!==void 0?d:!fn.UseOpenGLOrientationForUV,r=(C=i.samplingMode)!==null&&C!==void 0?C:Te.TRILINEAR_SAMPLINGMODE,n=(v=i.onLoad)!==null&&v!==void 0?v:null,o=(y=i.onError)!==null&&y!==void 0?y:null,l=(M=i.buffer)!==null&&M!==void 0?M:null,c=(b=i.deleteBuffer)!==null&&b!==void 0?b:!1,h=i.format,u=i.mimeType,p=i.loaderOptions,m=i.creationFlags,D=(E=i.useSRGBBuffer)!==null&&E!==void 0?E:!1,R=(S=i.internalTexture)!==null&&S!==void 0?S:null):I=!!i,this._noMipmap=I,this._invertY=s===void 0?!fn.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=l,this._deleteBuffer=c,this._mimeType=u,this._loaderOptions=p,this._creationFlags=m,this._useSRGBBuffer=D,this._forcedExtension=_,h&&(this._format=h);const L=this.getScene(),w=this._getEngine();if(!w)return;w.onBeforeTextureInitObservable.notifyObservers(this);const N=()=>{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),n&&n(),!this.isBlocking&&L&&L.resetCachedMaterial()},V=(W,G)=>{this._loadingError=!0,this._errorObject={message:W,exception:G},o&&o(W,G),Te.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!R){this._delayedOnLoad=N,this._delayedOnError=V;return}if(this._texture=R??this._getFromCache(this.url,I,r,this._invertY,D),this._texture)if(this._texture.isReady)wB.SetImmediate(()=>N());else{const W=this._texture.onLoadedObservable.add(N);this._texture.onErrorObservable.add(G=>{var ie;V(G.message,G.exception),(ie=this._texture)===null||ie===void 0||ie.onLoadedObservable.remove(W)})}else if(!L||!L.useDelayedTextureLoading){try{this._texture=w.createTexture(this.url,I,this._invertY,L,r,N,V,this._buffer,void 0,this._format,this._forcedExtension,u,p,m,D)}catch(W){throw V("error loading",W),W}c&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=N,this._delayedOnError=V}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1)),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,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._texture?this._delayedOnLoad&&(this._texture.isReady?wB.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,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,O.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.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=ge.Zero(),this._rowGenerationMatrix=new ge,this._t0=O.Zero(),this._t1=O.Zero(),this._t2=O.Zero()),ge.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(ge.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,ue.Matrix[0]),ge.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,ue.Matrix[1]),ge.ScalingToRef(this._cachedUScale,this._cachedVScale,0,ue.Matrix[2]),ge.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,ue.Matrix[3]),ue.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ue.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ue.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ue.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),ge.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===Te.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=ge.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=ge.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 Te.PLANAR_MODE:{ge.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 Te.PROJECTION_MODE:{ge.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:ge.IdentityToRef(this._cachedReflectionTextureMatrix);break}return t&&e.markAllMaterialsAsDirty(1,i=>i.getActiveTextures().indexOf(this)!==-1),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 Kt.Clone(()=>new Te(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;const i=this.name;Te.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const s=super.serialize(Te._SerializeInternalTextureUniqueId);return s?((Te.SerializeBuffers||Te.ForceSerializeBuffers)&&(typeof this._buffer=="string"&&this._buffer.substr(0,5)==="data:"?(s.base64String=this._buffer,s.name=s.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?s.base64String="data:image/png;base64,"+wG(this._buffer):(Te.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(s.base64String=!this._engine||this._engine._features.supportSyncTextureRead?K$(this):Q$(this))),s.invertY=this._invertY,s.samplingMode=this.samplingMode,s._creationFlags=this._creationFlags,s._useSRGBBuffer=this._useSRGBBuffer,Te._SerializeInternalTextureUniqueId&&(s.internalTextureUniqueId=(t=(e=this._texture)===null||e===void 0?void 0:e.uniqueId)!==null&&t!==void 0?t:void 0),this.name=i,s):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 c=mj.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&c.updateSamplingMode&&c._samplingMode&&c._samplingMode!==e.samplingMode&&c.updateSamplingMode(e.samplingMode),c}if(e.isCube&&!e.isRenderTarget)return Te._CubeTextureParser(e,t,i);const s=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const l=t.getEngine().getLoadedTexturesCache();for(const c of l)if(c.uniqueId===e.internalTextureUniqueId){r=c;break}}const n=l=>{var c;if(l&&l._texture&&(l._texture._cachedWrapU=null,l._texture._cachedWrapV=null,l._texture._cachedWrapR=null),e.samplingMode){const h=e.samplingMode;l&&l.samplingMode!==h&&l.updateSamplingMode(h)}if(l&&e.animations)for(let h=0;h{var l,c,h;let u=!0;if(e.noMipmap&&(u=!1),e.mirrorPlane){const p=Te._CreateMirror(e.name,e.renderTargetSize,t,u);return p._waitingRenderList=e.renderList,p.mirrorPlane=Zd.FromArray(e.mirrorPlane),n(p),p}else if(e.isRenderTarget){let p=null;if(e.isCube){if(t.reflectionProbes)for(let m=0;m{n(p)},(c=e._creationFlags)!==null&&c!==void 0?c:0,(h=e._useSRGBBuffer)!==null&&h!==void 0?h:!1),p.name=e.name;else{let m;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?m=e.name:m=i+e.name,e.url&&(e.url.startsWith("data:")||Te.UseSerializedUrlIfAny)&&(m=e.url);const _={noMipmap:!u,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(p)},internalTexture:r};p=new Te(m,t,_)}return p}},e,t)}static CreateFromBase64String(e,t,i,s,r,n=Te.TRILINEAR_SAMPLINGMODE,o=null,l=null,c=5,h){return new Te("data:"+t,i,s,r,n,o,l,e,!1,c,void 0,void 0,h)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,o=Te.TRILINEAR_SAMPLINGMODE,l=null,c=null,h=5,u){return e.substr(0,5)!=="data:"&&(e="data:"+e),new Te(e,i,r,n,o,l,c,t,s,h,void 0,void 0,u)}}Te.SerializeBuffers=!0;Te.ForceSerializeBuffers=!1;Te.OnTextureLoadErrorObservable=new Se;Te._SerializeInternalTextureUniqueId=!1;Te._CubeTextureParser=(a,e,t)=>{throw Ys("CubeTexture")};Te._CreateMirror=(a,e,t,i)=>{throw Ys("MirrorTexture")};Te._CreateRenderTargetTexture=(a,e,t,i,s)=>{throw Ys("RenderTargetTexture")};Te.NEAREST_SAMPLINGMODE=1;Te.NEAREST_NEAREST_MIPLINEAR=8;Te.BILINEAR_SAMPLINGMODE=2;Te.LINEAR_LINEAR_MIPNEAREST=11;Te.TRILINEAR_SAMPLINGMODE=3;Te.LINEAR_LINEAR_MIPLINEAR=3;Te.NEAREST_NEAREST_MIPNEAREST=4;Te.NEAREST_LINEAR_MIPNEAREST=5;Te.NEAREST_LINEAR_MIPLINEAR=6;Te.NEAREST_LINEAR=7;Te.NEAREST_NEAREST=1;Te.LINEAR_NEAREST_MIPNEAREST=9;Te.LINEAR_NEAREST_MIPLINEAR=10;Te.LINEAR_LINEAR=2;Te.LINEAR_NEAREST=12;Te.EXPLICIT_MODE=0;Te.SPHERICAL_MODE=1;Te.PLANAR_MODE=2;Te.CUBIC_MODE=3;Te.PROJECTION_MODE=4;Te.SKYBOX_MODE=5;Te.INVCUBIC_MODE=6;Te.EQUIRECTANGULAR_MODE=7;Te.FIXED_EQUIRECTANGULAR_MODE=8;Te.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;Te.CLAMP_ADDRESSMODE=0;Te.WRAP_ADDRESSMODE=1;Te.MIRROR_ADDRESSMODE=2;Te.UseSerializedUrlIfAny=!1;z([X()],Te.prototype,"url",void 0);z([X()],Te.prototype,"uOffset",void 0);z([X()],Te.prototype,"vOffset",void 0);z([X()],Te.prototype,"uScale",void 0);z([X()],Te.prototype,"vScale",void 0);z([X()],Te.prototype,"uAng",void 0);z([X()],Te.prototype,"vAng",void 0);z([X()],Te.prototype,"wAng",void 0);z([X()],Te.prototype,"uRotationCenter",void 0);z([X()],Te.prototype,"vRotationCenter",void 0);z([X()],Te.prototype,"wRotationCenter",void 0);z([X()],Te.prototype,"homogeneousRotationInUVTransform",void 0);z([X()],Te.prototype,"isBlocking",null);$e("BABYLON.Texture",Te);Kt._TextureParser=Te.Parse;Oi.prototype.updateRawTexture=function(a,e,t,i,s=null,r=0,n=!1){if(!a)return;const o=this._getRGBABufferInternalSizedFormat(r,t,n),l=this._getInternalFormat(t),c=this._getWebGLTextureType(r);this._bindTextureDirectly(this._gl.TEXTURE_2D,a,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.type=r,a.invertY=i,a._compression=s),a.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],a.width,a.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,a.width,a.height,0,l,c,e),a.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),a.isReady=!0};Oi.prototype.createRawTexture=function(a,e,t,i,s,r,n,o=null,l=0,c=0,h=!1){const u=new dn(this,hr.Raw);u.baseWidth=e,u.baseHeight=t,u.width=e,u.height=t,u.format=i,u.generateMipMaps=s,u.samplingMode=n,u.invertY=r,u._compression=o,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(h,!s),this._doNotHandleContextLost||(u._bufferView=a),this.updateRawTexture(u,a,i,r,o,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const p=this._getSamplingParameters(n,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,p.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,p.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u};Oi.prototype.createRawCubeTexture=function(a,e,t,i,s,r,n,o=null){const l=this._gl,c=new dn(this,hr.CubeRaw);c.isCube=!0,c.format=t,c.type=i,this._doNotHandleContextLost||(c._bufferViewArray=a);const h=this._getWebGLTextureType(i);let u=this._getInternalFormat(t);u===l.RGB&&(u=l.RGBA),h===l.FLOAT&&!this._caps.textureFloatLinearFiltering?(s=!1,n=1,Me.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?(s=!1,n=1,Me.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):h===l.FLOAT&&!this._caps.textureFloatRender?(s=!1,Me.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):h===l.HALF_FLOAT&&!this._caps.colorBufferFloat&&(s=!1,Me.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));const p=e,m=p;if(c.width=p,c.height=m,c.invertY=r,c._compression=o,!this.needPOTTextures||Be.IsExponentOfTwo(c.width)&&Be.IsExponentOfTwo(c.height)||(s=!1),a)this.updateRawCubeTexture(c,a,t,i,r,o);else{const d=this._getRGBABufferInternalSizedFormat(i),C=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,c,!0);for(let v=0;v<6;v++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+v,C,this.getCaps().s3tc[o],c.width,c.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+v,C,d,c.width,c.height,0,u,h,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,c,!0),a&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const f=this._getSamplingParameters(n,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,f.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,f.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),c.generateMipMaps=s,c.samplingMode=n,c.isReady=!0,c};Oi.prototype.updateRawCubeTexture=function(a,e,t,i,s,r=null,n=0){a._bufferViewArray=e,a.format=t,a.type=i,a.invertY=s,a._compression=r;const o=this._gl,l=this._getWebGLTextureType(i);let c=this._getInternalFormat(t);const h=this._getRGBABufferInternalSizedFormat(i);let u=!1;c===o.RGB&&(c=o.RGBA,u=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,a,!0),this._unpackFlipY(s===void 0?!0:!!s),a.width%4!==0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let m=0;m<6;m++){let _=e[m];r?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+m,n,this.getCaps().s3tc[r],a.width,a.height,0,_):(u&&(_=Ble(_,a.width,a.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+m,n,h,a.width,a.height,0,c,l,_))}(!this.needPOTTextures||Be.IsExponentOfTwo(a.width)&&Be.IsExponentOfTwo(a.height))&&a.generateMipMaps&&n===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),a.isReady=!0};Oi.prototype.createRawCubeTextureFromUrl=function(a,e,t,i,s,r,n,o,l=null,c=null,h=3,u=!1){const p=this._gl,m=this.createRawCubeTexture(null,t,i,s,!r,u,h,null);e?.addPendingData(m),m.url=a,m.isReady=!1,this._internalTexturesCache.push(m);const _=(d,C)=>{e?.removePendingData(m),c&&d&&c(d.status+" "+d.statusText,C)},f=d=>{const C=m.width,v=n(d);if(!!v){if(o){const y=this._getWebGLTextureType(s);let M=this._getInternalFormat(i);const b=this._getRGBABufferInternalSizedFormat(s);let E=!1;M===p.RGB&&(M=p.RGBA,E=!0),this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,m,!0),this._unpackFlipY(!1);const S=o(v);for(let I=0;I>I;for(let R=0;R<6;R++){let L=S[I][R];E&&(L=Ble(L,D,D,s)),p.texImage2D(R,I,b,D,D,0,M,y,L)}}this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(m,v,i,s,u);m.isReady=!0,e?.removePendingData(m),m.onLoadedObservable.notifyObservers(m),m.onLoadedObservable.clear(),l&&l()}};return this._loadFile(a,d=>{f(d)},void 0,e?.offlineProvider,!0,_),m};function Ble(a,e,t,i){let s,r=1;i===1?s=new Float32Array(e*t*4):i===2?(s=new Uint16Array(e*t*4),r=15360):i===7?s=new Uint32Array(e*t*4):s=new Uint8Array(e*t*4);for(let n=0;no+l.to-l.from+1,0);if(isNaN(i))throw new Error("Invalid animation ranges.");let s=0;const r=(t+1)*4*4*i,n=new Float32Array(r);this._scene.stopAnimation(this._mesh),this._mesh.skeleton.returnToRest();for(const o of e)for(let l=o.from;l<=o.to;l++)await this._executeAnimationFrame(n,l,s++);return n}async _executeAnimationFrame(e,t,i){return new Promise((s,r)=>{this._scene.beginAnimation(this._mesh.skeleton,t,t,!1,1,()=>{const n=this._mesh.skeleton.getTransformMatrices(this._mesh);e.set(n,i*n.length),s()})})}textureFromBakedVertexData(e){if(!this._mesh.skeleton)throw new Error("No skeleton in this mesh.");const t=this._mesh.skeleton.bones.length,i=Ya.CreateRGBATexture(e,(t+1)*4,e.length/((t+1)*4*4),this._scene,!1,!1,Te.NEAREST_NEAREST,1);return i.name="VAT"+this._mesh.skeleton.name,i}serializeBakedVertexDataToObject(e){if(!this._mesh.skeleton)throw new Error("No skeleton in this mesh.");const t=this._mesh.skeleton.bones.length,i=(t+1)*4,s=e.length/((t+1)*4*4);return{vertexData:wG(e),width:i,height:s}}loadBakedVertexDataFromObject(e){return new Float32Array(NG(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}class zle{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===mi.POINTERDOWN){this._isPointerDown=!0;return}i.type===mi.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=Zr.Now;let s=0;this._lastFrameTime!=null&&(s=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();const r=i-this._lastInteractionTime-this._idleRotationWaitTime,n=Math.max(Math.min(r/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*n,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(s/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??Zr.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(!i)return;i.computeWorldMatrix(!0);const s=i.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=s*.05,this.upperRadiusTransitionRange=s*.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||(RL.EasingFunction.setEasingMode(RL.EasingMode),this._radiusBounceTransition=at.CreateAnimation("radius",at.ANIMATIONTYPE_FLOAT,60,RL.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=at.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()}}RL.EasingFunction=new xle(.3);RL.EasingMode=Pc.EASINGMODE_EASEOUT;class u0{constructor(){this.onTargetFramingAnimationEndObservable=new Se,this._mode=u0.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();u0.EasingFunction.setEasingMode(u0.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===mi.POINTERDOWN){this._isPointerDown=!0;return}i.type===mi.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&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 s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new O(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let n=0;n{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),h&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const s=t.subtract(e).length(),r=this._getFrustumSlope(),o=s*.5*this._radiusScale,l=o*Math.sqrt(1+1/(r.x*r.x)),c=o*Math.sqrt(1+1/(r.y*r.y));let h=Math.max(l,c);const u=this._attachedCamera;return u?(u.lowerRadiusLimit&&this._mode===u0.IgnoreBoundsSizeMode&&(h=hu.upperRadiusLimit?u.upperRadiusLimit:h),h):0}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=Zr.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=at.CreateAnimation("beta",at.ANIMATIONTYPE_FLOAT,60,u0.EasingFunction));const s=at.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});s&&this._animatables.push(s)}}_getFrustumSlope(){const e=this._attachedCamera;if(!e)return lt.Zero();const i=e.getScene().getEngine().getAspectRatio(e),s=Math.tan(e.fov/2),r=s*i;return new lt(r,s)}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=Zr.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}}u0.EasingFunction=new ble;u0.EasingMode=Pc.EASINGMODE_EASEINOUT;u0.IgnoreBoundsSizeMode=0;u0.FitFrustumSidesMode=1;class uN{constructor(e,t=new O,i=0,s=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=s}}class B3e{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new uN(O.Up()),new uN(O.Down()),new uN(O.Left()),new uN(O.Right()),new uN(O.Forward()),new uN(O.Forward().scaleInPlace(-1))],this._tmpMatrix=new ge,this._tmpVector=new O,this._zeroVector=O.Zero(),this._lookAtTmpMatrix=new ge}init(){}_closestFace(e){return this._faceVectors.forEach(t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=ke.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),O.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=O.GetAngleBetweenVectors(t.rotatedDirection,e,O.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),O.TransformCoordinatesToRef(O.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach(r=>{i.direction.x&&r.direction.x&&(r.ignore=!0),i.direction.y&&r.direction.y&&(r.ignore=!0),i.direction.z&&r.direction.z&&(r.ignore=!0)});const s=this._closestFace(this._tmpVector);this._faceVectors.forEach(r=>{r.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=ke.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,s.rotatedDirection,this._ui.rotationQuaternion),s.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),s.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),s.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 yK{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||e===void 0?void 0:e.getScene().onBeforeRenderObservable.add(this._update))}_detachObserver(){var e;this._onBeforeRenderObserver&&((e=this._ownerNode)===null||e===void 0||e.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)}}class gr{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new gr(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=gr._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=gr._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n=0,o=Number.MAX_VALUE,l,c,h,u;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xr.x)return!1}else if(l=1/this.direction.x,c=(s.x-this.origin.x)*l,h=(r.x-this.origin.x)*l,h===-1/0&&(h=1/0),c>h&&(u=c,c=h,h=u),n=Math.max(c,n),o=Math.min(h,o),n>o)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.y)return!1}else if(l=1/this.direction.y,c=(s.y-this.origin.y)*l,h=(r.y-this.origin.y)*l,h===-1/0&&(h=1/0),c>h&&(u=c,c=h,h=u),n=Math.max(c,n),o=Math.min(h,o),n>o)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.z)return!1}else if(l=1/this.direction.z,c=(s.z-this.origin.z)*l,h=(r.z-this.origin.z)*l,h===-1/0&&(h=1/0),c>h&&(u=c,c=h,h=u),n=Math.max(c,n),o=Math.min(h,o),n>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,s=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=i*i+s*s+r*r,o=e.radius+t,l=o*o;if(n<=l)return!0;const c=i*this.direction.x+s*this.direction.y+r*this.direction.z;return c<0?!1:n-c*c<=l}intersectsTriangle(e,t,i){const s=gr._TmpVector3[0],r=gr._TmpVector3[1],n=gr._TmpVector3[2],o=gr._TmpVector3[3],l=gr._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),O.CrossToRef(this.direction,r,n);const c=O.Dot(s,n);if(c===0)return null;const h=1/c;this.origin.subtractToRef(e,o);const u=O.Dot(o,n)*h;if(u<0||u>1)return null;O.CrossToRef(o,s,l);const p=O.Dot(this.direction,l)*h;if(p<0||u+p>1)return null;const m=O.Dot(r,l)*h;return m>this.length?null:new hX(1-u-p,u,m)}intersectsPlane(e){let t;const i=O.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{const s=O.Dot(e.normal,this.origin);return t=(-e.d-s)/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 O(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 O(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 O(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t,i,s=!1,r,n=!1){const o=ue.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?gr.TransformToRef(this,o,this._tmpRay):this._tmpRay=gr.Transform(this,o),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=ue.Vector3[0],n=ue.Vector3[1],o=ue.Vector3[2],l=ue.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(gr._Rayl,o),s.addToRef(o,n),e.subtractToRef(s,l);const c=O.Dot(r,r),h=O.Dot(r,o),u=O.Dot(o,o),p=O.Dot(r,l),m=O.Dot(o,l),_=c*u-h*h;let f,d=_,C,v=_;_d&&(f=d,C=m+h,v=u)),C<0?(C=0,-p<0?f=0:-p>c?f=d:(f=-p,d=c)):C>v&&(C=v,-p+h<0?f=0:-p+h>c?f=d:(f=-p+h,d=c));const y=Math.abs(f)0&&M<=this.length&&S.lengthSquared()=a.distance?null:c};oi.prototype._internalPick=function(a,e,t,i,s){let r=null;const n=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),r=this.cameraToUseForPointers||this.activeCamera;for(let n=0;n(this._tempPickingRay||(this._tempPickingRay=gr.Zero()),this.createPickingRayToRef(a,e,n,this._tempPickingRay,s||null),this._tempPickingRay),t,i,!0);return r&&(r.ray=this.createPickingRay(a,e,ge.Identity(),s||null)),r};Object.defineProperty(oi.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1});oi.prototype.pick=function(a,e,t,i,s,r,n=!1){const o=this._internalPick((l,c)=>(this._tempPickingRay||(this._tempPickingRay=gr.Zero()),this.createPickingRayToRef(a,e,l,this._tempPickingRay,s||null,!1,c),this._tempPickingRay),t,i,!1,r);return o&&(o.ray=this.createPickingRay(a,e,ge.Identity(),s||null)),o};oi.prototype.pickWithRay=function(a,e,t,i){const s=this._internalPick(r=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=ge.Identity()),r.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=gr.Zero()),gr.TransformToRef(a,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t,!1,i);return s&&(s.ray=a),s};oi.prototype.multiPick=function(a,e,t,i,s){return this._internalMultiPick(r=>this.createPickingRay(a,e,r,i||null),t,s)};oi.prototype.multiPickWithRay=function(a,e,t){return this._internalMultiPick(i=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=ge.Identity()),i.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=gr.Zero()),gr.TransformToRef(a,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t)};Pi.prototype.getForwardRay=function(a=100,e,t){return this.getForwardRayToRef(new gr(O.Zero(),O.Zero(),a),a,e,t)};Pi.prototype.getForwardRayToRef=function(a,e=100,t,i){return t||(t=this.getWorldMatrix()),a.length=e,i?a.origin.copyFrom(i):a.origin.copyFrom(this.position),ue.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),O.TransformNormalToRef(ue.Vector3[2],t,ue.Vector3[3]),O.NormalizeToRef(ue.Vector3[3],a.direction),a};class yn{static _RemoveAndStorePivotPoint(e){e&&yn._PivotCached===0&&(e.getPivotPointToRef(yn._OldPivotPoint),yn._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,yn._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(ge.IdentityReadOnly),yn._OldPivotPoint.subtractToRef(e.getPivotPoint(),yn._PivotTranslation),yn._PivotTmpVector.copyFromFloats(1,1,1),yn._PivotTmpVector.subtractInPlace(e.scaling),yn._PivotTmpVector.multiplyInPlace(yn._PivotTranslation),e.position.addInPlace(yn._PivotTmpVector))),yn._PivotCached++}static _RestorePivotPoint(e){e&&!yn._OldPivotPoint.equalsToFloats(0,0,0)&&yn._PivotCached===1&&(e.setPivotPoint(yn._OldPivotPoint),e._postMultiplyPivotMatrix=yn._PivotPostMultiplyPivotMatrix,yn._PivotTmpVector.copyFromFloats(1,1,1),yn._PivotTmpVector.subtractInPlace(e.scaling),yn._PivotTmpVector.multiplyInPlace(yn._PivotTranslation),e.position.subtractInPlace(yn._PivotTmpVector)),this._PivotCached--}}yn._PivotCached=0;yn._OldPivotPoint=new O;yn._PivotTranslation=new O;yn._PivotTmpVector=new O;yn._PivotPostMultiplyPivotMatrix=!1;function MK(a){const e=[],t=[],i=[],s=[],r=a.width||a.size||1,n=a.height||a.size||1,o=a.sideOrientation===0?0:a.sideOrientation||Jt.DEFAULTSIDE,l=r/2,c=n/2;t.push(-l,-c,0),i.push(0,0,-1),s.push(0,fn.UseOpenGLOrientationForUV?1:0),t.push(l,-c,0),i.push(0,0,-1),s.push(1,fn.UseOpenGLOrientationForUV?1:0),t.push(l,c,0),i.push(0,0,-1),s.push(1,fn.UseOpenGLOrientationForUV?0:1),t.push(-l,c,0),i.push(0,0,-1),s.push(0,fn.UseOpenGLOrientationForUV?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),Jt._ComputeSides(o,t,e,i,s,a.frontUVs,a.backUVs);const h=new Jt;return h.indices=e,h.positions=t,h.normals=i,h.uvs=s,h}function Jd(a,e={},t=null){const i=new Oe(a,t);return e.sideOrientation=Oe._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,MK(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}const F3e={CreatePlane:Jd};Jt.CreatePlane=MK;Oe.CreatePlane=(a,e,t,i,s)=>Jd(a,{size:e,width:e,height:e,sideOrientation:s,updatable:i},t);class uc{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 Se,this.onDragStartObservable=new Se,this.onDragEndObservable=new Se,this.onEnabledObservable=new Se,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=i=>!0,this._tmpVector=new O(0,0,0),this._alternatePickedPoint=new O(0,0,0),this._worldDragAxis=new O(0,0,0),this._targetPosition=new O(0,0,0),this._attachedToElement=!1,this._startDragRay=new gr(new O,new O),this._lastPointerRay={},this._dragDelta=new O,this._pointA=new O(0,0,0),this._pointC=new O(0,0,0),this._localAxis=new O(0,0,0),this._lookAt=new O(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,uc._PlaneScene||(this._debugMode?uc._PlaneScene=this._scene:(uc._PlaneScene=new oi(this._scene.getEngine(),{virtual:!0}),uc._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{uc._PlaneScene.dispose(),uc._PlaneScene=null}))),this._dragPlane=Jd("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:Oe.DOUBLESIDE},uc._PlaneScene),this.lastDragPosition=new O(0,0,0);const i=t||(s=>this.attachedNode==s||s.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(s=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(s.type==mi.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&s.pickInfo&&s.pickInfo.hit&&s.pickInfo.pickedMesh&&s.pickInfo.pickedPoint&&s.pickInfo.ray&&i(s.pickInfo.pickedMesh)&&this._activeDragButton===-1&&this.dragButtons.indexOf(s.event.button)!==-1&&(this._activeDragButton=s.event.button,this._activePointerInfo=s,this._startDrag(s.event.pointerId,s.pickInfo.ray,s.pickInfo.pickedPoint));else if(s.type==mi.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==s.event.pointerId&&(this._activeDragButton===s.event.button||this._activeDragButton===-1)&&this.releaseDrag();else if(s.type==mi.POINTERMOVE){const r=s.event.pointerId;if(this.currentDraggingPointerId===uc._AnyMouseId&&r!==uc._AnyMouseId){const n=s.event;(n.pointerType==="mouse"||!this._scene.getEngine().hostInformation.isMobile&&n instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[r]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=r)}this._lastPointerRay[r]||(this._lastPointerRay[r]=new gr(new O,new O)),s.pickInfo&&s.pickInfo.ray&&(this._lastPointerRay[r].origin.copyFrom(s.pickInfo.ray.origin),this._lastPointerRay[r].direction.copyFrom(s.pickInfo.ray.direction),this.currentDraggingPointerId==r&&this.dragging&&this._moveDrag(s.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let s=!1;yn._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),s=!0),yn._RestorePivotPoint(this.attachedNode),s&&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=uc._AnyMouseId,t,i){this._startDrag(e,t,i);let s=this._lastPointerRay[e];e===uc._AnyMouseId&&(s=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),s&&this._moveDrag(s)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;yn._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 s=this._pickWithRayOnDragPlane(this._startDragRay);s?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(s),this.onDragStartObservable.notifyObservers({dragPlanePoint:s,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(),yn._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){yn._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?O.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=O.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),yn._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(O.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*O.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const s=O.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-s,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}else return null;const i=uc._PlaneScene.pickWithRay(e,s=>s==this._dragPlane);return i&&i.hit&&i.pickedMesh&&i.pickedPoint?i.pickedPoint:null}_updateDragPlanePosition(e,t){this._pointA.copyFrom(t),this._options.dragAxis?(this.useObjectOrientationForDragging?O.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),e.origin.subtractToRef(this._pointA,this._pointC),this._pointC.normalize(),Math.abs(O.Dot(this._localAxis,this._pointC))>.999?Math.abs(O.Dot(O.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(O.Right()):this._lookAt.copyFrom(O.UpReadOnly):(O.CrossToRef(this._localAxis,this._pointC,this._lookAt),O.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?O.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()}}uc._AnyMouseId=-2;class V3e{constructor(){this._startDistance=0,this._initialScale=new O(0,0,0),this._targetScale=new O(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new uc({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new uc({}),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 Fb{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new O,this._tmpQuaternion=new ke,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 Se,this.onDragObservable=new Se,this.onDragEndObservable=new Se,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 Ir("",Fb._virtualScene);e.rotationQuaternion=new ke;const t=new Ir("",Fb._virtualScene);t.rotationQuaternion=new ke;const i=new Ir("",Fb._virtualScene);return i.rotationQuaternion=new ke,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new O,startingPivotOrientation:new ke,startingPosition:new O,startingOrientation:new ke,lastOriginPosition:new O,lastDragPosition:new O}}_resetVirtualMeshesPosition(){for(let e=0;em&&(m=Math.min(_-u,0)),h.scaleInPlace(m),h.addToRef(r.pivotMesh.absolutePosition,this._tmpVector),r.pivotMesh.setAbsolutePosition(this._tmpVector),h.addToRef(r.dragMesh.absolutePosition,this._tmpVector),r.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),Fb._virtualScene||(Fb._virtualScene=new oi(this._scene.getEngine(),{virtual:!0}),Fb._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 s=i.event.pointerId;this._virtualMeshesInfo[s]||(this._virtualMeshesInfo[s]=this._createVirtualMeshInfo());const r=this._virtualMeshesInfo[s],n=i.event.pointerType==="xr-near";if(i.type==mi.POINTERDOWN){if(!r.dragging&&i.pickInfo&&i.pickInfo.hit&&i.pickInfo.pickedMesh&&i.pickInfo.pickedPoint&&i.pickInfo.ray&&(!n||i.pickInfo.aimTransform)&&t(i.pickInfo.pickedMesh)){if(!this.allowMultiPointer&&this.currentDraggingPointerIds.length>0)return;this._pointerCamera&&this._pointerCamera.cameraRigMode===Pi.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[s];n?(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),n?(o.originMesh.addChild(o.dragMesh),o.originMesh.addChild(o.pivotMesh)):o.originMesh.lookAt(o.dragMesh.position),o.dragging=!0,this.currentDraggingPointerIds.indexOf(s)===-1&&this.currentDraggingPointerIds.push(s),this.detachCameraControls&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.inputs&&this._pointerCamera.inputs.attachedToElement?(this._pointerCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1),this._targetDragStart(o.pivotMesh.position,o.pivotMesh.rotationQuaternion,s),this.onDragStartObservable.notifyObservers({position:o.pivotMesh.position})}}else if(i.type==mi.POINTERUP||i.type==mi.POINTERDOUBLETAP){const o=this.currentDraggingPointerIds.indexOf(s);r.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)),r.originMesh.removeChild(r.dragMesh),r.originMesh.removeChild(r.pivotMesh),this._targetDragEnd(s),this.onDragEndObservable.notifyObservers({}))}else if(i.type==mi.POINTERMOVE&&this.currentDraggingPointerIds.indexOf(s)!==-1&&r.dragging&&i.pickInfo&&(i.pickInfo.ray||i.pickInfo.aimTransform)){let l=this.zDragFactor;(this.currentDraggingPointerIds.length>1||i.pickInfo.originMesh)&&(l=0),this._ownerNode.computeWorldMatrix(!0),n?this._pointerUpdateXR(i.pickInfo.aimTransform,i.pickInfo.gripTransform,s,l):this._pointerUpdate2D(i.pickInfo.ray,s,l),this._tmpQuaternion.copyFrom(r.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,r.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),r.pivotMesh.absolutePosition.subtractToRef(r.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:r.pivotMesh.position,pickInfo:i.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,s),r.lastDragPosition.copyFrom(r.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 Z$ extends Fb{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new O(0,0,0),this._targetOrientation=new ke,this._targetScaling=new O(1,1,1),this._startingPosition=new O(0,0,0),this._startingOrientation=new ke,this._startingScaling=new O(1,1,1),this.onPositionChangedObservable=new Se,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 Ki("virtual_sixDof",Fb._virtualScene),this._virtualTransformNode.rotationQuaternion=ke.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add(()=>{if(this.currentDraggingPointerIds.length===1&&this._moving&&!this.disableMovement){const t=e.parent;e.setParent(null),e.position.addInPlace(this._targetPosition.subtract(e.position).scale(this.dragDeltaRatio)),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),(!t||t.scaling&&!t.scaling.isNonUniformWithinEpsilon(.001))&&ke.SlerpToRef(e.rotationQuaternion,this._targetOrientation,this.dragDeltaRatio,e.rotationQuaternion),e.setParent(t)}})}_getPositionOffsetAround(e,t,i){const s=ue.Matrix[0],r=ue.Matrix[1],n=ue.Matrix[2],o=ue.Matrix[3],l=ue.Matrix[4];return ge.TranslationToRef(e.x,e.y,e.z,s),ge.TranslationToRef(-e.x,-e.y,-e.z,r),ge.FromQuaternionToRef(i,n),ge.ScalingToRef(t,t,t,o),r.multiplyToRef(n,l),l.multiplyToRef(o,l),l.multiplyToRef(s,l),l.getTranslation()}_onePointerPositionUpdated(e,t){ue.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?ke.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,ue.Quaternion[0]):ue.Quaternion[0].copyFrom(t),ue.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=ue.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const s=ue.Vector3[1];t.subtractToRef(e,s);const r=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,n=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,o=ue.Vector3[2];r.addToRef(n,o),o.scaleInPlace(.5);const l=ue.Vector3[3];n.subtractToRef(r,l);const c=l.length()/s.length(),h=o.subtract(i),u=ke.FromEulerAngles(0,O.GetAngleBetweenVectorsOnPlane(s.normalize(),l.normalize(),O.UpReadOnly),0),p=this._ownerNode.parent;this._ownerNode.setParent(null);const m=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),c,u);this._virtualTransformNode.rotationQuaternion.multiplyToRef(u,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(c,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(h.addInPlace(m),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(p)}_targetDragStart(){const e=this.currentDraggingPointerIds.length,t=this._ownerNode.parent;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=ke.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));const i=this._ownerNode.getAbsolutePivotPoint();if(this._ownerNode.setParent(null),e===1){if(this._targetPosition.copyFrom(this._ownerNode.position),this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.scaling),this.faceCameraOnDragStart&&this._scene.activeCamera){const s=ue.Vector3[0];this._scene.activeCamera.position.subtractToRef(i,s),s.normalize();const r=ue.Quaternion[0];this._scene.useRightHandedSystem?ke.FromLookDirectionRHToRef(s,new O(0,1,0),r):ke.FromLookDirectionLHToRef(s,new O(0,1,0),r),r.normalize(),ke.RotationYawPitchRollToRef(r.toEulerAngles().y,0,0,ue.Quaternion[0]),this._targetOrientation.copyFrom(ue.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else e===2&&(this._virtualTransformNode.setPivotPoint(new O(0,0,0),sr.LOCAL),this._virtualTransformNode.position.copyFrom(this._ownerNode.position),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.scaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.rotationQuaternion),this._virtualTransformNode.setPivotPoint(i,sr.WORLD),this._resetVirtualMeshesPosition());this._ownerNode.setParent(t)}_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 Ule{constructor(){this._attachPointLocalOffset=new O,this._workingPosition=new O,this._workingQuaternion=new ke,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=ke.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 s=ue.Vector3[0];return s.copyFrom(t),s.scaleInPlace(this.hitNormalOffset),s.addInPlace(i),this._attachedMesh.parent&&(ue.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),O.TransformNormalToRef(s,ue.Matrix[0],s)),{position:s,quaternion:ke.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&&O.Distance(this._attachedMesh.position,i.position){this.enabled&&e.type==mi.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 kle{constructor(){this._tmpQuaternion=new ke,this._tmpVectors=[new O,new O,new O,new O,new O,new O,new O],this._tmpMatrix=new ge,this._tmpInvertView=new ge,this._tmpForward=new O,this._tmpNodeForward=new O,this._tmpPosition=new O,this._workingPosition=new O,this._workingQuaternion=new ke,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(O.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,s=this.maximumDistance;const r=this.defaultDistance,n=this._tmpVectors[0];n.copyFrom(e);let o=n.length();if(n.normalizeFromLength(o),this.ignoreCameraPitchAndRoll){i=this._length2D(n)*i,s=this._length2D(n)*s;const c=this._length2D(e);n.scaleInPlace(o/c),o=c}let l=o;return t?l=r:l=Bt.Clamp(o,i,s),e.copyFrom(n).scaleInPlace(l),o!==l}_applyVerticalClamp(e){this.verticalMaxDistance!==0&&(e.y=Bt.Clamp(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){ke.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),O.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),O.TransformNormalToRef(i,e,i),ke.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 s=this._tmpVectors[6];s.copyFromFloats(1,0,0),O.TransformNormalToRef(i,e,i),O.TransformNormalToRef(s,e,s);const r=O.UpReadOnly;if(t.length()p&&(ke.RotationAxisToRef(s,-u+p,l),t.rotateByQuaternionToRef(l,t),o=!0)}const c=this._angleBetweenVectorAndPlane(t,s)*(this._scene.useRightHandedSystem?-1:1),h=this.maxViewHorizontalDegrees*Math.PI/180*.5;return c<-h?(ke.RotationAxisToRef(r,-c-h,l),t.rotateByQuaternionToRef(l,t),o=!0):c>h&&(ke.RotationAxisToRef(r,-c+h,l),t.rotateByQuaternionToRef(l,t),o=!0),o}_orientationClamp(e,t){var i;const s=this._tmpVectors[0];s.copyFrom(e).scaleInPlace(-1).normalize();const r=this._tmpVectors[1],n=this._tmpVectors[2];r.copyFromFloats(0,1,0),O.CrossToRef(s,r,n);const o=n.length();othis.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),s=this._workingPosition,r=this._workingQuaternion,n=this.attachedNode.getPivotPoint(),o=this._tmpInvertView;o.copyFrom(e.getViewMatrix()),o.invert(),O.TransformCoordinatesToRef(n,i,s);const l=this._tmpPosition;l.copyFromFloats(0,0,0),O.TransformCoordinatesToRef(l,i,l),l.scaleInPlace(-1).subtractInPlace(n),s.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(o);let c=!1;const h=this._tmpForward;h.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),O.TransformNormalToRef(h,o,h);const u=this._tmpNodeForward;if(u.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),O.TransformNormalToRef(u,i,u),this._recenterNextUpdate)s.copyFrom(h).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const m=s.length();s.copyFrom(h).scaleInPlace(m)}else c=this._angularClamp(o,s);let p=!1;this.ignoreDistanceClamp||(p=this._distanceClamp(s,c),this._applyVerticalClamp(s)),this.useFixedVerticalOffset&&(s.y=l.y-e.globalPosition.y+this.fixedVerticalOffset),(c||p||this._passedOrientationDeadzone(s,u)||this._recenterNextUpdate)&&this._orientationClamp(s,r),this._workingPosition.subtractInPlace(n),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}}_updateTransformToGoal(e){if(!this.attachedNode||!this.followedCamera||!this._enabled)return;this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=ke.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 O;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),O.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const s=new ke;s.copyFrom(this.attachedNode.rotationQuaternion),ke.SmoothToRef(s,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 $r{}$r.ANCHOR_SYSTEM="xr-anchor-system";$r.BACKGROUND_REMOVER="xr-background-remover";$r.HIT_TEST="xr-hit-test";$r.MESH_DETECTION="xr-mesh-detection";$r.PHYSICS_CONTROLLERS="xr-physics-controller";$r.PLANE_DETECTION="xr-plane-detection";$r.POINTER_SELECTION="xr-controller-pointer-selection";$r.TELEPORTATION="xr-controller-teleportation";$r.FEATURE_POINTS="xr-feature-points";$r.HAND_TRACKING="xr-hand-tracking";$r.IMAGE_TRACKING="xr-image-tracking";$r.NEAR_INTERACTION="xr-near-interaction";$r.DOM_OVERLAY="xr-dom-overlay";$r.MOVEMENT="xr-controller-movement";$r.LIGHT_ESTIMATION="xr-light-estimation";$r.EYE_TRACKING="xr-eye-tracking";$r.WALKING_LOCOMOTION="xr-walking-locomotion";$r.LAYERS="xr-layers";$r.DEPTH_SENSING="xr-depth-sensing";$r.SPACE_WARP="xr-space-warp";class _l{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,s=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),s&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,s){const r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,s)}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()}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.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={},s=!0,r=!0){const n=typeof e=="string"?e:e.Name;let o=0;if(typeof t=="string"){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(t==="stable"?o=_l.GetStableVersionOfFeature(n):t==="latest"?o=_l.GetLatestVersionOfFeature(n):o=+t,o===-1||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const l=_l._ConflictingFeatures[n];if(l!==void 0&&this.getEnabledFeatures().indexOf(l)!==-1)throw new Error(`Feature ${n} cannot be enabled while ${l} is enabled.`);const c=this._features[n],h=_l.ConstructFeature(n,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${n}`);c&&this.disableFeature(n);const u=h();if(u.dependsOn&&!u.dependsOn.every(m=>!!this._features[m]))throw new Error(`Dependant features missing. Make sure the following features are enabled - ${u.dependsOn.join(", ")}`);if(u.isCompatible())return this._features[n]={featureImplementation:u,enabled:!0,version:o,required:r},s?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(r)throw new Error("required feature not compatible");return Be.Warn(`Feature ${n} 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 s=this._features[i],r=s.featureImplementation.xrNativeFeatureName;if(r&&(s.required?(e.requiredFeatures=e.requiredFeatures||[],e.requiredFeatures.indexOf(r)===-1&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.indexOf(r)===-1&&e.optionalFeatures.push(r))),s.featureImplementation.getXRSessionInitExtension){const n=await s.featureImplementation.getXRSessionInitExtension();e=Object.assign(Object.assign({},e),n)}}return e}}_l._AvailableFeatures={};_l._ConflictingFeatures={[$r.TELEPORTATION]:$r.MOVEMENT,[$r.MOVEMENT]:$r.TELEPORTATION};class ku{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName=""}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,t=>this._onXRFrame(t)),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach(e=>{e.observable.remove(e.observer)}),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0}isCompatible(){return!0}_addNewAttachObserver(e,t){this._removeOnDetach.push({observable:e,observer:e.add(t)})}}class $n{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)}}$n.DistanceJoint=0;$n.HingeJoint=1;$n.BallAndSocketJoint=2;$n.WheelJoint=3;$n.SliderJoint=4;$n.PrismaticJoint=5;$n.UniversalJoint=6;$n.Hinge2Joint=$n.WheelJoint;$n.PointToPointJoint=8;$n.SpringJoint=9;$n.LockJoint=10;class z3e extends $n{constructor(e){super($n.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class q$ extends $n{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 U3e extends q${constructor(e){super($n.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class k3e extends q${constructor(e){super($n.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)}}Oe._PhysicsImpostorParser=function(a,e,t){return new ys(e,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},a)};class ys{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},s){if(this.object=e,this.type=t,this._options=i,this._scene=s,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=O.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new ke,this._tmpQuat2=new ke,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 ke),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach(r=>{r(this)}))},this.afterStep=()=>{!this._physicsEngine||(this._onAfterPhysicsStepCallbacks.forEach(r=>{r(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,ys._TmpVecs[0]),this.object.translate(ys._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=r=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent||!this._physicsEngine)return;const n=this._physicsEngine.getImpostorWithPhysicsBody(r.body);n&&(this.onCollideEvent&&this.onCollideEvent(this,n),this._onPhysicsCollideCallbacks.filter(o=>o.otherImpostors.indexOf(n)!==-1).forEach(o=>{o.callback(this,n,r.point,r.distance,r.impulse,r.normal)}))},!this.object){Me.Error("No object was provided. A physics object is obligatory");return}this.object.parent&&i.mass!==0&&Me.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=ke.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new ke),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&&Me.Warn("You must affect impostors to children before affecting impostor to parent.")):Me.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 Ir?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=ys.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const r=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return r.x=Math.abs(r.x),r.y=Math.abs(r.y),r.z=Math.abs(r.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),r}else return ys.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):O.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):O.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):Me.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):Me.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 s=-1;this._onPhysicsCollideCallbacks.some((n,o)=>{if(n.callback===t&&n.otherImpostors.length===i.length){const l=n.otherImpostors.every(c=>i.indexOf(c)>-1);return l&&(s=o),l}return!1})?this._onPhysicsCollideCallbacks.splice(s,1):Me.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):ke.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 s=new $n(t,i);return this.addJoint(e,s),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,s,r){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,s,r),this):this}addHook(e,t,i,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,s),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 ys(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 ke),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,s,r){const n=ys._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(r){const l=ys._TmpQuat;o.rotationQuaternion.multiplyToRef(r,l),e.setRotationQuaternion(l,sr.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,sr.WORLD,t);n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),s==null&&(s=i.length()),n.x*=s,n.y*=s,n.z*=s),e.getParent()?(n.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const o=this.object;if(o.rotationQuaternion)if(r){const h=ys._TmpQuat;e.getRotationQuaternionToRef(sr.WORLD,t,h),h.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(sr.WORLD,t,o.rotationQuaternion);const l=ys._TmpVecs[0],c=ys._TmpVecs[1];n||(n=ys._TmpVecs[2],n.x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,c),e.getAbsolutePositionToRef(t,l),s==null&&i&&(s=i.length()),s!=null&&(l.x+=c.x*s,l.y+=c.y*s,l.z+=c.z*s),o.setAbsolutePosition(l)}}ys.DEFAULT_OBJECT_SIZE=new O(1,1,1);ys.IDENTITY_QUATERNION=ke.Identity();ys._TmpVecs=ah.BuildArray(3,O.Zero);ys._TmpQuat=ke.Identity();ys.NoImpostor=0;ys.SphereImpostor=1;ys.BoxImpostor=2;ys.PlaneImpostor=3;ys.MeshImpostor=4;ys.CapsuleImpostor=6;ys.CylinderImpostor=7;ys.ParticleImpostor=8;ys.HeightmapImpostor=9;ys.ConvexHullImpostor=10;ys.CustomImpostor=100;ys.RopeImpostor=101;ys.ClothImpostor=102;ys.SoftbodyImpostor=103;var TM;(function(a){a[a.Clean=0]="Clean",a[a.Stop=1]="Stop",a[a.Sync=2]="Sync",a[a.NoSync=3]="NoSync"})(TM||(TM={}));class As{static get ForceFullSceneLoadingForIncremental(){return Lh.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Lh.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Lh.ShowLoadingScreen}static set ShowLoadingScreen(e){Lh.ShowLoadingScreen=e}static get loggingLevel(){return Lh.loggingLevel}static set loggingLevel(e){Lh.loggingLevel=e}static get CleanBoneMatrixWeights(){return Lh.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Lh.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return As._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=As._RegisteredPlugins[e];return t||(Me.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"),As.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in As._RegisteredPlugins){const i=As._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return As._RegisteredPlugins[t]}return As.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");t!==-1&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return As._GetPluginForExtension(s)}static _GetDirectLoad(e){return e.substr(0,5)==="data:"?e.substr(5):null}static _FormatErrorMessage(e,t,i){let r="Unable to load from "+(e.rawData?"binary data":e.url);return t?r+=`: ${t}`:i&&(r+=`: ${i}`),r}static _LoadData(e,t,i,s,r,n,o,l){const c=As._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=o?As._GetPluginForExtension(o):c?As._GetPluginForDirectLoad(e.url):As._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(As.OnPluginActivatedObservable.notifyObservers(u),c&&(u.canDirectLoad&&u.canDirectLoad(e.url)||!BG(e.url))){if(u.directLoad){const M=u.directLoad(t,c);M.then?M.then(b=>{i(u,b)}).catch(b=>{r("Error in directLoad of _loadData: "+b,b)}):i(u,M)}else i(u,c);return u}const p=h.isBinary,m=(M,b)=>{if(t.isDisposed){r("Scene has been disposed");return}i(u,M,b)};let _=null,f=!1;const d=u.onDisposeObservable;d&&d.add(()=>{f=!0,_&&(_.abort(),_=null),n()});const C=()=>{if(f)return;const M=(b,E)=>{r(b?.statusText,E)};if(!u.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";_=u.loadFile?u.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,m,s,p,M,l):t._loadFile(e.file||e.url,m,s,!0,p,M)},v=t.getEngine();let y=v.enableOfflineSupport;if(y){let M=!1;for(const b of t.disableOfflineSupportExceptionRules)if(b.test(e.url)){M=!0;break}y=!M}return y&&He.OfflineProviderFactory?t.offlineProvider=He.OfflineProviderFactory(e.url,C,v.disableManifestCheck):C(),u}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(!t)i=e,s=Be.GetFilename(e),e=Be.GetFolderPath(e);else if(t.name){const o=t;i=`file:${o.name}`,s=o.name,r=o}else if(ArrayBuffer.isView(t))i="",s="arrayBuffer",n=t;else if(typeof t=="string"&&t.startsWith("data:"))i=t,s="";else{const o=t;if(o.substr(0,1)==="/")return Be.Error("Wrong sceneFilename parameter"),null;i=e+o,s=o}return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return As._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!As._RegisteredPlugins[e]}static RegisterPlugin(e){if(typeof e.extensions=="string"){const t=e.extensions;As._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach(i=>{As._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",s=Ii.LastCreatedScene,r=null,n=null,o=null,l=null,c=""){if(!s)return Me.Error("No scene available to import mesh to"),null;const h=As._GetFileInfo(t,i);if(!h)return null;const u={};s.addPendingData(u);const p=()=>{s.removePendingData(u)},m=(d,C)=>{const v=As._FormatErrorMessage(h,d,C);o?o(s,v,new nC(v,XM.SceneLoaderError,C)):Me.Error(v),p()},_=n?d=>{try{n(d)}catch(C){m("Error in onProgress callback: "+C,C)}}:void 0,f=(d,C,v,y,M,b,E)=>{if(s.importedMeshesFiles.push(h.url),r)try{r(d,C,v,y,M,b,E)}catch(S){m("Error in onSuccess callback: "+S,S)}s.removePendingData(u)};return As._LoadData(h,s,(d,C,v)=>{if(d.rewriteRootURL&&(h.rootUrl=d.rewriteRootURL(h.rootUrl,v)),d.importMesh){const y=d,M=new Array,b=new Array,E=new Array;if(!y.importMesh(e,s,C,h.rootUrl,M,b,E,m))return;s.loadingPluginName=d.name,f(M,b,E,[],[],[],[])}else d.importMeshAsync(e,s,C,h.rootUrl,_,h.name).then(M=>{s.loadingPluginName=d.name,f(M.meshes,M.particleSystems,M.skeletons,M.animationGroups,M.transformNodes,M.geometries,M.lights)}).catch(M=>{m(M.message,M)})},_,m,p,l,c)}static ImportMeshAsync(e,t,i="",s=Ii.LastCreatedScene,r=null,n=null,o=""){return new Promise((l,c)=>{As.ImportMesh(e,t,i,s,(h,u,p,m,_,f,d)=>{l({meshes:h,particleSystems:u,skeletons:p,animationGroups:m,transformNodes:_,geometries:f,lights:d})},r,(h,u,p)=>{c(p||new Error(u))},n,o)})}static Load(e,t="",i=Ii.LastCreatedEngine,s=null,r=null,n=null,o=null,l=""){return i?As.Append(e,t,new oi(i),s,r,n,o,l):(Be.Error("No engine available"),null)}static LoadAsync(e,t="",i=Ii.LastCreatedEngine,s=null,r=null,n=""){return new Promise((o,l)=>{As.Load(e,t,i,c=>{o(c)},s,(c,h,u)=>{l(u||new Error(h))},r,n)})}static Append(e,t="",i=Ii.LastCreatedScene,s=null,r=null,n=null,o=null,l=""){if(!i)return Me.Error("No scene available to append to"),null;const c=As._GetFileInfo(e,t);if(!c)return null;const h={};i.addPendingData(h);const u=()=>{i.removePendingData(h)};As.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));const p=(f,d)=>{const C=As._FormatErrorMessage(c,f,d);n?n(i,C,new nC(C,XM.SceneLoaderError,d)):Me.Error(C),u()},m=r?f=>{try{r(f)}catch(d){p("Error in onProgress callback",d)}}:void 0,_=()=>{if(s)try{s(i)}catch(f){p("Error in onSuccess callback",f)}i.removePendingData(h)};return As._LoadData(c,i,(f,d)=>{if(f.load){if(!f.load(i,d,c.rootUrl,p))return;i.loadingPluginName=f.name,_()}else f.loadAsync(i,d,c.rootUrl,m,c.name).then(()=>{i.loadingPluginName=f.name,_()}).catch(v=>{p(v.message,v)})},m,p,u,o,l)}static AppendAsync(e,t="",i=Ii.LastCreatedScene,s=null,r=null,n=""){return new Promise((o,l)=>{As.Append(e,t,i,c=>{o(c)},s,(c,h,u)=>{l(u||new Error(h))},r,n)})}static LoadAssetContainer(e,t="",i=Ii.LastCreatedScene,s=null,r=null,n=null,o=null,l=""){if(!i)return Me.Error("No scene available to load asset container to"),null;const c=As._GetFileInfo(e,t);if(!c)return null;const h={};i.addPendingData(h);const u=()=>{i.removePendingData(h)},p=(f,d)=>{const C=As._FormatErrorMessage(c,f,d);n?n(i,C,new nC(C,XM.SceneLoaderError,d)):Me.Error(C),u()},m=r?f=>{try{r(f)}catch(d){p("Error in onProgress callback",d)}}:void 0,_=f=>{if(s)try{s(f)}catch(d){p("Error in onSuccess callback",d)}i.removePendingData(h)};return As._LoadData(c,i,(f,d)=>{if(f.loadAssetContainer){const v=f.loadAssetContainer(i,d,c.rootUrl,p);if(!v)return;v.populateRootNodes(),i.loadingPluginName=f.name,_(v)}else f.loadAssetContainerAsync?f.loadAssetContainerAsync(i,d,c.rootUrl,m,c.name).then(v=>{v.populateRootNodes(),i.loadingPluginName=f.name,_(v)}).catch(v=>{p(v.message,v)}):p("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},m,p,u,o,l)}static LoadAssetContainerAsync(e,t="",i=Ii.LastCreatedScene,s=null,r=null){return new Promise((n,o)=>{As.LoadAssetContainer(e,t,i,l=>{n(l)},s,(l,c,h)=>{o(h||new Error(c))},r)})}static ImportAnimations(e,t="",i=Ii.LastCreatedScene,s=!0,r=TM.Clean,n=null,o=null,l=null,c=null,h=null){if(!i){Me.Error("No scene available to load animations to");return}if(s){for(const _ of i.animatables)_.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(_=>{_.dispose()}),i.getNodes().forEach(_=>{_.animations&&(_.animations=[])})}else switch(r){case TM.Clean:i.animationGroups.slice().forEach(m=>{m.dispose()});break;case TM.Stop:i.animationGroups.forEach(m=>{m.stop()});break;case TM.Sync:i.animationGroups.forEach(m=>{m.reset(),m.restart()});break;case TM.NoSync:break;default:Me.Error("Unknown animation group loading mode value '"+r+"'");return}const u=i.animatables.length,p=m=>{m.mergeAnimationsTo(i,i.animatables.slice(u),n),m.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)};this.LoadAssetContainer(e,t,i,p,l,c,h)}static ImportAnimationsAsync(e,t="",i=Ii.LastCreatedScene,s=!0,r=TM.Clean,n=null,o=null,l=null,c=null,h=null){return new Promise((u,p)=>{As.ImportAnimations(e,t,i,s,r,n,m=>{u(m)},l,(m,_,f)=>{p(f||new Error(_))},h)})}}As.NO_LOGGING=0;As.MINIMAL_LOGGING=1;As.SUMMARY_LOGGING=2;As.DETAILED_LOGGING=3;As.OnPluginActivatedObservable=new Se;As._RegisteredPlugins={};As._ShowingLoadingScreen=!1;class Bl extends Lt{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new ge,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){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}var he;(function(a){a[a.Float=1]="Float",a[a.Int=2]="Int",a[a.Vector2=4]="Vector2",a[a.Vector3=8]="Vector3",a[a.Vector4=16]="Vector4",a[a.Color3=32]="Color3",a[a.Color4=64]="Color4",a[a.Matrix=128]="Matrix",a[a.Object=256]="Object",a[a.AutoDetect=1024]="AutoDetect",a[a.BasedOnInput=2048]="BasedOnInput",a[a.All=4095]="All"})(he||(he={}));var Pe;(function(a){a[a.Vertex=1]="Vertex",a[a.Fragment=2]="Fragment",a[a.Neutral=4]="Neutral",a[a.VertexAndFragment=3]="VertexAndFragment"})(Pe||(Pe={}));class Dse{constructor(){this.supportUniformBuffers=!1,this.attributes=new Array,this.uniforms=new Array,this.constants=new Array,this.samplers=new Array,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===Pe.Fragment;this.compilationString=` +${t?`//Entry point +`:""}void main(void) { +${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` +${t?`//Constants +`:""}${this._constantDeclaration} +${this.compilationString}`);let s="";for(const r in this.functions)s+=this.functions[r]+` +`;this.compilationString=` +${s} +${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 r in this.extensions){const n=this.extensions[r];this.compilationString=` +${n} +${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 he.Float:return"float";case he.Int:return"int";case he.Vector2:return"vec2";case he.Color3:case he.Vector3:return"vec3";case he.Color4:case he.Vector4:return"vec4";case he.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 s=Ws.IncludesShadersStore[e]+` +`;if(this.sharedData.emitComments&&(s=t+` +`+s),!i)return s;if(i.replaceStrings)for(let r=0;r${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`:this.functions[r]=`#include<${e}>${i?.substitutionVars?"("+i?.substitutionVars+")":""} +`,this.sharedData.emitComments&&(this.functions[r]=t+` +`+this.functions[r]);return}if(this.functions[r]=Ws.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[r]=t+` +`+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/\s*?attribute .+?;/g,` +`)),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/\s*?uniform .*?;/g,` +`)),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/\s*?(varying|in) .+?;/g,` +`)),i.replaceStrings)for(let n=0;ne.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===Pe.Vertex||(e.ownerBlock.target===Pe.Neutral||e.ownerBlock.target===Pe.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===Pe.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===Pe.Vertex||e.target===Pe.Vertex||(e.ownerBlock.target===Pe.Neutral||e.ownerBlock.target===Pe.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===Pe.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===Pe.Fragment||(e.ownerBlock.target===Pe.Neutral||e.ownerBlock.target===Pe.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=he.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=new Array,this.excludedConnectionPointTypes=new Array,this.onConnectionObservable=new Se,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=Pe.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===c_.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===Pe.Fragment){if(i.target===Pe.Vertex)return c_.TargetIncompatible;for(const n of i.outputs)if(n.ownerBlock.target!=Pe.Neutral&&n.isConnectedInVertexShader)return c_.TargetIncompatible}if(this.type!==e.type&&e.innerType!==he.AutoDetect)return jP.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1||e._acceptedConnectionPointType&&jP.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?c_.Compatible:c_.TypeIncompatible;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return c_.TypeIncompatible;let s=i,r=t;return this.direction===xo.Input&&(s=t,r=i),s.isAnAncestorOf(r)?c_.HierarchyIssue:c_.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 os{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)===0&&(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=Pe.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===Pe.Neutral,this._isFinalMerger=i,this._isInput=this.getClassName()==="InputBlock",this._isTeleportOut=this.getClassName()==="NodeMaterialTeleportOutBlock",this._isTeleportIn=this.getClassName()==="NodeMaterialTeleportInBlock",this._name=e,this.uniqueId=VG.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===Pe.Neutral}initialize(e){}bind(e,t,i,s){}_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,s,r){return r=r??new jP(e,this,xo.Input),r.type=t,r.isOptional=i,s&&(r.target=s),this._inputs.push(r),this}registerOutput(e,t,i,s){return s=s??new jP(e,this,xo.Output),s.type=t,i&&(s.target=i),this._outputs.push(s),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===he.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===Pe.Neutral||(e.target&t.target)!==0)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),s=!0;for(;s;){const r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),s=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,s){}provideFallbacks(e,t){}initializeDefines(e,t,i,s=!1){}prepareDefines(e,t,i,s=!1,r){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,s){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput)||this.target===Pe.Vertex?!1:!!((this.target===Pe.VertexAndFragment||this.target===Pe.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,s=!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,s){e.build(t,s);const r=t._vertexState!=null,n=e._buildTarget===Pe.Vertex&&e.target!==Pe.VertexAndFragment;if(r&&((e.target&e._buildTarget)===0||(e.target&i.target)===0||this.target!==Pe.VertexAndFragment&&n)&&(!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!==Pe.Neutral&&((i.target&this.target)===0||(i.target&e.target)===0))continue;const s=i.connectedPoint.ownerBlock;s&&s!==this&&this._processBuild(s,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log(`${e.target===Pe.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case Pe.Vertex:e.sharedData.checks.emitVertex=!0;break;case Pe.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)!==0)for(const s of i.endpoints){const r=s.ownerBlock;r&&(r.target&e.target)!==0&&t.indexOf(r)!==-1&&this._processBuild(r,e,s,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 r=0;do r++,this._codeVariableName=i+r;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let s=` +// ${this.getClassName()} +`;this.comments&&(s+=`// ${this.comments} +`),s+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); +`,s+=this._dumpPropertiesCode();for(const r of this.inputs){if(!r.isConnected)continue;const o=r.connectedPoint.ownerBlock;t.indexOf(o)===-1&&(s+=o._dumpCode(e,t))}for(const r of this.outputs)if(!!r.hasEndpoints)for(const n of r.endpoints){const o=n.ownerBlock;o&&t.indexOf(o)===-1&&(s+=o._dumpCode(e,t))}return s}_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 s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); +`}return t}clone(e,t=""){const i=this.serialize(),s=Bo(i.customType);if(s){const r=new s;return r._deserialize(i,e,t),r}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){var s;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=(s=e.target)!==null&&s!==void 0?s:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((s,r)=>{s.displayName&&(this.inputs[r].displayName=s.displayName),s.isExposedOnFrame&&(this.inputs[r].isExposedOnFrame=s.isExposedOnFrame,this.inputs[r].exposedPortPosition=s.exposedPortPosition)}),i&&i.forEach((s,r)=>{s.displayName&&(this.outputs[r].displayName=s.displayName),s.isExposedOnFrame&&(this.outputs[r].isExposedOnFrame=s.isExposedOnFrame,this.outputs[r].exposedPortPosition=s.exposedPortPosition)})}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class uX extends os{constructor(e){super(e,Pe.Neutral),this.complementW=1,this.complementZ=0,this.target=Pe.Vertex,this.registerInput("vector",he.AutoDetect),this.registerInput("transform",he.Matrix),this.registerOutput("output",he.Vector4),this.registerOutput("xyz",he.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 s=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",s),e.sharedData.blocksWithDefines.push(this);const r=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${r} = mat3(${i.associatedVariableName}); +`,e.compilationString+=`#ifdef NONUNIFORMSCALING +`,e.compilationString+=`${r} = transposeMat3(inverseMat3(${r})); +`,e.compilationString+=`#endif +`,t.connectedPoint.type){case he.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); +`;break;case he.Vector3:case he.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); +`;break}}else{const s=i.associatedVariableName;switch(t.connectedPoint.type){case he.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); +`;break;case he.Vector3:case he.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * ${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}}$e("BABYLON.TransformBlock",uX);class vj extends os{constructor(e){super(e,Pe.Vertex,!0),this.registerInput("vector",he.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e){for(const t of e)if(t.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._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}}$e("BABYLON.VertexOutputBlock",vj);var Ms;(function(a){a[a.Boolean=0]="Boolean",a[a.Float=1]="Float",a[a.Int=2]="Int",a[a.Vector2=3]="Vector2",a[a.List=4]="List"})(Ms||(Ms={}));function ws(a,e=Ms.Boolean,t="PROPERTIES",i){return(s,r)=>{let n=s._propStore;n||(n=[],s._propStore=n),n.push({propertyName:r,displayName:a,type:e,groupName:t,options:i??{}})}}class tI extends os{constructor(e){super(e,Pe.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",he.Color4,!0),this.registerInput("rgb",he.AutoDetect,!0),this.registerInput("a",he.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(he.Color3|he.Vector3|he.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&&i&&ze.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,s=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||s.isConnected,e.sharedData.blocksWithDefines.push(this),this.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 r=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",r),t.connectedPoint)s.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${s.associatedVariableName}); +`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName}; +`;else if(i.connectedPoint){let n="1.0";s.connectedPoint&&(n=s.associatedVariableName),i.connectedPoint.type===he.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${n}); +`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${n}); +`}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.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){var s;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=(s=e.useLogarithmicDepth)!==null&&s!==void 0?s:!1}}z([ws("Convert to gamma space",Ms.Boolean,"PROPERTIES",{notifiers:{update:!0}})],tI.prototype,"convertToGammaSpace",void 0);z([ws("Convert to linear space",Ms.Boolean,"PROPERTIES",{notifiers:{update:!0}})],tI.prototype,"convertToLinearSpace",void 0);z([ws("Use logarithmic depth",Ms.Boolean,"PROPERTIES")],tI.prototype,"useLogarithmicDepth",void 0);$e("BABYLON.FragmentOutputBlock",tI);var Gd;(function(a){a[a.Uniform=0]="Uniform",a[a.Attribute=1]="Attribute",a[a.Varying=2]="Varying",a[a.Undefined=3]="Undefined"})(Gd||(Gd={}));var Rr;(function(a){a[a.World=1]="World",a[a.View=2]="View",a[a.Projection=3]="Projection",a[a.ViewProjection=4]="ViewProjection",a[a.WorldView=5]="WorldView",a[a.WorldViewProjection=6]="WorldViewProjection",a[a.CameraPosition=7]="CameraPosition",a[a.FogColor=8]="FogColor",a[a.DeltaTime=9]="DeltaTime",a[a.CameraParameters=10]="CameraParameters",a[a.MaterialAlpha=11]="MaterialAlpha"})(Rr||(Rr={}));class J${constructor(e=O.Zero(),t=O.Up()){this.position=e,this.normal=t}clone(){return new J$(this.position.clone(),this.normal.clone())}}class $${constructor(e=O.Zero(),t=O.Up(),i=lt.Zero()){this.position=e,this.normal=t,this.uv=i}clone(){return new $$(this.position.clone(),this.normal.clone(),this.uv.clone())}}var Z9;(function(a){a[a.None=0]="None",a[a.Time=1]="Time",a[a.RealTime=2]="RealTime"})(Z9||(Z9={}));const j3e={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},vZ={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},Ose={particle_texturemask:!0};class Er extends os{get type(){if(this._type===he.AutoDetect){if(this.isUniform&&this.value!=null){if(!isNaN(this.value))return this._type=he.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=he.Vector2,this._type;case"Vector3":return this._type=he.Vector3,this._type;case"Vector4":return this._type=he.Vector4,this._type;case"Color3":return this._type=he.Color3,this._type;case"Color4":return this._type=he.Color4,this._type;case"Matrix":return this._type=he.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=he.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=he.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=he.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=he.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Rr.World:case Rr.WorldView:case Rr.WorldViewProjection:case Rr.View:case Rr.ViewProjection:case Rr.Projection:return this._type=he.Matrix,this._type;case Rr.CameraPosition:return this._type=he.Vector3,this._type;case Rr.FogColor:return this._type=he.Color3,this._type;case Rr.DeltaTime:case Rr.MaterialAlpha:return this._type=he.Float,this._type;case Rr.CameraParameters:return this._type=he.Vector4,this._type}}return this._type}constructor(e,t=Pe.Vertex,i=he.AutoDetect){super(e,t,!1),this._mode=Gd.Undefined,this._animationType=Z9.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new Se,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=Gd.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===he.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=Gd.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=Gd.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===Gd.Undefined}get isUniform(){return this._mode===Gd.Uniform}set isUniform(e){this._mode=e?Gd.Uniform:Gd.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===Gd.Attribute}set isAttribute(e){this._mode=e?Gd.Attribute:Gd.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===Gd.Varying}set isVarying(e){this._mode=e?Gd.Varying:Gd.Undefined,this.associatedVariableName=""}get isSystemValue(){return this._systemValue!=null}get systemValue(){return this._systemValue}set systemValue(e){this._mode=Gd.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Z9.Time:{this.type===he.Float&&(this.value+=e.getAnimationRatio()*.01);break}case Z9.RealTime:{this.type===he.Float&&(this.value=(Zr.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 he.Float:this.value=0;break;case he.Vector2:this.value=lt.Zero();break;case he.Vector3:this.value=O.Zero();break;case he.Vector4:this.value=Ui.Zero();break;case he.Color3:this.value=Ie.White();break;case he.Color4:this.value=new Zt(1,1,1,1);break;case he.Matrix:this.value=ge.Identity();break}}_emitConstant(e){switch(this.type){case he.Float:return`${e._emitFloat(this.value)}`;case he.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case he.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case he.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case he.Color3:return hn.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&hn.Color3[0].toGammaSpaceToRef(hn.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hn.Color3[0].toLinearSpaceToRef(hn.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${hn.Color3[0].r}, ${hn.Color3[0].g}, ${hn.Color3[0].b})`;case he.Color4:return hn.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&hn.Color4[0].toGammaSpaceToRef(hn.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hn.Color4[0].toLinearSpaceToRef(hn.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${hn.Color4[0].r}, ${hn.Color4[0].g}, ${hn.Color4[0].b}, ${hn.Color4[0].a})`}return""}get _noContextSwitch(){return vZ[this.name]}_emit(e,t){var i;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 s=e.sharedData.hints;if(this._systemValue!==null&&this._systemValue!==void 0)switch(this._systemValue){case Rr.WorldView:s.needWorldViewMatrix=!0;break;case Rr.WorldViewProjection:s.needWorldViewProjectionMatrix=!0;break}else this._animationType!==Z9.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=(i=j3e[this.name])!==null&&i!==void 0?i:this.name,this.target===Pe.Vertex&&e._vertexState){vZ[this.name]?Ose[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),vZ[this.name]?Ose[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,s){if(!this._systemValue)return;const r=this.associatedVariableName;switch(this._systemValue){case Rr.World:e.setMatrix(r,t);break;case Rr.WorldView:e.setMatrix(r,i);break;case Rr.WorldViewProjection:e.setMatrix(r,s);break}}_transmit(e,t,i){if(this.isAttribute)return;const s=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case Rr.World:case Rr.WorldView:case Rr.WorldViewProjection:return;case Rr.View:e.setMatrix(s,t.getViewMatrix());break;case Rr.Projection:e.setMatrix(s,t.getProjectionMatrix());break;case Rr.ViewProjection:e.setMatrix(s,t.getTransformMatrix());break;case Rr.CameraPosition:t.bindEyePosition(e,s,!0);break;case Rr.FogColor:e.setColor3(s,t.fogColor);break;case Rr.DeltaTime:e.setFloat(s,t.deltaTime/1e3);break;case Rr.CameraParameters:t.activeCamera&&e.setFloat4(s,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Rr.MaterialAlpha:e.setFloat(s,i.alpha);break}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(r!==null)switch(this.type){case he.Float:e.setFloat(s,r);break;case he.Int:e.setInt(s,r);break;case he.Color3:hn.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&hn.Color3[0].toGammaSpaceToRef(hn.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hn.Color3[0].toLinearSpaceToRef(hn.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(s,hn.Color3[0]);break;case he.Color4:hn.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&hn.Color4[0].toGammaSpaceToRef(hn.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hn.Color4[0].toLinearSpaceToRef(hn.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(s,hn.Color4[0]);break;case he.Vector2:e.setVector2(s,r);break;case he.Vector3:e.setVector3(s,r);break;case he.Vector4:e.setVector4(s,r);break;case he.Matrix:e.setMatrix(s,r);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.${Rr[this._systemValue]}); +`;if(this.isUniform){const t=[];let i="";switch(this.type){case he.Float:i=`${this.value}`;break;case he.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case he.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case he.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case he.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case he.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 he.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`;break}return t.push(`${e}.value = ${i}`),this.type===he.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Z9[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===Gd.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===Gd.Attribute&&e.type===he.Vector3&&(this._type=he.Vector4),!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const s=Bo(e.valueType);s&&(this._storedValue=s.FromArray(e.value))}}}$e("BABYLON.InputBlock",Er);class eee extends os{constructor(e){super(e,Pe.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",he.AutoDetect,!1,Pe.VertexAndFragment),this.registerOutput("rgba",he.Color4,Pe.Neutral),this.registerOutput("rgb",he.Color3,Pe.Neutral),this.registerOutput("r",he.Float,Pe.Neutral),this.registerOutput("g",he.Float,Pe.Neutral),this.registerOutput("b",he.Float,Pe.Neutral),this.registerOutput("a",he.Float,Pe.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(he.Vector2|he.Vector3|he.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?Pe.VertexAndFragment:Pe.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===Pe.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}if(this.uv.ownerBlock.target===Pe.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,s=!1){if(s){if(e.target===Pe.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===Pe.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!==Pe.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=Te.Parse(e.texture,t,i))}}$e("BABYLON.CurrentScreenBlock",eee);class tee extends os{constructor(e){super(e,Pe.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",he.AutoDetect,!1,Pe.VertexAndFragment),this.registerOutput("rgba",he.Color4,Pe.Neutral),this.registerOutput("rgb",he.Color3,Pe.Neutral),this.registerOutput("r",he.Float,Pe.Neutral),this.registerOutput("g",he.Float,Pe.Neutral),this.registerOutput("b",he.Float,Pe.Neutral),this.registerOutput("a",he.Float,Pe.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(he.Vector2|he.Vector3|he.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(s=>s.isAttribute&&s.name==="particle_uv"&&t(s));i||(i=new Er("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===Pe.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=Te.Parse(e.texture,t,i))}}$e("BABYLON.ParticleTextureBlock",tee);class iee extends os{constructor(e){super(e,Pe.Fragment),this._isUnique=!0,this.registerInput("color",he.Color4,!1,Pe.Fragment),this.registerOutput("rampColor",he.Color4,Pe.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!==Pe.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}}$e("BABYLON.ParticleRampGradientBlock",iee);class see extends os{constructor(e){super(e,Pe.Fragment),this._isUnique=!0,this.registerInput("color",he.Color4,!1,Pe.Fragment),this.registerInput("alphaTexture",he.Float,!1,Pe.Fragment),this.registerInput("alphaColor",he.Float,!1,Pe.Fragment),this.registerOutput("blendColor",he.Color4,Pe.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!==Pe.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}}$e("BABYLON.ParticleBlendMultiplyBlock",see);class Fl{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 s=0;s0&&(r.computeBonesUsingShaders=!1);continue}if(!(!r.computeBonesUsingShaders||r.numBoneInfluencers===0)){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes){for(const n of r.subMeshes)if(n.effect===t){r.computeBonesUsingShaders=!1;break}}}}}else{const i=this._defines[this._currentRank];if(i)for(let s=0;s0}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,t;return(t=(e=this._textures)===null||e===void 0?void 0:e[0])!==null&&t!==void 0?t: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 s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){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=s,this._depthStencilTexture=null,this.label=r}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,s=1,r=14,n){var o;return(o=this._depthStencilTexture)===null||o===void 0||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},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 e,t,i,s,r,n,o,l;let c=null;if(this._isMulti){const h=this.textures;if(h&&h.length>0){let u=!1,p=h.length;const m=h[h.length-1]._source;(m===hr.Depth||m===hr.DepthStencil)&&(u=!0,p--);const _=[],f=[],d=[],C=[],v=[],y=[],M=[],b={};for(let I=0;I1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let i=0;(t=i<((e=this._textures)===null||e===void 0?void 0:e.length))!==null&&t!==void 0&&t;++i)this._textures[i].dispose();this._textures=null}dispose(e=!1){var t;e||((t=this._depthStencilTexture)===null||t===void 0||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class Y3e extends HG{constructor(e,t,i,s,r){super(e,t,i,s),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._context=r}_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}_shareDepth(e){super._shareDepth(e);const t=this._context,i=this._depthStencilBuffer,s=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;const r=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;this._engine._bindUnboundFramebuffer(s),t.framebufferRenderbuffer(t.FRAMEBUFFER,r,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,s=0){var r,n,o,l;if(!e._hardwareTexture)return;const c=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(c),this._engine.webGLVersion>1){const u=this._context,p=u["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=(n=i??((r=this.layerIndices)===null||r===void 0?void 0:r[t]))!==null&&n!==void 0?n:0,u.framebufferTextureLayer(u.FRAMEBUFFER,p,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=(l=i??((o=this.faceIndices)===null||o===void 0?void 0:o[t]))!==null&&l!==void 0?l:0,u.framebufferTexture2D(u.FRAMEBUFFER,p,u.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):u.framebufferTexture2D(u.FRAMEBUFFER,p,u.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const u=this._context,p=u["COLOR_ATTACHMENT"+t+"_WEBGL"],m=i!==void 0?u.TEXTURE_CUBE_MAP_POSITIVE_X+i:u.TEXTURE_2D;u.framebufferTexture2D(u.FRAMEBUFFER,p,m,e._hardwareTexture.underlyingResource,s)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,s;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const r=(s=(i=this._attachments)===null||i===void 0?void 0:i.length)!==null&&s!==void 0?s:this.textures.length;for(let n=0;n1&&(n.format===15?u=i.DEPTH_COMPONENT16:n.format===16?u=i.DEPTH_COMPONENT24:n.format===17||n.format===13?u=i.DEPTH24_STENCIL8:n.format===14?u=i.DEPTH_COMPONENT32F:n.format===18&&(u=i.DEPTH32F_STENCIL8)),n.is2DArray?i.texImage3D(r,0,u,n.width,n.height,s,0,h,c,null):i.texImage2D(r,0,u,n.width,n.height,0,h,c,null),this._bindTextureDirectly(r,null),this._internalTexturesCache.push(n);const p=t;if(p._depthStencilBuffer){const m=this._currentFramebuffer;this._bindUnboundFramebuffer(p._framebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,null),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,null),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.STENCIL_ATTACHMENT,i.RENDERBUFFER,null),this._bindUnboundFramebuffer(m),i.deleteRenderbuffer(p._depthStencilBuffer),p._depthStencilBuffer=null}return n};Oi.prototype.updateRenderTargetTextureSampleCount=function(a,e){if(this.webGLVersion<2||!a||!a.texture)return 1;if(a.samples===e)return e;const t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),a._depthStencilBuffer&&(t.deleteRenderbuffer(a._depthStencilBuffer),a._depthStencilBuffer=null),a._MSAAFramebuffer&&(t.deleteFramebuffer(a._MSAAFramebuffer),a._MSAAFramebuffer=null);const i=a.texture._hardwareTexture;if(i.releaseMSAARenderBuffers(),e>1&&typeof t.renderbufferStorageMultisample=="function"){const s=t.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");a._MSAAFramebuffer=s,this._bindUnboundFramebuffer(a._MSAAFramebuffer);const r=this._createRenderBuffer(a.texture.width,a.texture.height,e,-1,this._getRGBAMultiSampleBufferFormat(a.texture.type),t.COLOR_ATTACHMENT0,!1);if(!r)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(r)}else this._bindUnboundFramebuffer(a._framebuffer);return a.texture.samples=e,a._samples=e,a._depthStencilBuffer=this._setupFramebufferDepthAttachments(a._generateStencilBuffer,a._generateDepthBuffer,a.texture.width,a.texture.height,e),this._bindUnboundFramebuffer(null),e};class rs{static RegisterShaderCodeProcessing(e,t){if(!t){delete rs._CustomShaderCodeProcessing[e??""];return}rs._CustomShaderCodeProcessing[e??""]=t}static _GetShaderCodeProcessing(e){var t;return(t=rs._CustomShaderCodeProcessing[e])!==null&&t!==void 0?t:rs._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,s,r,n,o=1,l,c,h=null,u=0,p="postprocess",m,_=!1,f=5,d=Ao.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=new Array,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 Sc(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new lt(1,1),this._texelSize=lt.Zero(),this.onActivateObservable=new Se,this.onSizeChangedObservable=new Se,this.onApplyObservable=new Se,this.onBeforeRenderObservable=new Se,this.onAfterRenderObservable=new Se,this.name=e,n!=null?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):l&&(this._engine=l,this._engine.postProcesses.push(this)),this._options=r,this.renderTargetSamplingMode=o||1,this._reusable=c||!1,this._textureType=u,this._textureFormat=f,this._shaderLanguage=d,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=p,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=m,this._drawWrapper=new ml(this._engine),_||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 Sc(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,o,l){var c,h;const u=rs._GetShaderCodeProcessing(this.name);if(u?.defineCustomBindings){const p=(c=t?.slice())!==null&&c!==void 0?c:[];p.push(...this._parameters);const m=(h=i?.slice())!==null&&h!==void 0?h:[];m.push(...this._samplers),e=u.defineCustomBindings(this.name,e,p,m),t=p,i=m}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o??this._vertexUrl,fragment:l??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:[],samplers:i||this._samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:u?.processCodeAfterIncludes?(p,m)=>u.processCodeAfterIncludes(this.name,p,m):null,processFinalCode:u?.processFinalCode?(p,m)=>u.processFinalCode(this.name,p,m):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let r=0;r=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let s=0;s0&&this._textures.reset(),this.width=e,this.height=t;let n=null;for(let c=0;c{d.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(d,this.samples)}),this._flushTextureCache(),this._renderId++}let f;if(this._shareOutputWithPostProcess)f=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)f=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{f=this.inputTexture;let d;for(let C=0;C=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=Kt.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=rs.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 s=Bo(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return Kt.Parse(()=>new rs(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,s)}}rs._CustomShaderCodeProcessing={};z([X()],rs.prototype,"uniqueId",void 0);z([X()],rs.prototype,"name",void 0);z([X()],rs.prototype,"width",void 0);z([X()],rs.prototype,"height",void 0);z([X()],rs.prototype,"renderTargetSamplingMode",void 0);z([bF()],rs.prototype,"clearColor",void 0);z([X()],rs.prototype,"autoClear",void 0);z([X()],rs.prototype,"forceAutoClearInAlphaMode",void 0);z([X()],rs.prototype,"alphaMode",void 0);z([X()],rs.prototype,"alphaConstants",void 0);z([X()],rs.prototype,"enablePixelPerfectMode",void 0);z([X()],rs.prototype,"forceFullscreenViewport",void 0);z([X()],rs.prototype,"scaleMode",void 0);z([X()],rs.prototype,"alwaysForcePOT",void 0);z([X("samples")],rs.prototype,"_samples",void 0);z([X()],rs.prototype,"adaptScaleToCurrentViewport",void 0);$e("BABYLON.PostProcess",rs);class Cj extends os{constructor(e){super(e,Pe.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",he.Vector4,!0),this.registerInput("xyz ",he.Vector3,!0),this.registerInput("xy ",he.Vector2,!0),this.registerInput("zw ",he.Vector2,!0),this.registerInput("x",he.Float,!0),this.registerInput("y",he.Float,!0),this.registerInput("z",he.Float,!0),this.registerInput("w",he.Float,!0),this.registerOutput("xyzw",he.Vector4),this.registerOutput("xyz",he.Vector3),this.registerOutput("xy",he.Vector2),this.registerOutput("zw",he.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,s=this.z,r=this.w,n=this.xyIn,o=this.zwIn,l=this.xyzIn,c=this.xyzwIn,h=this._outputs[0],u=this._outputs[1],p=this._outputs[2],m=this._outputs[3];return c.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${c.associatedVariableName}${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${c.associatedVariableName}${this._buildSwizzle(3)}; +`),p.hasEndpoints&&(e.compilationString+=this._declareOutput(p,e)+` = ${c.associatedVariableName}${this._buildSwizzle(2)}; +`)):l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${l.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; +`),p.hasEndpoints&&(e.compilationString+=this._declareOutput(p,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; +`)):n.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)}; +`),p.hasEndpoints&&(e.compilationString+=this._declareOutput(p,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)}; +`),m.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(m,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; +`:e.compilationString+=this._declareOutput(m,e)+` = vec2(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"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"}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"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"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)}; +`),p.hasEndpoints&&(e.compilationString+=this._declareOutput(p,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)}; +`),m.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(m,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; +`:e.compilationString+=this._declareOutput(m,e)+` = vec2(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"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){var s,r,n,o;super._deserialize(e,t,i),this.xSwizzle=(s=e.xSwizzle)!==null&&s!==void 0?s:"x",this.ySwizzle=(r=e.ySwizzle)!==null&&r!==void 0?r:"y",this.zSwizzle=(n=e.zSwizzle)!==null&&n!==void 0?n:"z",this.wSwizzle=(o=e.wSwizzle)!==null&&o!==void 0?o:"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}}$e("BABYLON.VectorMergerBlock",Cj);class jG extends os{constructor(e){super(e,Pe.Neutral),this.sourceRange=new lt(-1,1),this.targetRange=new lt(0,1),this.registerInput("input",he.AutoDetect),this.registerInput("sourceMin",he.Float,!0),this.registerInput("sourceMax",he.Float,!0),this.registerInput("targetMin",he.Float,!0),this.registerInput("targetMax",he.Float,!0),this.registerOutput("output",he.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),s=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),r=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${r} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${r}) / (${s} - ${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=lt.FromArray(e.sourceRange),this.targetRange=lt.FromArray(e.targetRange)}}z([ws("From",Ms.Vector2)],jG.prototype,"sourceRange",void 0);z([ws("To",Ms.Vector2)],jG.prototype,"targetRange",void 0);$e("BABYLON.RemapBlock",jG);class dX extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("left",he.AutoDetect),this.registerInput("right",he.AutoDetect),this.registerOutput("output",he.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(he.Float),this._inputs[1].acceptedConnectionPointTypes.push(he.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}}$e("BABYLON.MultiplyBlock",dX);var Gf;(function(a){a[a.Material=0]="Material",a[a.PostProcess=1]="PostProcess",a[a.Particle=2]="Particle",a[a.ProceduralTexture=3]="ProceduralTexture"})(Gf||(Gf={}));class PL{constructor(){this.direction1=new O(0,1,0),this.direction2=new O(0,1,0),this.minEmitBox=new O(-.5,-.5,-.5),this.maxEmitBox=new O(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=Bt.RandomRange(this.direction1.x,this.direction2.x),n=Bt.RandomRange(this.direction1.y,this.direction2.y),o=Bt.RandomRange(this.direction1.z,this.direction2.z);if(s){t.x=r,t.y=n,t.z=o;return}O.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){const r=Bt.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),n=Bt.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),o=Bt.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(s){t.x=r,t.y=n,t.z=o;return}O.TransformCoordinatesFromFloatsToRef(r,n,o,e,t)}clone(){const e=new PL;return e2.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){O.FromArrayToRef(e.direction1,0,this.direction1),O.FromArrayToRef(e.direction2,0,this.direction2),O.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),O.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class GG{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,s){s?ue.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),ue.Vector3[0]).normalize();const r=Bt.RandomRange(0,this.directionRandomizer),n=Bt.RandomRange(0,this.directionRandomizer),o=Bt.RandomRange(0,this.directionRandomizer);t.x=ue.Vector3[0].x+r,t.y=ue.Vector3[0].y+n,t.z=ue.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,s){const r=Bt.RandomRange(0,Math.PI*2);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=Bt.RandomRange(0,this.heightRange),n=1-n*n);let o=this._radius-Bt.RandomRange(0,this._radius*this.radiusRange);o=o*n;const l=o*Math.sin(r),c=o*Math.cos(r),h=n*this._height;if(s){t.x=l,t.y=h,t.z=c;return}O.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new GG(this._radius,this._angle,this.directionRandomizer);return e2.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 MF{constructor(e=1,t=1,i=1,s=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=s,this._tempVector=O.Zero()}startDirectionFunction(e,t,i,s,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),O.TransformNormalToRef(this._tempVector,r,this._tempVector);const n=Bt.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);if(o+=Bt.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),s){t.copyFrom(this._tempVector);return}O.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,s){const r=Bt.RandomRange(-this.height/2,this.height/2),n=Bt.RandomRange(0,2*Math.PI),o=Bt.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),l=Math.sqrt(o)*this.radius,c=l*Math.cos(n),h=l*Math.sin(n);if(s){t.copyFromFloats(c,r,h);return}O.TransformCoordinatesFromFloatsToRef(c,r,h,e,t)}clone(){const e=new MF(this.radius,this.directionRandomizer);return e2.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 WG extends MF{constructor(e=1,t=1,i=1,s=new O(0,1,0),r=new O(0,1,0)){super(e,t,i),this.direction1=s,this.direction2=r}startDirectionFunction(e,t){const i=Bt.RandomRange(this.direction1.x,this.direction2.x),s=Bt.RandomRange(this.direction1.y,this.direction2.y),r=Bt.RandomRange(this.direction1.z,this.direction2.z);O.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new WG(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return e2.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 YG{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=Bt.RandomRange(0,this.directionRandomizer),o=Bt.RandomRange(0,this.directionRandomizer),l=Bt.RandomRange(0,this.directionRandomizer);if(r.x+=n,r.y+=o,r.z+=l,r.normalize(),s){t.copyFrom(r);return}O.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-Bt.RandomRange(0,this.radius*this.radiusRange),n=Bt.RandomRange(0,1),o=Bt.RandomRange(0,2*Math.PI),l=Math.acos(2*n-1),c=r*Math.cos(o)*Math.sin(l),h=r*Math.cos(l),u=r*Math.sin(o)*Math.sin(l);if(s){t.copyFromFloats(c,Math.abs(h),u);return}O.TransformCoordinatesFromFloatsToRef(c,Math.abs(h),u,e,t)}clone(){const e=new YG(this.radius,this.directionRandomizer);return e2.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 XG{constructor(){this.direction1=new O(0,1,0),this.direction2=new O(0,1,0)}startDirectionFunction(e,t,i,s){const r=Bt.RandomRange(this.direction1.x,this.direction2.x),n=Bt.RandomRange(this.direction1.y,this.direction2.y),o=Bt.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,o);return}O.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(s){t.copyFromFloats(0,0,0);return}O.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new XG;return e2.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){O.FromArrayToRef(e.direction1,0,this.direction1),O.FromArrayToRef(e.direction2,0,this.direction2)}}class TF{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=Bt.RandomRange(0,this.directionRandomizer),o=Bt.RandomRange(0,this.directionRandomizer),l=Bt.RandomRange(0,this.directionRandomizer);if(r.x+=n,r.y+=o,r.z+=l,r.normalize(),s){t.copyFrom(r);return}O.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-Bt.RandomRange(0,this.radius*this.radiusRange),n=Bt.RandomRange(0,1),o=Bt.RandomRange(0,2*Math.PI),l=Math.acos(2*n-1),c=r*Math.cos(o)*Math.sin(l),h=r*Math.cos(l),u=r*Math.sin(o)*Math.sin(l);if(s){t.copyFromFloats(c,h,u);return}O.TransformCoordinatesFromFloatsToRef(c,h,u,e,t)}clone(){const e=new TF(this.radius,this.directionRandomizer);return e2.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 KG extends TF{constructor(e=1,t=new O(0,1,0),i=new O(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=Bt.RandomRange(this.direction1.x,this.direction2.x),s=Bt.RandomRange(this.direction1.y,this.direction2.y),r=Bt.RandomRange(this.direction1.z,this.direction2.z);O.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new KG(this.radius,this.direction1,this.direction2);return e2.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 DL{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=ue.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const n=ue.Vector3[1];r.subtractToRef(i.position,n),n.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);if(s){t.copyFrom(r);return}O.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=ue.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s){t.copyFrom(r);return}O.TransformCoordinatesToRef(r,e,t)}clone(){const e=new DL;return e2.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e}parse(e){}}class TK{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(se.PositionKind),this._normals=e.getVerticesData(se.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=O.Zero(),this._mesh=null,this.direction1=new O(0,1,0),this.direction2=new O(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals){O.TransformNormalToRef(this._storedNormal,e,t);return}const r=Bt.RandomRange(this.direction1.x,this.direction2.x),n=Bt.RandomRange(this.direction1.y,this.direction2.y),o=Bt.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,o);return}O.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(!this._indices||!this._positions)return;const r=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),l=1-n-o,c=this._indices[r],h=this._indices[r+1],u=this._indices[r+2],p=ue.Vector3[0],m=ue.Vector3[1],_=ue.Vector3[2],f=ue.Vector3[3];O.FromArrayToRef(this._positions,c*3,p),O.FromArrayToRef(this._positions,h*3,m),O.FromArrayToRef(this._positions,u*3,_),f.x=n*p.x+o*m.x+l*_.x,f.y=n*p.y+o*m.y+l*_.y,f.z=n*p.z+o*m.z+l*_.z,s?t.copyFromFloats(f.x,f.y,f.z):O.TransformCoordinatesFromFloatsToRef(f.x,f.y,f.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(O.FromArrayToRef(this._normals,c*3,p),O.FromArrayToRef(this._normals,h*3,m),O.FromArrayToRef(this._normals,u*3,_),this._storedNormal.x=n*p.x+o*m.x+l*_.x,this._storedNormal.y=n*p.y+o*m.y+l*_.y,this._storedNormal.z=n*p.z+o*m.z+l*_.z)}clone(){const e=new TK(this.mesh);return e2.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 e;const t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=(e=this.mesh)===null||e===void 0?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){O.FromArrayToRef(e.direction1,0,this.direction1),O.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class lC{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:O.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:O.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:O.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:O.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 s=0;for(const r of t){if(r.gradient===e){t.splice(s,1);break}s++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=O.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._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new O(10,10,10),this.onAnimationEnd=null,this.blendMode=lC.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 lt(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new O(0,0,0),this._useLogarithmicDepth=!1,this.gravity=O.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 Zt(1,1,1,1),this.color2=new Zt(1,1,1,1),this.colorDead=new Zt(0,0,0,1),this.textureMask=new Zt(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new $oe,this.id=e,this.name=e}createPointEmitter(e,t){const i=new XG;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=new YG(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=new TF(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new O(0,1,0),i=new O(0,1,0)){const s=new KG(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=new MF(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new O(0,1,0),r=new O(0,1,0)){const n=new WG(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=new GG(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new PL;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}}lC.BLENDMODE_ONEONE=0;lC.BLENDMODE_STANDARD=1;lC.BLENDMODE_ADD=2;lC.BLENDMODE_MULTIPLY=3;lC.BLENDMODE_MULTIPLYADD=4;class ree extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("rgba",he.Color4,!0),this.registerInput("rgb ",he.Color3,!0),this.registerOutput("rgb",he.Color3),this.registerOutput("r",he.Float),this.registerOutput("g",he.Float),this.registerOutput("b",he.Float),this.registerOutput("a",he.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],s=this._outputs[1],r=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb; +`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.r; +`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.g; +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.b; +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.a; +`),this}}$e("BABYLON.ColorSplitterBlock",ree);Oi.prototype.createRenderTargetCubeTexture=function(a,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,a),i=Object.assign({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 s=this._gl,r=new dn(this,hr.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,r,!0);const n=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,Me.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,n.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,n.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let l=0;l<6;l++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),a,a,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,a,a),i.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=o,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,r.width=a,r.height=a,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=i.generateMipMaps,r.samplingMode=i.samplingMode,r.type=i.type,r.format=i.format,this._internalTexturesCache.push(r),t.setTextures(r),t};const CZ={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class QG{constructor(e,t=CZ){var i,s;this._fullscreenViewport=new hu(0,0,1,1);const r=(i=t.positions)!==null&&i!==void 0?i:CZ.positions,n=(s=t.indices)!==null&&s!==void 0?s:CZ.indices;this.engine=e,this._vertexBuffers={[se.PositionKind]:new se(e,r,se.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(n);for(const o in this._vertexBuffers)this._vertexBuffers[o]._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[se.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[se.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class KM{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.onApplyObservable=new Se;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 s=e.defines?e.defines.join(` +`):"";this._drawWrapper=new ml(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,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new Ws(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._wasPreviouslyReady=!1,this.effect._prepareEffect()}))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const Hle="passPixelShader",jle=`varying vec2 vUV;uniform sampler2D textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);}`;Ue.ShadersStore[Hle]=jle;const wse={name:Hle,shader:jle};class Nu{static _CreateDumpRenderer(){if(!Nu._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 Oi(e,!1,i)}catch{e=document.createElement("canvas"),t=new Oi(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;const s=new QG(t),r=new KM({engine:t,name:wse.name,fragmentShader:wse.shader,samplerNames:["textureSampler"]});Nu._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return Nu._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,o){const l=await i.readPixels(0,0,e,t),c=new Uint8Array(l.buffer);Nu.DumpData(e,t,c,s,r,n,!0,void 0,o)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,o=!1,l){return new Promise(c=>{Nu.DumpData(e,t,i,h=>c(h),s,r,n,o,l)})}static DumpData(e,t,i,s,r="image/png",n,o=!1,l=!1,c){const h=Nu._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){const p=new Uint8Array(i.length);let m=i.length;for(;m--;){const _=i[m];p[m]=Math.round(Bt.Clamp(_)*255)}i=p}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(),l?Be.ToBlob(h.canvas,p=>{const m=new FileReader;m.onload=_=>{const f=_.target.result;s&&s(f)},m.readAsArrayBuffer(p)},r,c):Be.EncodeScreenshotCanvasData(h.canvas,s,r,n,c),u.dispose()}static Dispose(){Nu._DumpToolsEngine&&(Nu._DumpToolsEngine.wrapper.dispose(),Nu._DumpToolsEngine.renderer.dispose(),Nu._DumpToolsEngine.engine.dispose()),Nu._DumpToolsEngine=null}}const X3e=()=>{Be.DumpData=Nu.DumpData,Be.DumpDataAsync=Nu.DumpDataAsync,Be.DumpFramebuffer=Nu.DumpFramebuffer};X3e();class Oa extends Te{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=Qoe(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 s=0;s{var w;const N=this._renderList?this._renderList.length:0;(L===0&&N>0||N===0)&&((w=this.getScene())===null||w===void 0||w.meshes.forEach(V=>{V._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new Se,this.onAfterUnbindObservable=new Se,this.onBeforeRenderObservable=new Se,this.onAfterRenderObservable=new Se,this.onClearObservable=new Se,this.onResizeObservable=new Se,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=O.Zero(),i=this.getScene(),!i)return;const D=this.getScene().getEngine();this._coordinatesMode=Te.PROJECTION_MODE,this.renderList=new Array,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=D.onResizeObservable.add(()=>{}),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new pd(i),this._renderingManager._useSceneAutoClearSetup=!0,!u&&(this._renderTargetOptions={generateMipMaps:s,type:n,format:(S=this._format)!==null&&S!==void 0?S:void 0,samplingMode:this.samplingMode,generateDepthBuffer:c,generateStencilBuffer:h,samples:_,creationFlags:f,noColorAttachment:d,useSRGBBuffer:C,colorAttachment:I,label:this.name},this.samplingMode===Te.NEAREST_SAMPLINGMODE&&(this.wrapU=Te.CLAMP_ADDRESSMODE,this.wrapV=Te.CLAMP_ADDRESSMODE),m||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Te.INVCUBIC_MODE,this._textureMatrix=ge.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,_!==void 0&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14){var n;(n=this._renderTarget)===null||n===void 0||n.createDepthStencilTexture(e,t,i,s,r)}_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 t;const i=this.isCube;(t=this._renderTarget)===null||t===void 0||t.dispose(),this._renderTarget=null;const s=this.getScene();!s||(this._processSizeParameter(e,!1),i?this._renderTarget=s.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=s.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){var s;const r=this.getScene();if(!r)return i;const n=r.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let u=0;u1||this.activeCamera&&this.activeCamera!==r.activeCamera)&&r.setTransformMatrix(r.activeCamera.getViewMatrix(),r.activeCamera.getProjectionMatrix(!0)),n.setViewport(r.activeCamera.viewport)),r.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){const s=e*t,r=He.NearestPOT(s+128*128/(128+s));return Math.min(He.FloorPOT(e),r)}_prepareRenderingManager(e,t,i,s){const r=this.getScene();if(!r)return;this._renderingManager.reset();const n=r.getRenderId();for(let o=0;o{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):(!s||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){var n,o,l,c,h,u;const p=this.getScene();if(!p)return;const m=p.getEngine();if((n=m._debugPushGroup)===null||n===void 0||n.call(m,`render to face #${e} layer #${s}`,1),this._prepareFrame(p,e,s,t),this.is2DArray?(m.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(m.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),m.snapshotRendering&&m.snapshotRenderingMode===1)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(m):this.skipInitialClear||m.clear(this.clearColor||p.clearColor,!0,!0,!0);else{let f=null;const d=this.renderList?this.renderList:p.getActiveMeshes().data,C=this.renderList?this.renderList.length:p.getActiveMeshes().length;this.getCustomRenderList&&(f=this.getCustomRenderList(this.is2DArray?s:e,d,C)),f?this._prepareRenderingManager(f,f.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(d,C,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),f=d);for(const y of p._beforeRenderTargetClearStage)y.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(m):this.skipInitialClear||m.clear(this.clearColor||p.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||p.updateTransformMatrix(!0);for(const y of p._beforeRenderTargetDrawStage)y.action(this,e,s);this._renderingManager.render(this.customRenderFunction,f,this.renderParticles,this.renderSprites);for(const y of p._afterRenderTargetDrawStage)y.action(this,e,s);const v=(l=(o=this._texture)===null||o===void 0?void 0:o.generateMipMaps)!==null&&l!==void 0?l:!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,(c=this._renderTarget)!==null&&c!==void 0?c:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&p.postProcessManager._finalizeFrame(!1,(h=this._renderTarget)!==null&&h!==void 0?h:void 0,e);for(const y of p._afterRenderTargetPostProcessStage)y.action(this,e,s);this._texture&&(this._texture.generateMipMaps=v),this._doNotChangeAspectRatio||p.updateTransformMatrix(!0),i&&Nu.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),m)}this._unbindFrameBuffer(m,e),this._texture&&this.isCube&&e===5&&m.generateMipMapsForCubemap(this._texture),(u=m._debugPopGroup)===null||u===void 0||u.call(m,1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new Oa(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&&t.customRenderTargets.splice(i,1);for(const s of t.cameras)i=s.customRenderTargets.indexOf(this),i>=0&&s.customRenderTargets.splice(i,1);(e=this._renderTarget)===null||e===void 0||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===Oa.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Oa.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}Oa.REFRESHRATE_RENDER_ONCE=0;Oa.REFRESHRATE_RENDER_ONEVERYFRAME=1;Oa.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;Te._CreateRenderTargetTexture=(a,e,t,i,s)=>new Oa(a,e,t,i);class Gle{constructor(e){this.name=ai.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=new Array}register(){this.scene._beforeClearStage.registerStep(ai.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Be.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}const K3e="proceduralVertexShader",Q3e=`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 +}`;Ue.ShadersStore[K3e]=Q3e;class fC extends Te{constructor(e,t,i,s,r=null,n=!0,o=!1,l=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new Se,this.onBeforeGenerationObservable=new Se,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=this.getScene()||Ii.LastCreatedScene;let c=s._getComponent(ai.NAME_PROCEDURALTEXTURE);c||(c=new Gle(s),s._addComponent(c)),s.proceduralTextures.push(this),this._fullEngine=s.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=l,this._generateMipMaps=n,this._drawWrapper=new ml(this._fullEngine),this.setFragment(i),this._fallbackTexture=r;const h=this._createRtWrapper(o,t,n,l);this._texture=h.texture;const u=[];u.push(1,1),u.push(-1,1),u.push(-1,-1),u.push(1,-1),this._vertexBuffers[se.PositionKind]=new se(this._fullEngine,u,se.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,s){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s}),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[se.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===Oa.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Oa.REFRESHRATE_RENDER_ONCE)}reset(){var e;(e=this._drawWrapper.effect)===null||e===void 0||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}isReady(){const e=this._fullEngine;let t;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const i=this._getDefines();return this._drawWrapper.effect&&i===this._cachedDefines&&this._drawWrapper.effect.isReady()?!0:(this._fragment.fragmentElement!==void 0?t={vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:t={vertex:"procedural",fragment:this._fragment},this._cachedDefines!==i&&(this._cachedDefines=i,this._drawWrapper.effect=e.createEffect(t,[se.PositionKind],this._uniforms,this._samplers,i,void 0,void 0,()=>{var s;(s=this._rtWrapper)===null||s===void 0||s.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 s=this._createRtWrapper(i,e,t,this._textureType);this._texture=s.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 t,i;const s=this.getScene();if(!s)return;const r=this._fullEngine;if(r.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),r.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 l=this._colors4[o];this._drawWrapper.effect.setFloat4(o,l.r,l.g,l.b,l.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;(t=r._debugPushGroup)===null||t===void 0||t.call(r,`procedural texture generation for ${this.name}`,1);const n=r.currentViewport;if(this.isCube)for(let o=0;o<6;o++)r.bindFramebuffer(this._rtWrapper,o,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",o),this.autoClear&&r.clear(s.clearColor,!0,!1,!1),r.drawElementsType(Lt.TriangleFillMode,0,6);else r.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&r.clear(s.clearColor,!0,!1,!1),r.drawElementsType(Lt.TriangleFillMode,0,6);r.unBindFramebuffer(this._rtWrapper,this.isCube),n&&r.setViewport(n),this.isCube&&r.generateMipMapsForCubemap(this._texture),(i=r._debugPopGroup)===null||i===void 0||i.call(r,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new fC(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[se.PositionKind];i&&(i.dispose(),this._vertexBuffers[se.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}z([X()],fC.prototype,"isEnabled",void 0);z([X()],fC.prototype,"autoClear",void 0);z([X()],fC.prototype,"_generateMipMaps",void 0);z([X()],fC.prototype,"_size",void 0);z([X()],fC.prototype,"refreshRate",null);$e("BABYLON.ProceduralTexture",fC);var yh;(function(a){a[a.Cos=0]="Cos",a[a.Sin=1]="Sin",a[a.Abs=2]="Abs",a[a.Exp=3]="Exp",a[a.Exp2=4]="Exp2",a[a.Round=5]="Round",a[a.Floor=6]="Floor",a[a.Ceiling=7]="Ceiling",a[a.Sqrt=8]="Sqrt",a[a.Log=9]="Log",a[a.Tan=10]="Tan",a[a.ArcTan=11]="ArcTan",a[a.ArcCos=12]="ArcCos",a[a.ArcSin=13]="ArcSin",a[a.Fract=14]="Fract",a[a.Sign=15]="Sign",a[a.Radians=16]="Radians",a[a.Degrees=17]="Degrees"})(yh||(yh={}));class nee extends os{constructor(e){super(e,Pe.Neutral),this.operation=yh.Cos,this.registerInput("input",he.AutoDetect),this.registerOutput("output",he.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 yh.Cos:{i="cos";break}case yh.Sin:{i="sin";break}case yh.Abs:{i="abs";break}case yh.Exp:{i="exp";break}case yh.Exp2:{i="exp2";break}case yh.Round:{i="round";break}case yh.Floor:{i="floor";break}case yh.Ceiling:{i="ceil";break}case yh.Sqrt:{i="sqrt";break}case yh.Log:{i="log";break}case yh.Tan:{i="tan";break}case yh.ArcTan:{i="atan";break}case yh.ArcCos:{i="acos";break}case yh.ArcSin:{i="asin";break}case yh.Fract:{i="fract";break}case yh.Sign:{i="sign";break}case yh.Radians:{i="radians";break}case yh.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.${yh[this.operation]}; +`}}$e("BABYLON.TrigonometryBlock",nee);const AZ={effect:null,subMesh:null};class lj extends ta{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 Pl extends Bl{static _BlockIsTextureBlock(e){return e.getClassName()==="TextureBlock"||e.getClassName()==="ReflectionTextureBaseBlock"||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||Ii.LastCreatedScene),this._buildId=Pl._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new ge,this._cachedWorldViewProjectionMatrix=new ge,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new Se,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=new Array,this._mode=Gf.Material,this.forceAlphaBlending=!1,this._options=Object.assign({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 Be.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&Pe.Vertex)!==0&&this._addVertexOutputNode(e),(e.target&Pe.Fragment)!==0&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return e.target===null?this:((e.target&Pe.Vertex)!==0&&this._removeVertexOutputNode(e),(e.target&Pe.Fragment)!==0&&this._removeFragmentOutputNode(e),this)}_addVertexOutputNode(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=Pe.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=Pe.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,s=!0){(e.target===Pe.VertexAndFragment||t.target===Pe.Fragment&&e.target===Pe.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,s)}_initializeBlock(e,t,i,s=!0){if(e.initialize(t),s&&e.autoConfigure(this),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1){if(e.isUnique){const r=e.getClassName();for(const n of this.attachedBlocks)if(n.getClassName()===r)throw`Cannot have multiple blocks of type ${r} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const r of e.inputs){r.associatedVariableName="";const n=r.connectedPoint;if(n){const o=n.ownerBlock;o!==e&&this._processInitializeOnLink(o,t,i,s)}}if(e.isTeleportOut){const r=e;r.entryPoint&&this._processInitializeOnLink(r.entryPoint,t,i,s)}for(const r of e.outputs)r.associatedVariableName=""}_resetDualBlocks(e,t){e.target===Pe.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._resetDualBlocks(r,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 s=this.getScene().getEngine(),r=this._mode===Gf.Particle;if(this._vertexOutputNodes.length===0&&!r)throw"You must define at least one vertexOutputNode";if(this._fragmentOutputNodes.length===0)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new Dse,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=Pe.Vertex,this._fragmentCompilationState=new Dse,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=Pe.Fragment,this._sharedData=new H3e,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=r;const n=[],o=[];for(const h of this._vertexOutputNodes)n.push(h),this._initializeBlock(h,this._vertexCompilationState,o,i);for(const h of this._fragmentOutputNodes)o.push(h),this._initializeBlock(h,this._fragmentCompilationState,n,i);this.optimize();for(const h of n)h.build(this._vertexCompilationState,n);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=Pl._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(console.log("Vertex shader:"),console.log(this._vertexCompilationState.compilationString),console.log("Fragment shader:"),console.log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const l=this.getScene().meshes;for(const h of l)if(!!h.subMeshes)for(const u of h.subMeshes){if(u.getMaterial()!==this||!u.materialDefines)continue;const p=u.materialDefines;p.markAllAsDirty(),p.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const c=this.getScene().prePassRenderer;c&&c.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,s=t.TANGENT,r=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(se.NormalKind),t.TANGENT=e.isVerticesDataPresent(se.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(se.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let c=1;c<=6;++c){const h=t["UV"+c];t["UV"+c]=e.isVerticesDataPresent(`uv${c===1?"":c}`),o=o||t["UV"+c]!==h}const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;ze.PrepareDefinesForPrePass(this.getScene(),t,!l),(i!==t.NORMAL||s!==t.TANGENT||r!==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 s of t)i.texturesRequired.includes(s)||i.texturesRequired.push(s);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,s,r,n=0,o=5){return this.mode!==Gf.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,o=0,l=5){let c=this.name+this._buildId;const h=new lj,u=new Ir(c+"PostProcess",this.getScene());let p=this._buildId;return this._processDefines(u,h),Ws.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,c,c):e=new rs(this.name+"PostProcess",c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,h.toString(),o,c,{maxSimultaneousLights:this.maxSimultaneousLights},!1,l),e.nodeMaterialSource=this,e.onApplyObservable.add(m=>{p!==this._buildId&&(delete Ws.ShadersStore[c+"VertexShader"],delete Ws.ShadersStore[c+"PixelShader"],c=this.name+this._buildId,h.markAllAsDirty(),p=this._buildId),this._processDefines(u,h)&&(Ws.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),wB.SetImmediate(()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,c,c))),this._checkInternals(m)}),e}createProceduralTexture(e,t){if(this.mode!==Gf.ProceduralTexture)return console.log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new fC(i,e,null,t),r=new Ir(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new lj,o=this._processDefines(r,n);Ws.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[se.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o?.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(l);let c=this._buildId;return s.onBeforeGenerationObservable.add(()=>{c!==this._buildId&&(delete Ws.ShadersStore[i+"VertexShader"],delete Ws.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),c=this._buildId);const h=this._processDefines(r,n);h&&(Ws.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),wB.SetImmediate(()=>{l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[se.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),h?.fallbacks,void 0),s._setEffect(l)})),this._checkInternals(l)}),s}_createEffectForParticles(e,t,i,s,r,n,o,l=""){let c=this.name+this._buildId+"_"+t;n||(n=new lj),o||(o=this.getScene().getMeshByName(this.name+"Particle"),o||(o=new Ir(this.name+"Particle",this.getScene()),o.reservedDataStore={hidden:!0}));let h=this._buildId;const u=[];let p=l;if(!r){const m=this._processDefines(o,n);Ws.RegisterShader(c,this._fragmentCompilationState._builtCompilationString),e.fillDefines(u,t),p=u.join(` +`),r=this.getScene().getEngine().createEffectForParticles(c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+` +`+p,m?.fallbacks,i,s,e),e.setCustomEffect(r,t)}r.onBindObservable.add(m=>{h!==this._buildId&&(delete Ws.ShadersStore[c+"PixelShader"],c=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),u.length=0,e.fillDefines(u,t);const _=u.join(` +`);_!==p&&(n.markAllAsDirty(),p=_);const f=this._processDefines(o,n);if(f){Ws.RegisterShader(c,this._fragmentCompilationState._builtCompilationString),m=this.getScene().getEngine().createEffectForParticles(c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+` +`+p,f?.fallbacks,i,s,e),e.setCustomEffect(m,t),this._createEffectForParticles(e,t,i,s,m,n,o,l);return}this._checkInternals(m)})}_checkInternals(e){if(this._sharedData.animatedInputs){const t=this.getScene(),i=t.getFrameId();if(this._animationFrame!==i){for(const s of this._sharedData.animatedInputs)s.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!==Gf.Particle){console.log("Incompatible material mode");return}this._createEffectForParticles(e,lC.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,lC.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==Gf.Material){console.log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,s){let r=null;const n=this.getScene();if(ze.PrepareDefinesForCamera(n,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,s)}),t.isDirty){const o=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach(p=>{p.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)});const l=[];this._sharedData.dynamicUniformBlocks.forEach(p=>{p.updateUniformsAndSamples(this._vertexCompilationState,this,t,l)});const c=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(p=>{c.indexOf(p)===-1&&c.push(p)});const h=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(p=>{h.indexOf(p)===-1&&h.push(p)});const u=new Fl;this._sharedData.blocksWithFallbacks.forEach(p=>{p.provideFallbacks(e,u)}),r={lightDisposed:o,uniformBuffers:l,mergedUniforms:c,mergedSamplers:h,fallbacks:u}}return r}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const s=this.getScene();if(this._sharedData.animatedInputs){const l=s.getFrameId();if(this._animationFrame!==l){for(const c of this._sharedData.animatedInputs)c.animate(s);this._animationFrame=l}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new lj);const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if(this._prepareDefinesForAttributes(e,r),this._sharedData.blockingBlocks.some(l=>!l.isReady(e,this,r,i)))return!1;const o=this._processDefines(e,r,i,t);if(o){const l=t.effect,c=r.toString();let h=n.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:o.mergedUniforms,uniformBuffersNames:o.uniformBuffers,samplers:o.mergedSamplers,defines:c,fallbacks:o.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:r.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS}},n);if(h)if(this._onEffectCreatedObservable&&(AZ.effect=h,AZ.subMesh=t,this._onEffectCreatedObservable.notifyObservers(AZ)),this.allowShaderHotSwapping&&l&&!h.isReady()){if(h=l,r.markAsUnprocessed(),o.lightDisposed)return r._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(h,r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._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 s of this._sharedData.inputBlocks)s._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(s,r,t.visibility),o=this._sharedData;if(n){for(const l of o.bindableBlocks)l.bind(r,this,t,i);for(const l of o.forcedBindableBlocks)l.bind(r,this,t,i);for(const l of o.inputBlocks)l._transmit(r,s,this)}else if(!this.isFrozen)for(const l of o.forcedBindableBlocks)l.bind(r,this,t,i);this._afterBind(t,this._activeEffect)}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)Pl._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 s of this.getTextureBlocks().filter(r=>r.texture).map(r=>r.texture))s.dispose();for(const s of this.attachedBlocks)s.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=Object.assign({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:Pl.EditorURL;Be.LoadScript(i,()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e?.nodeEditorConfig),t()})}else this._createNodeEditor(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 Er("Position");e.setAsAttribute("position");const t=new Er("World");t.setAsSystemValue(Rr.World);const i=new uX("WorldPos");e.connectTo(i),t.connectTo(i);const s=new Er("ViewProjection");s.setAsSystemValue(Rr.ViewProjection);const r=new uX("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new vj("VertexOutput");r.connectTo(n);const o=new Er("color");o.value=new Zt(.8,.8,.8,1);const l=new tI("FragmentOutput");o.connectTo(l),this.addOutputNode(n),this.addOutputNode(l),this._mode=Gf.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Er("Position");e.setAsAttribute("position2d");const t=new Er("Constant1");t.isConstant=!0,t.value=1;const i=new Cj("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new vj("VertexOutput");i.connectTo(s);const r=new Er("Scale");r.visibleInInspector=!0,r.value=new lt(1,1);const n=new jG("uv0");e.connectTo(n);const o=new dX("UV scale");n.connectTo(o),r.connectTo(o);const l=new eee("CurrentScreen");o.connectTo(l),l.texture=new Te("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const c=new tI("FragmentOutput");l.connectTo(c,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(c),this._mode=Gf.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Er("Position");e.setAsAttribute("position2d");const t=new Er("Constant1");t.isConstant=!0,t.value=1;const i=new Cj("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new vj("VertexOutput");i.connectTo(s);const r=new Er("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=Z9.Time,r.isConstant=!1;const n=new Er("Color3");n.value=new Ie(1,1,1),n.isConstant=!1;const o=new tI("FragmentOutput"),l=new Cj("VectorMerger");l.visibleInInspector=!1;const c=new nee("Cos");c.operation=yh.Cos,e.connectTo(l),r.output.connectTo(c.input),c.output.connectTo(l.z),l.xyzOut.connectTo(o.rgb),this.addOutputNode(s),this.addOutputNode(o),this._mode=Gf.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Er("uv");e.setAsAttribute("particle_uv");const t=new tee("ParticleTexture");e.connectTo(t);const i=new Er("Color");i.setAsAttribute("particle_color");const s=new dX("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new iee("ParticleRampGradient");s.connectTo(r);const n=new ree("ColorSplitter");i.connectTo(n);const o=new see("ParticleBlendMultiply");r.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const l=new tI("FragmentOutput");o.connectTo(l),this.addOutputNode(l),this._mode=Gf.Particle}async loadAsync(e,t=""){return Pl.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 s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._gatherBlocks(r,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 n of this._vertexOutputNodes)this._gatherBlocks(n,t);const s=[];for(const n of this._fragmentOutputNodes)this._gatherBlocks(n,s);let r=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); +`;r+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${Gf[this.mode]}; +`;for(const n of t)n.isInput&&e.indexOf(n)===-1&&(r+=n._dumpCode(i,e));for(const n of s)n.isInput&&e.indexOf(n)===-1&&(r+=n._dumpCode(i,e));e=[],r+=` +// Connections +`;for(const n of this._vertexOutputNodes)r+=n._dumpCodeForOutputConnections(e);for(const n of this._fragmentOutputNodes)r+=n._dumpCodeForOutputConnections(e);r+=` +// Output nodes +`;for(const n of this._vertexOutputNodes)r+=`nodeMaterial.addOutputNode(${n._codeVariableName}); +`;for(const n of this._fragmentOutputNodes)r+=`nodeMaterial.addOutputNode(${n._codeVariableName}); +`;return r+=`nodeMaterial.build(); +`,r}serialize(e){const t=e?{}:Kt.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 s of this._vertexOutputNodes)this._gatherBlocks(s,i),t.outputNodes.push(s.uniqueId);for(const s of this._fragmentOutputNodes)this._gatherBlocks(s,i),t.outputNodes.indexOf(s.uniqueId)===-1&&t.outputNodes.push(s.uniqueId)}t.blocks=[];for(const s of i)t.blocks.push(s.serialize());if(!e)for(const s of this.attachedBlocks)i.indexOf(s)===-1&&t.blocks.push(s.serialize());return t}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(!!n){for(const o of r.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===s.name){const l=n.getInputByName(o.inputName);if(!l||l.isConnected)continue;s.connectTo(l,!0),this._restoreConnections(n,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){var s;i||this.clear();const r={};for(const n of e.blocks){const o=Bo(n.customType);if(o){const l=new o;l._deserialize(n,this.getScene(),t),r[n.id]=l,this.attachedBlocks.push(l)}}for(const n of this.attachedBlocks)if(n.isTeleportOut){const o=n,l=o._tempEntryPointUniqueId;l&&r[l].attachToEndpoint(o)}for(let n=0;nnew Pl(e,this.getScene(),this.options),this);return s.id=e,s.name=e,s.parseSerializedObject(i),s._buildId=this._buildId,s.build(!1,!t),s}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach(t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((s,r)=>{i.onLoadedObservable.addOnce(()=>{s()}),i.onErrorObservable.addOnce(n=>{r(n)})}))}),Promise.all(e)}static Parse(e,t,i=""){const s=Kt.Parse(()=>new Pl(e.name,t),e,t,i);return s.parseSerializedObject(e,i),s.build(),s}static async ParseFromFileAsync(e,t,i,s="",r=!1,n){const o=n??new Pl(e,i),l=await i._loadFileAsync(t),c=JSON.parse(l);return o.parseSerializedObject(c,s),r||o.build(),o}static ParseFromSnippetAsync(e,t=Ii.LastCreatedScene,i="",s,r=!1,n=!1){return e==="_BLANK"?Promise.resolve(Pl.CreateDefault("blank",t)):new Promise((o,l)=>{const c=new wl;c.addEventListener("readystatechange",()=>{if(c.readyState==4)if(c.status==200){const h=JSON.parse(JSON.parse(c.responseText).jsonPayload),u=JSON.parse(h.nodeMaterial);s||(s=Kt.Parse(()=>new Pl(e,t),u,t,i),s.uniqueId=t.getUniqueId()),s.parseSerializedObject(u),s.snippetId=e;try{r||s.build()}catch(p){l(p)}n?s.whenTexturesReadyAsync().then(()=>{o(s)}).catch(p=>{l(p)}):o(s)}else l("Unable to load the snippet "+e)}),c.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),c.send()})}static CreateDefault(e,t){const i=new Pl(e,t);return i.setToDefault(),i.build(),i}}Pl._BuildIdGenerator=0;Pl.EditorURL=`https://unpkg.com/babylonjs-node-editor@${He.Version}/babylon.nodeEditor.js`;Pl.SnippetUrl="https://snippet.babylonjs.com";Pl.IgnoreTexturesAtLoadTime=!1;z([X()],Pl.prototype,"ignoreAlpha",void 0);z([X()],Pl.prototype,"maxSimultaneousLights",void 0);z([X("mode")],Pl.prototype,"_mode",void 0);z([X("comment")],Pl.prototype,"comment",void 0);z([X()],Pl.prototype,"forceAlphaBlending",void 0);$e("BABYLON.NodeMaterial",Pl);function SK(a){const e=a.sideOrientation||Jt.DEFAULTSIDE,t=a.radius||1,i=a.flat===void 0?!0:a.flat,s=(a.subdivisions||4)|0,r=a.radiusX||t,n=a.radiusY||t,o=a.radiusZ||t,l=(1+Math.sqrt(5))/2,c=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,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],p=[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],m=138/1024,_=239/1024,f=60/1024,d=26/1024,C=-40/1024,v=20/1024,y=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],M=new Array,b=new Array,E=new Array,S=new Array;let I=0;const D=new Array(3),R=new Array(3);let L;for(L=0;L<3;L++)D[L]=O.Zero(),R[L]=lt.Zero();for(let N=0;N<20;N++){for(L=0;L<3;L++){const W=h[3*N+L];D[L].copyFromFloats(c[3*u[W]],c[3*u[W]+1],c[3*u[W]+2]),D[L].normalize(),R[L].copyFromFloats(p[2*W]*m+f+y[N]*C,p[2*W+1]*_+d+y[N]*v)}const V=(W,G,ie,Z)=>{const q=O.Lerp(D[0],D[2],G/s),K=O.Lerp(D[1],D[2],G/s),j=s===G?D[2]:O.Lerp(q,K,W/(s-G));j.normalize();let H;if(i){const re=O.Lerp(D[0],D[2],Z/s),ee=O.Lerp(D[1],D[2],Z/s);H=O.Lerp(re,ee,ie/(s-Z))}else H=new O(j.x,j.y,j.z);H.x/=r,H.y/=n,H.z/=o,H.normalize();const Y=lt.Lerp(R[0],R[2],G/s),J=lt.Lerp(R[1],R[2],G/s),te=s===G?R[2]:lt.Lerp(Y,J,W/(s-G));b.push(j.x*r,j.y*n,j.z*o),E.push(H.x,H.y,H.z),S.push(te.x,fn.UseOpenGLOrientationForUV?1-te.y:te.y),M.push(I),I++};for(let W=0;WZG(a,e,t);var U9;(function(a){a.WRIST="wrist",a.THUMB="thumb",a.INDEX="index",a.MIDDLE="middle",a.RING="ring",a.LITTLE="little"})(U9||(U9={}));var ks;(function(a){a.WRIST="wrist",a.THUMB_METACARPAL="thumb-metacarpal",a.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",a.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",a.THUMB_TIP="thumb-tip",a.INDEX_FINGER_METACARPAL="index-finger-metacarpal",a.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",a.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",a.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",a.INDEX_FINGER_TIP="index-finger-tip",a.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",a.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",a.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",a.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",a.MIDDLE_FINGER_TIP="middle-finger-tip",a.RING_FINGER_METACARPAL="ring-finger-metacarpal",a.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",a.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",a.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",a.RING_FINGER_TIP="ring-finger-tip",a.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",a.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",a.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",a.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",a.PINKY_FINGER_TIP="pinky-finger-tip"})(ks||(ks={}));const Lb=[ks.WRIST,ks.THUMB_METACARPAL,ks.THUMB_PHALANX_PROXIMAL,ks.THUMB_PHALANX_DISTAL,ks.THUMB_TIP,ks.INDEX_FINGER_METACARPAL,ks.INDEX_FINGER_PHALANX_PROXIMAL,ks.INDEX_FINGER_PHALANX_INTERMEDIATE,ks.INDEX_FINGER_PHALANX_DISTAL,ks.INDEX_FINGER_TIP,ks.MIDDLE_FINGER_METACARPAL,ks.MIDDLE_FINGER_PHALANX_PROXIMAL,ks.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ks.MIDDLE_FINGER_PHALANX_DISTAL,ks.MIDDLE_FINGER_TIP,ks.RING_FINGER_METACARPAL,ks.RING_FINGER_PHALANX_PROXIMAL,ks.RING_FINGER_PHALANX_INTERMEDIATE,ks.RING_FINGER_PHALANX_DISTAL,ks.RING_FINGER_TIP,ks.PINKY_FINGER_METACARPAL,ks.PINKY_FINGER_PHALANX_PROXIMAL,ks.PINKY_FINGER_PHALANX_INTERMEDIATE,ks.PINKY_FINGER_PHALANX_DISTAL,ks.PINKY_FINGER_TIP],q3e={[U9.WRIST]:[ks.WRIST],[U9.THUMB]:[ks.THUMB_METACARPAL,ks.THUMB_PHALANX_PROXIMAL,ks.THUMB_PHALANX_DISTAL,ks.THUMB_TIP],[U9.INDEX]:[ks.INDEX_FINGER_METACARPAL,ks.INDEX_FINGER_PHALANX_PROXIMAL,ks.INDEX_FINGER_PHALANX_INTERMEDIATE,ks.INDEX_FINGER_PHALANX_DISTAL,ks.INDEX_FINGER_TIP],[U9.MIDDLE]:[ks.MIDDLE_FINGER_METACARPAL,ks.MIDDLE_FINGER_PHALANX_PROXIMAL,ks.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ks.MIDDLE_FINGER_PHALANX_DISTAL,ks.MIDDLE_FINGER_TIP],[U9.RING]:[ks.RING_FINGER_METACARPAL,ks.RING_FINGER_PHALANX_PROXIMAL,ks.RING_FINGER_PHALANX_INTERMEDIATE,ks.RING_FINGER_PHALANX_DISTAL,ks.RING_FINGER_TIP],[U9.LITTLE]:[ks.PINKY_FINGER_METACARPAL,ks.PINKY_FINGER_PHALANX_PROXIMAL,ks.PINKY_FINGER_PHALANX_INTERMEDIATE,ks.PINKY_FINGER_PHALANX_DISTAL,ks.PINKY_FINGER_TIP]};class Wle{get handMesh(){return this._handMesh}getHandPartMeshes(e){return q3e[e].map(t=>this._jointMeshes[Lb.indexOf(t)])}getJointMesh(e){return this._jointMeshes[Lb.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=o,this._jointTransforms=new Array(Lb.length),this._jointTransformMatrices=new Float32Array(Lb.length*16),this._tempJointMatrix=new ge,this._jointRadii=new Float32Array(Lb.length),this._scene=t[0].getScene();for(let l=0;l{l.rootMesh&&l.rootMesh.setEnabled(!1)})),this.xrController.onMotionControllerInitObservable.add(l=>{l.onModelLoadedObservable.add(c=>{c.rootMesh&&c.rootMesh.setEnabled(!1)}),l.rootMesh&&l.rootMesh.setEnabled(!1)})}setHandMesh(e,t){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach(i=>i.alwaysSelectAsActiveMesh=!0),this._handMesh.skeleton){const i=this._handMesh.skeleton;Lb.forEach((s,r)=>{const n=i.getBoneIndexByName(t?t[s]:s);n!==-1&&i.bones[n].linkTransformNode(this._jointTransforms[r])})}}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=Lb.map(o=>s[o]||i.get(o));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){n=!0;for(let o=0;o{const c=this._jointTransforms[l];ge.FromArrayToRef(this._jointTransformMatrices,l*16,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,c.rotationQuaternion,c.position);const h=this._jointRadii[l]*this._jointScaleFactor,u=this._jointMeshes[l];u.isVisible=!this._handMesh&&!this._jointsInvisible,u.position.copyFrom(c.position),u.rotationQuaternion.copyFrom(c.rotationQuaternion),u.scaling.setAll(h),this._scene.useRightHandedSystem||(u.position.z*=-1,u.rotationQuaternion.z*=-1,u.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(c.position.z*=-1,c.rotationQuaternion.z*=-1,c.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}}class ha extends ku{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map(i=>{var s,r,n,o,l;const c=[],h=((s=e.jointMeshes)===null||s===void 0?void 0:s.sourceMesh)||ZG("jointParent",ha._ICOSPHERE_PARAMS);h.isVisible=!!(!((r=e.jointMeshes)===null||r===void 0)&&r.keepOriginalVisible);for(let u=0;u{var s,r,n,o,l;const c={};!((r=(s=ha._RightHandGLB)===null||s===void 0?void 0:s.meshes[1])===null||r===void 0)&&r.isDisposed()&&(ha._RightHandGLB=null),!((o=(n=ha._LeftHandGLB)===null||n===void 0?void 0:n.meshes[1])===null||o===void 0)&&o.isDisposed()&&(ha._LeftHandGLB=null);const h=!!(ha._RightHandGLB&&ha._LeftHandGLB),u=await Promise.all([ha._RightHandGLB||As.ImportMeshAsync("",ha.DEFAULT_HAND_MODEL_BASE_URL,ha.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),ha._LeftHandGLB||As.ImportMeshAsync("",ha.DEFAULT_HAND_MODEL_BASE_URL,ha.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);ha._RightHandGLB=u[0],ha._LeftHandGLB=u[1];const p=new Pl("handShader",e,{emitComments:!1});await p.loadAsync(ha.DEFAULT_HAND_MODEL_SHADER_URL),p.needDepthPrePass=!0,p.transparencyMode=Lt.MATERIAL_ALPHABLEND,p.alphaMode=2,p.build(!1);const m=Object.assign({base:Ie.FromInts(116,63,203),fresnel:Ie.FromInts(149,102,229),fingerColor:Ie.FromInts(177,130,255),tipFresnel:Ie.FromInts(220,200,255)},(l=t?.handMeshes)===null||l===void 0?void 0:l.customColors),_={base:p.getBlockByName("baseColor"),fresnel:p.getBlockByName("fresnelColor"),fingerColor:p.getBlockByName("fingerColor"),tipFresnel:p.getBlockByName("tipFresnelColor")};_.base.value=m.base,_.fresnel.value=m.fresnel,_.fingerColor.value=m.fingerColor,_.tipFresnel.value=m.tipFresnel,["left","right"].forEach(f=>{const d=f=="left"?ha._LeftHandGLB:ha._RightHandGLB;if(!d)throw new Error("Could not load hand model");const C=d.meshes[1];C._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,C.material=p.clone(`${f}HandShaderClone`,!0),C.isVisible=!1,c[f]=C,!h&&!e.useRightHandedSystem&&d.meshes[1].rotate(Fo.Y,Math.PI)}),p.dispose(),i({left:c.left,right:c.right})})}static _GenerateDefaultHandMeshRigMapping(e){const t=e=="right"?"R":"L";return{[ks.WRIST]:`wrist_${t}`,[ks.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[ks.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[ks.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[ks.THUMB_TIP]:`thumb_tip_${t}`,[ks.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[ks.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[ks.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[ks.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[ks.INDEX_FINGER_TIP]:`index_tip_${t}`,[ks.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[ks.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[ks.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[ks.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[ks.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[ks.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[ks.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[ks.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[ks.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[ks.RING_FINGER_TIP]:`ring_tip_${t}`,[ks.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[ks.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[ks.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[ks.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[ks.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.onHandAddedObservable=new Se,this.onHandRemovedObservable=new Se,this._attachHand=r=>{var n,o,l;if(!r.inputSource.hand||r.inputSource.handedness=="none"||!this._handResources.jointMeshes)return;const c=r.inputSource.handedness,h=new Wle(r,this._handResources.jointMeshes[c],this._handResources.handMeshes&&this._handResources.handMeshes[c],this._handResources.rigMappings&&this._handResources.rigMappings[c],(n=this.options.handMeshes)===null||n===void 0?void 0:n.meshesUseLeftHandedCoordinates,(o=this.options.jointMeshes)===null||o===void 0?void 0:o.invisible,(l=this.options.jointMeshes)===null||l===void 0?void 0:l.scaleFactor);this._attachedHands[r.uniqueId]=h,this._trackingHands[c]=h,this.onHandAddedObservable.notifyObservers(h)},this._detachHand=r=>{this._detachHandById(r.uniqueId)},this.xrNativeFeatureName="hand-tracking";const s=t.jointMeshes;if(s&&(typeof s.disableDefaultHandMesh<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=s.disableDefaultHandMesh),typeof s.handMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=s.handMeshes),typeof s.leftHandedSystemMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=s.leftHandedSystemMeshes),typeof s.rigMapping<"u")){t.handMeshes=t.handMeshes||{};const r={},n={};[[s.rigMapping.left,r],[s.rigMapping.right,n]].forEach(o=>{const l=o[0],c=o[1];l.forEach((h,u)=>{c[Lb[u]]=h})}),t.handMeshes.customRigMappings={left:r,right:n}}}attach(){var e,t,i,s;return super.attach()?(this._handResources={jointMeshes:ha._GenerateTrackedJointMeshes(this.options),handMeshes:((e=this.options.handMeshes)===null||e===void 0?void 0:e.customMeshes)||null,rigMappings:((t=this.options.handMeshes)===null||t===void 0?void 0:t.customRigMappings)||null},!(!((i=this.options.handMeshes)===null||i===void 0)&&i.customMeshes)&&!(!((s=this.options.handMeshes)===null||s===void 0)&&s.disableDefaultMeshes)&&ha._GenerateDefaultHandMeshesAsync(Ii.LastCreatedScene,this.options).then(r=>{var n,o;this._handResources.handMeshes=r,this._handResources.rigMappings={left:ha._GenerateDefaultHandMeshRigMapping("left"),right:ha._GenerateDefaultHandMeshRigMapping("right")},(n=this._trackingHands.left)===null||n===void 0||n.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left),(o=this._trackingHands.right)===null||o===void 0||o.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right)}),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===void 0||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),(i=this._trackingHands.right)===null||i===void 0||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e){var t;const i=this.getHandByControllerId(e);if(i){const s=i.xrController.inputSource.handedness=="left"?"left":"right";((t=this._trackingHands[s])===null||t===void 0?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[s]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(),delete this._attachedHands[e]}}detach(){return super.detach()?(Object.keys(this._attachedHands).forEach(e=>this._detachHandById(e)),!0):!1}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!(!((e=this.options.handMeshes)===null||e===void 0)&&e.customMeshes)&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),ha._RightHandGLB=null,ha._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose()))}}ha.Name=$r.HAND_TRACKING;ha.Version=1;ha.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/";ha.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb";ha.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb";ha.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json";ha._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2};ha._RightHandGLB=null;ha._LeftHandGLB=null;_l.AddWebXRFeature(ha.Name,(a,e)=>()=>new ha(a,e),ha.Version,!1);var mL;(function(a){a[a.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",a[a.RADIAL_SIDE=1]="RADIAL_SIDE",a[a.ULNAR_SIDE=2]="ULNAR_SIDE",a[a.BELOW_WRIST=3]="BELOW_WRIST"})(mL||(mL={}));var k9;(function(a){a[a.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",a[a.HAND_ROTATION=1]="HAND_ROTATION"})(k9||(k9={}));var _L;(function(a){a[a.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",a[a.PALM_UP=1]="PALM_UP",a[a.GAZE_FOCUS=2]="GAZE_FOCUS",a[a.PALM_AND_GAZE=3]="PALM_AND_GAZE"})(_L||(_L={}));class Yle{constructor(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=_L.PALM_AND_GAZE,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=mL.ULNAR_SIDE,this.zoneOrientationMode=k9.HAND_ROTATION,this.nodeOrientationMode=k9.HAND_ROTATION,this.handedness="none",this.lerpTime=100,this._zoneAxis[mL.ABOVE_FINGER_TIPS]=new O(0,1,0),this._zoneAxis[mL.RADIAL_SIDE]=new O(-1,0,0),this._zoneAxis[mL.ULNAR_SIDE]=new O(1,0,0),this._zoneAxis[mL.BELOW_WRIST]=new O(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(ks.PINKY_FINGER_METACARPAL),i=e.getJointMesh(ks.MIDDLE_FINGER_METACARPAL),s=e.getJointMesh(ks.WRIST);if(s&&i&&t){const r={position:i.absolutePosition,quaternion:new ke,id:e.xrController.uniqueId},n=ue.Vector3[0],o=ue.Vector3[1],l=ue.Vector3[2];return n.copyFrom(i.absolutePosition).subtractInPlace(s.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),O.CrossToRef(n,o,o),O.CrossToRef(o,n,l),ke.FromLookDirectionLHToRef(o,n,r.quaternion),r}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=ke.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 s=ue.Vector3[0],r=this._scene.activeCamera;s.copyFrom(this._zoneAxis[this.targetZone]);const n=ue.Quaternion[0];if(r&&(this.zoneOrientationMode===k9.LOOK_AT_CAMERA||this.nodeOrientationMode===k9.LOOK_AT_CAMERA)){const h=ue.Vector3[1];h.copyFrom(r.position).subtractInPlace(i.position).normalize(),this._scene.useRightHandedSystem?ke.FromLookDirectionRHToRef(h,O.UpReadOnly,n):ke.FromLookDirectionLHToRef(h,O.UpReadOnly,n)}this.zoneOrientationMode===k9.HAND_ROTATION?i.quaternion.toRotationMatrix(ue.Matrix[0]):n.toRotationMatrix(ue.Matrix[0]),O.TransformNormalToRef(s,ue.Matrix[0],s),s.scaleInPlace(this.targetOffset);const o=ue.Vector3[2],l=ue.Quaternion[1];o.copyFrom(i.position).addInPlace(s),this.nodeOrientationMode===k9.HAND_ROTATION?l.copyFrom(i.quaternion):l.copyFrom(n);const c=Date.now()-t;O.SmoothToRef(this._node.position,o,c,this.lerpTime,this._node.position),ke.SmoothToRef(this._node.rotationQuaternion,l,c,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 s=this._scene.activeCamera;if(s){const r=s.getForwardRay();if(this.handConstraintVisibility===_L.GAZE_FOCUS||this.handConstraintVisibility===_L.PALM_AND_GAZE){i=!1;let n;this._eyeTracking&&(n=this._eyeTracking.getEyeGaze()),n=n||r;const o=ue.Vector3[0];e?e.position.subtractToRef(n.origin,o):this._node.getAbsolutePosition().subtractToRef(n.origin,o);const l=O.Dot(o,n.direction),c=l*l;l>0&&o.lengthSquared()-cthis.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)Be.Error("XR features manager must be available or provided directly for the Hand Menu to work");else{try{this._eyeTracking=t.getEnabledFeature($r.EYE_TRACKING)}catch{}try{this._handTracking=t.getEnabledFeature($r.HAND_TRACKING)}catch{Be.Error("Hand tracking must be enabled for the Hand Menu to work")}}}}class h_{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=O.Zero(),this.poleTargetPosition=O.Zero(),this.poleTargetLocalOffset=O.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=ke.Identity(),this._bone1Mat=ge.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=O.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const s=t.getParent();if(!s){this._notEnoughInformation=!0,Me.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=s,this._bone2.children.length===0&&!this._bone2.length){this._notEnoughInformation=!0,Me.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 r=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,r.x>r.y&&r.x>r.z&&(this._adjustRoll=Math.PI*.5,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const n=this._bone1.getScale(),o=this._bone2.getScale();this._bone1Length=this._bone1.length*n.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 n=this._bone2.children[0].getAbsolutePosition(e),o=this._bone2.getAbsolutePosition(e),l=this._bone1.getAbsolutePosition(e);this._bone2Length=O.Distance(n,o),this._bone1Length=O.Distance(o,l)}else{e.computeWorldMatrix(!0);const n=this._bone2.getScale();this._bone2Length=this._bone2.length*n.y*this.mesh.scaling.y;const o=this._bone2.getAbsolutePosition(e),l=this._bone1.getAbsolutePosition(e);this._bone1Length=O.Distance(o,l)}this._bone1.getRotationMatrixToRef(sr.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=h_._TmpMats[0],s=h_._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&O.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const r=h_._TmpVecs[0],n=h_._TmpVecs[1],o=h_._TmpVecs[2],l=h_._TmpVecs[3],c=h_._TmpVecs[4],h=h_._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,r),t.subtractToRef(r,c),c.x==0&&c.y==0&&c.z==0?c.y=1:c.normalize(),e.subtractToRef(r,l),l.normalize(),O.CrossToRef(l,c,n),n.normalize(),O.CrossToRef(l,n,o),o.normalize(),ge.FromXYZAxesToRef(o,l,n,i);const u=this._bone1Length,p=this._bone2Length;let m=O.Distance(r,e);this._maxReach>0&&(m=Math.min(this._maxReach,m));let _=(p*p+m*m-u*u)/(2*p*m),f=(m*m+u*u-p*p)/(2*m*u);_>1&&(_=1),f>1&&(f=1),_<-1&&(_=-1),f<-1&&(f=-1);const d=Math.acos(_),C=Math.acos(f);let v=-d-C;if(this._rightHandedSystem)ge.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(i,i),ge.RotationAxisToRef(this._bendAxis,C,s),s.multiplyToRef(i,i);else{const y=h_._TmpVecs[5];y.copyFrom(this._bendAxis),y.x*=-1,ge.RotationAxisToRef(y,-C,s),s.multiplyToRef(i,i)}this.poleAngle&&(ge.RotationAxisToRef(l,this.poleAngle,s),i.multiplyToRef(s,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||ke.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),ke.FromRotationMatrixToRef(i,h),ke.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),v=this._bone2Ang*(1-this.slerpAmount)+v*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,sr.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,sr.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,v,sr.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=v}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new ke),e.getRotationQuaternionToRef(sr.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}h_._TmpVecs=[O.Zero(),O.Zero(),O.Zero(),O.Zero(),O.Zero(),O.Zero()];h_._TmpQuat=ke.Identity();h_._TmpMats=[ge.Identity(),ge.Identity()];class Wd{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,s){if(this.upAxis=O.Up(),this.upAxisSpace=sr.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=ke.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=O.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,s){if(s.adjustYaw&&(this.adjustYaw=s.adjustYaw),s.adjustPitch&&(this.adjustPitch=s.adjustPitch),s.adjustRoll&&(this.adjustRoll=s.adjustRoll),s.maxYaw!=null?this.maxYaw=s.maxYaw:this.maxYaw=Math.PI,s.minYaw!=null?this.minYaw=s.minYaw:this.minYaw=-Math.PI,s.maxPitch!=null?this.maxPitch=s.maxPitch:this.maxPitch=Math.PI,s.minPitch!=null?this.minPitch=s.minPitch:this.minPitch=-Math.PI,s.slerpAmount!=null&&(this.slerpAmount=s.slerpAmount),s.upAxis!=null&&(this.upAxis=s.upAxis),s.upAxisSpace!=null&&(this.upAxisSpace=s.upAxisSpace),s.yawAxis!=null||s.pitchAxis!=null){let r=Fo.Y,n=Fo.X;s.yawAxis!=null&&(r=s.yawAxis.clone(),r.normalize()),s.pitchAxis!=null&&(n=s.pitchAxis.clone(),n.normalize());const o=O.Cross(n,r);this._transformYawPitch=ge.Identity(),ge.FromXYZAxesToRef(n,r,o,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}s.useAbsoluteValueForYaw!==void 0&&(this.useAbsoluteValueForYaw=s.useAbsoluteValueForYaw)}!t.getParent()&&this.upAxisSpace==sr.BONE&&(this.upAxisSpace=sr.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped){this._firstFrameSkipped=!0;return}const e=this.bone,t=Wd._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const s=Wd._TmpMats[0],r=Wd._TmpMats[1],n=this.mesh,o=e.getParent(),l=Wd._TmpVecs[1];l.copyFrom(this.upAxis),this.upAxisSpace==sr.BONE&&o?(this._transformYawPitch&&O.TransformCoordinatesToRef(l,this._transformYawPitchInv,l),o.getDirectionToRef(l,this.mesh,l)):this.upAxisSpace==sr.LOCAL&&(n.getDirectionToRef(l,l),(n.scaling.x!=1||n.scaling.y!=1||n.scaling.z!=1)&&l.normalize());let c=!1,h=!1;if((this._maxYaw!=Math.PI||this._minYaw!=-Math.PI)&&(c=!0),(this._maxPitch!=Math.PI||this._minPitch!=-Math.PI)&&(h=!0),c||h){const f=Wd._TmpMats[2],d=Wd._TmpMats[3];if(this.upAxisSpace==sr.BONE&&l.y==1&&o)o.getRotationMatrixToRef(sr.WORLD,this.mesh,f);else if(this.upAxisSpace==sr.LOCAL&&l.y==1&&!o)f.copyFrom(n.getWorldMatrix());else{let v=Wd._TmpVecs[2];v.copyFrom(this._fowardAxis),this._transformYawPitch&&O.TransformCoordinatesToRef(v,this._transformYawPitchInv,v),o?o.getDirectionToRef(v,this.mesh,v):n.getDirectionToRef(v,v);const y=O.Cross(l,v);y.normalize(),v=O.Cross(y,l),ge.FromXYZAxesToRef(y,l,v,f)}f.invertToRef(d);let C=null;if(h){const v=Wd._TmpVecs[3];i.subtractToRef(t,v),O.TransformCoordinatesToRef(v,d,v),C=Math.sqrt(v.x*v.x+v.z*v.z);const y=Math.atan2(v.y,C);let M=y;y>this._maxPitch?(v.y=this._maxPitchTan*C,M=this._maxPitch):ythis._maxYaw||MMath.PI?this._isAngleBetween(y,this._maxYaw,this._midYawConstraint)?(v.z=this._maxYawCos*C,v.x=this._maxYawSin*C,b=this._maxYaw):this._isAngleBetween(y,this._midYawConstraint,this._minYaw)&&(v.z=this._minYawCos*C,v.x=this._minYawSin*C,b=this._minYaw):M>this._maxYaw?(v.z=this._maxYawCos*C,v.x=this._maxYawSin*C,y<0&&this.useAbsoluteValueForYaw&&(v.x*=-1),b=this._maxYaw):MMath.PI){const E=Wd._TmpVecs[8];E.copyFrom(Fo.Z),this._transformYawPitch&&O.TransformCoordinatesToRef(E,this._transformYawPitchInv,E);const S=Wd._TmpMats[4];this._boneQuat.toRotationMatrix(S),this.mesh.getWorldMatrix().multiplyToRef(S,S),O.TransformCoordinatesToRef(E,S,E),O.TransformCoordinatesToRef(E,d,E);const I=Math.atan2(E.x,E.z),D=this._getAngleBetween(I,y),R=this._getAngleBetween(I,this._midYawConstraint);if(D>R){C==null&&(C=Math.sqrt(v.x*v.x+v.z*v.z));const L=this._getAngleBetween(I,this._maxYaw);this._getAngleBetween(I,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&&e0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){return this.needInitialSkinMatrix?(e._bonesTransformMatrices||this.prepare(),e._bonesTransformMatrices):((!this._transformMatrices||this._isDirty)&&this.prepare(),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 s in this._ranges)i&&(t+=", ",i=!1),t+=s;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 s=this._isDirty;if((!t._bonesTransformMatrices||t._bonesTransformMatrices.length!==16*(this.bones.length+1))&&(t._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),s=!0),!!s){if(this._synchronizedWithMesh!==t){this._synchronizedWithMesh=t;for(const r of this.bones)r.getParent()||(r.getBindMatrix().multiplyToRef(i,ue.Matrix[1]),r._updateAbsoluteBindMatrices(ue.Matrix[1]));if(this.isUsingTextureForMatrices){const r=(this.bones.length+1)*4;(!t._transformMatrixTexture||t._transformMatrixTexture.getSize().width!==r)&&(t._transformMatrixTexture&&t._transformMatrixTexture.dispose(),t._transformMatrixTexture=Ya.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=Ya.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 e;const t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(n.animation=s.animations[0].serialize()),t.ranges=[];for(const o in this._ranges){const l=this._ranges[o];if(!l)continue;const c={};c.name=o,c.from=l.from,c.to=l.to,t.ranges.push(c)}}return t}static Parse(e,t){const i=new qM(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=O.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix;let s;for(s=0;s-1&&(o=i.bones[r.parentBoneIndex]);const l=r.rest?ge.FromArray(r.rest):null,c=new ca(r.name,i,o,ge.FromArray(r.matrix),l,null,n);r.id!==void 0&&r.id!==null&&(c.id=r.id),r.length&&(c.length=r.length),r.metadata&&(c.metadata=r.metadata),r.animation&&c.animations.push(at.Parse(r.animation)),r.linkedTransformNodeId!==void 0&&r.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,c._waitingTransformNodeId=r.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=new Array,t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}}class Xle{constructor(e,t,i=3){this._engine=e,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){!this._buffer||this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i){return this._engine.readFromStorageBuffer(this._buffer,e,t,i)}dispose(){const e=this._engine._storageBuffers,t=e.indexOf(this);t!==-1&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}}class qG{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new Se,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=Be.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==mi.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===rD.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,mi.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"}}z([X()],qG.prototype,"wheelPrecisionX",void 0);z([X()],qG.prototype,"wheelPrecisionY",void 0);z([X()],qG.prototype,"wheelPrecisionZ",void 0);class IK{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Be.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=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 l,c;const h=o.event,u=h.pointerType==="touch";if(t.isInVRExclusivePointerMode||o.type!==mi.POINTERMOVE&&this.buttons.indexOf(h.button)===-1)return;const p=h.target;if(this._altKey=h.altKey,this._ctrlKey=h.ctrlKey,this._metaKey=h.metaKey,this._shiftKey=h.shiftKey,this._buttonsPressed=h.buttons,t.isPointerLock){const m=h.movementX,_=h.movementY;this.onTouch(null,m,_),this._pointA=null,this._pointB=null}else{if(o.type!==mi.POINTERDOWN&&u&&((l=this._pointA)===null||l===void 0?void 0:l.pointerId)!==h.pointerId&&((c=this._pointB)===null||c===void 0?void 0:c.pointerId)!==h.pointerId)return;if(o.type===mi.POINTERDOWN&&(this._currentActiveButton===-1||u)){try{p?.setPointerCapture(h.pointerId)}catch{}if(this._pointA===null)this._pointA={x:h.clientX,y:h.clientY,pointerId:h.pointerId,type:h.pointerType};else if(this._pointB===null)this._pointB={x:h.clientX,y:h.clientY,pointerId:h.pointerId,type:h.pointerType};else return;this._currentActiveButton===-1&&!u&&(this._currentActiveButton=h.button),this.onButtonDown(h),e||(h.preventDefault(),i&&i.focus())}else if(o.type===mi.POINTERDOUBLETAP)this.onDoubleTap(h.pointerType);else if(o.type===mi.POINTERUP&&(this._currentActiveButton===h.button||u)){try{p?.releasePointerCapture(h.pointerId)}catch{}u||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==h.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==h.pointerId?this._pointB=null:this._pointA=this._pointB=null,(s!==0||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(h),e||h.preventDefault()}else if(o.type===mi.POINTERMOVE){if(e||h.preventDefault(),this._pointA&&this._pointB===null){const m=h.clientX-this._pointA.x,_=h.clientY-this._pointA.y;this.onTouch(this._pointA,m,_),this._pointA.x=h.clientX,this._pointA.y=h.clientY}else if(this._pointA&&this._pointB){const m=this._pointA.pointerId===h.pointerId?this._pointA:this._pointB;m.x=h.clientX,m.y=h.clientY;const _=this._pointA.x-this._pointB.x,f=this._pointA.y-this._pointB.y,d=_*_+f*f,C={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:h.pointerId,type:o.type};this.onMultiTouch(this._pointA,this._pointB,s,d,r,C),r=C,s=d}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,mi.POINTERDOWN|mi.POINTERUP|mi.POINTERMOVE|mi.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=this.onContextMenu.bind(this),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Be.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Be.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,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}z([X()],IK.prototype,"buttons",void 0);var i1={};class JG{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();if(this.attached[t]){Me.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=Pi.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 s=this.attached[i],r=Kt.Serialize(s);t[s.getClassName()]=r}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const i in t){const s=i1[i];if(s){const r=t[i],n=Kt.Parse(()=>new s,r,null);this.add(n)}}}else for(const i in this.attached){const s=i1[this.attached[i].getClassName()];if(s){const r=Kt.Parse(()=>new s,e,null);this.remove(this.attached[i]),this.add(r)}}}}class J3e{constructor(e,t){this.x=e,this.y=t}}class fc{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=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=fc.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,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(){}}fc.GAMEPAD=0;fc.GENERIC=1;fc.XBOX=2;fc.POSE_ENABLED=3;fc.DUALSHOCK=4;class Kle extends fc{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new Se,this.onButtonUpObservable=new Se,this.type=fc.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!==fc.POSE_ENABLED&&(!this.gamepad||t.type===fc.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(fc.XBOX)}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 s=t.x/this.gamepadRotationSensibility;s!=0&&Math.abs(s)>.005&&(e.inertialAlphaOffset+=s)}if(t.y!=0){const s=t.y/this.gamepadRotationSensibility*this._yAxisScale;s!=0&&Math.abs(s)>.005&&(e.inertialBetaOffset+=s)}}const i=this.gamepad.leftStick;if(i&&i.y!=0){const s=i.y/this.gamepadMoveSensibility;s!=0&&Math.abs(s)>.005&&(this.camera.inertialRadiusOffset-=s)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}z([X()],$G.prototype,"gamepadRotationSensibility",void 0);z([X()],$G.prototype,"gamepadMoveSensibility",void 0);i1.ArcRotateCameraGamepadInput=$G;class pC{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=Be.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===i7.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 s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,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=s/(1+this.wheelDeltaPercentage):i=s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Be.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==mi.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===rD.DOM_DELTA_LINE?$3e:1,n=-(i.deltaY*r);if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let o=this.camera.radius,l=this.camera.inertialRadiusOffset+s;for(let c=0;c<20&&Math.abs(l)>.001;c++)o-=l,l*=this.camera.inertia;o=Bt.Clamp(o,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,o)}}else s=n/(this.wheelPrecision*40);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,mi.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=Zd.FromPositionAndNormal(e.target,t)}_getPosition(){var e;const t=this.camera,i=t.getScene(),s=i.createPickingRay(i.pointerX,i.pointerY,ge.Identity(),t,!1);(t.targetScreenOffset.x!==0||t.targetScreenOffset.y!==0)&&(this._viewOffset.set(t.targetScreenOffset.x,t.targetScreenOffset.y,0),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),this._globalOffset=O.TransformNormal(this._viewOffset,t._cameraTransformMatrix),s.origin.addInPlace(this._globalOffset));let r=0;return this._hitPlane&&(r=(e=s.intersectsPlane(this._hitPlane))!==null&&e!==void 0?e:0),s.origin.addInPlace(s.direction.scaleInPlace(r))}_zoomToMouse(e){var t,i;const s=this.camera,r=1-s.inertia;if(s.lowerRadiusLimit){const h=(t=s.lowerRadiusLimit)!==null&&t!==void 0?t:0;s.radius-(s.inertialRadiusOffset+e)/rh&&(e=(s.radius-h)*r-s.inertialRadiusOffset)}const o=e/r/s.radius,l=this._getPosition(),c=ue.Vector3[6];l.subtractToRef(s.target,c),c.scaleInPlace(o),c.scaleInPlace(r),this._inertialPanning.addInPlace(c),s.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}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}}x0.MinimumRadiusForPinch=.001;z([X()],x0.prototype,"buttons",void 0);z([X()],x0.prototype,"angularSensibilityX",void 0);z([X()],x0.prototype,"angularSensibilityY",void 0);z([X()],x0.prototype,"pinchPrecision",void 0);z([X()],x0.prototype,"pinchDeltaPercentage",void 0);z([X()],x0.prototype,"useNaturalPinchZoom",void 0);z([X()],x0.prototype,"pinchZoom",void 0);z([X()],x0.prototype,"panningSensibility",void 0);z([X()],x0.prototype,"multiTouchPanning",void 0);z([X()],x0.prototype,"multiTouchPanAndZoom",void 0);i1.ArcRotateCameraPointersInput=x0;class LK extends JG{constructor(e){super(e)}addMouseWheel(){return this.add(new SF),this}addPointers(){return this.add(new x0),this}addKeyboard(){return this.add(new pC),this}}LK.prototype.addVRDeviceOrientation=function(){return this.add(new aee),this};class aee{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=this._onOrientationEvent.bind(this)}attachControl(e){e=Be.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):Be.Warn("Permission not granted.")}).catch(i=>{Be.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"}}i1.ArcRotateCameraVRDeviceOrientationInput=aee;class OI{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=Be.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===i7.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 s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,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)},mi.POINTERDOWN|mi.POINTERUP|mi.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,s=this.camera.getEngine();if(s.isInVRExclusivePointerMode||!this.touchEnabled&&t.pointerType==="touch"||e.type!==mi.POINTERMOVE&&this.buttons.indexOf(t.button)===-1)return;const r=t.target;if(e.type===mi.POINTERDOWN){try{r?.setPointerCapture(t.pointerId)}catch{}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),s.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===mi.POINTERUP){try{r?.releasePointerCapture(t.pointerId)}catch{}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===mi.POINTERMOVE){if(!this._previousPosition){s.isPointerLock&&this._onMouseMove(e.event);return}const n=t.clientX-this._previousPosition.x,o=t.clientY-this._previousPosition.y;this._rotateCamera(n,o),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){const i=this.camera.getEngine();if(!i.isPointerLock||i.isInVRExclusivePointerMode)return;const s=e.movementX,r=e.movementY;this._rotateCamera(s,r),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,s=i._calculateHandednessMultiplier();e*=s;const r=e/this.angularSensibility,n=t/this.angularSensibility,o=ke.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let l;if(this.buttonsPitch.some(c=>c===this.activeButton)&&(l=ke.RotationAxis(Fo.X,n),o.multiplyInPlace(l)),this.buttonsYaw.some(c=>c===this.activeButton)){l=ke.RotationAxis(Fo.Y,r),o.multiplyInPlace(l);const c=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-cc===this.activeButton)&&(l=ke.RotationAxis(Fo.Z,-r),i._trackRoll-=r,o.multiplyInPlace(l)),o.toEulerAnglesToRef(i.rotation)}}z([X()],eW.prototype,"buttons",void 0);z([X()],eW.prototype,"angularSensibility",void 0);i1.FlyCameraMouseInput=eW;class Ad{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=Be.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===i7.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 s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,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}}z([X()],Ad.prototype,"keysHeightOffsetIncr",void 0);z([X()],Ad.prototype,"keysHeightOffsetDecr",void 0);z([X()],Ad.prototype,"keysHeightOffsetModifierAlt",void 0);z([X()],Ad.prototype,"keysHeightOffsetModifierCtrl",void 0);z([X()],Ad.prototype,"keysHeightOffsetModifierShift",void 0);z([X()],Ad.prototype,"keysRotationOffsetIncr",void 0);z([X()],Ad.prototype,"keysRotationOffsetDecr",void 0);z([X()],Ad.prototype,"keysRotationOffsetModifierAlt",void 0);z([X()],Ad.prototype,"keysRotationOffsetModifierCtrl",void 0);z([X()],Ad.prototype,"keysRotationOffsetModifierShift",void 0);z([X()],Ad.prototype,"keysRadiusIncr",void 0);z([X()],Ad.prototype,"keysRadiusDecr",void 0);z([X()],Ad.prototype,"keysRadiusModifierAlt",void 0);z([X()],Ad.prototype,"keysRadiusModifierCtrl",void 0);z([X()],Ad.prototype,"keysRadiusModifierShift",void 0);z([X()],Ad.prototype,"heightSensibility",void 0);z([X()],Ad.prototype,"rotationSensibility",void 0);z([X()],Ad.prototype,"radiusSensibility",void 0);i1.FollowCameraKeyboardMoveInput=Ad;class YL{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Be.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==mi.POINTERWHEEL)return;const i=t.event;let s=0;const r=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(console.assert(this.axisControlRadius+this.axisControlHeight+this.axisControlRotation<=1,"wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?s=r*.01*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?s=r*.01*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(s=r*.01*this.wheelDeltaPercentage*this.camera.rotationOffset)):s=r*this.wheelPrecision,s&&(this.axisControlRadius?this.camera.radius+=s:this.axisControlHeight?this.camera.heightOffset-=s:this.axisControlRotation&&(this.camera.rotationOffset-=s)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,mi.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}z([X()],YL.prototype,"axisControlRadius",void 0);z([X()],YL.prototype,"axisControlHeight",void 0);z([X()],YL.prototype,"axisControlRotation",void 0);z([X()],YL.prototype,"wheelPrecision",void 0);z([X()],YL.prototype,"wheelDeltaPercentage",void 0);i1.FollowCameraMouseWheelInput=YL;class b0 extends IK{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,s,r,n){if(i===0&&r===null||s===0&&n===null)return;let o=(s-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: ";console.assert(this.axisXControlRotation+this.axisXControlHeight+this.axisXControlRadius<=1,e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),console.assert(this.axisYControlRotation+this.axisYControlHeight+this.axisYControlRadius<=1,e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),console.assert(this.axisPinchControlRotation+this.axisPinchControlHeight+this.axisPinchControlRadius<=1,e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}z([X()],b0.prototype,"angularSensibilityX",void 0);z([X()],b0.prototype,"angularSensibilityY",void 0);z([X()],b0.prototype,"pinchPrecision",void 0);z([X()],b0.prototype,"pinchDeltaPercentage",void 0);z([X()],b0.prototype,"axisXControlRadius",void 0);z([X()],b0.prototype,"axisXControlHeight",void 0);z([X()],b0.prototype,"axisXControlRotation",void 0);z([X()],b0.prototype,"axisYControlRadius",void 0);z([X()],b0.prototype,"axisYControlHeight",void 0);z([X()],b0.prototype,"axisYControlRotation",void 0);z([X()],b0.prototype,"axisPinchControlRadius",void 0);z([X()],b0.prototype,"axisPinchControlHeight",void 0);z([X()],b0.prototype,"axisPinchControlRotation",void 0);i1.FollowCameraPointersInput=b0;class y_{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=Be.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===i7.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 s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,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 r=s.event,n=r.pointerType==="touch";if(t.isInVRExclusivePointerMode||!this.touchEnabled&&n||s.type!==mi.POINTERMOVE&&this.buttons.indexOf(r.button)===-1)return;const o=r.target;if(s.type===mi.POINTERDOWN){if(n&&this._activePointerId!==-1||!n&&this._currentActiveButton!==-1)return;this._activePointerId=r.pointerId;try{o?.setPointerCapture(r.pointerId)}catch{}this._currentActiveButton===-1&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===mi.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{o?.releasePointerCapture(r.pointerId)}catch{}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===mi.POINTERMOVE&&(this._activePointerId===r.pointerId||!n)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const l=this.camera._calculateHandednessMultiplier(),c=(r.clientX-this._previousPosition.x)*l,h=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=c/this.angularSensibility,this.camera.cameraRotation.x+=h/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:c,offsetY:h}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}}),this._onMouseMove=s=>{if(!t.isPointerLock||t.isInVRExclusivePointerMode)return;const r=this.camera._calculateHandednessMultiplier(),n=s.movementX*r;this.camera.cameraRotation.y+=n/this.angularSensibility;const o=s.movementY;this.camera.cameraRotation.x+=o/this.angularSensibility,this._previousPosition=null,e||s.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,mi.POINTERDOWN|mi.POINTERUP|mi.POINTERMOVE),i&&(this._contextMenuBind=this.onContextMenu.bind(this),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"}}z([X()],tW.prototype,"buttons",void 0);z([X()],tW.prototype,"angularSensibility",void 0);i1.FreeCameraMouseInput=tW;var co;(function(a){a[a.MoveRelative=0]="MoveRelative",a[a.RotateRelative=1]="RotateRelative",a[a.MoveScene=2]="MoveScene"})(co||(co={}));class mC extends qG{constructor(){super(...arguments),this._moveRelative=O.Zero(),this._rotateRelative=O.Zero(),this._moveScene=O.Zero(),this._wheelXAction=co.MoveRelative,this._wheelXActionCoordinate=pL.X,this._wheelYAction=co.MoveRelative,this._wheelYActionCoordinate=pL.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==co.MoveRelative||(this._wheelXAction=co.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==co.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==co.MoveRelative||(this._wheelYAction=co.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==co.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==co.MoveRelative||(this._wheelZAction=co.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==co.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==co.RotateRelative||(this._wheelXAction=co.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==co.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==co.RotateRelative||(this._wheelYAction=co.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==co.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==co.RotateRelative||(this._wheelZAction=co.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==co.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==co.MoveScene||(this._wheelXAction=co.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==co.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==co.MoveScene||(this._wheelYAction=co.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==co.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==co.MoveScene||(this._wheelZAction=co.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==co.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=ge.Zero();this.camera.getViewMatrix().invertToRef(e);const t=O.Zero();O.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 s=null;switch(t){case co.MoveRelative:s=this._moveRelative;break;case co.RotateRelative:s=this._rotateRelative;break;case co.MoveScene:s=this._moveScene;break}switch(i){case pL.X:s.set(e,0,0);break;case pL.Y:s.set(0,e,0);break;case pL.Z:s.set(0,0,e);break}}}z([X()],mC.prototype,"wheelXMoveRelative",null);z([X()],mC.prototype,"wheelYMoveRelative",null);z([X()],mC.prototype,"wheelZMoveRelative",null);z([X()],mC.prototype,"wheelXRotateRelative",null);z([X()],mC.prototype,"wheelYRotateRelative",null);z([X()],mC.prototype,"wheelZRotateRelative",null);z([X()],mC.prototype,"wheelXMoveScene",null);z([X()],mC.prototype,"wheelYMoveScene",null);z([X()],mC.prototype,"wheelZMoveScene",null);i1.FreeCameraMouseWheelInput=mC;class iW{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=Be.IsSafari()}attachControl(e){e=Be.BackCompatCameraNoPreventDefault(arguments);let t=null;if(this._pointerInput===void 0&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,r=s.pointerType==="mouse"||this._isSafari&&typeof s.pointerType>"u";if(!(!this.allowMouse&&r)){if(i.type===mi.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),this._pointerPressed.length!==1)return;t={x:s.clientX,y:s.clientY}}else if(i.type===mi.POINTERUP){e||s.preventDefault();const n=this._pointerPressed.indexOf(s.pointerId);if(n===-1||(this._pointerPressed.splice(n,1),n!=0))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===mi.POINTERMOVE){if(e||s.preventDefault(),!t||this._pointerPressed.indexOf(s.pointerId)!=0)return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,mi.POINTERDOWN|mi.POINTERUP|mi.POINTERMOVE),this._onLostFocus){const s=this.camera.getEngine().getInputElement();s&&s.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 s=e._computeLocalCameraSpeed(),r=new O(0,0,this.touchMoveSensibility!==0?s*this._offsetY/this.touchMoveSensibility:0);ge.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(O.TransformCoordinates(r,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}z([X()],iW.prototype,"touchAngularSensibility",void 0);z([X()],iW.prototype,"touchMoveSensibility",void 0);i1.FreeCameraTouchInput=iW;class sW extends JG{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new y_),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new tW(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new mC,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new iW),this}clear(){super.clear(),this._mouseInput=null}}sW.prototype.addDeviceOrientation=function(a){return this._deviceOrientationInput||(this._deviceOrientationInput=new oee,a&&(this._deviceOrientationInput.smoothFactor=a),this.add(this._deviceOrientationInput)),this};class oee{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let s=!1;const r=()=>{window.removeEventListener("deviceorientation",r),s=!0,t()};e&&setTimeout(()=>{s||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))},e),typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(n=>{n=="granted"?window.addEventListener("deviceorientation",r):Be.Warn("Permission not granted.")}).catch(n=>{Be.Error(n)}):window.addEventListener("deviceorientation",r)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new ke,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new Se,this._orientationChanged=()=>{this._screenOrientationAngle=window.orientation!==void 0?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Be.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?Be.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=e.beta!==null?Be.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=e.gamma!==null?Be.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 ke(-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 ke),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():Be.Warn("Permission not granted.")}).catch(i=>{Be.Error(i)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){!this._alpha||(ke.RotationYawPitchRollToRef(Be.ToRadians(this._alpha),Be.ToRadians(this._beta),-Be.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"}}i1.FreeCameraDeviceOrientationInput=oee;class rW{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=ge.Identity(),this._deltaTransform=O.Zero(),this._vector3=O.Zero(),this._vector2=lt.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!==fc.POSE_ENABLED&&(!this.gamepad||t.type===fc.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(fc.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):ge.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const s=e._computeLocalCameraSpeed()*50;this._vector3.copyFromFloats(t.x*s,0,-t.y*s),O.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"}}z([X()],rW.prototype,"gamepadAngularSensibility",void 0);z([X()],rW.prototype,"gamepadMoveSensibility",void 0);i1.FreeCameraGamepadInput=rW;var eu;(function(a){a[a.X=0]="X",a[a.Y=1]="Y",a[a.Z=2]="Z"})(eu||(eu={}));class Cs{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=Object.assign(Object.assign({},Cs._GetDefaultOptions()),t);if(e?this._leftJoystick=!0:this._leftJoystick=!1,Cs._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=eu.X,this._axisTargetedByUpAndDown=eu.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new aX,this.deltaPosition=O.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{Cs._VJCanvasWidth=window.innerWidth,Cs._VJCanvasHeight=window.innerHeight,Cs.Canvas&&(Cs.Canvas.width=Cs._VJCanvasWidth,Cs.Canvas.height=Cs._VJCanvasHeight),Cs._HalfWidth=Cs._VJCanvasWidth/2},!Cs.Canvas){window.addEventListener("resize",this._onResize,!1),Cs.Canvas=document.createElement("canvas"),Cs._VJCanvasWidth=window.innerWidth,Cs._VJCanvasHeight=window.innerHeight,Cs.Canvas.width=window.innerWidth,Cs.Canvas.height=window.innerHeight,Cs.Canvas.style.width="100%",Cs.Canvas.style.height="100%",Cs.Canvas.style.position="absolute",Cs.Canvas.style.backgroundColor="transparent",Cs.Canvas.style.top="0px",Cs.Canvas.style.left="0px",Cs.Canvas.style.zIndex="5",Cs.Canvas.style.touchAction="none",Cs.Canvas.setAttribute("touch-action","none");const s=Cs.Canvas.getContext("2d");if(!s)throw new Error("Unable to create canvas for virtual joystick");Cs._VJCanvasContext=s,Cs._VJCanvasContext.strokeStyle="#ffffff",Cs._VJCanvasContext.lineWidth=2,document.body.appendChild(Cs.Canvas)}Cs._HalfWidth=Cs.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&&Cs._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new lt(0,0),this._joystickPreviousPointerPos=new lt(0,0),this._joystickPointerStartPos=new lt(0,0),this._deltaJoystickVector=new lt(0,0),this._onPointerDownHandlerRef=s=>{this._onPointerDown(s)},this._onPointerMoveHandlerRef=s=>{this._onPointerMove(s)},this._onPointerUpHandlerRef=s=>{this._onPointerUp(s)},Cs.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),Cs.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),Cs.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),Cs.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),Cs.Canvas.addEventListener("contextmenu",s=>{s.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.clientXCs._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)):Cs._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 n=new lt(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),o=n.length();o>this.containerSize&&n.scaleInPlace(this.containerSize/o),this._joystickPointerPos.x=this._joystickPointerStartPos.x+n.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+n.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?Cs._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,this.containerSize*2,this.containerSize*2):(Cs._VJCanvasContext.beginPath(),Cs._VJCanvasContext.strokeStyle=this._joystickColor,Cs._VJCanvasContext.lineWidth=2,Cs._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,Math.PI*2,!0),Cs._VJCanvasContext.stroke(),Cs._VJCanvasContext.closePath(),Cs._VJCanvasContext.beginPath(),Cs._VJCanvasContext.lineWidth=6,Cs._VJCanvasContext.strokeStyle=this._joystickColor,Cs._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,Math.PI*2,!0),Cs._VJCanvasContext.stroke(),Cs._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?Cs._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,this.puckSize*2,this.puckSize*2):(Cs._VJCanvasContext.beginPath(),Cs._VJCanvasContext.strokeStyle=this._joystickColor,Cs._VJCanvasContext.lineWidth=2,Cs._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,Math.PI*2,!0),Cs._VJCanvasContext.stroke(),Cs._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()):(Cs._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),Cs._VJCanvasContext.beginPath(),Cs._VJCanvasContext.fillStyle="white",Cs._VJCanvasContext.beginPath(),Cs._VJCanvasContext.strokeStyle="red",Cs._VJCanvasContext.lineWidth=6,Cs._VJCanvasContext.arc(t.x,t.y,40,0,Math.PI*2,!0),Cs._VJCanvasContext.stroke(),Cs._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){Cs.Canvas&&(Cs.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),Cs.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),Cs.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),Cs.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(Cs.Canvas),Cs.Canvas=null),this._released=!0}}Cs._GlobalJoystickIndex=0;Cs._AlwaysVisibleSticks=0;sW.prototype.addVirtualJoystick=function(){return this.add(new lee),this};class lee{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=e._computeLocalCameraSpeed()*50,i=ge.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=O.TransformCoordinates(new O(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(s),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 Cs(!0),this._leftjoystick.setAxisForUpDown(eu.Z),this._leftjoystick.setAxisForLeftRight(eu.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new Cs(!1),this._rightjoystick.setAxisForUpDown(eu.X),this._rightjoystick.setAxisForLeftRight(eu.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"}}i1.FreeCameraVirtualJoystickInput=lee;class Zl extends Pi{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=O.Zero(),this._tmpTargetVector=O.Zero(),this.cameraDirection=new O(0,0,0),this.cameraRotation=new lt(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new ke,this.rotation=new O(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=O.Zero(),this._initialFocalDistance=1,this._viewMatrix=ge.Zero(),this._camMatrix=ge.Zero(),this._cameraTransformMatrix=ge.Zero(),this._cameraRotationMatrix=ge.Zero(),this._referencePoint=new O(0,0,1),this._transformedReferencePoint=O.Zero(),this._deferredPositionUpdate=new O,this._deferredRotationQuaternionUpdate=new ke,this._deferredRotationUpdate=new O,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=O.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 O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new ke(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+=Ls),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),ge.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&&ke.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(ue.Matrix[0]),O.TransformNormalToRef(this.cameraDirection,ue.Matrix[0],ue.Vector3[0]),this._deferredPositionUpdate.addInPlace(ue.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()&&(ke.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(n),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>He.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 sW(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Be.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new O(0,0,0),this.cameraRotation=new lt(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=O.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 s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=O.Zero(),this._transformedDirection=O.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"}}z([bo()],q1.prototype,"ellipsoid",void 0);z([bo()],q1.prototype,"ellipsoidOffset",void 0);z([X()],q1.prototype,"checkCollisions",void 0);z([X()],q1.prototype,"applyGravity",void 0);pn.AddNodeConstructor("TouchCamera",(a,e)=>()=>new cee(a,O.Zero(),e));class cee extends q1{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}}pn.AddNodeConstructor("ArcRotateCamera",(a,e)=>()=>new dr(a,0,0,1,O.Zero(),e));class dr extends Zl{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 ge,this._upToYMatrix=new ge,this._upVector=O.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){ge.RotationAlignToRef(O.UpReadOnly,this._upVector,this._yToUpMatrix),ge.RotationAlignToRef(this._upVector,O.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 RL,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 u0,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 zle,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,o=!0){super(e,O.Zero(),n,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=O.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=lt.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new ge,this.panningAxis=new O(1,1,0),this._transformedDirection=new O,this.mapPanning=!1,this.onMeshTargetChangedObservable=new Se,this.checkCollisions=!1,this.collisionRadius=new O(.5,.5,.5),this._previousPosition=O.Zero(),this._collisionVelocity=O.Zero(),this._newPosition=O.Zero(),this._computationVector=O.Zero(),this._onCollisionPositionChange=(l,c,h=null)=>{h?(this.setPosition(c),this.onCollide&&this.onCollide(h)):this._previousPosition.copyFrom(this._position);const u=Math.cos(this.alpha),p=Math.sin(this.alpha),m=Math.cos(this.beta);let _=Math.sin(this.beta);_===0&&(_=1e-4);const f=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*u*_,this.radius*m,this.radius*p*_),f.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let d=this.upVector;this.allowUpsideDown&&this.beta<0&&(d=d.clone(),d=d.negate()),this._computeViewMatrix(this._position,f,d),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=O.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new LK(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new O(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=lt.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,s=2){const r=arguments;t=Be.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,typeof r[0]=="boolean"&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[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)&&O.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,s=!1){var r;if(s=(r=this.overrideCloneAlphaBetaRadius)!==null&&r!==void 0?r:s,e.getBoundingInfo)t?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 n=e,o=this._getTargetPosition();if(o&&!i&&o.equals(n))return;this._targetHost=null,this._target=n,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);s===0&&(s=1e-4),this.radius===0&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&O.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const n=this.getScene().collisionCoordinator;this._collider||(this._collider=n.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,n.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let n=this.upVector;this.allowUpsideDown&&s<0&&(n=n.negate()),this._computeViewMatrix(this._position,r,n),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Oe.MinMax(e),s=O.Distance(i.min,i.max);this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(e.min===void 0){const r=e||this.getScene().meshes;i=Oe.MinMax(r),s=O.Distance(i.min,i.max)}else{const r=e;i=r,s=r.distance}this._target=Oe.Center(i),t||(this.maxZ=s*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case Pi.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Pi.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Pi.RIG_MODE_STEREOSCOPIC_INTERLACED:case Pi.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const s=new dr(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case Pi.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Pi.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Pi.RIG_MODE_STEREOSCOPIC_INTERLACED:case Pi.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle;break}super._updateRigCameras()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}z([X()],dr.prototype,"alpha",void 0);z([X()],dr.prototype,"beta",void 0);z([X()],dr.prototype,"radius",void 0);z([X()],dr.prototype,"overrideCloneAlphaBetaRadius",void 0);z([bo("target")],dr.prototype,"_target",void 0);z([xF("targetHost")],dr.prototype,"_targetHost",void 0);z([X()],dr.prototype,"inertialAlphaOffset",void 0);z([X()],dr.prototype,"inertialBetaOffset",void 0);z([X()],dr.prototype,"inertialRadiusOffset",void 0);z([X()],dr.prototype,"lowerAlphaLimit",void 0);z([X()],dr.prototype,"upperAlphaLimit",void 0);z([X()],dr.prototype,"lowerBetaLimit",void 0);z([X()],dr.prototype,"upperBetaLimit",void 0);z([X()],dr.prototype,"lowerRadiusLimit",void 0);z([X()],dr.prototype,"upperRadiusLimit",void 0);z([X()],dr.prototype,"inertialPanningX",void 0);z([X()],dr.prototype,"inertialPanningY",void 0);z([X()],dr.prototype,"pinchToPanMaxDistance",void 0);z([X()],dr.prototype,"panningDistanceLimit",void 0);z([bo()],dr.prototype,"panningOriginTarget",void 0);z([X()],dr.prototype,"panningInertia",void 0);z([X()],dr.prototype,"zoomToMouseLocation",null);z([X()],dr.prototype,"zoomOnFactor",void 0);z([FG()],dr.prototype,"targetScreenOffset",void 0);z([X()],dr.prototype,"allowUpsideDown",void 0);z([X()],dr.prototype,"useInputToRestoreState",void 0);pn.AddNodeConstructor("DeviceOrientationCamera",(a,e)=>()=>new RK(a,O.Zero(),e));class RK extends q1{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new ke,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new ke,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(s=>{this._dragFactor!=0&&(this._initialQuaternion||(this._initialQuaternion=new ke),ke.FromEulerAnglesToRef(0,s.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=Fo.Y){!this.rotationQuaternion||(this._initialQuaternion||(this._initialQuaternion=new ke),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 Qle extends JG{constructor(e){super(e)}addKeyboard(){return this.add(new OI),this}addMouse(){return this.add(new eW),this}}class nW extends Zl{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,s=!0){super(e,t,i,s),this.ellipsoid=new O(1,1,1),this.ellipsoidOffset=new O(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=O.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=O.Zero(),this._diffPosition=O.Zero(),this._newPosition=O.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(r,n,o=null)=>{(c=>{this._newPosition.copyFrom(c),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>He.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&o&&this.onCollide(o))})(n)},this.inputs=new Qle(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Be.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new O(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=O.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 s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=O.Zero(),this._transformedDirection=O.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,s=t-i,r=.001;Math.abs(s)>=r&&(this.rotation.z+=s/e,Math.abs(t-this.rotation.z)<=r&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}z([bo()],nW.prototype,"ellipsoid",void 0);z([bo()],nW.prototype,"ellipsoidOffset",void 0);z([X()],nW.prototype,"checkCollisions",void 0);z([X()],nW.prototype,"applyGravity",void 0);class Zle extends JG{constructor(e){super(e)}addKeyboard(){return this.add(new Ad),this}addMouseWheel(){return this.add(new YL),this}addPointers(){return this.add(new b0),this}addVRDeviceOrientation(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}pn.AddNodeConstructor("FollowCamera",(a,e)=>()=>new M_(a,O.Zero(),e));pn.AddNodeConstructor("ArcFollowCamera",(a,e)=>()=>new qle(a,0,0,1,null,e));class M_ extends Zl{constructor(e,t,i,s=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=s,this.inputs=new Zle(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=ue.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=Be.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,o=r.z+Math.cos(s)*this.radius,l=n-this.position.x,c=r.y+this.heightOffset-this.position.y,h=o-this.position.z;let u=l*this.cameraAcceleration*2,p=c*this.cameraAcceleration,m=h*this.cameraAcceleration*2;(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(p>this.maxCameraSpeed||p<-this.maxCameraSpeed)&&(p=p<1?-this.maxCameraSpeed:this.maxCameraSpeed),(m>this.maxCameraSpeed||m<-this.maxCameraSpeed)&&(m=m<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new O(this.position.x+u,this.position.y+p,this.position.z+m),this.setTarget(r)}attachControl(e,t){t=Be.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"}}z([X()],M_.prototype,"radius",void 0);z([X()],M_.prototype,"lowerRadiusLimit",void 0);z([X()],M_.prototype,"upperRadiusLimit",void 0);z([X()],M_.prototype,"rotationOffset",void 0);z([X()],M_.prototype,"lowerRotationOffsetLimit",void 0);z([X()],M_.prototype,"upperRotationOffsetLimit",void 0);z([X()],M_.prototype,"heightOffset",void 0);z([X()],M_.prototype,"lowerHeightOffsetLimit",void 0);z([X()],M_.prototype,"upperHeightOffsetLimit",void 0);z([X()],M_.prototype,"cameraAcceleration",void 0);z([X()],M_.prototype,"maxCameraSpeed",void 0);z([xF("lockedTargetId")],M_.prototype,"lockedTarget",void 0);class qle extends Zl{constructor(e,t,i,s,r,n){super(e,O.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=O.Zero(),this.setMeshTarget(r)}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 s7;(function(a){a[a.VIVE=0]="VIVE",a[a.OCULUS=1]="OCULUS",a[a.WINDOWS=2]="WINDOWS",a[a.GEAR_VR=3]="GEAR_VR",a[a.DAYDREAM=4]="DAYDREAM",a[a.GENERIC=5]="GENERIC"})(s7||(s7={}));class oT{static InitiateController(e){for(const t of this._ControllerFactories)if(t.canCreate(e))return t.create(e);if(this._DefaultControllerFactory)return this._DefaultControllerFactory(e);throw"The type of gamepad you are trying to load needs to be imported first or is not supported."}}oT._ControllerFactories=[];oT._DefaultControllerFactory=null;class GP extends fc{_disableTrackPosition(e){this._trackPosition&&(this._calculatedPosition.copyFrom(e),this._trackPosition=!1)}constructor(e){super(e.id,e.index,e),this.isXR=!1,this._deviceRoomPosition=O.Zero(),this._deviceRoomRotationQuaternion=new ke,this.devicePosition=O.Zero(),this.deviceRotationQuaternion=new ke,this.deviceScaleFactor=1,this._trackPosition=!0,this._maxRotationDistFromHeadset=Math.PI/5,this._draggedRoomRotation=0,this._leftHandSystemQuaternion=new ke,this._deviceToWorld=ge.Identity(),this._pointingPoseNode=null,this._workingMatrix=ge.Identity(),this._meshAttachedObservable=new Se,this.type=fc.POSE_ENABLED,this.controllerType=s7.GENERIC,this.position=O.Zero(),this.rotationQuaternion=new ke,this._calculatedPosition=O.Zero(),this._calculatedRotation=new ke,ke.RotationYawPitchRollToRef(Math.PI,0,0,this._leftHandSystemQuaternion)}update(){super.update(),this._updatePoseAndMesh()}_updatePoseAndMesh(){if(this.isXR)return;const e=this.browserGamepad.pose;if(this.updateFromDevice(e),!this._trackPosition&&Ii.LastCreatedScene&&Ii.LastCreatedScene.activeCamera&&Ii.LastCreatedScene.activeCamera.devicePosition){const t=Ii.LastCreatedScene.activeCamera;if(t._computeDevicePosition(),this._deviceToWorld.setTranslation(t.devicePosition),t.deviceRotationQuaternion){t._deviceRoomRotationQuaternion.toEulerAnglesToRef(ue.Vector3[0]);const i=Math.atan2(Math.sin(ue.Vector3[0].y-this._draggedRoomRotation),Math.cos(ue.Vector3[0].y-this._draggedRoomRotation));if(Math.abs(i)>this._maxRotationDistFromHeadset){const s=i-(i<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=s;const r=Math.sin(-s),n=Math.cos(-s);this._calculatedPosition.x=this._calculatedPosition.x*n-this._calculatedPosition.z*r,this._calculatedPosition.z=this._calculatedPosition.x*r+this._calculatedPosition.z*n}}}O.TransformCoordinatesToRef(this._calculatedPosition,this._deviceToWorld,this.devicePosition),this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),ke.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation),this._mesh&&(this._mesh.position.copyFrom(this.devicePosition),this._mesh.rotationQuaternion&&this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion))}updateFromDevice(e){if(!this.isXR&&e){this.rawPose=e,e.position&&(this._deviceRoomPosition.copyFromFloats(e.position[0],e.position[1],-e.position[2]),this._mesh&&this._mesh.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1),this._trackPosition&&this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor,this._calculatedPosition),this._calculatedPosition.addInPlace(this.position));const t=this.rawPose;e.orientation&&t.orientation&&t.orientation.length===4&&(this._deviceRoomRotationQuaternion.copyFromFloats(t.orientation[0],t.orientation[1],-t.orientation[2],-t.orientation[3]),this._mesh&&(this._mesh.getScene().useRightHandedSystem?(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1):this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion,this._deviceRoomRotationQuaternion)),this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion,this._calculatedRotation))}}attachToMesh(e){if(this._mesh&&(this._mesh.parent=null),this._mesh=e,this._poseControlledCamera&&(this._mesh.parent=this._poseControlledCamera),this._mesh.rotationQuaternion||(this._mesh.rotationQuaternion=new ke),!this.isXR&&(this._updatePoseAndMesh(),this._pointingPoseNode)){const t=[];let i=this._pointingPoseNode;for(;i.parent;)t.push(i.parent),i=i.parent;t.reverse().forEach(s=>{s.computeWorldMatrix(!0)})}this._meshAttachedObservable.notifyObservers(e)}attachToPoseControlledCamera(e){this._poseControlledCamera=e,this._mesh&&(this._mesh.parent=this._poseControlledCamera)}dispose(){this._mesh&&this._mesh.dispose(),this._mesh=null,super.dispose()}get mesh(){return this._mesh}getForwardRay(e=100){if(!this.mesh)return new gr(O.Zero(),new O(0,0,1),e);const t=this._pointingPoseNode?this._pointingPoseNode.getWorldMatrix():this.mesh.getWorldMatrix(),i=t.getTranslation(),s=new O(0,0,-1),r=O.TransformNormal(s,t),n=O.Normalize(r);return new gr(i,n,e)}}GP.POINTING_POSE="POINTING_POSE";var X3;(function(a){a[a.A=0]="A",a[a.B=1]="B",a[a.X=2]="X",a[a.Y=3]="Y",a[a.LB=4]="LB",a[a.RB=5]="RB",a[a.Back=8]="Back",a[a.Start=9]="Start",a[a.LeftStick=10]="LeftStick",a[a.RightStick=11]="RightStick"})(X3||(X3={}));var mP;(function(a){a[a.Up=12]="Up",a[a.Down=13]="Down",a[a.Left=14]="Left",a[a.Right=15]="Right"})(mP||(mP={}));class Jle extends fc{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new Se,this.onButtonUpObservable=new Se,this.onPadDownObservable=new Se,this.onPadUpObservable=new Se,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=fc.XBOX,this._isXboxOnePad=s}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,X3.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,X3.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,X3.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,X3.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,X3.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,X3.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,X3.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,X3.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,X3.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,X3.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,mP.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,mP.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,mP.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,mP.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 q6;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.Share=8]="Share",a[a.Options=9]="Options",a[a.LeftStick=10]="LeftStick",a[a.RightStick=11]="RightStick"})(q6||(q6={}));var _P;(function(a){a[a.Up=12]="Up",a[a.Down=13]="Down",a[a.Left=14]="Left",a[a.Right=15]="Right"})(_P||(_P={}));class $le extends fc{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 Se,this.onButtonUpObservable=new Se,this.onPadDownObservable=new Se,this.onPadUpObservable=new Se,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=fc.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,q6.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,q6.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,q6.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,q6.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,q6.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,q6.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,q6.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,q6.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,q6.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,q6.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,_P.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,_P.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,_P.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,_P.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 ece{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new Se,ql()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new Se(t=>{for(const i in this._babylonGamepads){const s=this._babylonGamepads[i];s&&s._isConnected&&this.onGamepadConnectedObservable.notifyObserver(t,s)}}),this._onGamepadConnectedEvent=t=>{const i=t.gamepad;if(i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected)return;let s;this._babylonGamepads[i.index]?(s=this._babylonGamepads[i.index],s.browserGamepad=i,s._isConnected=!0):s=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(s),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=t=>{const i=t.gamepad;for(const s in this._babylonGamepads)if(this._babylonGamepads[s].index===i.index){const r=this._babylonGamepads[s];r._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(r),r.dispose&&r.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=fc.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,s=e.id.search("Xbox One")!==-1;return s||e.id.search("Xbox 360")!==-1||e.id.search("xinput")!==-1||e.id.search("045e")!==-1&&e.id.search("Surface Dock")===-1?t=new Jle(e.id,e.index,e,s):i?t=new $le(e.id,e.index,e):e.pose?t=oT.InitiateController(e):t=new Kle(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&&(Be.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&He.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new XL(a,O.Zero(),e));class XL extends cee{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"}}Pi._CreateDefaultParsedCamera=(a,e)=>new XL(a,O.Zero(),e);pn.AddNodeConstructor("GamepadCamera",(a,e)=>()=>new PK(a,O.Zero(),e));class PK extends XL{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}const e4e="passCubePixelShader",t4e=`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 +}`;Ue.ShadersStore[e4e]=t4e;class l7 extends rs{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,o=0,l=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,o,void 0,null,l)}static _Parse(e,t,i,s){return Kt.Parse(()=>new l7(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}$e("BABYLON.PassPostProcess",l7);class hee extends rs{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,s,r,n,o=0,l=!1){super(e,"passCube",null,null,t,i,s,r,n,"#define POSITIVEX",o,void 0,null,l),this._face=0}static _Parse(e,t,i,s){return Kt.Parse(()=>new hee(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}He._RescalePostProcessFactory=a=>new l7("rescale",1,null,2,a,!1,0);const i4e="anaglyphPixelShader",s4e=`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);}`;Ue.ShadersStore[i4e]=s4e;class uee extends rs{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,s,r,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],s,r,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(o=>{o.setTextureFromPostProcess("leftSampler",this._passedProcess)})}}$e("BABYLON.AnaglyphPostProcess",uee);function aW(a){a._rigCameras[0]._rigPostProcess=new l7(a.name+"_passthru",1,a._rigCameras[0]),a._rigCameras[1]._rigPostProcess=new uee(a.name+"_anaglyph",1,a._rigCameras)}pn.AddNodeConstructor("AnaglyphArcRotateCamera",(a,e,t)=>()=>new ice(a,0,0,1,O.Zero(),t.interaxial_distance,e));class ice extends dr{constructor(e,t,i,s,r,n,o){super(e,t,i,s,r,o),this._setRigMode=aW.bind(null,this),this.interaxialDistance=n,this.setCameraRigMode(Pi.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}pn.AddNodeConstructor("AnaglyphFreeCamera",(a,e,t)=>()=>new sce(a,O.Zero(),t.interaxial_distance,e));class sce extends q1{constructor(e,t,i,s){super(e,t,s),this._setRigMode=aW.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(Pi.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}pn.AddNodeConstructor("AnaglyphGamepadCamera",(a,e,t)=>()=>new rce(a,O.Zero(),t.interaxial_distance,e));class rce extends PK{constructor(e,t,i,s){super(e,t,s),this._setRigMode=aW.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(Pi.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}pn.AddNodeConstructor("AnaglyphUniversalCamera",(a,e,t)=>()=>new nce(a,O.Zero(),t.interaxial_distance,e));class nce extends XL{constructor(e,t,i,s){super(e,t,s),this._setRigMode=aW.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(Pi.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}const r4e="stereoscopicInterlacePixelShader",n4e=`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);} +`;Ue.ShadersStore[r4e]=n4e;class ace extends rs{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,o,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new lt(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new lt(1/this.width,1/this.height)}),this.onApplyObservable.add(l=>{l.setTextureFromPostProcess("camASampler",this._passedProcess),l.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}}class a4e extends rs{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,s,r,n){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,r,n,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new lt(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new lt(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 oW(a){const e=a.cameraRigMode===Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||a.cameraRigMode===Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,t=a.cameraRigMode===Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;a.cameraRigMode===Pi.RIG_MODE_STEREOSCOPIC_INTERLACED?(a._rigCameras[0]._rigPostProcess=new l7(a.name+"_passthru",1,a._rigCameras[0]),a._rigCameras[1]._rigPostProcess=new ace(a.name+"_stereoInterlace",a._rigCameras,!1,!0)):(a._rigCameras[t?1:0].viewport=new hu(0,0,e?.5:1,e?1:.5),a._rigCameras[t?0:1].viewport=new hu(e?.5:0,e?0:.5,e?.5:1,e?1:.5))}pn.AddNodeConstructor("StereoscopicArcRotateCamera",(a,e,t)=>()=>new oce(a,0,0,1,O.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class oce extends dr{constructor(e,t,i,s,r,n,o,l){super(e,t,i,s,r,l),this._setRigMode=oW.bind(null,this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Pi.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}pn.AddNodeConstructor("StereoscopicFreeCamera",(a,e,t)=>()=>new lce(a,O.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class lce extends q1{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=oW.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Pi.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}pn.AddNodeConstructor("StereoscopicGamepadCamera",(a,e,t)=>()=>new cce(a,O.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class cce extends PK{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=oW.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Pi.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}pn.AddNodeConstructor("StereoscopicFreeCamera",(a,e,t)=>()=>new hce(a,O.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class hce extends XL{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=oW.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Pi.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}class o4e extends XL{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,s=1,r=.065){super(e,t,i),this._distanceBetweenEyes=r,this._distanceToProjectionPlane=s,this.setCameraRigMode(Pi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=r}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new Zl(e,O.Zero(),this.getScene()),i=new Ki("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(ge.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e()=>new uce(a,O.Zero(),e));class uce extends q1{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class KL{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 ge.Translation(t,0,0)}get rightHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return ge.Translation(-t,0,0)}get leftPreViewMatrix(){return ge.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return ge.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new KL;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 l4e="vrDistortionCorrectionPixelShader",c4e=`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);}}`;Ue.ShadersStore[l4e]=c4e;class Dq extends rs{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,Te.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=s.distortionK,this._postProcessScaleFactor=s.postProcessScaleFactor,this._lensCenterOffset=s.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new lt(2,2/this.aspectRatio),this._scaleFactor=new lt(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new lt(this._isRightEye?.5-this._lensCenterOffset*.5:.5+this._lensCenterOffset*.5,.5)}),this.onApplyObservable.add(r=>{r.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),r.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),r.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),r.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])})}}const h4e="vrMultiviewToSingleviewPixelShader",u4e=`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));}`;Ue.ShadersStore[h4e]=u4e;class Oq extends Oa{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}}He.prototype.createMultiviewRenderTargetTexture=function(a,e,t,i){const s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const r=this._createHardwareRenderTargetWrapper(!1,!1,{width:a,height:e});r._framebuffer=s.createFramebuffer();const n=new dn(this,hr.Unknown,!0);return n.width=a,n.height=e,n.isMultiview=!0,t||(t=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,t),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,a,e,2)),r._colorTextureArray=t,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,a,e,2)),r._depthStencilTextureArray=i,n.isReady=!0,r.setTextures(n),r._depthStencilTexture=n,r};He.prototype.bindMultiviewFramebuffer=function(a){const e=a,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"};He.prototype.bindSpaceWarpFramebuffer=function(a){const e=a,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")};Pi.prototype._useMultiviewToSingleView=!1;Pi.prototype._multiviewTexture=null;Pi.prototype._resizeOrCreateMultiviewTexture=function(a,e){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=a||this._multiviewTexture.getRenderHeight()!=e)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new Oq(this.getScene(),{width:a,height:e})):this._multiviewTexture=new Oq(this.getScene(),{width:a,height:e})};function dce(a,e){const t=new es(a,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 d4e=oi.prototype.createSceneUniformBuffer;oi.prototype._transformMatrixR=ge.Zero();oi.prototype._multiviewSceneUbo=null;oi.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=dce(this.getEngine(),"scene_multiview")};oi.prototype.createSceneUniformBuffer=function(a){return this._multiviewSceneUbo?dce(this.getEngine(),a):d4e.bind(this)(a)};oi.prototype._updateMultiviewUbo=function(a,e){a&&e&&a.multiplyToRef(e,this._transformMatrixR),a&&e&&(a.multiplyToRef(e,ue.Matrix[0]),p_.GetRightPlaneToRef(ue.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))};oi.prototype._renderMultiviewToSingleView=function(a){a._resizeOrCreateMultiviewTexture(a._rigPostProcess&&a._rigPostProcess&&a._rigPostProcess.width>0?a._rigPostProcess.width:this.getEngine().getRenderWidth(!0),a._rigPostProcess&&a._rigPostProcess&&a._rigPostProcess.height>0?a._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),a.outputRenderTarget=a._multiviewTexture,this._renderForCamera(a),a.outputRenderTarget=null;for(let e=0;e{}),this.onApplyObservable.add(r=>{s._scene.activeCamera&&s._scene.activeCamera.isLeftCamera?r.setInt("imageIndex",0):r.setInt("imageIndex",1),r.setTexture("multiviewSampler",s._multiviewTexture)})}}function DK(a,e){const t=e.vrCameraMetrics||KL.GetDefault();a._rigCameras[0]._cameraRigParams.vrMetrics=t,a._rigCameras[0].viewport=new hu(0,0,.5,1),a._rigCameras[0]._cameraRigParams.vrWorkMatrix=new ge,a._rigCameras[0]._cameraRigParams.vrHMatrix=t.leftHMatrix,a._rigCameras[0]._cameraRigParams.vrPreViewMatrix=t.leftPreViewMatrix,a._rigCameras[0].getProjectionMatrix=a._rigCameras[0]._getVRProjectionMatrix,a._rigCameras[1]._cameraRigParams.vrMetrics=t,a._rigCameras[1].viewport=new hu(.5,0,.5,1),a._rigCameras[1]._cameraRigParams.vrWorkMatrix=new ge,a._rigCameras[1]._cameraRigParams.vrHMatrix=t.rightHMatrix,a._rigCameras[1]._cameraRigParams.vrPreViewMatrix=t.rightPreViewMatrix,a._rigCameras[1].getProjectionMatrix=a._rigCameras[1]._getVRProjectionMatrix,t.multiviewEnabled&&(a.getScene().getEngine().getCaps().multiview?(a._useMultiviewToSingleView=!0,a._rigPostProcess=new dee("VRMultiviewToSingleview",a,t.postProcessScaleFactor)):(Me.Warn("Multiview is not supported, falling back to standard rendering"),t.multiviewEnabled=!1)),t.compensateDistortion&&(a._rigCameras[0]._rigPostProcess=new Dq("VR_Distort_Compensation_Left",a._rigCameras[0],!1,t),a._rigCameras[1]._rigPostProcess=new Dq("VR_Distort_Compensation_Right",a._rigCameras[1],!0,t))}pn.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(a,e)=>()=>new fce(a,0,0,1,O.Zero(),e));class fce extends dr{constructor(e,t,i,s,r,n,o=!0,l=KL.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=DK.bind(null,this),l.compensateDistortion=o,this.setCameraRigMode(Pi.RIG_MODE_VR,{vrCameraMetrics:l}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}pn.AddNodeConstructor("VRDeviceOrientationFreeCamera",(a,e)=>()=>new OK(a,O.Zero(),e));class OK extends RK{constructor(e,t,i,s=!0,r=KL.GetDefault()){super(e,t,i),this._setRigMode=DK.bind(null,this),r.compensateDistortion=s,this.setCameraRigMode(Pi.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}pn.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(a,e)=>()=>new pce(a,O.Zero(),e));class pce extends OK{constructor(e,t,i,s=!0,r=KL.GetDefault()){super(e,t,i,s,r),this._setRigMode=DK.bind(null,this),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}pn.AddNodeConstructor("Light_Type_3",(a,e)=>()=>new gn(a,O.Zero(),e));class gn extends pr{constructor(e,t,i){super(e,i),this.groundColor=new Ie(0,0,0),this.direction=t||O.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=O.Normalize(e.subtract(O.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=O.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=O.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=ge.Identity()),this._worldMatrix}getTypeID(){return pr.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}z([Br()],gn.prototype,"groundColor",void 0);z([bo()],gn.prototype,"direction",void 0);function mce(a,e){if(e.vrDisplay){const t=e.vrDisplay.getEyeParameters("left"),i=e.vrDisplay.getEyeParameters("right");a._rigCameras[0].viewport=new hu(0,0,.5,1),a._rigCameras[0].setCameraRigParameter("left",!0),a._rigCameras[0].setCameraRigParameter("specs",e.specs),a._rigCameras[0].setCameraRigParameter("eyeParameters",t),a._rigCameras[0].setCameraRigParameter("frameData",e.frameData),a._rigCameras[0].setCameraRigParameter("parentCamera",e.parentCamera),a._rigCameras[0]._cameraRigParams.vrWorkMatrix=new ge,a._rigCameras[0].getProjectionMatrix=a._getWebVRProjectionMatrix,a._rigCameras[0].parent=a,a._rigCameras[0]._getViewMatrix=a._getWebVRViewMatrix,a._rigCameras[1].viewport=new hu(.5,0,.5,1),a._rigCameras[1].setCameraRigParameter("eyeParameters",i),a._rigCameras[1].setCameraRigParameter("specs",e.specs),a._rigCameras[1].setCameraRigParameter("frameData",e.frameData),a._rigCameras[1].setCameraRigParameter("parentCamera",e.parentCamera),a._rigCameras[1]._cameraRigParams.vrWorkMatrix=new ge,a._rigCameras[1].getProjectionMatrix=a._getWebVRProjectionMatrix,a._rigCameras[1].parent=a,a._rigCameras[1]._getViewMatrix=a._getWebVRViewMatrix}}Object.defineProperty(He.prototype,"isInVRExclusivePointerMode",{get:function(){return this._vrExclusivePointerMode},enumerable:!0,configurable:!0});He.prototype._prepareVRComponent=function(){this._vrSupported=!1,this._vrExclusivePointerMode=!1,this.onVRDisplayChangedObservable=new Se,this.onVRRequestPresentComplete=new Se,this.onVRRequestPresentStart=new Se};He.prototype.isVRDevicePresent=function(){return!!this._vrDisplay};He.prototype.getVRDevice=function(){return this._vrDisplay};He.prototype.initWebVR=function(){return this.initWebVRAsync(),this.onVRDisplayChangedObservable};He.prototype.initWebVRAsync=function(){const a=()=>{const e={vrDisplay:this._vrDisplay,vrSupported:this._vrSupported};this.onVRDisplayChangedObservable.notifyObservers(e),this._webVRInitPromise=new Promise(t=>{t(e)})};if(!this._onVrDisplayConnect){this._onVrDisplayConnect=t=>{this._vrDisplay=t.display,a()},this._onVrDisplayDisconnect=()=>{this._vrDisplay.cancelAnimationFrame(this._frameHandler),this._vrDisplay=void 0,this._frameHandler=He.QueueNewFrame(this._boundRenderFunction),a()},this._onVrDisplayPresentChange=()=>{this._vrExclusivePointerMode=this._vrDisplay&&this._vrDisplay.isPresenting};const e=this.getHostWindow();e&&(e.addEventListener("vrdisplayconnect",this._onVrDisplayConnect),e.addEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),e.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange))}return this._webVRInitPromise=this._webVRInitPromise||this._getVRDisplaysAsync(),this._webVRInitPromise.then(a),this._webVRInitPromise};He.prototype._getVRDisplaysAsync=function(){return new Promise(a=>{navigator.getVRDisplays?navigator.getVRDisplays().then(e=>{this._vrSupported=!0,this._vrDisplay=e[0],a({vrDisplay:this._vrDisplay,vrSupported:this._vrSupported})}):(this._vrDisplay=void 0,this._vrSupported=!1,a({vrDisplay:this._vrDisplay,vrSupported:this._vrSupported}))})};He.prototype.enableVR=function(a){if(this._vrDisplay&&!this._vrDisplay.isPresenting){const e=()=>{this.onVRRequestPresentComplete.notifyObservers(!0),this._onVRFullScreenTriggered()},t=()=>{this.onVRRequestPresentComplete.notifyObservers(!1)};this.onVRRequestPresentStart.notifyObservers(this);const i={highRefreshRate:this.vrPresentationAttributes?this.vrPresentationAttributes.highRefreshRate:!1,foveationLevel:this.vrPresentationAttributes?this.vrPresentationAttributes.foveationLevel:1,multiview:(this.getCaps().multiview||this.getCaps().oculusMultiview)&&a.useMultiview};this._vrDisplay.requestPresent([Object.assign({source:this.getRenderingCanvas(),attributes:i},i)]).then(e).catch(t)}};He.prototype._onVRFullScreenTriggered=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting){this._oldSize=new __(this.getRenderWidth(),this.getRenderHeight()),this._oldHardwareScaleFactor=this.getHardwareScalingLevel();const a=this._vrDisplay.getEyeParameters("left");this.setHardwareScalingLevel(1),this.setSize(a.renderWidth*2,a.renderHeight)}else this.setHardwareScalingLevel(this._oldHardwareScaleFactor),this.setSize(this._oldSize.width,this._oldSize.height)};He.prototype.disableVR=function(){this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.exitPresent().then(()=>this._onVRFullScreenTriggered()).catch(()=>this._onVRFullScreenTriggered()),ql()&&(window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null))};He.prototype._connectVREvents=function(a,e){if(this._onVRDisplayPointerRestricted=()=>{a&&a.requestPointerLock()},this._onVRDisplayPointerUnrestricted=()=>{if(!e){const t=this.getHostWindow();t.document&&t.document.exitPointerLock&&t.document.exitPointerLock();return}!e.exitPointerLock||e.exitPointerLock()},ql()){const t=this.getHostWindow();t.addEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted,!1),t.addEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted,!1)}};He.prototype._submitVRFrame=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting)try{this._vrDisplay.submitFrame()}catch(a){Be.Warn("webVR submitFrame has had an unexpected failure: "+a)}};He.prototype.isVRPresenting=function(){return this._vrDisplay&&this._vrDisplay.isPresenting};He.prototype._requestVRFrame=function(){this._frameHandler=He.QueueNewFrame(this._boundRenderFunction,this._vrDisplay)};pn.AddNodeConstructor("WebVRFreeCamera",(a,e)=>()=>new wK(a,O.Zero(),e));pn.AddNodeConstructor("WebVRGamepadCamera",(a,e)=>()=>new wK(a,O.Zero(),e));class wK extends q1{constructor(e,t,i,s={}){super(e,t,i),this._webVROptions=s,this._vrDevice=null,this.rawPose=null,this._specsVersion="1.1",this._attached=!1,this._descendants=[],this._deviceRoomPosition=O.Zero(),this._deviceRoomRotationQuaternion=ke.Identity(),this._standingMatrix=null,this.devicePosition=O.Zero(),this.deviceRotationQuaternion=ke.Identity(),this.deviceScaleFactor=1,this._deviceToWorld=ge.Identity(),this._worldToDevice=ge.Identity(),this.controllers=[],this.onControllersAttachedObservable=new Se,this.onControllerMeshLoadedObservable=new Se,this.onPoseUpdatedFromDeviceObservable=new Se,this._poseSet=!1,this.rigParenting=!0,this._defaultHeight=void 0,this._setRigMode=mce.bind(null,this),this._detachIfAttached=()=>{const n=this.getEngine().getVRDevice();n&&!n.isPresenting&&this.detachControl()},this._workingVector=O.Zero(),this._oneVector=O.One(),this._workingMatrix=ge.Identity(),this._tmpMatrix=new ge,this._cache.position=O.Zero(),s.defaultHeight&&(this._defaultHeight=s.defaultHeight,this.position.y=this._defaultHeight),this.minZ=.1,arguments.length===5&&(this._webVROptions=arguments[4]),this._webVROptions.trackPosition==null&&(this._webVROptions.trackPosition=!0),this._webVROptions.controllerMeshes==null&&(this._webVROptions.controllerMeshes=!0),this._webVROptions.defaultLightingOnControllers==null&&(this._webVROptions.defaultLightingOnControllers=!0),this.rotationQuaternion=new ke,this._webVROptions&&this._webVROptions.positionScale&&(this.deviceScaleFactor=this._webVROptions.positionScale);const r=this.getEngine();this._onVREnabled=n=>{n&&this.initControllers()},r.onVRRequestPresentComplete.add(this._onVREnabled),r.initWebVR().add(n=>{!n.vrDisplay||this._vrDevice===n.vrDisplay||(this._vrDevice=n.vrDisplay,this.setCameraRigMode(Pi.RIG_MODE_WEBVR,{parentCamera:this,vrDisplay:this._vrDevice,frameData:this._frameData,specs:this._specsVersion}),this._attached&&this.getEngine().enableVR(this._webVROptions))}),typeof VRFrameData<"u"&&(this._frameData=new VRFrameData),s.useMultiview&&(this.getScene().getEngine().getCaps().multiview?(this._useMultiviewToSingleView=!0,this._rigPostProcess=new dee("VRMultiviewToSingleview",this,1)):(Me.Warn("Multiview is not supported, falling back to standard rendering"),this._useMultiviewToSingleView=!1)),this.getScene().onBeforeCameraRenderObservable.add(n=>{n.parent===this&&this.rigParenting&&(this._descendants=this.getDescendants(!0,o=>{const l=this.controllers.some(h=>h._mesh===o),c=this._rigCameras.indexOf(o)!==-1;return!l&&!c}),this._descendants.forEach(o=>{o.parent=n}))}),this.getScene().onAfterCameraRenderObservable.add(n=>{n.parent===this&&this.rigParenting&&this._descendants.forEach(o=>{o.parent=this})})}deviceDistanceToRoomGround(){return this._standingMatrix?(this._standingMatrix.getTranslationToRef(this._workingVector),this._deviceRoomPosition.y+this._workingVector.y):this._defaultHeight||0}useStandingMatrix(e=t=>{}){this.getEngine().initWebVRAsync().then(t=>{!t.vrDisplay||!t.vrDisplay.stageParameters||!t.vrDisplay.stageParameters.sittingToStandingTransform||!this._webVROptions.trackPosition?e(!1):(this._standingMatrix=new ge,ge.FromFloat32ArrayToRefScaled(t.vrDisplay.stageParameters.sittingToStandingTransform,0,1,this._standingMatrix),this.getScene().useRightHandedSystem||this._standingMatrix&&this._standingMatrix.toggleModelMatrixHandInPlace(),e(!0))})}useStandingMatrixAsync(){return new Promise(e=>{this.useStandingMatrix(t=>{e(t)})})}dispose(){this._detachIfAttached(),this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled),this._updateCacheWhenTrackingDisabledObserver&&this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver),super.dispose()}getControllerByName(e){for(const t of this.controllers)if(t.hand===e)return t;return null}get leftController(){return this._leftController||(this._leftController=this.getControllerByName("left")),this._leftController}get rightController(){return this._rightController||(this._rightController=this.getControllerByName("right")),this._rightController}getForwardRay(e=100){return this.leftCamera?super.getForwardRay(e,this.leftCamera.getWorldMatrix(),this.leftCamera.globalPosition):super.getForwardRay(e)}_checkInputs(){this._vrDevice&&this._vrDevice.isPresenting&&(this._vrDevice.getFrameData(this._frameData),this.updateFromDevice(this._frameData.pose)),super._checkInputs()}updateFromDevice(e){e&&e.orientation&&e.orientation.length===4&&(this.rawPose=e,this._deviceRoomRotationQuaternion.copyFromFloats(e.orientation[0],e.orientation[1],-e.orientation[2],-e.orientation[3]),this.getScene().useRightHandedSystem&&(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1),this._webVROptions.trackPosition&&this.rawPose.position&&(this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2]),this.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1)),this._poseSet=!0)}attachControl(e){e=Be.BackCompatCameraNoPreventDefault(arguments),super.attachControl(e),this._attached=!0,e=Pi.ForceAttachControlToAlwaysPreventDefault?!1:e,this._vrDevice&&this.getEngine().enableVR(this._webVROptions);const t=this._scene.getEngine().getHostWindow();t&&t.addEventListener("vrdisplaypresentchange",this._detachIfAttached)}detachControl(){this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),super.detachControl(),this._attached=!1,this.getEngine().disableVR(),window.removeEventListener("vrdisplaypresentchange",this._detachIfAttached)}getClassName(){return"WebVRFreeCamera"}resetToCurrentRotation(){this._vrDevice.resetPose()}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];e.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),t.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),e.position.copyFrom(this._deviceRoomPosition),t.position.copyFrom(this._deviceRoomPosition)}_correctPositionIfNotTrackPosition(e,t=!1){this.rawPose&&this.rawPose.position&&!this._webVROptions.trackPosition&&(ge.TranslationToRef(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2],this._tmpMatrix),t||this._tmpMatrix.invert(),this._tmpMatrix.multiplyToRef(e,e))}_updateCache(e){(!this.rotationQuaternion.equals(this._cache.rotationQuaternion)||!this.position.equals(this._cache.position))&&(this._updateCacheCalled||(this._updateCacheCalled=!0,this.update()),this.rotationQuaternion.toRotationMatrix(this._workingMatrix),O.TransformCoordinatesToRef(this._deviceRoomPosition,this._workingMatrix,this._workingVector),this.devicePosition.subtractToRef(this._workingVector,this._workingVector),ge.ComposeToRef(this._oneVector,this.rotationQuaternion,this._workingVector,this._deviceToWorld),this._deviceToWorld.getTranslationToRef(this._workingVector),this._workingVector.addInPlace(this.position),this._workingVector.subtractInPlace(this._cache.position),this._deviceToWorld.setTranslation(this._workingVector),this._deviceToWorld.invertToRef(this._worldToDevice),this.controllers.forEach(t=>{t._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(t._deviceToWorld),t.update()})),e||super._updateCache(),this._updateCacheCalled=!1}_computeDevicePosition(){O.TransformCoordinatesToRef(this._deviceRoomPosition,this._deviceToWorld,this.devicePosition)}update(){this._computeDevicePosition(),ge.FromQuaternionToRef(this._deviceRoomRotationQuaternion,this._workingMatrix),this._workingMatrix.multiplyToRef(this._deviceToWorld,this._workingMatrix),ke.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this._poseSet&&this.onPoseUpdatedFromDeviceObservable.notifyObservers(null),super.update()}_getViewMatrix(){return ge.Identity()}_getWebVRViewMatrix(){const e=this._cameraRigParams.parentCamera;e._updateCache();const t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return ge.FromArrayToRef(t,0,this._webvrViewMatrix),this.getScene().useRightHandedSystem||this._webvrViewMatrix.toggleModelMatrixHandInPlace(),this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix),O.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),e.deviceScaleFactor!==1&&(this._webvrViewMatrix.invert(),e.deviceScaleFactor&&(this._webvrViewMatrix.multiplyAtIndex(12,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(13,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(14,e.deviceScaleFactor)),this._webvrViewMatrix.invert()),e._correctPositionIfNotTrackPosition(this._webvrViewMatrix,!0),e._worldToDevice.multiplyToRef(this._webvrViewMatrix,this._webvrViewMatrix),this._workingMatrix=this._workingMatrix||ge.Identity(),this._webvrViewMatrix.invertToRef(this._workingMatrix),this._workingMatrix.multiplyToRef(e.getWorldMatrix(),this._workingMatrix),this._workingMatrix.getTranslationToRef(this._globalPosition),this._markSyncedWithParent(),this._webvrViewMatrix}_getWebVRProjectionMatrix(){const e=this.parent;e._vrDevice.depthNear=e.minZ,e._vrDevice.depthFar=e.maxZ;const t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return ge.FromArrayToRef(t,0,this._projectionMatrix),this.getScene().useRightHandedSystem||this._projectionMatrix.toggleProjectionMatrixHandInPlace(),this._projectionMatrix}initControllers(){this.controllers.length=0;const e=this.getScene().gamepadManager;this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{if(t.type===fc.POSE_ENABLED){const i=t;i.defaultModel&&i.defaultModel.setEnabled(!1),i.hand==="right"&&(this._rightController=null),i.hand==="left"&&(this._leftController=null);const s=this.controllers.indexOf(i);s!==-1&&this.controllers.splice(s,1)}}),this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(t=>{if(t.type===fc.POSE_ENABLED){const i=t;if(this._webVROptions.trackPosition||(i._disableTrackPosition(new O(i.hand=="left"?-.15:.15,-.5,.25)),this._updateCacheWhenTrackingDisabledObserver||(this._updateCacheWhenTrackingDisabledObserver=this._scene.onBeforeRenderObservable.add(()=>{this._updateCache()}))),i.deviceScaleFactor=this.deviceScaleFactor,i._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(i._deviceToWorld),this._webVROptions.controllerMeshes&&(i.defaultModel?i.defaultModel.setEnabled(!0):i.initControllerMesh(this.getScene(),s=>{if(s.scaling.scaleInPlace(this.deviceScaleFactor),this.onControllerMeshLoadedObservable.notifyObservers(i),this._webVROptions.defaultLightingOnControllers){this._lightOnControllers||(this._lightOnControllers=new gn("vrControllersLight",new O(0,1,0),this.getScene()));const r=function(n,o){const l=n.getChildren();l&&l.length!==0&&l.forEach(c=>{o.includedOnlyMeshes.push(c),r(c,o)})};this._lightOnControllers.includedOnlyMeshes.push(s),r(s,this._lightOnControllers)}})),i.attachToPoseControlledCamera(this),this.controllers.indexOf(i)===-1){this.controllers.push(i);let s=!1;for(let r=0;r=2&&this.onControllersAttachedObservable.notifyObservers(this.controllers)}}})}}class QL extends GP{onButtonStateChange(e){this._onButtonStateChange=e}get defaultModel(){return this._defaultModel}constructor(e){super(e),this.onTriggerStateChangedObservable=new Se,this.onMainButtonStateChangedObservable=new Se,this.onSecondaryButtonStateChangedObservable=new Se,this.onPadStateChangedObservable=new Se,this.onPadValuesChangedObservable=new Se,this.pad={x:0,y:0},this._changes={pressChanged:!1,touchChanged:!1,valueChanged:!1,changed:!1},this._buttons=new Array(e.buttons.length),this.hand=e.hand}update(){super.update();for(let e=0;e +#define ADDITIONAL_FRAGMENT_DECLARATION +`;Ue.IncludesShadersStore[m4e]=_4e;const g4e="sceneUboDeclaration",v4e=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; +#ifdef MULTIVIEW +mat4 viewProjectionR; +#endif +mat4 view;mat4 projection;vec4 vEyePosition;}; +`;Ue.IncludesShadersStore[g4e]=v4e;const C4e="meshUboDeclaration",A4e=`#ifdef WEBGL2 +uniform mat4 world;uniform float visibility; +#else +layout(std140,column_major) uniform;uniform Mesh +{mat4 world;float visibility;}; +#endif +#define WORLD_UBO +`;Ue.IncludesShadersStore[C4e]=A4e;const x4e="defaultUboDeclaration",b4e=`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 +`;Ue.IncludesShadersStore[x4e]=b4e;const E4e="prePassDeclaration",y4e=`#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 +`;Ue.IncludesShadersStore[E4e]=y4e;const M4e="oitDeclaration",T4e=`#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 +`;Ue.IncludesShadersStore[M4e]=T4e;const S4e="mainUVVaryingDeclaration",I4e=`#ifdef MAINUV{X} +varying vec2 vMainUV{X}; +#endif +`;Ue.IncludesShadersStore[S4e]=I4e;const L4e="helperFunctions",R4e=`const float PI=3.1415926535897932384626433832795;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;} +`;Ue.IncludesShadersStore[L4e]=R4e;const P4e="lightFragmentDeclaration",D4e=`#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 +`;Ue.IncludesShadersStore[P4e]=D4e;const O4e="lightUboDeclaration",w4e=`#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 +`;Ue.IncludesShadersStore[O4e]=w4e;const N4e="lightsFragmentFunctions",B4e=`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;}`;Ue.IncludesShadersStore[N4e]=B4e;const F4e="shadowsFragmentFunctions",V4e=`#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 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) +{vec3 directionToLight=vPositionW-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 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) +{vec3 directionToLight=vPositionW-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 +#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.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,0.), +vec3(0.,0.,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 +`;Ue.IncludesShadersStore[q4e]=J4e;const $4e="clipPlaneFragmentDeclaration",eme=`#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 +`;Ue.IncludesShadersStore[$4e]=eme;const tme="logDepthDeclaration",ime=`#ifdef LOGARITHMICDEPTH +uniform float logarithmicDepthConstant;varying float vFragmentDepth; +#endif +`;Ue.IncludesShadersStore[tme]=ime;const sme="fogFragmentDeclaration",rme=`#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 +`;Ue.IncludesShadersStore[sme]=rme;const nme="clipPlaneFragment",ame=`#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 +`;Ue.IncludesShadersStore[nme]=ame;const ome="bumpFragment",lme=`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 +`;Ue.IncludesShadersStore[ome]=lme;const cme="decalFragment",hme=`#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 +`;Ue.IncludesShadersStore[cme]=hme;const ume="depthPrePass",dme=`#ifdef DEPTHPREPASS +gl_FragColor=vec4(0.,0.,0.,1.0);return; +#endif +`;Ue.IncludesShadersStore[ume]=dme;const fme="lightFragment",pme=`#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(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(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(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(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 +`;Ue.IncludesShadersStore[fme]=pme;const mme="logDepthFragment",_me=`#ifdef LOGARITHMICDEPTH +gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; +#endif +`;Ue.IncludesShadersStore[mme]=_me;const gme="fogFragment",vme=`#ifdef FOG +float fog=CalcFogFactor(); +#ifdef PBR +fog=toLinearSpace(fog); +#endif +color.rgb=mix(vFogColor,color.rgb,fog); +#endif +`;Ue.IncludesShadersStore[gme]=vme;const Cme="oitFragment",Ame=`#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 +#define RECIPROCAL_PI2 0.15915494 +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 +} +`;Ue.ShadersStore[xme]=bme;const Eme="decalVertexDeclaration",yme=`#ifdef DECAL +uniform vec4 vDecalInfos;uniform mat4 decalMatrix; +#endif +`;Ue.IncludesShadersStore[Eme]=yme;const Mme="defaultVertexDeclaration",Tme=`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 +`;Ue.IncludesShadersStore[Mme]=Tme;const Sme="uvAttributeDeclaration",Ime=`#ifdef UV{X} +attribute vec2 uv{X}; +#endif +`;Ue.IncludesShadersStore[Sme]=Ime;const Lme="bonesDeclaration",Rme=`#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 sampler2D boneSampler;uniform float boneTextureWidth; +#else +uniform mat4 mBones[BonesPerMesh]; +#ifdef BONES_VELOCITY_ENABLED +uniform mat4 mPreviousBones[BonesPerMesh]; +#endif +#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 +`;Ue.IncludesShadersStore[Lme]=Rme;const Pme="bakedVertexAnimationDeclaration",Dme=`#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 +`;Ue.IncludesShadersStore[Pme]=Dme;const Ome="instancesDeclaration",wme=`#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 +`;Ue.IncludesShadersStore[Ome]=wme;const Nme="prePassVertexDeclaration",Bme=`#ifdef PREPASS +#ifdef PREPASS_DEPTH +varying vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#endif +`;Ue.IncludesShadersStore[Nme]=Bme;const Fme="samplerVertexDeclaration",Vme=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +varying vec2 v_VARYINGNAME_UV; +#endif +`;Ue.IncludesShadersStore[Fme]=Vme;const zme="bumpVertexDeclaration",Ume=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +varying mat3 vTBN; +#endif +#endif +`;Ue.IncludesShadersStore[zme]=Ume;const kme="clipPlaneVertexDeclaration",Hme=`#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 +`;Ue.IncludesShadersStore[kme]=Hme;const jme="fogVertexDeclaration",Gme=`#ifdef FOG +varying vec3 vFogDistance; +#endif +`;Ue.IncludesShadersStore[jme]=Gme;const Wme="lightVxFragmentDeclaration",Yme=`#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 +`;Ue.IncludesShadersStore[Wme]=Yme;const Xme="lightVxUboDeclaration",Kme=`#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 +`;Ue.IncludesShadersStore[Xme]=Kme;const Qme="morphTargetsVertexGlobalDeclaration",Zme=`#ifdef MORPHTARGETS +uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; +#ifdef MORPHTARGETS_TEXTURE +precision mediump sampler2DArray; +uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform 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 +`;Ue.IncludesShadersStore[Qme]=Zme;const qme="morphTargetsVertexDeclaration",Jme=`#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 +#endif +#endif +`;Ue.IncludesShadersStore[qme]=Jme;const $me="morphTargetsVertexGlobal",e_e=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +float vertexID; +#endif +#endif +`;Ue.IncludesShadersStore[$me]=e_e;const t_e="morphTargetsVertex",i_e=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];vertexID+=1.0; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}]; +#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 +`;Ue.IncludesShadersStore[t_e]=i_e;const s_e="instancesVertex",r_e=`#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 +`;Ue.IncludesShadersStore[s_e]=r_e;const n_e="bonesVertex",a_e=`#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 +`;Ue.IncludesShadersStore[n_e]=a_e;const o_e="bakedVertexAnimation",l_e=`#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 +`;Ue.IncludesShadersStore[o_e]=l_e;const c_e="prePassVertex",h_e=`#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 +`;Ue.IncludesShadersStore[c_e]=h_e;const u_e="uvVariableDeclaration",d_e=`#if !defined(UV{X}) && defined(MAINUV{X}) +vec2 uv{X}=vec2(0.,0.); +#endif +#ifdef MAINUV{X} +vMainUV{X}=uv{X}; +#endif +`;Ue.IncludesShadersStore[u_e]=d_e;const f_e="samplerVertexImplementation",p_e=`#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 +`;Ue.IncludesShadersStore[f_e]=p_e;const m_e="bumpVertex",__e=`#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 +`;Ue.IncludesShadersStore[m_e]=__e;const g_e="clipPlaneVertex",v_e=`#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 +`;Ue.IncludesShadersStore[g_e]=v_e;const C_e="fogVertex",A_e=`#ifdef FOG +vFogDistance=(view*worldPos).xyz; +#endif +`;Ue.IncludesShadersStore[C_e]=A_e;const x_e="shadowsVertex",b_e=`#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 +} +`;Ue.ShadersStore[L_e]=R_e;const P_e=new RegExp("^([gimus]+)!");class iI{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let s=0;ss.priority-r.priority),this._codeInjectionPoints={};const i={};i[iI._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const s of this._plugins)s.collectDefines(i),this._collectPointNames("vertex",s.getCustomCode("vertex")),this._collectPointNames("fragment",s.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&&s.uniforms.push(...this._uniformList),this._samplerList.length>0&&s.samplers.push(...this._samplerList),this._uboList.length>0&&s.uniformBuffersNames.push(...this._uboList),s.customCode=this._injectCustomCode(s,s.customCode);break}case zu.PrepareUniformBuffer:{const s=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const r of this._plugins){const n=r.getUniforms();if(n){if(n.ubo)for(const o of n.ubo){if(o.size&&o.type){const l=(i=o.arraySize)!==null&&i!==void 0?i:0;s.ubo.addUniform(o.name,o.size,l),this._uboDeclaration+=`${o.type} ${o.name}${l>0?`[${l}]`:""}; +`}this._uniformList.push(o.name)}n.vertex&&(this._vertexDeclaration+=n.vertex+` +`),n.fragment&&(this._fragmentDeclaration+=n.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,s)=>{var r,n;t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const o=(r=this._codeInjectionPoints)===null||r===void 0?void 0:r[i];if(!o)return s;let l=null;for(let c in o){let h="";for(const u of this._activePlugins){let p=(n=u.getCustomCode(i))===null||n===void 0?void 0:n[c];if(!!p){if(u.resolveIncludes){if(l===null){const m=Ao.GLSL;l={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Ue.GetShadersRepository(m),includesShadersStore:Ue.GetIncludesShadersStore(m),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}l.isFragment=i==="fragment",rv._ProcessIncludes(p,l,m=>p=m)}h+=p+` +`}}if(h.length>0)if(c.charAt(0)==="!"){c=c.substring(1);let u="g";if(c.charAt(0)==="!")u="",c=c.substring(1);else{const f=P_e.exec(c);f&&f.length>=2&&(u=f[1],c=c.substring(u.length+1))}u.indexOf("g")<0&&(u+="g");const p=s,m=new RegExp(c,u);let _=m.exec(p);for(;_!==null;){let f=h;for(let d=0;d<_.length;++d)f=f.replace("$"+d,_[d]);s=s.replace(_[0],f),_=m.exec(p)}}else{const u="#define "+c;s=s.replace(u,` +`+h+` +`+u)}}return s}}}iI._MaterialPluginClassToMainDefine={};iI._MaterialPluginCounter=0;Ii.OnEnginesDisposedObservable.add(()=>{fee()});const xL=[];let wq=!1,Nq=null;function D_e(a,e){wq||(Nq=Lt.OnEventObservable.add(i=>{for(const[,s]of xL)s(i)},zu.Created),wq=!0);const t=xL.filter(([i,s])=>i===a);t.length>0?t[0][1]=e:xL.push([a,e])}function O_e(a){for(let e=0;e{e.pluginManager=void 0})),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}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){Kt.Clone(()=>e,this)}serialize(){return Kt.Serialize(this)}parse(e,t,i){Kt.Parse(()=>this,e,t,i)}}z([X()],l4.prototype,"name",void 0);z([X()],l4.prototype,"priority",void 0);z([X()],l4.prototype,"resolveIncludes",void 0);z([X()],l4.prototype,"registerForExtraEvents",void 0);class _ce extends ta{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class lT extends l4{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new _ce,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Lt.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&&Xt.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&&Xt.DetailTextureEnabled&&this._isEnabled?(ze.PrepareDefinesForMergedUV(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&&Xt.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),ze.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Xt.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===void 0||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"}]}}}z([xs("detailTexture"),_t("_markAllSubMeshesAsTexturesDirty")],lT.prototype,"texture",void 0);z([X()],lT.prototype,"diffuseBlendLevel",void 0);z([X()],lT.prototype,"roughnessBlendLevel",void 0);z([X()],lT.prototype,"bumpLevel",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],lT.prototype,"normalBlendMethod",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],lT.prototype,"isEnabled",void 0);const xZ={effect:null,subMesh:null};class gce extends ta{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 jt extends Bl{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 Ie(0,0,0),this.diffuseColor=new Ie(1,1,1),this.specularColor=new Ie(1,1,1),this.emissiveColor=new Ie(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 Sc(16),this._worldViewProjectionMatrix=ge.Zero(),this._globalAmbientColor=new Ie(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new lT(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new fX,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),jt.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),jt.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 jt.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||jt.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()}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===Lt.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Lt.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(zu.GetDefineNames,this._eventInfo),t.materialDefines=new gce(this._eventInfo.defineNames));const s=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();r._needNormals=ze.PrepareDefinesForLights(s,e,r,!0,this._maxSimultaneousLights,this._disableLighting),ze.PrepareDefinesForMultiview(s,r);const o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(ze.PrepareDefinesForPrePass(s,r,this.canRenderToMRT&&!o),ze.PrepareDefinesForOIT(s,r,o),r._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r._needUVs=!1;for(let c=1;c<=6;++c)r["MAINUV"+c]=!1;if(s.texturesEnabled){if(r.DIFFUSEDIRECTUV=0,r.BUMPDIRECTUV=0,r.AMBIENTDIRECTUV=0,r.OPACITYDIRECTUV=0,r.EMISSIVEDIRECTUV=0,r.SPECULARDIRECTUV=0,r.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&jt.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())ze.PrepareDefinesForMergedUV(this._diffuseTexture,r,"DIFFUSE");else return!1;else r.DIFFUSE=!1;if(this._ambientTexture&&jt.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())ze.PrepareDefinesForMergedUV(this._ambientTexture,r,"AMBIENT");else return!1;else r.AMBIENT=!1;if(this._opacityTexture&&jt.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())ze.PrepareDefinesForMergedUV(this._opacityTexture,r,"OPACITY"),r.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else r.OPACITY=!1;if(this._reflectionTexture&&jt.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(r._needNormals=!0,r.REFLECTION=!0,r.ROUGHNESS=this._roughness>0,r.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,r.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Te.INVCUBIC_MODE,r.REFLECTIONMAP_3D=this._reflectionTexture.isCube,r.REFLECTIONMAP_OPPOSITEZ=r.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,r.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Te.EXPLICIT_MODE:r.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Te.PLANAR_MODE:r.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Te.PROJECTION_MODE:r.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Te.SKYBOX_MODE:r.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Te.SPHERICAL_MODE:r.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Te.EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Te.FIXED_EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Te.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Te.CUBIC_MODE:case Te.INVCUBIC_MODE:default:r.setReflectionMode("REFLECTIONMAP_CUBIC");break}r.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else r.REFLECTION=!1,r.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&jt.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())ze.PrepareDefinesForMergedUV(this._emissiveTexture,r,"EMISSIVE");else return!1;else r.EMISSIVE=!1;if(this._lightmapTexture&&jt.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())ze.PrepareDefinesForMergedUV(this._lightmapTexture,r,"LIGHTMAP"),r.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,r.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else r.LIGHTMAP=!1;if(this._specularTexture&&jt.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())ze.PrepareDefinesForMergedUV(this._specularTexture,r,"SPECULAR"),r.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else r.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&jt.BumpTextureEnabled){if(this._bumpTexture.isReady())ze.PrepareDefinesForMergedUV(this._bumpTexture,r,"BUMP"),r.PARALLAX=this._useParallax,r.PARALLAX_RHS=s.useRightHandedSystem,r.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;r.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else r.BUMP=!1,r.PARALLAX=!1,r.PARALLAX_RHS=!1,r.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&jt.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())r._needUVs=!0,r.REFRACTION=!0,r.REFRACTIONMAP_3D=this._refractionTexture.isCube,r.RGBDREFRACTION=this._refractionTexture.isRGBD,r.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else r.REFRACTION=!1;r.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else r.DIFFUSE=!1,r.AMBIENT=!1,r.OPACITY=!1,r.REFLECTION=!1,r.EMISSIVE=!1,r.LIGHTMAP=!1,r.BUMP=!1,r.REFRACTION=!1;r.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),r.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,r.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,r.SPECULAROVERALPHA=this._useSpecularOverAlpha,r.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,r.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,r.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}r._areFresnelDirty&&(jt.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(r.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,r.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,r.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,r.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,r.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,r.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,r._needNormals=!0,r.FRESNEL=!0):r.FRESNEL=!1),ze.PrepareDefinesForMisc(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,r,this._applyDecalMapAfterDetailMap),ze.PrepareDefinesForFrameBoundValues(s,n,this,r,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=r,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ze.PrepareDefinesForAttributes(e,r,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(r.isDirty){const c=r._areLightsDisposed;r.markAsProcessed();const h=new Fl;r.REFLECTION&&h.addFallback(0,"REFLECTION"),r.SPECULAR&&h.addFallback(0,"SPECULAR"),r.BUMP&&h.addFallback(0,"BUMP"),r.PARALLAX&&h.addFallback(1,"PARALLAX"),r.PARALLAX_RHS&&h.addFallback(1,"PARALLAX_RHS"),r.PARALLAXOCCLUSION&&h.addFallback(0,"PARALLAXOCCLUSION"),r.SPECULAROVERALPHA&&h.addFallback(0,"SPECULAROVERALPHA"),r.FOG&&h.addFallback(1,"FOG"),r.POINTSIZE&&h.addFallback(0,"POINTSIZE"),r.LOGARITHMICDEPTH&&h.addFallback(0,"LOGARITHMICDEPTH"),ze.HandleFallbacksForShadows(r,h,this._maxSimultaneousLights),r.SPECULARTERM&&h.addFallback(0,"SPECULARTERM"),r.DIFFUSEFRESNEL&&h.addFallback(1,"DIFFUSEFRESNEL"),r.OPACITYFRESNEL&&h.addFallback(2,"OPACITYFRESNEL"),r.REFLECTIONFRESNEL&&h.addFallback(3,"REFLECTIONFRESNEL"),r.EMISSIVEFRESNEL&&h.addFallback(4,"EMISSIVEFRESNEL"),r.FRESNEL&&h.addFallback(4,"FRESNEL"),r.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");const u=[se.PositionKind];r.NORMAL&&u.push(se.NormalKind),r.TANGENT&&u.push(se.TangentKind);for(let b=1;b<=6;++b)r["UV"+b]&&u.push(`uv${b===1?"":b}`);r.VERTEXCOLOR&&u.push(se.ColorKind),ze.PrepareAttributesForBones(u,e,r,h),ze.PrepareAttributesForInstances(u,r),ze.PrepareAttributesForMorphTargets(u,e,r),ze.PrepareAttributesForBakedVertexAnimation(u,e,r);let p="default";const m=["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"],f=["Material","Scene","Mesh"],d={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=0,this._eventInfo.defines=r,this._eventInfo.uniforms=m,this._eventInfo.attributes=u,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=d,this._callbackPluginEventGeneric(zu.PrepareEffect,this._eventInfo),fX.AddUniforms(m),Dr&&(Dr.PrepareUniforms(m,r),Dr.PrepareSamplers(_,r)),ze.PrepareUniformsAndSamplersList({uniformsNames:m,uniformBuffersNames:f,samplers:_,defines:r,maxSimultaneousLights:this._maxSimultaneousLights}),lh(m);const C={};this.customShaderNameResolve&&(p=this.customShaderNameResolve(p,m,f,_,r,u,C));const v=r.toString(),y=t.effect;let M=s.getEngine().createEffect(p,{attributes:u,uniformsNames:m,uniformBuffersNames:f,samplers:_,defines:v,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:d,processFinalCode:C.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:r.PREPASS},n);if(this._eventInfo.customCode=void 0,M)if(this._onEffectCreatedObservable&&(xZ.effect=M,xZ.subMesh=t,this._onEffectCreatedObservable.notifyObservers(xZ)),this.allowShaderHotSwapping&&y&&!M.isReady()){if(M=y,r.markAsUnprocessed(),l=this.isFrozen,c)return r._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(M,r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!l,t.effect._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 s;const r=this.getScene(),n=i.materialDefines;if(!n)return;const o=i.effect;if(!o)return;this._activeEffect=o,t.getMeshUniformBuffer().bindToEffect(o,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(o,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const l=o._forceRebindOnNextCall||this._mustRebind(r,o,t.visibility);ze.BindBonesParameters(t,o);const c=this._uniformBuffer;if(l){if(this.bindViewProjection(o),!c.useUbo||!this.isFrozen||!c.isSync||o._forceRebindOnNextCall){if(jt.FresnelEnabled&&n.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 Ie(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&&jt.DiffuseTextureEnabled&&(c.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ze.BindTextureMatrix(this._diffuseTexture,c,"diffuse")),this._ambientTexture&&jt.AmbientTextureEnabled&&(c.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),ze.BindTextureMatrix(this._ambientTexture,c,"ambient")),this._opacityTexture&&jt.OpacityTextureEnabled&&(c.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ze.BindTextureMatrix(this._opacityTexture,c,"opacity")),this._hasAlphaChannel()&&c.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&jt.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&&jt.EmissiveTextureEnabled&&(c.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ze.BindTextureMatrix(this._emissiveTexture,c,"emissive")),this._lightmapTexture&&jt.LightmapTextureEnabled&&(c.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ze.BindTextureMatrix(this._lightmapTexture,c,"lightmap")),this._specularTexture&&jt.SpecularTextureEnabled&&(c.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),ze.BindTextureMatrix(this._specularTexture,c,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&jt.BumpTextureEnabled&&(c.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),ze.BindTextureMatrix(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&&jt.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),n.SPECULARTERM&&c.updateColor4("vSpecularColor",this.specularColor,this.specularPower),c.updateColor3("vEmissiveColor",jt.EmissiveTextureEnabled?this.emissiveColor:Ie.BlackReadOnly),c.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),c.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&jt.DiffuseTextureEnabled&&o.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&jt.AmbientTextureEnabled&&o.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&jt.OpacityTextureEnabled&&o.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&jt.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?o.setTexture("reflectionCubeSampler",this._reflectionTexture):o.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&jt.EmissiveTextureEnabled&&o.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&jt.LightmapTextureEnabled&&o.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&jt.SpecularTextureEnabled&&o.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&jt.BumpTextureEnabled&&o.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&jt.RefractionTextureEnabled&&(this._refractionTexture.isCube?o.setTexture("refractionCubeSampler",this._refractionTexture):o.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(o),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),wc(o,this,r),this.bindEyePosition(o)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&ze.BindLights(r,t,o,n,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==oi.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(o),ze.BindFogParameters(r,t,o),n.NUM_MORPH_INFLUENCERS&&ze.BindMorphTargetParameters(t,o),n.BAKED_VERTEX_ANIMATION_TEXTURE&&((s=t.bakedVertexAnimationManager)===null||s===void 0||s.bind(o,n.INSTANCES)),this.useLogarithmicDepth&&ze.BindLogDepth(n,o,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),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,s,r,n,o,l,c,h,u;t&&((i=this._diffuseTexture)===null||i===void 0||i.dispose(),(s=this._ambientTexture)===null||s===void 0||s.dispose(),(r=this._opacityTexture)===null||r===void 0||r.dispose(),(n=this._reflectionTexture)===null||n===void 0||n.dispose(),(o=this._emissiveTexture)===null||o===void 0||o.dispose(),(l=this._specularTexture)===null||l===void 0||l.dispose(),(c=this._bumpTexture)===null||c===void 0||c.dispose(),(h=this._lightmapTexture)===null||h===void 0||h.dispose(),(u=this._refractionTexture)===null||u===void 0||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=Kt.Clone(()=>new jt(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=Kt.Parse(()=>new jt(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Lt._parsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return Xt.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Xt.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Xt.DetailTextureEnabled}static set DetailTextureEnabled(e){Xt.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Xt.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Xt.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Xt.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Xt.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Xt.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Xt.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Xt.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Xt.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Xt.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Xt.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Xt.BumpTextureEnabled}static set BumpTextureEnabled(e){Xt.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Xt.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Xt.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Xt.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Xt.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Xt.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Xt.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Xt.FresnelEnabled}static set FresnelEnabled(e){Xt.FresnelEnabled=e}}z([xs("diffuseTexture")],jt.prototype,"_diffuseTexture",void 0);z([_t("_markAllSubMeshesAsTexturesAndMiscDirty")],jt.prototype,"diffuseTexture",void 0);z([xs("ambientTexture")],jt.prototype,"_ambientTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"ambientTexture",void 0);z([xs("opacityTexture")],jt.prototype,"_opacityTexture",void 0);z([_t("_markAllSubMeshesAsTexturesAndMiscDirty")],jt.prototype,"opacityTexture",void 0);z([xs("reflectionTexture")],jt.prototype,"_reflectionTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"reflectionTexture",void 0);z([xs("emissiveTexture")],jt.prototype,"_emissiveTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"emissiveTexture",void 0);z([xs("specularTexture")],jt.prototype,"_specularTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"specularTexture",void 0);z([xs("bumpTexture")],jt.prototype,"_bumpTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"bumpTexture",void 0);z([xs("lightmapTexture")],jt.prototype,"_lightmapTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"lightmapTexture",void 0);z([xs("refractionTexture")],jt.prototype,"_refractionTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"refractionTexture",void 0);z([Br("ambient")],jt.prototype,"ambientColor",void 0);z([Br("diffuse")],jt.prototype,"diffuseColor",void 0);z([Br("specular")],jt.prototype,"specularColor",void 0);z([Br("emissive")],jt.prototype,"emissiveColor",void 0);z([X()],jt.prototype,"specularPower",void 0);z([X("useAlphaFromDiffuseTexture")],jt.prototype,"_useAlphaFromDiffuseTexture",void 0);z([_t("_markAllSubMeshesAsTexturesAndMiscDirty")],jt.prototype,"useAlphaFromDiffuseTexture",void 0);z([X("useEmissiveAsIllumination")],jt.prototype,"_useEmissiveAsIllumination",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"useEmissiveAsIllumination",void 0);z([X("linkEmissiveWithDiffuse")],jt.prototype,"_linkEmissiveWithDiffuse",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"linkEmissiveWithDiffuse",void 0);z([X("useSpecularOverAlpha")],jt.prototype,"_useSpecularOverAlpha",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"useSpecularOverAlpha",void 0);z([X("useReflectionOverAlpha")],jt.prototype,"_useReflectionOverAlpha",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"useReflectionOverAlpha",void 0);z([X("disableLighting")],jt.prototype,"_disableLighting",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],jt.prototype,"disableLighting",void 0);z([X("useObjectSpaceNormalMap")],jt.prototype,"_useObjectSpaceNormalMap",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"useObjectSpaceNormalMap",void 0);z([X("useParallax")],jt.prototype,"_useParallax",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"useParallax",void 0);z([X("useParallaxOcclusion")],jt.prototype,"_useParallaxOcclusion",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"useParallaxOcclusion",void 0);z([X()],jt.prototype,"parallaxScaleBias",void 0);z([X("roughness")],jt.prototype,"_roughness",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"roughness",void 0);z([X()],jt.prototype,"indexOfRefraction",void 0);z([X()],jt.prototype,"invertRefractionY",void 0);z([X()],jt.prototype,"alphaCutOff",void 0);z([X("useLightmapAsShadowmap")],jt.prototype,"_useLightmapAsShadowmap",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"useLightmapAsShadowmap",void 0);z([AF("diffuseFresnelParameters")],jt.prototype,"_diffuseFresnelParameters",void 0);z([_t("_markAllSubMeshesAsFresnelDirty")],jt.prototype,"diffuseFresnelParameters",void 0);z([AF("opacityFresnelParameters")],jt.prototype,"_opacityFresnelParameters",void 0);z([_t("_markAllSubMeshesAsFresnelAndMiscDirty")],jt.prototype,"opacityFresnelParameters",void 0);z([AF("reflectionFresnelParameters")],jt.prototype,"_reflectionFresnelParameters",void 0);z([_t("_markAllSubMeshesAsFresnelDirty")],jt.prototype,"reflectionFresnelParameters",void 0);z([AF("refractionFresnelParameters")],jt.prototype,"_refractionFresnelParameters",void 0);z([_t("_markAllSubMeshesAsFresnelDirty")],jt.prototype,"refractionFresnelParameters",void 0);z([AF("emissiveFresnelParameters")],jt.prototype,"_emissiveFresnelParameters",void 0);z([_t("_markAllSubMeshesAsFresnelDirty")],jt.prototype,"emissiveFresnelParameters",void 0);z([X("useReflectionFresnelFromSpecular")],jt.prototype,"_useReflectionFresnelFromSpecular",void 0);z([_t("_markAllSubMeshesAsFresnelDirty")],jt.prototype,"useReflectionFresnelFromSpecular",void 0);z([X("useGlossinessFromSpecularMapAlpha")],jt.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"useGlossinessFromSpecularMapAlpha",void 0);z([X("maxSimultaneousLights")],jt.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],jt.prototype,"maxSimultaneousLights",void 0);z([X("invertNormalMapX")],jt.prototype,"_invertNormalMapX",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"invertNormalMapX",void 0);z([X("invertNormalMapY")],jt.prototype,"_invertNormalMapY",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"invertNormalMapY",void 0);z([X("twoSidedLighting")],jt.prototype,"_twoSidedLighting",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],jt.prototype,"twoSidedLighting",void 0);z([X("applyDecalMapAfterDetailMap")],jt.prototype,"_applyDecalMapAfterDetailMap",void 0);z([_t("_markAllSubMeshesAsMiscDirty")],jt.prototype,"applyDecalMapAfterDetailMap",void 0);z([X()],jt.prototype,"useLogarithmicDepth",null);$e("BABYLON.StandardMaterial",jt);oi.DefaultMaterialFactory=a=>new jt("default material",a);Oi.prototype.createDynamicTexture=function(a,e,t,i){const s=new dn(this,hr.Dynamic);return s.baseWidth=a,s.baseHeight=e,t&&(a=this.needPOTTextures?Oi.GetExponentOfTwo(a,this._caps.maxTextureSize):a,e=this.needPOTTextures?Oi.GetExponentOfTwo(e,this._caps.maxTextureSize):e),s.width=a,s.height=e,s.isReady=!1,s.generateMipMaps=t,s.samplingMode=i,this.updateTextureSamplingMode(i,s),this._internalTexturesCache.push(s),s};Oi.prototype.updateDynamicTexture=function(a,e,t,i=!1,s,r=!1,n=!1){if(!a)return;const o=this._gl,l=o.TEXTURE_2D,c=this._bindTextureDirectly(l,a,!0,r);this._unpackFlipY(t===void 0?a.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const h=this._getWebGLTextureType(a.type),u=this._getInternalFormat(s||a.format),p=this._getRGBABufferInternalSizedFormat(a.type,u);o.texImage2D(l,0,p,u,h,e),a.generateMipMaps&&o.generateMipmap(l),c||this._bindTextureDirectly(l,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),a.isReady=!0};class ep extends Te{constructor(e,t,i=null,s=!1,r=3,n=5,o){super(null,i,!s,o,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=Te.CLAMP_ADDRESSMODE,this.wrapV=Te.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const l=this._getEngine();if(!l)return;t.getContext?(this._canvas=t,this._texture=l.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=l.createCanvas(1,1),t.width||t.width===0?this._texture=l.createDynamicTexture(t.width,t.height,s,r):this._texture=l.createDynamicTexture(t,t,s,r));const c=this.getSize();this._canvas.width!==c.width&&(this._canvas.width=c.width),this._canvas.height!==c.height&&(this._canvas.height=c.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(){const e=this.getSize();this._context.fillRect(0,0,e.width,e.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,s,r,n,o,l=!0){const c=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,c.width,c.height)),this._context.font=s,t==null){const h=this._context.measureText(e);t=(c.width-h.width)/2}if(i==null){const h=parseInt(s.replace(/\D/g,""));i=c.height/2+h/3.65}this._context.fillStyle=r||"",this._context.fillText(e,t,i),l&&this.update(o)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new ep(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()&&Me.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return ep._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()}}const w_e="imageProcessingPixelShader",N_e=`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;}`;Ue.ShadersStore[w_e]=N_e;class lW extends rs{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 s=this.getEngine(),r=this.getCamera();if(r)i=r.getScene();else if(s&&s.scenes){const n=s.scenes;i=n[n.length-1]}else i=Ii.LastCreatedScene;i?this._imageProcessingConfiguration=i.imageProcessingConfiguration:this._imageProcessingConfiguration=new Dr}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,s,r,n,o=0,l){super(e,"imageProcessing",[],[],t,i,s,r,n,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},l?(l.applyByPostProcess=!0,this._attachImageProcessingConfiguration(l,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=c=>{this.imageProcessingConfiguration.bind(c,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const s in this._defines)this._defines[s]&&(e+=`#define ${s}; +`);const t=["textureSampler"],i=["scale"];Dr&&(Dr.PrepareSamplers(t,this._defines),Dr.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)}}z([X()],lW.prototype,"_fromLinearSpace",void 0);class pee{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}}constructor(e,t,i,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.createRenderTargetTextureProvider=r}}class mee{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new dn(this._engine,hr.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new gF(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,s,r,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},l=n?new Oq(this._scene,o):new Oa("XR renderTargetTexture",o,this._scene),c=l.renderTarget;if(c._samples=l.samples,(i||!s)&&(c._framebuffer=i),s)if(n)c._colorTextureArray=s;else{const h=this._createInternalTexture(o,s);c.setTexture(h,0),l._texture=h}return r&&(n?c._depthStencilTextureArray=r:c._depthStencilTexture=this._createInternalTexture(o,r)),l.disableRescaling(),typeof XRWebGLBinding<"u"&&(l.skipInitialClear=!0),this._renderTargetTextures.push(l),l}_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 _ee extends pee{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new B_e(t.scene,this)),this.layer=e}}class B_e extends mee{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 s=this._framebufferDimensions.framebufferWidth,r=this._framebufferDimensions.framebufferHeight;return e.x=i.x/s,e.y=i.y/r,e.width=i.width/s,e.height=i.height/r,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,s=this._layer.framebuffer;return(!this._rtt||t!==this._framebufferDimensions.framebufferWidth||i!==this._framebufferDimensions.framebufferHeight||s!==this._framebuffer)&&(this._rtt=this._createRenderTargetTexture(t,i,s),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=s),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class cW{static GetDefaults(e){const t=new cW;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 vce{constructor(e,t=cW.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new Se,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 _ee(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{Be.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 Cce extends pee{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new Ace(t,this)),this.layer=e}}class Ace extends mee{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 xce{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 hW{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new Se,this.onXRReferenceSpaceChanged=new Se,this.onXRSessionEnded=new Se,this.onXRSessionInit=new Se,this.inXRFrameLoop=!1,this.inXRSession=!1,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(),(e=this._engine)===null||e===void 0||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch(()=>{Me.Warn("Could not end XR session.")})):Promise.resolve()}trySetViewportForView(e,t){var i;return((i=this._baseLayerRTTProvider)===null||i===void 0?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return((t=this._baseLayerRTTProvider)===null||t===void 0?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return((t=this._baseLayerRTTProvider)===null||t===void 0?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new xce(this):(e=e||cW.GetDefaults(t),e.canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new vce(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.onXRSessionInit.notifyObservers(i),this.inXRSession=!0,this.session.addEventListener("end",()=>{var s;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&&((s=this._baseLayerRTTProvider)===null||s===void 0||s.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return hW.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;!this.inXRSession||!this._engine||(this._engine.customAnimationFrameRequester={requestAnimationFrame:this.session.requestAnimationFrame.bind(this.session),renderFunction:(t,i)=>{var s;!this.inXRSession||!this._engine||(this.currentFrame=i,this.currentTimestamp=t,i&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=((s=this._baseLayerRTTProvider)===null||s===void 0?void 0:s.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(i),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=((e=this._baseLayerRTTProvider)===null||e===void 0?void 0:e.getFramebufferDimensions())||null,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=>(Me.Error("XR.requestReferenceSpace failed for the following reason: "),Me.Error(t),Me.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(i=>{const s=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return i.getOffsetReferenceSpace(s)},i=>{throw Me.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.referenceSpace))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&((t=this._baseLayerRTTProvider)===null||t===void 0||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=((i=this._baseLayerWrapper)===null||i===void 0?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Cce(e.baseLayer):new _ee(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 s=typeof i>"u"?!0:i;return Promise.resolve(s)}).catch(i=>(Me.Warn(i),Promise.resolve(!1))):Promise.resolve(!1)}get isNative(){var e;return(e=this._xrNavigator.xr.native)!==null&&e!==void 0?e:!1}get currentFrameRate(){var e;return(e=this.session)===null||e===void 0?void 0:e.frameRate}get supportedFrameRates(){var e;return(e=this.session)===null||e===void 0?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||e===void 0?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return((e=this._baseLayerWrapper)===null||e===void 0?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,t;return(t=(e=this.session)===null||e===void 0?void 0:e.enabledFeatures)!==null&&t!==void 0?t:null}}var Ih;(function(a){a[a.ENTERING_XR=0]="ENTERING_XR",a[a.EXITING_XR=1]="EXITING_XR",a[a.IN_XR=2]="IN_XR",a[a.NOT_IN_XR=3]="NOT_IN_XR"})(Ih||(Ih={}));var gP;(function(a){a[a.NOT_TRACKING=0]="NOT_TRACKING",a[a.TRACKING_LOST=1]="TRACKING_LOST",a[a.TRACKING=2]="TRACKING"})(gP||(gP={}));function NK(a){const e=a.height||2;let t=a.diameterTop===0?0:a.diameterTop||a.diameter||1,i=a.diameterBottom===0?0:a.diameterBottom||a.diameter||1;t=t||1e-5,i=i||1e-5;const s=(a.tessellation||24)|0,r=(a.subdivisions||1)|0,n=!!a.hasRings,o=!!a.enclose,l=a.cap===0?0:a.cap||Oe.CAP_ALL,c=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,h=a.sideOrientation===0?0:a.sideOrientation||Jt.DEFAULTSIDE,u=a.faceUV||new Array(3),p=a.faceColors,m=c!==1&&o?2:0,_=n?r:1,f=2+(1+m)*_;let d;for(d=0;d{const oe=ee?t/2:i/2;if(oe===0)return;let ae,fe,de;const me=ee?u[f-1]:u[0];let Fe=null;p&&(Fe=ee?p[f-1]:p[0]);const je=v.length/3,nt=ee?e/2:-e/2,we=new O(0,nt,0);v.push(we.x,we.y,we.z),y.push(0,ee?1:-1,0);const Ke=me.y+(me.w-me.y)*.5;M.push(me.x+(me.z-me.x)*.5,fn.UseOpenGLOrientationForUV?1-Ke:Ke),Fe&&b.push(Fe.r,Fe.g,Fe.b,Fe.a);const ft=new lt(.5,.5);for(de=0;de<=s;de++){ae=Math.PI*2*de*c/s;const yt=Math.cos(-ae),Ze=Math.sin(-ae);fe=new O(yt*oe,nt,Ze*oe);const mt=new lt(yt*ft.x+.5,Ze*ft.y+.5);v.push(fe.x,fe.y,fe.z),y.push(0,ee?1:-1,0);const Je=me.y+(me.w-me.y)*mt.y;M.push(me.x+(me.z-me.x)*mt.x,fn.UseOpenGLOrientationForUV?1-Je:Je),Fe&&b.push(Fe.r,Fe.g,Fe.b,Fe.a)}for(de=0;de((n===void 0||!(n instanceof oi))&&(n!==void 0&&(l=o||Oe.DEFAULTSIDE,o=n),n=r,r=1),J1(a,{height:e,diameterTop:t,diameterBottom:i,tessellation:s,subdivisions:r,sideOrientation:l,updatable:o},n));function BK(a){const e=[],t=[],i=[],s=[],r=a.diameter||1,n=a.thickness||.5,o=(a.tessellation||16)|0,l=a.sideOrientation===0?0:a.sideOrientation||Jt.DEFAULTSIDE,c=o+1;for(let u=0;u<=o;u++){const p=u/o,m=u*Math.PI*2/o-Math.PI/2,_=ge.Translation(r/2,0,0).multiply(ge.RotationY(m));for(let f=0;f<=o;f++){const d=1-f/o,C=f*Math.PI*2/o+Math.PI,v=Math.cos(C),y=Math.sin(C);let M=new O(v,y,0),b=M.scale(n/2);const E=new lt(p,d);b=O.TransformCoordinates(b,_),M=O.TransformNormal(M,_),t.push(b.x,b.y,b.z),i.push(M.x,M.y,M.z),s.push(E.x,fn.UseOpenGLOrientationForUV?1-E.y:E.y);const S=(u+1)%c,I=(f+1)%c;e.push(u*c+f),e.push(u*c+I),e.push(S*c+f),e.push(u*c+I),e.push(S*c+I),e.push(S*c+f)}}Jt._ComputeSides(l,t,e,i,s,a.frontUVs,a.backUVs);const h=new Jt;return h.indices=e,h.positions=t,h.normals=i,h.uvs=s,h}function r7(a,e={},t){const i=new Oe(a,t);return e.sideOrientation=Oe._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,BK(e).applyToMesh(i,e.updatable),i}const V_e={CreateTorus:r7};Jt.CreateTorus=BK;Oe.CreateTorus=(a,e,t,i,s,r,n)=>r7(a,{diameter:e,thickness:t,tessellation:i,sideOrientation:n,updatable:r},s);Oe._GroundMeshParser=(a,e)=>IF.Parse(a,e);class IF extends Oe{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(),s=ue.Matrix[5];i.invertToRef(s);const r=ue.Vector3[8];if(O.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.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 n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return O.TransformCoordinatesFromFloatsToRef(0,o,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new O(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=ue.Matrix[5];s.invertToRef(r);const n=ue.Vector3[8];if(O.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return O.TransformNormalFromFloatsToRef(o.x,o.y,o.z,s,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),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return ta.maxHeight){c=!0;const u=a.maxHeight;a.maxHeight=a.minHeight,a.minHeight=u}for(r=0;r<=a.subdivisions;r++)for(n=0;n<=a.subdivisions;n++){const u=new O(n*a.width/a.subdivisions-a.width/2,0,(a.subdivisions-r)*a.height/a.subdivisions-a.height/2),p=(u.x+a.width/2)/a.width*(a.bufferWidth-1)|0,m=(1-(u.z+a.height/2)/a.height)*(a.bufferHeight-1)|0,_=(p+m*a.bufferWidth)*4;let f=a.buffer[_]/255,d=a.buffer[_+1]/255,C=a.buffer[_+2]/255;const v=a.buffer[_+3]/255;c&&(f=1-f,d=1-d,C=1-C);const y=f*o.r+d*o.g+C*o.b;v>=l?u.y=a.minHeight+(a.maxHeight-a.minHeight)*y:u.y=a.minHeight-Ls,t.push(u.x,u.y,u.z),i.push(0,0,0),s.push(n/a.subdivisions,1-r/a.subdivisions)}for(r=0;r=a.minHeight,d=t[p*3+1]>=a.minHeight,C=t[m*3+1]>=a.minHeight;f&&d&&C&&(e.push(u),e.push(p),e.push(m)),t[_*3+1]>=a.minHeight&&f&&C&&(e.push(_),e.push(u),e.push(m))}Jt.ComputeNormals(t,e,i);const h=new Jt;return h.indices=e,h.positions=t,h.normals=i,h.uvs=s,h}function aD(a,e={},t){const i=new IF(a,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,SM(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function FK(a,e,t=null){const i=new Oe(a,t);return gee(e).applyToMesh(i,e.updatable),i}function VK(a,e,t={},i=null){const s=t.width||10,r=t.height||10,n=t.subdivisions||1,o=t.minHeight||0,l=t.maxHeight||1,c=t.colorFilter||new Ie(.3,.59,.11),h=t.alphaFilter||0,u=t.updatable,p=t.onReady;i=i||Ii.LastCreatedScene;const m=new IF(a,i);m._subdivisionsX=n,m._subdivisionsY=n,m._width=s,m._height=r,m._maxX=m._width/2,m._maxZ=m._height/2,m._minX=-m._maxX,m._minZ=-m._maxZ,m._setReady(!1);const _=f=>{const d=f.width,C=f.height;if(i.isDisposed)return;const v=i?.getEngine().resizeImageBitmap(f,d,C);vee({width:s,height:r,subdivisions:n,minHeight:o,maxHeight:l,colorFilter:c,buffer:v,bufferWidth:d,bufferHeight:C,alphaFilter:h}).applyToMesh(m,u),p&&p(m),m._setReady(!0)};return Be.LoadImage(e,_,()=>{},i.offlineProvider),m}const z_e={CreateGround:aD,CreateGroundFromHeightMap:VK,CreateTiledGround:FK};Jt.CreateGround=SM;Jt.CreateTiledGround=gee;Jt.CreateGroundFromHeightMap=vee;Oe.CreateGround=(a,e,t,i,s,r)=>aD(a,{width:e,height:t,subdivisions:i,updatable:r},s);Oe.CreateTiledGround=(a,e,t,i,s,r,n,o,l)=>FK(a,{xmin:e,zmin:t,xmax:i,zmax:s,subdivisions:r,precision:n,updatable:l},o);Oe.CreateGroundFromHeightMap=(a,e,t,i,s,r,n,o,l,c,h)=>VK(a,e,{width:t,height:i,subdivisions:s,minHeight:r,maxHeight:n,updatable:l,onReady:c,alphaFilter:h},o);class uW{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=uW._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=r7("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const i=new jt("targetMat",e);i.specularColor=Ie.Black(),i.emissiveColor=new Ie(.7,.7,.7),i.backFaceCulling=!1,this._gazeTracker.material=i}}_getForwardRay(e){return new gr(O.Zero(),new O(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()}}uW._IdCounter=0;class U_e extends uW{constructor(e,t,i){super(t,i),this.webVRController=e,this._laserPointer=J1("laserPointer",{updatable:!1,height:1,diameterTop:.004,diameterBottom:2e-4,tessellation:20,subdivisions:1},t);const s=new jt("laserPointerMat",t);if(s.emissiveColor=new Ie(.7,.7,.7),s.alpha=.6,this._laserPointer.material=s,this._laserPointer.rotation.x=Math.PI/2,this._laserPointer.position.z=-.5,this._laserPointer.isVisible=!1,this._laserPointer.isPickable=!1,!e.mesh){const r=new Oe("preloadControllerMesh",t),n=new Oe(GP.POINTING_POSE,t);n.rotation.x=-.7,r.addChild(n),e.attachToMesh(r)}this._setLaserPointerParent(e.mesh),this._meshAttachedObserver=e._meshAttachedObservable.add(r=>{this._setLaserPointerParent(r)})}_getForwardRay(e){return this.webVRController.getForwardRay(e)}_activatePointer(){super._activatePointer(),this._laserPointer.isVisible=!0}_deactivatePointer(){super._deactivatePointer(),this._laserPointer.isVisible=!1}_setLaserPointerColor(e){this._laserPointer.material.emissiveColor=e}_setLaserPointerLightingDisabled(e){this._laserPointer.material.disableLighting=e}_setLaserPointerParent(e){const t=r=>{r.isPickable=!1,r.getChildMeshes().forEach(n=>{t(n)})};t(e);const i=e.getChildren(void 0,!1);let s=e;this.webVRController._pointingPoseNode=null;for(let r=0;r=0){s=i[r],this.webVRController._pointingPoseNode=s;break}this._laserPointer.parent=s}_updatePointerDistance(e=100){this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2}dispose(){super.dispose(),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)}}class Nse extends uW{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new gr(O.Zero(),O.Forward())}}class k_e{}class WP{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get onControllerMeshLoaded(){return this.onControllerMeshLoadedObservable}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._leftController&&this._leftController._gazeTracker&&this._leftController._gazeTracker.dispose(),this._rightController&&this._rightController._gazeTracker&&this._rightController._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",this._leftController&&(this._leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this._rightController&&(this._rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))}get leftControllerGazeTrackerMesh(){return this._leftController?this._leftController._gazeTracker:null}get rightControllerGazeTrackerMesh(){return this._rightController?this._rightController._gazeTracker:null}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1))}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e,e?(this._rightController&&this._rightController._activatePointer(),this._leftController&&this._leftController._activatePointer()):(this._rightController&&(this._rightController._deactivatePointer(),this._rightController._gazeTracker.isVisible=!1),this._leftController&&(this._leftController._deactivatePointer(),this._leftController._gazeTracker.isVisible=!1))}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._webVRready?this._webVRCamera:this._scene.activeCamera}get webVRCamera(){return this._webVRCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated||this._leftController!==null&&this._leftController._teleportationRequestInitiated||this._rightController!==null&&this._rightController._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new Se,this.onAfterEnteringVRObservable=new Se,this.onExitingVRObservable=new Se,this.onControllerMeshLoadedObservable=new Se,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=WP.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new O(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new O(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._leftController=null,this._rightController=null,this._gazeColor=new Ie(.7,.7,.7),this._laserColor=new Ie(.7,.7,.7),this._pickedLaserColor=new Ie(.2,.2,1),this._pickedGazeColor=new Ie(0,0,1),this.onNewMeshSelected=new Se,this.onMeshSelectedWithController=new Se,this.onNewMeshPicked=new Se,this.onBeforeCameraTeleport=new Se,this.onAfterCameraTeleport=new Se,this.onSelectedMeshUnselected=new Se,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!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._fullscreenVRpresenting&&this._webVRready&&this.exitVR()},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._leftController&&this._leftController._activePointer&&this._castRayAndSelectObject(this._leftController),this._rightController&&this._rightController._activePointer&&this._castRayAndSelectObject(this._rightController),this._noControllerIsActive&&(this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock)?this._castRayAndSelectObject(this._cameraGazer):this._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=s=>{if(s.type!==fc.POSE_ENABLED)s.leftStick&&s.onleftstickchanged(r=>{this._teleportationInitialized&&this.teleportationEnabled&&(!this._leftController&&!this._rightController||this._leftController&&!this._leftController._activePointer&&this._rightController&&!this._rightController._activePointer)&&(this._checkTeleportWithRay(r,this._cameraGazer),this._checkTeleportBackwards(r,this._cameraGazer))}),s.rightStick&&s.onrightstickchanged(r=>{this._teleportationInitialized&&this._checkRotate(r,this._cameraGazer)}),s.type===fc.XBOX&&(s.onbuttondown(r=>{this._interactionsEnabled&&r===X3.A&&this._cameraGazer._selectionPointerDown()}),s.onbuttonup(r=>{this._interactionsEnabled&&r===X3.A&&this._cameraGazer._selectionPointerUp()}));else{const r=s,n=new U_e(r,this._scene,this._cameraGazer._gazeTracker);r.hand==="right"||this._leftController&&this._leftController.webVRController!=r?this._rightController=n:this._leftController=n,this._tryEnableInteractionOnController(n)}},this._tryEnableInteractionOnController=s=>{this._interactionsRequested&&!s._interactionsEnabled&&this._enableInteractionOnController(s),this._teleportationRequested&&!s._teleportationEnabled&&this._enableTeleportationOnController(s)},this._onNewGamepadDisconnected=s=>{s instanceof QL&&(s.hand==="left"&&this._leftController!=null&&(this._leftController.dispose(),this._leftController=null),s.hand==="right"&&this._rightController!=null&&(this._rightController.dispose(),this._rightController=null))},this._workingVector=O.Zero(),this._workingQuaternion=ke.Identity(),this._workingMatrix=ge.Identity(),Me.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),t.defaultHeight===void 0&&(t.defaultHeight=1.7),t.useCustomVRButton&&(this._useCustomVRButton=!0,t.customVRButton&&(this._btnVR=t.customVRButton)),t.rayLength&&(this._rayLength=t.rayLength),this._defaultHeight=t.defaultHeight,t.positionScale&&(this._rayLength*=t.positionScale,this._defaultHeight*=t.positionScale),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new O(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new RK("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 Zl&&this._scene.activeCamera.rotation)){const s=this._scene.activeCamera;s.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(s.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(ke.RotationYawPitchRoll(s.rotation.y,s.rotation.x,s.rotation.z)),this._deviceOrientationCamera.rotation=s.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?hW.IsSessionSupportedAsync("immersive-vr").then(s=>{s?(Me.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then(r=>{this.xr=r,this.xrTestDone=!0,this._cameraGazer=new Nse(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(n=>{switch(n){case Ih.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case Ih.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case Ih.IN_XR:this._hasEnteredVR=!0;break;case Ih.NOT_IN_XR:this._hasEnteredVR=!1;break}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(t.useMultiview&&(t.vrDeviceOrientationCameraMetrics||(t.vrDeviceOrientationCameraMetrics=KL.GetDefault()),t.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new OK("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new wK("WebVRHelper",this._position,this._scene,t),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new Nse(()=>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 r=".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) }";r+=".babylonVRicon.vrdisplaypresenting { display: none; }";const n=document.createElement("style");n.appendChild(document.createTextNode(r)),document.getElementsByTagName("head")[0].appendChild(n),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode?this._scene.getEngine().disableVR():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._scene.getEngine().onVRDisplayChangedObservable.add(s=>{s.vrDisplay&&this._displayVRButton()}),this._onKeyDown=s=>{s.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())},mi.POINTERDOUBLETAP,!1),this._onVRDisplayChangedBind=s=>this._onVRDisplayChanged(s),this._onVrDisplayPresentChangeBind=()=>this._onVrDisplayPresentChange(),this._onVRRequestPresentStart=()=>{this._webVRrequesting=!0,this._updateButtonVisibility()},this._onVRRequestPresentComplete=()=>{this._webVRrequesting=!1,this._updateButtonVisibility()},e.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChangedBind),e.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),e.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),i.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),e.onDisposeObservable.add(()=>{this.dispose()}),this._webVRCamera.onControllerMeshLoadedObservable.add(s=>this._onDefaultMeshLoaded(s)),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this._updateButtonVisibility(),this._circleEase=new Ale,this._circleEase.setEasingMode(Pc.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(s=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&s.event.pointerType==="mouse"&&(s.type===mi.POINTERDOWN?this._cameraGazer._selectionPointerDown():s.type===mi.POINTERUP&&this._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}_onDefaultMeshLoaded(e){this._leftController&&this._leftController.webVRController==e&&e.mesh&&this._leftController._setLaserPointerParent(e.mesh),this._rightController&&this._rightController.webVRController==e&&e.mesh&&this._rightController._setLaserPointerParent(e.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(e)}catch(t){Me.Warn("Error in your custom logic onControllerMeshLoaded: "+t)}}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===Ih.IN_XR||this._webVRpresenting||this._fullscreenVRpresenting}_onVrDisplayPresentChange(){const e=this._scene.getEngine().getVRDevice();if(e){const t=this._webVRpresenting;this._webVRpresenting=e.isPresenting,t&&!this._webVRpresenting&&this.exitVR()}else Me.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this._updateButtonVisibility()}_onVRDisplayChanged(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this._updateButtonVisibility()}_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":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))}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){Me.Warn("Error in your custom logic onEnteringVR: "+e)}if(this._scene.activeCamera){if(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=ke.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this.webVRCamera){const e=this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y,i=ke.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y-e,s=this.webVRCamera.rotationQuaternion.toEulerAngles().y;this.webVRCamera.rotationQuaternion=ke.FromEulerAngles(0,s+i,0)}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._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._scene.getEngine().onVRRequestPresentComplete.addOnce(e=>{this.onAfterEnteringVRObservable.notifyObservers({success:e})}),this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):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._displayLaserPointer&&[this._leftController,this._rightController].forEach(e=>{e&&e._activatePointer()}),this._hasEnteredVR=!0)}exitVR(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(t){Me.Warn("Error in your custom logic onExitingVR: "+t)}this._webVRpresenting&&this._scene.getEngine().disableVR(),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._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1)),this._scene.getEngine().resize(),[this._leftController,this._rightController].forEach(t=>{t&&t._deactivatePointer()}),this._hasEnteredVR=!1;const e=this._scene.getEngine();e._onVrDisplayPresentChange&&e._onVrDisplayPresentChange()}}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._interactionsRequested=!0,this.xr){this.xr.baseExperience.state===Ih.IN_XR&&this.xr.pointerSelection.attach();return}this._leftController&&this._enableInteractionOnController(this._leftController),this._rightController&&this._enableInteractionOnController(this._rightController),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}}get _noControllerIsActive(){return!(this._leftController&&this._leftController._activePointer)&&!(this._rightController&&this._rightController._activePointer)}_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._teleportationRequested=!0,this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const i=e.floorMeshes||[];if(!i.length){const s=this._scene.getMeshByName(e.floorMeshName);s&&i.push(s)}if(this.xr){i.forEach(s=>{this.xr.teleportation.addFloorMesh(s)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}else if(!this.xrTestDone){const s=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(s),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(s);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),this._leftController!=null&&this._enableTeleportationOnController(this._leftController),this._rightController!=null&&this._enableTeleportationOnController(this._rightController);const t=new Dr;t.vignetteColor=new Zt(0,0,0,0),t.vignetteEnabled=!0,this._postProcessMove=new lW("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,t),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}}_enableInteractionOnController(e){e.webVRController.mesh&&(e._interactionsEnabled=!0,this.isInVRMode&&this._displayLaserPointer&&e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add(i=>{this._displayLaserPointer&&i.value===1&&(e._activePointer?e._deactivatePointer():e._activatePointer(),this.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))}),e.webVRController.onTriggerStateChangedObservable.add(i=>{let s=e;this._noControllerIsActive&&(s=this._cameraGazer),s._pointerDownOnMeshAsked?i.valuethis._padSensibilityUp&&s._selectionPointerDown()}))}_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;let i=ke.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),s=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(i=this.currentVRCamera.deviceRotationQuaternion,s=this.currentVRCamera.devicePosition),i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,ke.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),O.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const r=new gr(s,this._workingVector),n=this._scene.pickWithRay(r,this._raySelectionPredicate);n&&n.pickedPoint&&n.pickedMesh&&this._isTeleportationFloor(n.pickedMesh)&&n.distance<5&&this.teleportCamera(n.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_enableTeleportationOnController(e){e.webVRController.mesh&&(e._interactionsEnabled||this._enableInteractionOnController(e),e._interactionsEnabled=!0,e._teleportationEnabled=!0,e.webVRController.controllerType===s7.VIVE&&(e._dpadPressed=!1,e.webVRController.onPadStateChangedObservable.add(i=>{e._dpadPressed=i.pressed,e._dpadPressed||(e._rotationLeftAsked=!1,e._rotationRightAsked=!1,e._teleportationBackRequestInitiated=!1)})),e.webVRController.onPadValuesChangedObservable.add(i=>{this.teleportationEnabled&&(this._checkTeleportBackwards(i,e),this._checkTeleportWithRay(i,e)),this._checkRotate(i,e)}))}_createTeleportationCircles(){this._teleportationTarget=aD("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=512,t=new ep("DynamicTexture",e,this._scene,!0);t.hasAlpha=!0;const i=t.getContext(),s=e/2,r=e/2,n=200;i.beginPath(),i.arc(s,r,n,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 jt("TextPlaneMaterial",this._scene);o.diffuseTexture=t,this._teleportationTarget.material=o;const l=r7("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);l.isPickable=!1,l.parent=this._teleportationTarget;const c=new at("animationInnerCircle","position.y",30,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CYCLE),h=[];h.push({frame:0,value:0}),h.push({frame:30,value:.4}),h.push({frame:60,value:0}),c.setKeys(h);const u=new W$;u.setEasingMode(Pc.EASINGMODE_EASEINOUT),c.setEasingFunction(u),l.animations=[],l.animations.push(c),this._scene.beginAnimation(l,0,60,!0),this._hideTeleportationTarget()}_displayTeleportationTarget(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof q1))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=ke.FromRotationMatrix(ge.RotationY(Math.PI/4*this._rotationAngle)),i=new at("animationRotation","rotationQuaternion",90,at.ANIMATIONTYPE_QUATERNION,at.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),s.push({frame:6,value:t}),i.setKeys(s),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const r=new at("animationPP","vignetteWeight",90,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),r.setKeys(n),r.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(r);const o=new at("animationPP2","vignetteStretch",90,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:3,value:10}),l.push({frame:6,value:0}),o.setKeys(l),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,()=>{this._webVRCamera.detachPostProcess(this._postProcessMove)}),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}_moveTeleportationSelectorTo(e,t,i){if(e.pickedPoint){t._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(e.pickedPoint),this._teleportationTarget.position.copyFrom(e.pickedPoint));const s=this._convertNormalToDirectionOfRay(e.getNormal(!0,!1),i);if(s){const r=O.Cross(Fo.Y,s),n=O.Cross(s,r);O.RotationFromAxisToRef(n,s,r,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}}teleportCamera(e){if(!(this.currentVRCamera instanceof q1))return;this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),e.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(e),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector);const t=90;let i,s;if(this._teleportationMode==WP.TELEPORTATIONMODE_CONSTANTSPEED){s=t;const p=O.Distance(this.currentVRCamera.position,this._workingVector);i=this._teleportationSpeed/p}else s=Math.round(this._teleportationTime*t/1e3),i=1;this.currentVRCamera.animations=[];const r=new at("animationCameraTeleportation","position",t,at.ANIMATIONTYPE_VECTOR3,at.ANIMATIONLOOPMODE_CONSTANT),n=[{frame:0,value:this.currentVRCamera.position},{frame:s,value:this._workingVector}];r.setKeys(n),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];const o=Math.round(s/2),l=new at("animationPP","vignetteWeight",t,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CONSTANT),c=[];c.push({frame:0,value:0}),c.push({frame:o,value:8}),c.push({frame:s,value:0}),l.setKeys(c),this._postProcessMove.animations.push(l);const h=new at("animationPP2","vignetteStretch",t,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CONSTANT),u=[];u.push({frame:0,value:0}),u.push({frame:o,value:10}),u.push({frame:s,value:0}),h.setKeys(u),this._postProcessMove.animations.push(h),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,s,!1,i,()=>{this._webVRCamera.detachPostProcess(this._postProcessMove)}),this._scene.beginAnimation(this.currentVRCamera,0,s,!1,i,()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)}),this._hideTeleportationTarget()}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(O.Dot(e,t.direction))!(a.x>t.x+i||t.x-i>e.x||a.y>t.y+i||t.y-i>e.y||a.z>t.z+i||t.z-i>e.z),dN=function(){const a={root:0,found:!1};return function(e,t,i,s){a.root=0,a.found=!1;const r=t*t-4*e*i;if(r<0)return a;const n=Math.sqrt(r);let o=(-t-n)/(2*e),l=(-t+n)/(2*e);if(o>l){const c=l;l=o,o=c}return o>0&&o0&&l=0)}_canDoCollision(e,t,i,s){const r=O.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!H_e(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,o){let l,c=!1;t||(t=[]),t[e]||(t[e]=new Zd(0,0,0,0),t[e].copyFromPoints(i,s,r));const h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;const u=h.signedDistanceTo(this._basePoint),p=O.Dot(h.normal,this._velocity);if(dW.DoubleSidedCheck&&p>1e-4)return;if(p==0){if(Math.abs(u)>=1)return;c=!0,l=0}else{l=(-1-u)/p;let f=(1-u)/p;if(l>f){const d=f;f=l,l=d}if(l>1||f<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);let m=!1,_=1;if(c||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,s,r,h.normal)&&(m=!0,_=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!m){let f=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let d=2*O.Dot(this._velocity,this._tempVector),C=this._tempVector.lengthSquared()-1,v=dN(f,d,C,_);v.found&&(_=v.root,m=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),d=2*O.Dot(this._velocity,this._tempVector),C=this._tempVector.lengthSquared()-1,v=dN(f,d,C,_),v.found&&(_=v.root,m=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),d=2*O.Dot(this._velocity,this._tempVector),C=this._tempVector.lengthSquared()-1,v=dN(f,d,C,_),v.found&&(_=v.root,m=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let y=this._edge.lengthSquared(),M=O.Dot(this._edge,this._velocity),b=O.Dot(this._edge,this._baseToVertex);if(f=y*-this._velocitySquaredLength+M*M,d=2*(y*O.Dot(this._velocity,this._baseToVertex)-M*b),C=y*(1-this._baseToVertex.lengthSquared())+b*b,v=dN(f,d,C,_),v.found){const E=(M*v.root-b)/y;E>=0&&E<=1&&(_=v.root,m=!0,this._edge.scaleInPlace(E),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),y=this._edge.lengthSquared(),M=O.Dot(this._edge,this._velocity),b=O.Dot(this._edge,this._baseToVertex),f=y*-this._velocitySquaredLength+M*M,d=2*(y*O.Dot(this._velocity,this._baseToVertex)-M*b),C=y*(1-this._baseToVertex.lengthSquared())+b*b,v=dN(f,d,C,_),v.found){const E=(M*v.root-b)/y;E>=0&&E<=1&&(_=v.root,m=!0,this._edge.scaleInPlace(E),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),y=this._edge.lengthSquared(),M=O.Dot(this._edge,this._velocity),b=O.Dot(this._edge,this._baseToVertex),f=y*-this._velocitySquaredLength+M*M,d=2*(y*O.Dot(this._velocity,this._baseToVertex)-M*b),C=y*(1-this._baseToVertex.lengthSquared())+b*b,v=dN(f,d,C,_),v.found){const E=(M*v.root-b)/y;E>=0&&E<=1&&(_=v.root,m=!0,this._edge.scaleInPlace(E),r.addToRef(this._edge,this._collisionPoint))}}if(m){const f=_*_*this._velocitySquaredLength;(!this.collisionFound||f=s){r.copyFrom(e);return}const l=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const c=n&&n.surroundingMeshes||this._scene.meshes;for(let h=0;hnew bce;class YP{constructor(e,t,i,s=""){var r,n;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new Se,this.onErrorObservable=new Se,this.onBindObservable=new Se,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=Ao.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=YP._UniqueIdSeed++,this.defines=(r=t.defines)!==null&&r!==void 0?r:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=(n=t.entryPoint)!==null&&n!==void 0?n:"main",this._shaderStore=Ue.GetShadersStore(this._shaderLanguage),this._shaderRepository=Ue.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Ue.GetIncludesShadersStore(this._shaderLanguage);let o;const l=ql()?this._engine.getHostDocument():null;e.computeSource?o="source:"+e.computeSource:e.computeElement?(o=l?l.getElementById(e.computeElement):null,o||(o=e.computeElement)):o=e.compute||e;const c={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(o,"Compute","",h=>{rv.Initialize(c),rv.PreProcess(h,c,u=>{this._rawComputeSourceCode=h,t.processFinalCode&&(u=t.processFinalCode(u));const p=rv.Finalize(u,"",c);this._useFinalCode(p.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,s){if(typeof HTMLElement<"u"&&e instanceof HTMLElement){const n=OG(e);s(n);return}if(e.substr(0,7)==="source:"){s(e.substr(7));return}if(e.substr(0,7)==="base64:"){const n=window.atob(e.substr(7));s(n);return}if(this._shaderStore[e+t+"Shader"]){s(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){s(this._shaderStore[e+i+"Shader"]);return}let r;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?r=e:r=this._shaderRepository+e,this._engine._loadFile(r+"."+t.toLowerCase()+".fx",s)}get computeSourceCode(){var e,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:(t=(e=this._pipelineContext)===null||e===void 0?void 0:e._getComputeShaderCode())!==null&&t!==void 0?t: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 s=null;if(t&&e){const r=t.match(i);if(r&&r.length===2){const n=parseInt(r[1]),o=e.split(` +`,-1);o.length>=n&&(s=`Offending line [${n}] in compute code: ${o[n-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,Me.Error("Unable to compile compute effect:"),Me.Error(`Defines: +`+this.defines),YP.LogShaderCodeOnCompilationError){let s=null,r=null;!((i=this._pipelineContext)===null||i===void 0)&&i._getComputeShaderCode()&&([r,s]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),r&&(Me.Error("Compute code:"),Me.Error(r))),s&&Me.Error(s)}Me.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){Ue.GetShadersStore(Ao.WGSL)[`${e}ComputeShader`]=t}}YP._UniqueIdSeed=0;YP.LogShaderCodeOnCompilationError=!0;var go;(function(a){a[a.Texture=0]="Texture",a[a.StorageTexture=1]="StorageTexture",a[a.UniformBuffer=2]="UniformBuffer",a[a.StorageBuffer=3]="StorageBuffer",a[a.TextureWithoutSampler=4]="TextureWithoutSampler",a[a.Sampler=5]="Sampler",a[a.ExternalTexture=6]="ExternalTexture"})(go||(go={}));Oi.prototype.createComputeEffect=function(a,e){throw new Error("createComputeEffect: This engine does not support compute shaders!")};Oi.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")};Oi.prototype.createComputeContext=function(){};Oi.prototype.computeDispatch=function(a,e,t,i,s,r,n){throw new Error("computeDispatch: This engine does not support compute shaders!")};Oi.prototype.areAllComputeEffectsReady=function(){return!0};Oi.prototype.releaseComputeEffects=function(){};Oi.prototype._prepareComputePipelineContext=function(a,e,t,i,s){};Oi.prototype._rebuildComputeEffects=function(){};Oi.prototype._executeWhenComputeStateIsCompiled=function(a,e){e()};Oi.prototype._releaseComputeEffect=function(a){};Oi.prototype._deleteComputePipelineContext=function(a){};class LF{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,s={}){if(this._bindings={},this._samplers={},this._contextIsDirty=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=VG.UniqueId,!this._engine.getCaps().supportComputeShaders){Me.Error("This engine does not support compute shaders!");return}if(!s.bindingsMapping){Me.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!");return}this._context=t.createComputeContext(),this._shaderPath=i,this._options=Object.assign({bindingsMapping:{},defines:[]},s)}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){const s=this._bindings[e];this._bindings[e]={type:i?go.Texture:go.TextureWithoutSampler,object:t,indexInGroupEntries:s?.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!s||s.object!==t||s.type!==this._bindings[e].type)}setStorageTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:go.StorageTexture,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setExternalTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:go.ExternalTexture,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setVideoTexture(e,t){return t.externalTexture?(this.setExternalTexture(e,t.externalTexture),!0):!1}setUniformBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:go.UniformBuffer,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setStorageBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:go.StorageBuffer,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setTextureSampler(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:go.Sampler,object:t,indexInGroupEntries:i?.indexInGroupEntries}}isReady(){let e=this._effect;for(const r in this._bindings){const n=this._bindings[r],o=n.type,l=n.object;switch(o){case go.Texture:case go.TextureWithoutSampler:case go.StorageTexture:{if(!l.isReady())return!1;break}case go.ExternalTexture:{if(!l.isReady())return!1;break}}}const t=[],i=this._shaderPath;if(this._options.defines)for(let r=0;r{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()})}serialize(){const e=Kt.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],s=i.object;switch(i.type){case go.Texture:case go.TextureWithoutSampler:case go.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case go.UniformBuffer:break}}return e}static Parse(e,t,i){const s=Kt.Parse(()=>new LF(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(const r in e.textures){const n=e.bindings[r],o=Te.Parse(e.textures[r],t,i);n.type===go.Texture?s.setTexture(r,o):n.type===go.TextureWithoutSampler?s.setTexture(r,o,!1):s.setStorageTexture(r,o)}return s}}z([X()],LF.prototype,"name",void 0);$e("BABYLON.ComputeShader",LF);class Vj{constructor(e,t,i,s,r,n){this.entries=new Array,this._boundingVectors=new Array,this._capacity=i,this._depth=s,this._maxDepth=r,this._creationFunc=n,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=a.getBoundingInfo();!a.isBlocked&&t.boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(a)};XP.CreationFuncForSubMeshes=(a,e)=>{a.getBoundingInfo().boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(a)};oi.prototype.createOrUpdateSelectionOctree=function(a=64,e=2){let t=this._getComponent(ai.NAME_OCTREE);t||(t=new Cee(this),this._addComponent(t)),this._selectionOctree||(this._selectionOctree=new XP(XP.CreationFuncForMeshes,a,e));const i=this.getWorldExtends();return this._selectionOctree.update(i.min,i.max,this.meshes),this._selectionOctree};Object.defineProperty(oi.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0});Ir.prototype.createOrUpdateSubmeshesOctree=function(a=64,e=2){const t=this.getScene();let i=t._getComponent(ai.NAME_OCTREE);i||(i=new Cee(t),t._addComponent(i)),this._submeshesOctree||(this._submeshesOctree=new XP(XP.CreationFuncForSubMeshes,a,e)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class Cee{constructor(e){this.name=ai.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new gr(O.Zero(),new O(1,1,1)),e=e||Ii.LastCreatedScene,e&&(this.scene=e,this.scene.getActiveMeshCandidates=this.getActiveMeshCandidates.bind(this),this.scene.getActiveSubMeshCandidates=this.getActiveSubMeshCandidates.bind(this),this.scene.getCollidingSubMeshCandidates=this.getCollidingSubMeshCandidates.bind(this),this.scene.getIntersectingSubMeshCandidates=this.getIntersectingSubMeshCandidates.bind(this))}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?.addMesh(e)})}getActiveMeshCandidates(){var e;return((e=this.scene._selectionOctree)===null||e===void 0?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?(gr.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(){}}class Mn{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 gn("shared gizmo light",new O(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Ie.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return Mn._DefaultUtilityLayer==null?Mn._CreateDefaultUtilityLayerFromScene(Ii.LastCreatedScene):Mn._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Mn._DefaultUtilityLayer=new Mn(e),Mn._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{Mn._DefaultUtilityLayer=null}),Mn._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return Mn._DefaultKeepDepthUtilityLayer==null&&(Mn._DefaultKeepDepthUtilityLayer=new Mn(Ii.LastCreatedScene),Mn._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Mn._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{Mn._DefaultKeepDepthUtilityLayer=null})),Mn._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 Se,this.utilityLayerScene=new oi(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!==mi.POINTERMOVE&&i.type!==mi.POINTERUP&&i.type!==mi.POINTERDOWN&&i.type!==mi.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const s=i.event;if(e.isPointerCaptured(s.pointerId)){this._pointerCaptures[s.pointerId]=!1;return}const r=o=>{let l=null;if(i.nearInteractionPickingInfo)i.nearInteractionPickingInfo.pickedMesh.getScene()==o?l=i.nearInteractionPickingInfo:l=new cu;else if(o!==this.utilityLayerScene&&i.originalPickingInfo)l=i.originalPickingInfo;else{let c=null;this._renderCamera&&(c=o._activeCamera,o._activeCamera=this._renderCamera,i.ray=null),l=i.ray?o.pickWithRay(i.ray):o.pick(e.pointerX,e.pointerY),c&&(o._activeCamera=c)}return l},n=r(this.utilityLayerScene);if(!i.ray&&n&&(i.ray=n.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(i),this.onlyCheckPointerDownEvents&&i.type!=mi.POINTERDOWN){i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new J6(i.type,i.event,n),i.type),i.type===mi.POINTERUP&&this._pointerCaptures[s.pointerId]&&(this._pointerCaptures[s.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)n&&n.hit&&(i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new J6(i.type,i.event,n),i.type),i.skipOnPointerObservable=!0);else{const o=r(e),l=i.event;o&&n&&(n.distance===0&&o.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(o.pickedMesh)?(this._notifyObservers(i,o,l),i.skipOnPointerObservable=!0):i.type===mi.POINTERDOWN?this._pointerCaptures[l.pointerId]=!0:(i.type===mi.POINTERMOVE||i.type===mi.POINTERUP)&&(this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,o,l)):!this._pointerCaptures[l.pointerId]&&(n.distance0)):!this._pointerCaptures[l.pointerId]&&n.distance>=o.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(o.pickedMesh)?(this._notifyObservers(i,o,l),i.skipOnPointerObservable=!0):((i.type===mi.POINTERMOVE||i.type===mi.POINTERUP)&&this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,n,l))),i.type===mi.POINTERUP&&this._pointerCaptures[l.pointerId]&&(this._pointerCaptures[l.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 J6(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()}}Mn._DefaultUtilityLayer=null;Mn._DefaultKeepDepthUtilityLayer=null;var zj;(function(a){a[a.Origin=0]="Origin",a[a.Pivot=1]="Pivot"})(zj||(zj={}));var UB;(function(a){a[a.World=0]="World",a[a.Local=1]="Local"})(UB||(UB={}));class ua{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}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==UB.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=t}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=Mn.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=zj.Origin,this._updateScale=!0,this._coordinatesMode=UB.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=ge.RotationY(Math.PI),this._rootMesh=new Oe("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=ke.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==zj.Pivot&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new O(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,ua.PreserveScaling?i:void 0)}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;let i=t.globalPosition;t.devicePosition&&(i=t.devicePosition),this._rootMesh.position.subtractToRef(i,ue.Vector3[0]);let s=this.scaleRatio;if(t.mode==Pi.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){const r=t.orthoTop-t.orthoBottom;s*=r}}else{const r=t.getScene().useRightHandedSystem?O.RightHandedForwardReadOnly:O.LeftHandedForwardReadOnly,n=t.getDirection(r);s*=O.Dot(ue.Vector3[0],n)}this._rootMesh.scaling.setAll(s),e._getWorldMatrixDeterminant()<0&&!ua.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_handlePivot(){const e=this._attachedNode;e.isUsingPivotMatrix&&e.isUsingPivotMatrix()&&e.position&&e.getWorldMatrix().setTranslation(e.position)}_matrixChanged(){if(!!this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const r=ue.Matrix[1];e.parent._worldMatrix.invertToRef(r),this._attachedNode._worldMatrix.multiplyToRef(r,ue.Matrix[0]),t=ue.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,ue.Matrix[1]),i=ue.Matrix[1]):i=t,i.decompose(ue.Vector3[1],ue.Quaternion[0],ue.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 r=this._attachedNode;r.rotation=ue.Quaternion[0].toEulerAngles(),r.rotationQuaternion&&(r.rotationQuaternion.copyFrom(ue.Quaternion[0]),r.rotationQuaternion.normalize())}e.position.copyFrom(ue.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=ue.Matrix[0],i=ue.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i),i.decompose(ue.Vector3[0],ue.Quaternion[0],e.position,ua.PreserveScaling?e:void 0)}else this._attachedNode._worldMatrix.decompose(ue.Vector3[0],ue.Quaternion[0],e.position,ua.PreserveScaling?e:void 0);ue.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(ue.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(ue.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=ue.Quaternion[0].toEulerAngles())}else if(this._attachedNode.getClassName()==="Bone"){const e=this._attachedNode,t=e.getParent();if(t){const i=ue.Matrix[0],s=ue.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,s),e.getLocalMatrix().copyFrom(s)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===pr.LIGHTTYPEID_DIRECTIONALLIGHT||t===pr.LIGHTTYPEID_SPOTLIGHT||t===pr.LIGHTTYPEID_POINTLIGHT){const i=e.parent;if(i){const s=ue.Matrix[0],r=ue.Matrix[1];i.getWorldMatrix().invertToRef(s),e.getWorldMatrix().multiplyToRef(s,r),r.decompose(void 0,ue.Quaternion[0],ue.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,ue.Quaternion[0],ue.Vector3[0]);e.position=new O(ue.Vector3[0].x,ue.Vector3[0].y,ue.Vector3[0].z),e.direction&&(e.direction=new O(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(r=>{var n,o;if(r.pickInfo){if(r.type===mi.POINTERMOVE){if(i)return;t.forEach(l=>{var c,h;if(l.colliderMeshes&&l.gizmoMeshes){const u=((c=l.colliderMeshes)===null||c===void 0?void 0:c.indexOf((h=r?.pickInfo)===null||h===void 0?void 0:h.pickedMesh))!=-1,p=l.dragBehavior.enabled?u||l.active?l.hoverMaterial:l.material:l.disableMaterial;l.gizmoMeshes.forEach(m=>{m.material=p,m.color&&(m.color=p.diffuseColor)})}})}if(r.type===mi.POINTERDOWN&&t.has((n=r.pickInfo.pickedMesh)===null||n===void 0?void 0:n.parent)){i=!0;const l=t.get((o=r.pickInfo.pickedMesh)===null||o===void 0?void 0:o.parent);l.active=!0,t.forEach(c=>{var h,u;const m=(((h=c.colliderMeshes)===null||h===void 0?void 0:h.indexOf((u=r?.pickInfo)===null||u===void 0?void 0:u.pickedMesh))!=-1||c.active)&&c.dragBehavior.enabled?c.hoverMaterial:c.disableMaterial;c.gizmoMeshes.forEach(_=>{_.material=m,_.color&&(_.color=m.diffuseColor)})})}r.type===mi.POINTERUP&&t.forEach(l=>{l.active=!1,i=!1,l.gizmoMeshes.forEach(c=>{c.material=l.dragBehavior.enabled?l.material:l.disableMaterial,c.color&&(c.color=l.material.diffuseColor)})})}})}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}ua.PreserveScaling=!1;class tv extends ua{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,s=!1){const r=new Ki("arrow",e),n=J1("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=J1("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return n.parent=r,n.material=t,n.rotation.x=Math.PI/2,n.position.z+=.3,o.parent=r,o.material=t,o.position.z+=.275/2,o.rotation.x=Math.PI/2,s&&(o.visibility=0,n.visibility=0),r}static _CreateArrowInstance(e,t){const i=new Ki("arrow",e);for(const s of t.getChildMeshes()){const r=s.createInstance(s.name);r.parent=i}return i}constructor(e,t=Ie.Gray(),i=Mn.DefaultUtilityLayer,s=null,r=1){var n;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Se,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=s,this._coloredMaterial=new jt("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ie(.1,.1,.1)),this._hoverMaterial=new jt("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=Ie.Yellow(),this._disableMaterial=new jt("",i.utilityLayerScene),this._disableMaterial.diffuseColor=Ie.Gray(),this._disableMaterial.alpha=.4;const o=tv._CreateArrow(i.utilityLayerScene,this._coloredMaterial,r),l=tv._CreateArrow(i.utilityLayerScene,this._coloredMaterial,r+4,!0);this._gizmoMesh=new Oe("",i.utilityLayerScene),this._gizmoMesh.addChild(o),this._gizmoMesh.addChild(l),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let c=0;const h={snapDistance:0};this.dragBehavior=new uc({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add(m=>{if(this.attachedNode){this._handlePivot();let _=!1;if(this.snapDistance==0)this.attachedNode.getWorldMatrix().getTranslationToRef(ue.Vector3[2]),ue.Vector3[2].addInPlace(m.delta),this.dragBehavior.validateDrag(ue.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(m.delta.x,m.delta.y,m.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(m.delta.x,m.delta.y,m.delta.z),this.attachedNode.updateCache(),_=!0);else if(c+=m.dragDistance,Math.abs(c)>this.snapDistance){const f=Math.floor(Math.abs(c)/this.snapDistance);c=c%this.snapDistance,m.delta.normalizeToRef(ue.Vector3[1]),ue.Vector3[1].scaleInPlace(this.snapDistance*f),this.attachedNode.getWorldMatrix().getTranslationToRef(ue.Vector3[2]),ue.Vector3[2].addInPlace(ue.Vector3[1]),this.dragBehavior.validateDrag(ue.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(ue.Vector3[1].x,ue.Vector3[1].y,ue.Vector3[1].z),this.attachedNode.updateCache(),h.snapDistance=this.snapDistance*f,this.onSnapObservable.notifyObservers(h),_=!0)}_&&this._matrixChanged()}}),this.dragBehavior.onDragStartObservable.add(()=>{this._dragging=!0}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1});const u=i._getSharedGizmoLight();u.includedOnlyMeshes=u.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const p={gizmoMeshes:o.getChildMeshes(),colliderMeshes:l.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(n=this._parent)===null||n===void 0||n.addToAxisCache(l,p),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(m=>{var _;if(!this._customMeshSet&&(this._isHovered=p.colliderMeshes.indexOf((_=m?.pickInfo)===null||_===void 0?void 0:_.pickedMesh)!=-1,!this._parent)){const f=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(p.gizmoMeshes,f)}}),this.dragBehavior.onEnabledObservable.add(m=>{this._setGizmoMeshMaterial(p.gizmoMeshes,m?p.material:p.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 sI{get xAxis(){return this._xAxis}get yAxis(){return this._yAxis}get zAxis(){return this._zAxis}constructor(e,t=1,i=2,s,r,n,o=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this.scaleLines=1,e=e||Ii.LastCreatedScene,!!e){if(this.scaleLines=t,!s){const l=new jt("xAxisMaterial",e);l.disableLighting=!0,l.emissiveColor=Ie.Red().scale(.5),s=tv._CreateArrow(e,l,o)}if(!r){const l=new jt("yAxisMaterial",e);l.disableLighting=!0,l.emissiveColor=Ie.Green().scale(.5),r=tv._CreateArrow(e,l,o)}if(!n){const l=new jt("zAxisMaterial",e);l.disableLighting=!0,l.emissiveColor=Ie.Blue().scale(.5),n=tv._CreateArrow(e,l,o)}this._xAxis=s,this._xAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._yAxis=r,this._yAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._zAxis=n,this._zAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),i!=null&&(sI._SetRenderingGroupId(this._xAxis,i),sI._SetRenderingGroupId(this._yAxis,i),sI._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new O,O.Right(),O.Up(),O.Forward())}}update(e,t,i,s){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._xAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._yAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(s),this._zAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor)}createInstance(){const e=tv._CreateArrowInstance(this.scene,this._xAxis),t=tv._CreateArrowInstance(this.scene,this._yAxis),i=tv._CreateArrowInstance(this.scene,this._zAxis),s=new sI(this.scene,this.scaleLines,null,e,t,i);return s._instanced=!0,s}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 j_e extends sI{constructor(e,t,i,s=1){super(e,s),this.pos=O.Zero(),this.xaxis=O.Zero(),this.yaxis=O.Zero(),this.zaxis=O.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(Fo.X,this.mesh,this.xaxis),e.getDirectionToRef(Fo.Y,this.mesh,this.yaxis),e.getDirectionToRef(Fo.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())}}function zK(a){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],s=[];let r=[];const n=a.width||a.size||1,o=a.height||a.size||1,l=a.depth||a.size||1,c=a.wrap||!1;let h=a.topBaseAt===void 0?1:a.topBaseAt,u=a.bottomBaseAt===void 0?0:a.bottomBaseAt;h=(h+4)%4,u=(u+4)%4;const p=[2,0,3,1],m=[2,0,1,3];let _=p[h],f=m[u],d=[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(c){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],d=[-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 S=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],I=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const D=[17,18,19,16],R=[22,23,20,21];for(;_>0;)S.unshift(S.pop()),D.unshift(D.pop()),_--;for(;f>0;)I.unshift(I.pop()),R.unshift(R.pop()),f--;S=S.flat(),I=I.flat(),d=d.concat(S).concat(I),t.push(D[0],D[2],D[3],D[0],D[1],D[2]),t.push(R[0],R[2],R[3],R[0],R[1],R[2])}const C=[n/2,o/2,l/2];r=d.reduce((S,I,D)=>S.concat(I*C[D%3]),[]);const v=a.sideOrientation===0?0:a.sideOrientation||Jt.DEFAULTSIDE,y=a.faceUV||new Array(6),M=a.faceColors,b=[];for(let S=0;S<6;S++)y[S]===void 0&&(y[S]=new Ui(0,0,1,1)),M&&M[S]===void 0&&(M[S]=new Zt(1,1,1,1));for(let S=0;S<6;S++)if(s.push(y[S].z,fn.UseOpenGLOrientationForUV?1-y[S].w:y[S].w),s.push(y[S].x,fn.UseOpenGLOrientationForUV?1-y[S].w:y[S].w),s.push(y[S].x,fn.UseOpenGLOrientationForUV?1-y[S].y:y[S].y),s.push(y[S].z,fn.UseOpenGLOrientationForUV?1-y[S].y:y[S].y),M)for(let I=0;I<4;I++)b.push(M[S].r,M[S].g,M[S].b,M[S].a);Jt._ComputeSides(v,r,t,i,s,a.frontUVs,a.backUVs);const E=new Jt;if(E.indices=t,E.positions=r,E.normals=i,E.uvs=s,M){const S=v===Jt.DOUBLESIDE?b.concat(b):b;E.colors=S}return E}function Ece(a){const e=a.width||a.size||1,t=a.height||a.size||1,i=a.depth||a.size||1,s=(a.widthSegments||a.segments||1)|0,r=(a.heightSegments||a.segments||1)|0,n=(a.depthSegments||a.segments||1)|0,o=new ge,l=new ge,c=new ge,h=SM({width:e,height:i,subdivisionsX:s,subdivisionsY:n});ge.TranslationToRef(0,-t/2,0,l),ge.RotationZToRef(Math.PI,o),o.multiplyToRef(l,c),h.transform(c);const u=SM({width:e,height:i,subdivisionsX:s,subdivisionsY:n});ge.TranslationToRef(0,t/2,0,c),u.transform(c);const p=SM({width:t,height:i,subdivisionsX:r,subdivisionsY:n});ge.TranslationToRef(-e/2,0,0,l),ge.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,c),p.transform(c);const m=SM({width:t,height:i,subdivisionsX:r,subdivisionsY:n});ge.TranslationToRef(e/2,0,0,l),ge.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,c),m.transform(c);const _=SM({width:e,height:t,subdivisionsX:s,subdivisionsY:r});ge.TranslationToRef(0,0,-i/2,l),ge.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,c),_.transform(c);const f=SM({width:e,height:t,subdivisionsX:s,subdivisionsY:r});return ge.TranslationToRef(0,0,i/2,l),ge.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,c),f.transform(c),h.merge([u,m,p,_,f],!0),h}function pl(a,e={},t=null){const i=new Oe(a,t);return e.sideOrientation=Oe._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,zK(e).applyToMesh(i,e.updatable),i}const G_e={CreateBox:pl};Jt.CreateBox=zK;Oe.CreateBox=(a,e,t=null,i,s)=>pl(a,{size:e,sideOrientation:s,updatable:i},t);function UK(a){const e=(a.segments||32)|0,t=a.diameterX||a.diameter||1,i=a.diameterY||a.diameter||1,s=a.diameterZ||a.diameter||1,r=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,n=a.slice&&a.slice<=0?1:a.slice||1,o=a.sideOrientation===0?0:a.sideOrientation||Jt.DEFAULTSIDE,l=!!a.dedupTopBottomIndices,c=new O(t/2,i/2,s/2),h=2+e,u=2*h,p=[],m=[],_=[],f=[];for(let C=0;C<=h;C++){const v=C/h,y=v*Math.PI*n;for(let M=0;M<=u;M++){const b=M/u,E=b*Math.PI*2*r,S=ge.RotationZ(-y),I=ge.RotationY(E),D=O.TransformCoordinates(O.Up(),S),R=O.TransformCoordinates(D,I),L=R.multiply(c),w=R.divide(c).normalize();m.push(L.x,L.y,L.z),_.push(w.x,w.y,w.z),f.push(b,fn.UseOpenGLOrientationForUV?1-v:v)}if(C>0){const M=m.length/3;for(let b=M-2*(u+1);b+u+21&&(p.push(b),p.push(b+1),p.push(b+u+1)),(C$d(a,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:r,updatable:s},i);function kK(a={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(a.subdivisions?a.subdivisions:2,1)|0,t=Math.max(a.tessellation?a.tessellation:16,3)|0,i=Math.max(a.height?a.height:1,0),s=Math.max(a.radius?a.radius:.25,0),r=Math.max(a.capSubdivisions?a.capSubdivisions:6,1)|0,n=t,o=e,l=Math.max(a.radiusTop?a.radiusTop:s,0),c=Math.max(a.radiusBottom?a.radiusBottom:s,0),h=i-(l+c),u=0,p=2*Math.PI,m=Math.max(a.topCapSubdivisions?a.topCapSubdivisions:r,1),_=Math.max(a.bottomCapSubdivisions?a.bottomCapSubdivisions:r,1),f=Math.acos((c-l)/i);let d=[];const C=[],v=[],y=[];let M=0;const b=[],E=h*.5,S=Math.PI*.5;let I,D;const R=O.Zero(),L=O.Zero(),w=Math.cos(f),N=Math.sin(f),V=new lt(l*N,E+l*w).subtract(new lt(c*N,-E+c*w)).length(),W=l*f+V+c*(S-f);let G=0;for(D=0;D<=m;D++){const K=[],j=S-f*(D/m);G+=l*f/m;const H=Math.cos(j),Y=Math.sin(j),J=H*l;for(I=0;I<=n;I++){const te=I/n,re=te*p+u,ee=Math.sin(re),oe=Math.cos(re);L.x=J*ee,L.y=E+Y*l,L.z=J*oe,C.push(L.x,L.y,L.z),R.set(H*ee,Y,H*oe),v.push(R.x,R.y,R.z),y.push(te,fn.UseOpenGLOrientationForUV?G/W:1-G/W),K.push(M),M++}b.push(K)}const ie=i-l-c+w*l-w*c,Z=N*(c-l)/ie;for(D=1;D<=o;D++){const K=[];G+=V/o;const j=N*(D*(c-l)/o+l);for(I=0;I<=n;I++){const H=I/n,Y=H*p+u,J=Math.sin(Y),te=Math.cos(Y);L.x=j*J,L.y=E+w*l-D*ie/o,L.z=j*te,C.push(L.x,L.y,L.z),R.set(J,Z,te).normalize(),v.push(R.x,R.y,R.z),y.push(H,fn.UseOpenGLOrientationForUV?G/W:1-G/W),K.push(M),M++}b.push(K)}for(D=1;D<=_;D++){const K=[],j=S-f-(Math.PI-f)*(D/_);G+=c*f/_;const H=Math.cos(j),Y=Math.sin(j),J=H*c;for(I=0;I<=n;I++){const te=I/n,re=te*p+u,ee=Math.sin(re),oe=Math.cos(re);L.x=J*ee,L.y=-E+Y*c,L.z=J*oe,C.push(L.x,L.y,L.z),R.set(H*ee,Y,H*oe),v.push(R.x,R.y,R.z),y.push(te,fn.UseOpenGLOrientationForUV?G/W:1-G/W),K.push(M),M++}b.push(K)}for(I=0;IfW(a,e,t);Jt.CreateCapsule=kK;function Aee(a){let e=a.pathArray;const t=a.closeArray||!1,i=a.closePath||!1,s=a.invertUV||!1,r=Math.floor(e[0].length/2);let n=a.offset||r;n=n>r?r:Math.floor(n);const o=a.sideOrientation===0?0:a.sideOrientation||Jt.DEFAULTSIDE,l=a.uvs,c=a.colors,h=[],u=[],p=[],m=[],_=[],f=[],d=[],C=[];let v;const y=[],M=[];let b,E,S;if(e.length<2){const de=[],me=[];for(E=0;E0&&(w=R[S].subtract(R[S-1]).length(),N=w+d[b],_[b].push(N),d[b]=N),S++;i&&(S--,h.push(R[0].x,R[0].y,R[0].z),w=R[S].subtract(R[0]).length(),N=w+d[b],_[b].push(N),d[b]=N),y[b]=L+D,M[b]=I,I+=L+D}let V,W,G=null,ie=null;for(E=0;E{let _=i[0].length;const f=o;let d=0;const C=f._originalBuilderSideOrientation===Oe.DOUBLESIDE?2:1;for(let v=1;v<=C;++v)for(let y=0;yxI(a,{pathArray:e,closeArray:t,closePath:i,offset:s,updatable:n,sideOrientation:o,instance:l},r);function jK(a){const e=new Array,t=new Array,i=new Array,s=new Array,r=a.radius||.5,n=a.tessellation||64,o=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,l=a.sideOrientation===0?0:a.sideOrientation||Jt.DEFAULTSIDE;e.push(0,0,0),s.push(.5,.5);const c=Math.PI*2*o,h=o===1?c/n:c/(n-1);let u=0;for(let _=0;_RF(a,{radius:e,tessellation:t,sideOrientation:r,updatable:s},i);function qN(a){const e=a.pattern||Oe.NO_FLIP,t=a.tileWidth||a.tileSize||1,i=a.tileHeight||a.tileSize||1,s=a.alignHorizontal||0,r=a.alignVertical||0,n=a.width||a.size||1,o=Math.floor(n/t);let l=n-o*t;const c=a.height||a.size||1,h=Math.floor(c/i);let u=c-h*i;const p=t*o/2,m=i*h/2;let _=0,f=0,d=0,C=0,v=0,y=0;if(l>0||u>0){switch(d=-p,C=-m,v=p,y=m,s){case Oe.CENTER:l/=2,d-=l,v+=l;break;case Oe.LEFT:v+=l,_=-l/2;break;case Oe.RIGHT:d-=l,_=l/2;break}switch(r){case Oe.CENTER:u/=2,C-=u,y+=u;break;case Oe.BOTTOM:y+=u,f=-u/2;break;case Oe.TOP:C-=u,f=u/2;break}}const M=[],b=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],(e===Oe.ROTATE_TILE||e===Oe.ROTATE_ROW)&&(E[1]=[1,1,0,1,0,0,1,0]),(e===Oe.FLIP_TILE||e===Oe.FLIP_ROW)&&(E[1]=[1,0,0,0,0,1,1,1]),(e===Oe.FLIP_N_ROTATE_TILE||e===Oe.FLIP_N_ROTATE_ROW)&&(E[1]=[0,1,1,1,1,0,0,0]);let S=[];const I=[],D=[];let R=0;for(let V=0;V0||u>0){const V=u>0&&(r===Oe.CENTER||r===Oe.TOP),W=u>0&&(r===Oe.CENTER||r===Oe.BOTTOM),G=l>0&&(s===Oe.CENTER||s===Oe.RIGHT),ie=l>0&&(s===Oe.CENTER||s===Oe.LEFT);let Z=[],q,K,j,H;if(V&&G&&(M.push(d+_,C+f,0),M.push(-p+_,C+f,0),M.push(-p+_,C+u+f,0),M.push(d+_,C+u+f,0),D.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,q=1-l/t,K=1-u/i,j=1,H=1,Z=[q,K,j,K,j,H,q,H],e===Oe.ROTATE_ROW&&(Z=[1-q,1-K,1-j,1-K,1-j,1-H,1-q,1-H]),e===Oe.FLIP_ROW&&(Z=[1-q,K,1-j,K,1-j,H,1-q,H]),e===Oe.FLIP_N_ROTATE_ROW&&(Z=[q,1-K,j,1-K,j,1-H,q,1-H]),S=S.concat(Z),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),V&&ie&&(M.push(p+_,C+f,0),M.push(v+_,C+f,0),M.push(v+_,C+u+f,0),M.push(p+_,C+u+f,0),D.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,q=0,K=1-u/i,j=l/t,H=1,Z=[q,K,j,K,j,H,q,H],(e===Oe.ROTATE_ROW||e===Oe.ROTATE_TILE&&o%2===0)&&(Z=[1-q,1-K,1-j,1-K,1-j,1-H,1-q,1-H]),(e===Oe.FLIP_ROW||e===Oe.FLIP_TILE&&o%2===0)&&(Z=[1-q,K,1-j,K,1-j,H,1-q,H]),(e===Oe.FLIP_N_ROTATE_ROW||e===Oe.FLIP_N_ROTATE_TILE&&o%2===0)&&(Z=[q,1-K,j,1-K,j,1-H,q,1-H]),S=S.concat(Z),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),W&&G&&(M.push(d+_,m+f,0),M.push(-p+_,m+f,0),M.push(-p+_,y+f,0),M.push(d+_,y+f,0),D.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,q=1-l/t,K=0,j=1,H=u/i,Z=[q,K,j,K,j,H,q,H],(e===Oe.ROTATE_ROW&&h%2===1||e===Oe.ROTATE_TILE&&h%1===0)&&(Z=[1-q,1-K,1-j,1-K,1-j,1-H,1-q,1-H]),(e===Oe.FLIP_ROW&&h%2===1||e===Oe.FLIP_TILE&&h%2===0)&&(Z=[1-q,K,1-j,K,1-j,H,1-q,H]),(e===Oe.FLIP_N_ROTATE_ROW&&h%2===1||e===Oe.FLIP_N_ROTATE_TILE&&h%2===0)&&(Z=[q,1-K,j,1-K,j,1-H,q,1-H]),S=S.concat(Z),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),W&&ie&&(M.push(p+_,m+f,0),M.push(v+_,m+f,0),M.push(v+_,y+f,0),M.push(p+_,y+f,0),D.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,q=0,K=0,j=l/t,H=u/i,Z=[q,K,j,K,j,H,q,H],(e===Oe.ROTATE_ROW&&h%2===1||e===Oe.ROTATE_TILE&&(h+o)%2===1)&&(Z=[1-q,1-K,1-j,1-K,1-j,1-H,1-q,1-H]),(e===Oe.FLIP_ROW&&h%2===1||e===Oe.FLIP_TILE&&(h+o)%2===1)&&(Z=[1-q,K,1-j,K,1-j,H,1-q,H]),(e===Oe.FLIP_N_ROTATE_ROW&&h%2===1||e===Oe.FLIP_N_ROTATE_TILE&&(h+o)%2===1)&&(Z=[q,1-K,j,1-K,j,1-H,q,1-H]),S=S.concat(Z),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),V){const Y=[];q=0,K=1-u/i,j=1,H=1,Y[0]=[q,K,j,K,j,H,q,H],Y[1]=[q,K,j,K,j,H,q,H],(e===Oe.ROTATE_TILE||e===Oe.ROTATE_ROW)&&(Y[1]=[1-q,1-K,1-j,1-K,1-j,1-H,1-q,1-H]),(e===Oe.FLIP_TILE||e===Oe.FLIP_ROW)&&(Y[1]=[1-q,K,1-j,K,1-j,H,1-q,H]),(e===Oe.FLIP_N_ROTATE_TILE||e===Oe.FLIP_N_ROTATE_ROW)&&(Y[1]=[q,1-K,j,1-K,j,1-H,q,1-H]);for(let J=0;JY+L)),L+=S[j].length,i)for(let Y=0;Y<4;Y++)E.push(i[j].r,i[j].g,i[j].b,i[j].a)}const w=new O(0,0,f),N=ge.RotationY(Math.PI);v=S[0].map(j=>O.TransformNormal(j,N).add(w)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[]),y=I[0].map(j=>O.TransformNormal(j,N)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[]),v=v.concat(S[1].map(j=>j.subtract(w)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[])),y=y.concat(I[1].map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[]));const V=new O(m,0,0),W=ge.RotationY(-Math.PI/2);v=v.concat(S[2].map(j=>O.TransformNormal(j,W).add(V)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[])),y=y.concat(I[2].map(j=>O.TransformNormal(j,W)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[]));const G=ge.RotationY(Math.PI/2);v=v.concat(S[3].map(j=>O.TransformNormal(j,G).subtract(V)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[])),y=y.concat(I[3].map(j=>O.TransformNormal(j,G)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[]));const ie=new O(0,_,0),Z=ge.RotationX(Math.PI/2);v=v.concat(S[4].map(j=>O.TransformNormal(j,Z).add(ie)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[])),y=y.concat(I[4].map(j=>O.TransformNormal(j,Z)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[]));const q=ge.RotationX(-Math.PI/2);v=v.concat(S[5].map(j=>O.TransformNormal(j,q).subtract(ie)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[])),y=y.concat(I[5].map(j=>O.TransformNormal(j,q)).map(j=>[j.x,j.y,j.z]).reduce((j,H)=>j.concat(H),[])),Jt._ComputeSides(p,v,b,y,M);const K=new Jt;if(K.indices=b,K.positions=v,K.normals=y,K.uvs=M,i){const j=p===Jt.DOUBLESIDE?E.concat(E):E;K.colors=j}return K}function Eee(a,e,t=null){const i=new Oe(a,t);return e.sideOrientation=Oe._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,bee(e).applyToMesh(i,e.updatable),i}const Z_e={CreateTiledBox:Eee};Jt.CreateTiledBox=bee;function yee(a){const e=new Array,t=new Array,i=new Array,s=new Array,r=a.radius||2,n=a.tube||.5,o=a.radialSegments||32,l=a.tubularSegments||32,c=a.p||2,h=a.q||3,u=a.sideOrientation===0?0:a.sideOrientation||Jt.DEFAULTSIDE,p=d=>{const C=Math.cos(d),v=Math.sin(d),y=h/c*d,M=Math.cos(y),b=r*(2+M)*.5*C,E=r*(2+M)*v*.5,S=r*Math.sin(y)*.5;return new O(b,E,S)};let m,_;for(m=0;m<=o;m++){const C=m%o/o*2*c*Math.PI,v=p(C),y=p(C+.01),M=y.subtract(v);let b=y.add(v);const E=O.Cross(M,b);for(b=O.Cross(E,M),E.normalize(),b.normalize(),_=0;_GK(a,{radius:e,tube:t,radialSegments:i,tubularSegments:s,p:r,q:n,sideOrientation:c,updatable:l},o);const bZ={effect:null,subMesh:null};class oh extends Bl{constructor(e,t,i,s={},r=!0){super(e,t,r),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 ge,this._cachedWorldViewProjectionMatrix=new ge,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options=Object.assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},s)}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,s)=>(s.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,s)=>(s.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,s)=>(s.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 s=0;sr===e||r.startsWith(i));return s>=0&&this.options.defines.splice(s,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){var s,r,n,o;const l=i&&this._storeEffectOnSubMeshes;if(this.isFrozen)if(l){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{const D=this._drawWrapper.effect;if(D&&D._wasPreviouslyReady&&D._wasPreviouslyUsingInstances===t)return!0}const c=this.getScene(),h=c.getEngine(),u=[],p=[],m=new Fl;let _=this._shaderPath,f=this._options.uniforms,d=this._options.uniformBuffers,C=this._options.samplers;h.getCaps().multiview&&c.activeCamera&&c.activeCamera.outputRenderTarget&&c.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,u.push("#define MULTIVIEW"),this._options.uniforms.indexOf("viewProjection")!==-1&&this._options.uniforms.indexOf("viewProjectionR")===-1&&this._options.uniforms.push("viewProjectionR"));for(let D=0;D4&&(p.push(se.MatricesIndicesExtraKind),p.push(se.MatricesWeightsExtraKind));const D=e.skeleton;u.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),m.addCPUSkinningFallback(0,e),D.isUsingTextureForMatrices?(u.push("#define BONETEXTURE"),this._options.uniforms.indexOf("boneTextureWidth")===-1&&this._options.uniforms.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(u.push("#define BonesPerMesh "+(D.bones.length+1)),this._options.uniforms.indexOf("mBones")===-1&&this._options.uniforms.push("mBones"))}else u.push("#define NUM_BONE_INFLUENCERS 0");let v=0;const y=e?e.morphTargetManager:null;if(y){const D=y.supportsUVs&&u.indexOf("#define UV1")!==-1,R=y.supportsTangents&&u.indexOf("#define TANGENT")!==-1,L=y.supportsNormals&&u.indexOf("#define NORMAL")!==-1;v=y.numInfluencers,D&&u.push("#define MORPHTARGETS_UV"),R&&u.push("#define MORPHTARGETS_TANGENT"),L&&u.push("#define MORPHTARGETS_NORMAL"),v>0&&u.push("#define MORPHTARGETS"),y.isUsingTextureForTargets&&(u.push("#define MORPHTARGETS_TEXTURE"),this._options.uniforms.indexOf("morphTargetTextureIndices")===-1&&this._options.uniforms.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),u.push("#define NUM_MORPH_INFLUENCERS "+v);for(let w=0;w0&&(f=f.slice(),f.push("morphTargetInfluences"),f.push("morphTargetTextureInfo"),f.push("morphTargetTextureIndices"))}else u.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const D=e.bakedVertexAnimationManager;D&&D.isEnabled&&(u.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),this._options.uniforms.indexOf("bakedVertexAnimationSettings")===-1&&this._options.uniforms.push("bakedVertexAnimationSettings"),this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),this._options.uniforms.indexOf("bakedVertexAnimationTime")===-1&&this._options.uniforms.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),ze.PrepareAttributesForBakedVertexAnimation(p,e,u)}for(const D in this._textures)if(!this._textures[D].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&u.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(lh(f),PI(this,c,u)),this.customShaderNameResolve&&(f=f.slice(),d=d.slice(),C=C.slice(),_=this.customShaderNameResolve(_,f,d,C,u,p));const M=l?i._getDrawWrapper():this._drawWrapper,b=(s=M?.effect)!==null&&s!==void 0?s:null,E=(r=M?.defines)!==null&&r!==void 0?r:null,S=u.join(` +`);let I=b;return E!==S&&(I=h.createEffect(_,{attributes:p,uniformsNames:f,uniformBuffersNames:d,samplers:C,defines:S,fallbacks:m,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:v},shaderLanguage:this._options.shaderLanguage},h),l?i.setEffect(I,S,this._materialContext):M&&M.setEffect(I,S),this._onEffectCreatedObservable&&(bZ.effect=I,bZ.subMesh=(n=i??e?.subMeshes[0])!==null&&n!==void 0?n:null,this._onEffectCreatedObservable.notifyObservers(bZ))),I._wasPreviouslyUsingInstances=!!t,!((o=!I?.isReady())!==null&&o!==void 0)||o?!1:(b!==I&&c.resetCachedMaterial(),I._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();!s||(this._options.uniforms.indexOf("world")!==-1&&s.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var s;this.bind(e,t,(s=i._drawWrapperOverride)===null||s===void 0?void 0:s.effect,i)}bind(e,t,i,s){var r;const n=s&&this._storeEffectOnSubMeshes,o=i??(n?s.effect:this.getEffect());if(!o)return;this._activeEffect=o,this.bindOnlyWorldMatrix(e,i);const l=this._options.uniformBuffers;let c=!1;if(o&&l&&l.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let u=0;u0&&ze.BindMorphTargetParameters(t,o);const p=t.bakedVertexAnimationManager;p&&p.isEnabled&&((r=t.bakedVertexAnimationManager)===null||r===void 0||r.bind(o,!!o._wasPreviouslyUsingInstances))}this._afterBind(t,o)}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 s=0;snew oh(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath=Object.assign({},t._shaderPath)),this._options=Object.assign({},this._options),Object.keys(this._options).forEach(i=>{const s=this._options[i];Array.isArray(s)&&(this._options[i]=s.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 s;for(s in this._textures)this._textures[s].dispose();for(s in this._textureArrays){const r=this._textureArrays[s];for(let n=0;nnew oh(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);let r;e.stencil&&s.stencil.parse(e.stencil,t,i);for(r in e.textures)s.setTexture(r,Te.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],o=new Array;for(let l=0;l(c%3===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>Ie.FromArray(o));s.setColor3Array(r,n)}for(r in e.colors4)s.setColor4(r,Zt.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const n=e.colors4Arrays[r].reduce((o,l,c)=>(c%4===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>Zt.FromArray(o));s.setColor4Array(r,n)}for(r in e.vectors2)s.setVector2(r,lt.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,O.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,Ui.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,ke.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,ge.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise((r,n)=>{const o=new wl;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),c=this.Parse(l,i||Ii.LastCreatedScene,s);e&&(c.name=e),r(c)}else n("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((s,r)=>{const n=new wl;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(o.shaderMaterial),c=this.Parse(l,t||Ii.LastCreatedScene,i);c.snippetId=e,s(c)}else r("Unable to load the snippet "+e)}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}oh.SnippetUrl="https://snippet.babylonjs.com";oh.CreateFromSnippetAsync=oh.ParseFromSnippetAsync;$e("BABYLON.ShaderMaterial",oh);const J_e="colorPixelShader",$_e=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +#define VERTEXCOLOR +varying vec4 vColor; +#else +uniform vec4 color; +#endif +#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 +#define CUSTOM_FRAGMENT_MAIN_END +}`;Ue.ShadersStore[J_e]=$_e;const ege="colorVertexShader",tge=`attribute vec3 position; +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#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 +#define CUSTOM_VERTEX_MAIN_END +}`;Ue.ShadersStore[ege]=tge;Oe._LinesMeshParser=(a,e)=>n7.Parse(a,e);class n7 extends Oe{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,s=null,r,n,o,l){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=o,this.color=new Ie(1,1,1),this.alpha=1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const c=[],h={attributes:[se.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:c,useClipPlane:null};o===!1?h.needAlphaBlending=!1:h.defines.push("#define VERTEXALPHA"),n?(h.defines.push("#define VERTEXCOLOR"),h.attributes.push(se.ColorKind)):(h.uniforms.push("color"),this._color4=new Zt),l?this.material=l:(this.material=new oh("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=Lt.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:s,g:r,b:n}=this.color;this._color4.set(s,r,n,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 s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(Lt.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(Lt.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 n7(e,this.getScene(),t,this,i)}createInstance(e){const t=new Mee(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 n7(e.name,t);return i.color=Ie.FromArray(e.color),i.alpha=e.alpha,i}}class Mee extends ov{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function Tee(a){const e=[],t=[],i=a.lines,s=a.colors,r=[];let n=0;for(let l=0;l0&&(e.push(n-1),e.push(n)),n++}}const o=new Jt;return o.indices=e,o.positions=t,s&&(o.colors=r),o}function See(a){const e=a.dashSize||3,t=a.gapSize||1,i=a.dashNb||200,s=a.points,r=new Array,n=new Array,o=O.Zero();let l=0,c=0,h=0,u=0,p=0,m=0,_=0;for(_=0;_{const u=O.Zero(),p=h.length/6;let m=0,_=0,f=0,d=0,C=0,v=0,y=0,M=0;for(y=0;yGa(a,{points:e,updatable:i,instance:s},t);Oe.CreateDashedLines=(a,e,t,i,s,r=null,n,o)=>WK(a,{points:e,dashSize:t,gapSize:i,dashNb:s,updatable:n,instance:o},r);class sge extends lt{constructor(e,t){super(e.x,e.y),this.index=t}}class EZ{constructor(){this.elements=new Array}add(e){const t=new Array;return e.forEach(i=>{const s=new sge(i,this.elements.length);t.push(s),this.elements.push(s)}),t}computeBounds(){const e=new lt(this.elements[0].x,this.elements[0].y),t=new lt(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 rge{static Rectangle(e,t,i,s){return[new lt(e,t),new lt(i,t),new lt(i,s),new lt(e,s)]}static Circle(e,t=0,i=0,s=32){const r=new Array;let n=0;const o=Math.PI*2/s;for(let l=0;l!isNaN(r));let i;const s=[];for(i=0;i<(t.length&2147483646);i+=2)s.push(new lt(t[i],t[i+1]));return s}static StartingAt(e,t){return yF.StartingAt(e,t)}}class yce{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){this._points=new EZ,this._outlinepoints=new EZ,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||Ii.LastCreatedScene;let r;t instanceof yF?r=t.getPoints():r=t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),typeof this.bjsEarcut>"u"&&Me.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new EZ;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 s=new Oe(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(se.PositionKind,r.positions,e),s.setVerticesData(se.NormalKind,r.normals,e),s.setVerticesData(se.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new Jt,s=new Array,r=new Array,n=new Array,o=this._points.computeBounds();this._points.elements.forEach(h=>{s.push(0,1,0),r.push(h.x,0,h.y),n.push((h.x-o.min.x)/o.width,(h.y-o.min.y)/o.height)});const l=new Array,c=this.bjsEarcut(this._epoints,this._eholes,2);for(let h=0;h0){const h=r.length/3;this._points.elements.forEach(p=>{s.push(0,-1,0),r.push(p.x,-e,p.y),n.push(1-(p.x-o.min.x)/o.width,1-(p.y-o.min.y)/o.height)});const u=l.length;for(let p=0;p{this._addSide(r,s,n,l,o,p,e,!0,t)})}return i.indices=l,i.positions=r,i.normals=s,i.uvs=n,i}_addSide(e,t,i,s,r,n,o,l,c){let h=e.length/3,u=0;for(let p=0;pc?Sc?IpW(a,{shape:e,holes:i,updatable:s,sideOrientation:r},t,n);Oe.ExtrudePolygon=(a,e,t,i,s,r,n,o=earcut)=>mW(a,{shape:e,holes:s,depth:t,updatable:r,sideOrientation:n},i,o);function _W(a,e,t=null){const i=e.path,s=e.shape,r=e.scale||1,n=e.rotation||0,o=e.cap===0?0:e.cap||Oe.NO_CAP,l=e.updatable,c=Oe._GetDefaultSideOrientation(e.sideOrientation),h=e.instance||null,u=e.invertUV||!1,p=e.closeShape||!1,m=e.closePath||!1;return Mce(a,s,i,r,n,null,null,m,p,o,!1,t,!!l,c,h,u,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function gW(a,e,t=null){const i=e.path,s=e.shape,r=e.scaleFunction||(()=>1),n=e.rotationFunction||(()=>0),o=e.closePath||e.ribbonCloseArray||!1,l=e.closeShape||e.ribbonClosePath||!1,c=e.cap===0?0:e.cap||Oe.NO_CAP,h=e.updatable,u=e.firstNormal||null,p=e.adjustFrame||!1,m=Oe._GetDefaultSideOrientation(e.sideOrientation),_=e.instance,f=e.invertUV||!1;return Mce(a,s,i,null,null,r,n,o,l,c,!0,t,!!h,m,_||null,f,e.frontUVs||null,e.backUVs||null,u,p)}function Mce(a,e,t,i,s,r,n,o,l,c,h,u,p,m,_,f,d,C,v,y){const M=(D,R,L,w,N,V,W,G,ie,Z,q)=>{const K=L.getTangents(),j=L.getNormals(),H=L.getBinormals(),Y=L.getDistances();if(q){for(let me=0;me0){let Fe=K[me-1];O.Dot(Fe,K[me])<0&&K[me].scaleInPlace(-1),Fe=j[me-1],O.Dot(Fe,j[me])<0&&j[me].scaleInPlace(-1),Fe=H[me-1],O.Dot(Fe,H[me])<0&&H[me].scaleInPlace(-1)}}let J=0;const te=()=>N!==null?N:1,ee=Z&&G?G:()=>V!==null?V:0,oe=Z&&W?W:te;let ae=ie===Oe.NO_CAP||ie===Oe.CAP_END?0:2;const fe=ue.Matrix[0];for(let me=0;me{const Fe=Array(),je=O.Zero();let nt;for(nt=0;nt3?0:c,E=M(e,t,b,S,i,s,r,n,c,h,y);const I=xI(a,{pathArray:E,closeArray:o,closePath:l,updatable:p,sideOrientation:m,invertUV:f,frontUVs:d||void 0,backUVs:C||void 0},u);return I._creationDataStorage.pathArray=E,I._creationDataStorage.path3D=b,I._creationDataStorage.cap=c,I}const age={ExtrudeShape:_W,ExtrudeShapeCustom:gW};Oe.ExtrudeShape=(a,e,t,i,s,r,n=null,o,l,c)=>{const h={shape:e,path:t,scale:i,rotation:s,cap:r===0?0:r||Oe.NO_CAP,sideOrientation:l,instance:c,updatable:o};return _W(a,h,n)};Oe.ExtrudeShapeCustom=(a,e,t,i,s,r,n,o,l,c,h,u)=>{const p={shape:e,path:t,scaleFunction:i,rotationFunction:s,ribbonCloseArray:r,ribbonClosePath:n,cap:o===0?0:o||Oe.NO_CAP,sideOrientation:h,instance:u,updatable:c};return gW(a,p,l)};function YK(a,e,t=null){const i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,s=e.closed===void 0?!0:e.closed,r=e.shape,n=e.radius||1,o=e.tessellation||64,l=e.clip||0,c=e.updatable,h=Oe._GetDefaultSideOrientation(e.sideOrientation),u=e.cap||Oe.NO_CAP,p=Math.PI*2,m=new Array,_=e.invertUV||!1;let f=0,d=0;const C=p/o*i;let v,y;for(f=0;f<=o-l;f++){for(y=[],(u==Oe.CAP_START||u==Oe.CAP_ALL)&&(y.push(new O(0,r[0].y,0)),y.push(new O(Math.cos(f*C)*r[0].x*n,r[0].y,Math.sin(f*C)*r[0].x*n))),d=0;dYK(a,{shape:e,radius:t,tessellation:i,sideOrientation:n,updatable:r},s);function XK(a,e,t=null){const i=e.path;let s=e.instance,r=1;e.radius!==void 0?r=e.radius:s&&(r=s._creationDataStorage.radius);const n=e.tessellation||64,o=e.radiusFunction||null;let l=e.cap||Oe.NO_CAP;const c=e.invertUV||!1,h=e.updatable,u=Oe._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const p=(C,v,y,M,b,E,S,I)=>{const D=v.getTangents(),R=v.getNormals(),L=v.getDistances(),N=Math.PI*2/b*I,W=E||(()=>M);let G,ie,Z,q;const K=ue.Matrix[0];let j=S===Oe.NO_CAP||S===Oe.CAP_END?0:2;for(let Y=0;Y{const te=Array();for(let re=0;re3?0:l,_=p(i,m,f,r,n,o,l,e.arc);const d=xI(a,{pathArray:_,closePath:!0,closeArray:!1,updatable:h,sideOrientation:u,invertUV:c,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return d._creationDataStorage.pathArray=_,d._creationDataStorage.path3D=m,d._creationDataStorage.tessellation=n,d._creationDataStorage.cap=l,d._creationDataStorage.arc=e.arc,d._creationDataStorage.radius=r,d}const lge={CreateTube:XK};Oe.CreateTube=(a,e,t,i,s,r,n,o,l,c)=>XK(a,{path:e,radius:t,tessellation:i,radiusFunction:s,arc:1,cap:r,updatable:o,sideOrientation:l,instance:c},n);function Lee(a){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=a.type&&(a.type<0||a.type>=e.length)?0:a.type||0,i=a.size,s=a.sizeX||i||1,r=a.sizeY||i||1,n=a.sizeZ||i||1,o=a.custom||e[t],l=o.face.length,c=a.faceUV||new Array(l),h=a.faceColors,u=a.flat===void 0?!0:a.flat,p=a.sideOrientation===0?0:a.sideOrientation||Jt.DEFAULTSIDE,m=new Array,_=new Array,f=new Array,d=new Array,C=new Array;let v=0,y=0;const M=new Array;let b=0,E=0,S,I,D,R,L,w;if(u)for(E=0;EKP(a,e,t);const hge=new O(1,0,0),uge=new O(-1,0,0),dge=new O(0,1,0),fge=new O(0,-1,0),pge=new O(0,0,1),mge=new O(0,0,-1);class pX{constructor(e=O.Zero(),t=O.Up(),i=lt.Zero(),s=0,r=0,n=null,o=null,l=null,c=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=r,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=l,this.matrixWeightsOverride=c}clone(){var e,t,i,s;return new pX(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)===null||e===void 0?void 0:e.slice(),(t=this.localNormalOverride)===null||t===void 0?void 0:t.slice(),(i=this.matrixIndicesOverride)===null||i===void 0?void 0:i.slice(),(s=this.matrixWeightsOverride)===null||s===void 0?void 0:s.slice())}}function KK(a,e,t){var i,s,r,n;const o=!!e.skeleton,l=t.localMode||o,c=e.overrideMaterialSideOrientation!==null&&e.overrideMaterialSideOrientation!==void 0,h=e.getIndices(),u=o?e.getPositionData(!0,!0):e.getVerticesData(se.PositionKind),p=o?e.getNormalsData(!0,!0):e.getVerticesData(se.NormalKind),m=l?o?e.getVerticesData(se.PositionKind):u:null,_=l?o?e.getVerticesData(se.NormalKind):p:null,f=e.getVerticesData(se.UVKind),d=o?e.getVerticesData(se.MatricesIndicesKind):null,C=o?e.getVerticesData(se.MatricesWeightsKind):null,v=o?e.getVerticesData(se.MatricesIndicesExtraKind):null,y=o?e.getVerticesData(se.MatricesWeightsExtraKind):null,M=t.position||O.Zero();let b=t.normal||O.Up();const E=t.size||O.One(),S=t.angle||0;if(!b){const j=new O(0,0,1),H=e.getScene().activeCamera,Y=O.TransformCoordinates(j,H.getWorldMatrix());b=H.globalPosition.subtract(Y)}const I=-Math.atan2(b.z,b.x)-Math.PI/2,D=Math.sqrt(b.x*b.x+b.z*b.z),R=Math.atan2(b.y,D),L=new Jt;L.indices=[],L.positions=[],L.normals=[],L.uvs=[],L.matricesIndices=o?[]:null,L.matricesWeights=o?[]:null,L.matricesIndicesExtra=v?[]:null,L.matricesWeightsExtra=y?[]:null;let w=0;const N=(j,H)=>{const Y=new pX;if(!h||!u||!p)return Y;const J=h[j];if(Y.vertexIdx=J*3,Y.vertexIdxForBones=J*4,Y.position=new O(u[J*3],u[J*3+1],u[J*3+2]),O.TransformCoordinatesToRef(Y.position,H,Y.position),Y.normal=new O(p[J*3],p[J*3+1],p[J*3+2]),O.TransformNormalToRef(Y.normal,H,Y.normal),t.captureUVS&&f){const te=f[J*2+1];Y.uv=new lt(f[J*2],fn.UseOpenGLOrientationForUV?1-te:te)}return Y},V=[0,0,0,0],W=(j,H)=>{if(j.length===0)return j;const Y=.5*Math.abs(O.Dot(E,H)),J=(ee,oe,ae,fe)=>{for(let de=0;de{var ae,fe,de,me,Fe,je,nt,we,Ke,ft,yt,Ze,mt,Je,Yt,Vt;const Ot=O.GetClipFactor(ee.position,oe.position,H,Y);let et=V,Xe=V;if(d&&C){const Ts=ee.matrixIndicesOverride?0:ee.vertexIdxForBones,Dt=(ae=ee.matrixIndicesOverride)!==null&&ae!==void 0?ae:d,xt=(fe=ee.matrixWeightsOverride)!==null&&fe!==void 0?fe:C,Wt=oe.matrixIndicesOverride?0:oe.vertexIdxForBones,Tt=(de=oe.matrixIndicesOverride)!==null&&de!==void 0?de:d,$i=(me=oe.matrixWeightsOverride)!==null&&me!==void 0?me:C;et=[0,0,0,0],Xe=[0,0,0,0];let Di=0;for(let Qi=0;Qi<4;++Qi)if(xt[Ts+Qi]>0){const St=J(Tt,Dt[Ts+Qi],Wt,4);et[Di]=Dt[Ts+Qi],Xe[Di]=Bt.Lerp(xt[Ts+Qi],St>=0?$i[St]:0,Ot),Di++}for(let Qi=0;Qi<4&&Di<4;++Qi){const St=Tt[Wt+Qi];J(Dt,St,Ts,4)===-1&&(et[Di]=St,Xe[Di]=Bt.Lerp(0,$i[Wt+Qi],Ot),Di++)}const is=Xe[0]+Xe[1]+Xe[2]+Xe[3];Xe[0]/=is,Xe[1]/=is,Xe[2]/=is,Xe[3]/=is}const ct=ee.localPositionOverride?ee.localPositionOverride[0]:(Fe=m?.[ee.vertexIdx])!==null&&Fe!==void 0?Fe:0,wt=ee.localPositionOverride?ee.localPositionOverride[1]:(je=m?.[ee.vertexIdx+1])!==null&&je!==void 0?je:0,Ut=ee.localPositionOverride?ee.localPositionOverride[2]:(nt=m?.[ee.vertexIdx+2])!==null&&nt!==void 0?nt:0,hi=oe.localPositionOverride?oe.localPositionOverride[0]:(we=m?.[oe.vertexIdx])!==null&&we!==void 0?we:0,Ri=oe.localPositionOverride?oe.localPositionOverride[1]:(Ke=m?.[oe.vertexIdx+1])!==null&&Ke!==void 0?Ke:0,Bi=oe.localPositionOverride?oe.localPositionOverride[2]:(ft=m?.[oe.vertexIdx+2])!==null&&ft!==void 0?ft:0,Yi=ee.localNormalOverride?ee.localNormalOverride[0]:(yt=_?.[ee.vertexIdx])!==null&&yt!==void 0?yt:0,Vi=ee.localNormalOverride?ee.localNormalOverride[1]:(Ze=_?.[ee.vertexIdx+1])!==null&&Ze!==void 0?Ze:0,Ji=ee.localNormalOverride?ee.localNormalOverride[2]:(mt=_?.[ee.vertexIdx+2])!==null&&mt!==void 0?mt:0,st=oe.localNormalOverride?oe.localNormalOverride[0]:(Je=_?.[oe.vertexIdx])!==null&&Je!==void 0?Je:0,Ht=oe.localNormalOverride?oe.localNormalOverride[1]:(Yt=_?.[oe.vertexIdx+1])!==null&&Yt!==void 0?Yt:0,kt=oe.localNormalOverride?oe.localNormalOverride[2]:(Vt=_?.[oe.vertexIdx+2])!==null&&Vt!==void 0?Vt:0,si=Yi+(st-Yi)*Ot,Qt=Vi+(Ht-Vi)*Ot,Ci=Ji+(kt-Ji)*Ot,Ni=Math.sqrt(si*si+Qt*Qt+Ci*Ci);return new pX(O.Lerp(ee.position,oe.position,Ot),O.Lerp(ee.normal,oe.normal,Ot).normalize(),lt.Lerp(ee.uv,oe.uv,Ot),-1,-1,m?[ct+(hi-ct)*Ot,wt+(Ri-wt)*Ot,Ut+(Bi-Ut)*Ot]:null,_?[si/Ni,Qt/Ni,Ci/Ni]:null,et,Xe)};let re=null;j.length>3&&(re=new Array);for(let ee=0;ee0,Ke=je>0,ft=nt>0;switch(oe=(we?1:0)+(Ke?1:0)+(ft?1:0),oe){case 0:j.length>3?(re.push(j[ee]),re.push(j[ee+1]),re.push(j[ee+2])):re=j;break;case 1:if(re=re??new Array,we&&(ae=j[ee+1],fe=j[ee+2],de=te(j[ee],ae),me=te(j[ee],fe)),Ke){ae=j[ee],fe=j[ee+2],de=te(j[ee+1],ae),me=te(j[ee+1],fe),re.push(de),re.push(fe.clone()),re.push(ae.clone()),re.push(fe.clone()),re.push(de.clone()),re.push(me);break}ft&&(ae=j[ee],fe=j[ee+1],de=te(j[ee+2],ae),me=te(j[ee+2],fe)),ae&&fe&&de&&me&&(re.push(ae.clone()),re.push(fe.clone()),re.push(de),re.push(me),re.push(de.clone()),re.push(fe.clone()));break;case 2:re=re??new Array,we||(ae=j[ee].clone(),fe=te(ae,j[ee+1]),de=te(ae,j[ee+2]),re.push(ae),re.push(fe),re.push(de)),Ke||(ae=j[ee+1].clone(),fe=te(ae,j[ee+2]),de=te(ae,j[ee]),re.push(ae),re.push(fe),re.push(de)),ft||(ae=j[ee+2].clone(),fe=te(ae,j[ee]),de=te(ae,j[ee+1]),re.push(ae),re.push(fe),re.push(de));break}}return re},G=e instanceof Oe?e:null,ie=G?._thinInstanceDataStorage.matrixData,Z=G?.thinInstanceCount||1,q=ue.Matrix[0];q.copyFrom(ge.IdentityReadOnly);for(let j=0;jKK(a,e,{position:t,normal:i,size:s,angle:r});class Ml{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&Me.Warn("x is not an integer, floor(x) used"),t!==Math.floor(t)&&Me.Warn("y is not an integer, floor(y) used")}clone(){return new Ml(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)&&Me.Warn("m not an integer only floor(m) used"),t!==Math.floor(t)&&Me.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)&&Me.Warn("m is not an integer, floor(m) used"),t!==Math.floor(t)&&Me.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=O.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 Ml(0,0)}}class Ree{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new mX("icosahedron","Regular",[[0,sh,-1],[-sh,1,0],[-1,0,-sh],[1,0,-sh],[sh,1,0],[0,sh,1],[-1,0,sh],[-sh,-1,0],[0,-sh,-1],[sh,-1,0],[1,0,sh],[0,-sh,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,s=this.n;let r=i,n=1,o=0;s!==0&&(r=Bt.HCF(i,s)),n=i/r,o=s/r;let l,c,h,u,p;const m=Ml.Zero(),_=new Ml(i,s),f=new Ml(-s,i+s),d=Ml.Zero(),C=Ml.Zero(),v=Ml.Zero();let y=[],M,b,E,S;const I=[],D=this.vertByDist,R=(L,w,N,V)=>{M=L+"|"+N,b=w+"|"+V,M in t||b in t?M in t&&!(b in t)?t[b]=t[M]:b in t&&!(M in t)&&(t[M]=t[b]):(t[M]=e,t[b]=e,e++),D[N][0]>2?I[t[M]]=[-D[N][0],D[N][1],t[M]]:I[t[M]]=[y[D[N][0]],D[N][1],t[M]]};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 L=0;L<20;L++){if(y=this.IDATA.face[L],h=y[2],u=y[1],p=y[0],E=m.x+"|"+m.y,M=L+"|"+E,M in t||(t[M]=h,I[h]=[y[D[E][0]],D[E][1]]),E=_.x+"|"+_.y,M=L+"|"+E,M in t||(t[M]=u,I[u]=[y[D[E][0]],D[E][1]]),E=f.x+"|"+f.y,M=L+"|"+E,M in t||(t[M]=p,I[p]=[y[D[E][0]],D[E][1]]),l=this.IDATA.edgematch[L][0],c=this.IDATA.edgematch[L][1],c==="B")for(let w=1;w2?I[t[M]]=[-D[E][0],D[E][1],t[M]]:I[t[M]]=[y[D[E][0]],D[E][1],t[M]])}this.closestTo=I,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,s=e*e+t*t+e*t;this.coau=(e+t)/s,this.cobu=-t/s,this.coav=-i*(e-t)/s,this.cobv=i*(2*e+t)/s}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&s0){const b=Bt.HCF(e,t),E=e/b,S=t/b;for(let D=1;Db.x-E.x),i.sort((b,E)=>b.y-E.y);const o=new Array(e+t+1),l=new Array(e+t+1);for(let b=0;b{const S=b.clone();return E==="A"&&S.rotateNeg120(e,t),E==="B"&&S.rotate120(e,t),S.x<0?S.y:S.x+S.y},m=[],_=[],f=[],d=[],C={},v=[];let y=-1,M=-1;for(let b=0;bb[2]-E[2]),v.sort((b,E)=>b[3]-E[3]),v.sort((b,E)=>b[1]-E[1]),v.sort((b,E)=>b[0]-E[0]);for(let b=0;bt.vecToidx[e+s]))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let s=0;s-1?i[n][1]>0&&t[i[n][0]].push([n,i[n][1]]):t[12].push([n,i[n][0]]);const s=[];for(let n=0;n<12;n++)s[n]=n;let r=12;for(let n=0;n<12;n++){t[n].sort((o,l)=>o[1]-l[1]);for(let o=0;on[3]-o[3]);for(let n=0;n0;)r=t[l],this.face[r].indexOf(o)>-1?(n=(this.face[r].indexOf(o)+1)%3,o=this.face[r][n],i.push(o),s.push(r),t.splice(l,1),l=0):l++;return this.adjacentFaces.push(i),s}toGoldbergPolyhedronData(){const e=new mX("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let c=0;c{s=0,r=0,n=0,o=this.face[h];for(let u=0;u<3;u++)l=this.vertex[o[u]],s+=l[0],r+=l[1],n+=l[2];e.vertex[h]=[s/3,r/3,n/3]});return e}static BuildGeodesicData(e){const t=new vW("Geodesic-m-n","Geodesic",[[0,sh,-1],[-sh,1,0],[-1,0,-sh],[1,0,-sh],[sh,1,0],[0,sh,1],[-1,0,sh],[-sh,-1,0],[0,-sh,-1],[sh,-1,0],[1,0,sh],[0,-sh,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let s=0;si){const c=s;s=i,i=c,Me.Warn("n > m therefore m and n swapped")}const r=new Ree;r.build(i,s);const o={custom:vW.BuildGeodesicData(r),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 KP(a,o,t)}Oe._GoldbergMeshParser=(a,e)=>CW.Parse(a,e);class CW extends Oe{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&&(Me.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(Me.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(Me.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),c.push(u,p);for(let m=0;m<6;m++)u=n.x+o*Math.cos(l+m*Math.PI/3),p=n.y+o*Math.sin(l+m*Math.PI/3),u<0&&(u=0),u>1&&(u=1),h.push(u,p);for(let m=s;mZt.FromArray(r)),i.faceCenters=i.faceCenters.map(r=>O.FromArray(r)),i.faceZaxis=i.faceZaxis.map(r=>O.FromArray(r)),i.faceXaxis=i.faceXaxis.map(r=>O.FromArray(r)),i.faceYaxis=i.faceYaxis.map(r=>O.FromArray(r));const s=new CW(e.name,t);return s.goldbergData=i,s}}function Sce(a,e){const t=a.size,i=a.sizeX||t||1,s=a.sizeY||t||1,r=a.sizeZ||t||1,n=a.sideOrientation===0?0:a.sideOrientation||Jt.DEFAULTSIDE,o=new Array,l=new Array,c=new Array,h=new Array;let u=1/0,p=-1/0,m=1/0,_=-1/0;for(let C=0;Co){const _=l;l=o,o=_,Me.Warn("n > m therefore m and n swapped")}const c=new Ree;c.build(o,l);const h=vW.BuildGeodesicData(c),u=h.toGoldbergPolyhedronData(),p=new CW(a,t);e.sideOrientation=Oe._GetDefaultSideOrientation(e.sideOrientation),p._originalBuilderSideOrientation=e.sideOrientation,Sce(e,u).applyToMesh(p,e.updatable),p.goldbergData.nbSharedFaces=h.sharedNodes,p.goldbergData.nbUnsharedFaces=h.poleNodes,p.goldbergData.adjacentFaces=h.adjacentFaces,p.goldbergData.nbFaces=p.goldbergData.nbSharedFaces+p.goldbergData.nbUnsharedFaces,p.goldbergData.nbFacesAtPole=(p.goldbergData.nbUnsharedFaces-12)/12;for(let _=0;_0?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 vge(a,e,t,i,s,r){const n=r.glyphs[a]||r.glyphs["?"];if(!n)return null;const o=new gge(s);if(n.o){const l=n.o.split(" ");for(let c=0,h=l.length;cLs&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>Ls&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>Ls&&(e.z=1*Math.sign(e.z))}_updateDebugConstraint(e,t){if(!e._initOptions)return;const{pivotA:i,pivotB:s,axisA:r,axisB:n,perpAxisA:o,perpAxisB:l}=e._initOptions;!i||!s||!r||!n||!o||!l||t.getDescendants(!0).forEach(c=>{const h=c.getDescendants(!0)[0],u=c.getDescendants(!0)[1],{parentBody:p,parentBodyIndex:m}=h.metadata,{childBody:_,childBodyIndex:f}=u.metadata,d=this._getTransformFromBodyToRef(p,ue.Matrix[0],m),C=this._getTransformFromBodyToRef(_,ue.Matrix[1],f);d.decomposeToTransformNode(h),this._makeScalingUnitInPlace(h.scaling),C.decomposeToTransformNode(u),this._makeScalingUnitInPlace(u.scaling);const v=h.getDescendants(!0)[0];v.position.copyFrom(i);const y=u.getDescendants(!0)[0];y.position.copyFrom(s),ke.FromRotationMatrixToRef(ge.FromXYZAxesToRef(r,o,O.CrossToRef(r,o,ue.Vector3[0]),ue.Matrix[0]),v.rotationQuaternion),ke.FromRotationMatrixToRef(ge.FromXYZAxesToRef(n,l,O.CrossToRef(n,l,ue.Vector3[1]),ue.Matrix[1]),y.rotationQuaternion)})}showImpostor(e,t){if(!this._scene)return null;for(let s=0;s-1&&this._debugMeshMeshes.splice(n,1),this._numMeshes--,this._numMeshes>0?(this._meshes[s]=this._meshes[this._numMeshes],this._impostors[s]=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 s=0;s0?(this._bodyMeshes[s]=this._bodyMeshes[this._numBodies],this._bodies[s]=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 s=0;s0?(this._constraints[s]=this._constraints[this._numConstraints],this._constraintMeshes[s]=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 jt("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=Ie.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugInertiaMaterial(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new jt("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=pl("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=ke.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=$d("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=ke.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=fW("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=ke.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=J1("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=ke.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new Oe(e.name,t,null,e);return i.setParent(e),i.position=O.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 s=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return Me.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case ys.BoxImpostor:i=this._getDebugBoxMesh(s),e.getBoxSizeToRef(i.scaling);break;case ys.SphereImpostor:{i=this._getDebugSphereMesh(s);const r=e.getRadius();i.scaling.x=r*2,i.scaling.y=r*2,i.scaling.z=r*2;break}case ys.CapsuleImpostor:{i=this._getDebugCapsuleMesh(s);const r=e.object.getBoundingInfo();i.scaling.x=(r.boundingBox.maximum.x-r.boundingBox.minimum.x)*2*e.object.scaling.x,i.scaling.y=(r.boundingBox.maximum.y-r.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(r.boundingBox.maximum.z-r.boundingBox.minimum.z)*2*e.object.scaling.z;break}case ys.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,s));break;case ys.NoImpostor:t?t.getChildMeshes().filter(n=>n.physicsImpostor?1:0).forEach(n=>{if(n.physicsImpostor&&n.getClassName()==="Mesh"){const o=n.getBoundingInfo(),l=o.boundingBox.minimum,c=o.boundingBox.maximum;switch(n.physicsImpostor.type){case ys.BoxImpostor:i=this._getDebugBoxMesh(s),i.position.copyFrom(l),i.position.addInPlace(c),i.position.scaleInPlace(.5);break;case ys.SphereImpostor:i=this._getDebugSphereMesh(s);break;case ys.CylinderImpostor:i=this._getDebugCylinderMesh(s);break;default:i=null;break}i&&(i.scaling.x=c.x-l.x,i.scaling.y=c.y-l.y,i.scaling.z=c.z-l.z,i.parent=n)}}):Me.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case ys.CylinderImpostor:{i=this._getDebugCylinderMesh(s);const r=e.object.getBoundingInfo();i.scaling.x=(r.boundingBox.maximum.x-r.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(r.boundingBox.maximum.y-r.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(r.boundingBox.maximum.z-r.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new Oe("custom",t),s=new Jt,r=e.getGeometry();if(s.positions=r.positions,s.indices=r.indices,s.applyToMesh(i),e._pluginDataInstances){const n=new Float32Array(e._pluginDataInstances.length*16);i.thinInstanceSetBuffer("matrix",n,16)}return i.material=this._getDebugMaterial(t),i}_getMeshDebugInertiaMatrixToRef(e,t){var i,s,r;const n=(i=e.inertiaOrientation)!==null&&i!==void 0?i:ke.Identity(),o=(s=e.inertia)!==null&&s!==void 0?s:O.Zero(),l=(r=e.centerOfMass)!==null&&r!==void 0?r:O.Zero(),c=(o.x-o.y+o.z)*6,h=Math.sqrt(Math.max(c,0)),u=o.x*12-c,p=Math.sqrt(Math.max(u,0)),m=o.z*12-c,_=Math.sqrt(Math.max(m,0)),f=ue.Vector3[0];f.set(_,h,p);const d=ge.ScalingToRef(f.x,f.y,f.z,ue.Matrix[0]),C=n.toRotationMatrix(ue.Matrix[1]),v=ge.TranslationToRef(l.x,l.y,l.z,ue.Matrix[2]);return d.multiplyToRef(C,t),t.multiplyToRef(v,t),t}_getDebugInertiaMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=nl.CreateBox("custom",{size:1},t),s=ge.Identity();if(e._pluginDataInstances.length){const r=new Float32Array(e._pluginDataInstances.length*16);for(let n=0;n=0?ge.FromArrayToRef(s._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(s.getWorldMatrix())}_getDebugConstraintMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;const{pivotA:i,pivotB:s,axisA:r,axisB:n,perpAxisA:o,perpAxisB:l}=e._initOptions;if(!i||!s||!r||!n||!o||!l)return null;const c=new Oe("parentingDebugConstraint",t),h=e.getBodiesUsingConstraint();for(const u of h){const p=new Ki("parentOfPair",t);p.parent=c;const{parentBody:m,parentBodyIndex:_,childBody:f,childBodyIndex:d}=u,C=this._getTransformFromBodyToRef(m,ue.Matrix[0],_),v=this._getTransformFromBodyToRef(f,ue.Matrix[1],d),y=new Ki("parentCoordSystem",t);y.parent=p,y.metadata={parentBody:m,parentBodyIndex:_},C.decomposeToTransformNode(y);const M=new Ki("childCoordSystem",t);M.parent=p,M.metadata={childBody:f,childBodyIndex:d},v.decomposeToTransformNode(M);const b=ke.FromRotationMatrix(ge.FromXYZAxesToRef(r,o,r.cross(o),ue.Matrix[0])),E=ke.FromRotationMatrix(ge.FromXYZAxesToRef(n,l,n.cross(l),ue.Matrix[0])),S=i,I=s,D=new Ki("constraint_parent",t);D.position.copyFrom(S),D.rotationQuaternion=b,D.parent=y;const R=new Ki("constraint_child",t);R.parent=M,R.position.copyFrom(I),R.rotationQuaternion=E;const L=new sI(t,this._constraintAxesSize);L.xAxis.parent=D,L.yAxis.parent=D,L.zAxis.parent=D;const w=new sI(t,this._constraintAxesSize);w.xAxis.parent=R,w.yAxis.parent=R,w.zAxis.parent=R}return c}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 Dee{static CreateAndShow(e,t,i){const s=new Dee(e);return s.show(t,i),s}constructor(e){this.ray=e}show(e,t){if(!this._renderFunction&&this.ray){const i=this.ray;this._renderFunction=this._render.bind(this),this._scene=e,this._renderPoints=[i.origin,i.origin.add(i.direction.scale(i.length))],this._renderLine=Ga("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 e;const t=this.ray;if(!t)return;const i=this._renderPoints[1],s=Math.min(t.length,1e6);i.copyFrom(t.direction),i.scaleInPlace(s),i.addInPlace(t.origin),this._renderPoints[0].copyFrom(t.origin),Ga("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),(e=this._renderLine)===null||e===void 0||e.refreshBoundingInfo()}attachToMesh(e,t,i,s){this._attachedToMesh=e;const r=this.ray;!r||(r.direction||(r.direction=O.Zero()),r.origin||(r.origin=O.Zero()),s&&(r.length=s),i||(i=O.Zero()),t||(t=new O(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),O.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)}}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}class h0{static CreateBoneWeightShader(e,t){var i,s,r,n,o,l;const c=e.skeleton,h=(i=e.colorBase)!==null&&i!==void 0?i:Ie.Black(),u=(s=e.colorZero)!==null&&s!==void 0?s:Ie.Blue(),p=(r=e.colorQuarter)!==null&&r!==void 0?r:Ie.Green(),m=(n=e.colorHalf)!==null&&n!==void 0?n:Ie.Yellow(),_=(o=e.colorFull)!==null&&o!==void 0?o:Ie.Red(),f=(l=e.targetBoneIndex)!==null&&l!==void 0?l:0;Ws.ShadersStore["boneWeights:"+c.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; + }`,Ws.ShadersStore["boneWeights:"+c.name+"FragmentShader"]=` + precision highp float; + varying vec3 vPosition; + + varying vec3 vColor; + + void main() { + vec4 color = vec4(vColor, 1.0); + gl_FragColor = color; + } + `;const d=new oh("boneWeight:"+c.name,t,{vertex:"boneWeights:"+c.name,fragment:"boneWeights:"+c.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return d.setColor3("colorBase",h),d.setColor3("colorZero",u),d.setColor3("colorQuarter",p),d.setColor3("colorHalf",m),d.setColor3("colorFull",_),d.setFloat("targetBoneIndex",f),d.getClassName=()=>"BoneWeightShader",d.transparencyMode=Lt.MATERIAL_OPAQUE,d}static CreateSkeletonMapShader(e,t){var i;const s=e.skeleton,r=(i=e.colorMap)!==null&&i!==void 0?i:[{color:new Ie(1,.38,.18),location:0},{color:new Ie(.59,.18,1),location:.2},{color:new Ie(.59,1,.18),location:.4},{color:new Ie(1,.87,.17),location:.6},{color:new Ie(1,.17,.42),location:.8},{color:new Ie(.17,.68,1),location:1}],n=s.bones.length+1,o=h0._CreateBoneMapColorBuffer(n,r,t),l=new oh("boneWeights:"+s.name,t,{vertexSource:`precision highp float; + + attribute vec3 position; + attribute vec2 uv; + + uniform mat4 view; + uniform mat4 projection; + uniform mat4 worldViewProjection; + uniform float colorMap[`+s.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 l.setFloats("colorMap",o),l.getClassName=()=>"SkeletonMapShader",l.transparencyMode=Lt.MATERIAL_OPAQUE,l}static _CreateBoneMapColorBuffer(e,t,i){const s=new ep("temp",{width:e,height:1},i,!1),r=s.getContext(),n=r.createLinearGradient(0,0,e,0);t.forEach(h=>{n.addColorStop(h.location,h.color.toHexString())}),r.fillStyle=n,r.fillRect(0,0,e,1),s.update();const o=[],l=r.getImageData(0,0,e,1).data,c=1/255;for(let h=0;hh0.DISPLAY_SPHERE_AND_SPURS&&(e=h0.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,s=!0,r=3,n={}){var o,l,c,h,u,p,m,_,f,d,C,v,y,M;this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=s,this.renderingGroupId=r,this.options=n,this.color=Ie.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=(o=n.pauseAnimations)!==null&&o!==void 0?o:!0,n.returnToRest=(l=n.returnToRest)!==null&&l!==void 0?l:!1,n.displayMode=(c=n.displayMode)!==null&&c!==void 0?c:h0.DISPLAY_LINES,n.displayOptions=(h=n.displayOptions)!==null&&h!==void 0?h:{},n.displayOptions.midStep=(u=n.displayOptions.midStep)!==null&&u!==void 0?u:.235,n.displayOptions.midStepFactor=(p=n.displayOptions.midStepFactor)!==null&&p!==void 0?p:.155,n.displayOptions.sphereBaseSize=(m=n.displayOptions.sphereBaseSize)!==null&&m!==void 0?m:.15,n.displayOptions.sphereScaleUnit=(_=n.displayOptions.sphereScaleUnit)!==null&&_!==void 0?_:2,n.displayOptions.sphereFactor=(f=n.displayOptions.sphereFactor)!==null&&f!==void 0?f:.865,n.displayOptions.spurFollowsChild=(d=n.displayOptions.spurFollowsChild)!==null&&d!==void 0?d:!1,n.displayOptions.showLocalAxes=(C=n.displayOptions.showLocalAxes)!==null&&C!==void 0?C:!1,n.displayOptions.localAxesSize=(v=n.displayOptions.localAxesSize)!==null&&v!==void 0?v:.075,n.computeBonesUsingShaders=(y=n.computeBonesUsingShaders)!==null&&y!==void 0?y:!0,n.useAllBones=(M=n.useAllBones)!==null&&M!==void 0?M:!0;const b=t.getVerticesData(se.MatricesIndicesKind),E=t.getVerticesData(se.MatricesWeightsKind);if(this._boneIndices=new Set,!n.useAllBones&&b&&E)for(let I=0;Ih0.DISPLAY_SPHERE_AND_SPURS&&(S=h0.DISPLAY_LINES),this.displayMode=S,this.update(),this._bindObs()}_bindObs(){switch(this.displayMode){case h0.DISPLAY_LINES:{this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()});break}}}update(){switch(this.displayMode){case h0.DISPLAY_LINES:{this._displayLinesUpdate();break}case h0.DISPLAY_SPHERES:{this._buildSpheresAndSpurs(!0);break}case h0.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,s=0,r=0,n=0){const o=ue.Matrix[0],l=t.getParent();if(o.copyFrom(t.getLocalMatrix()),s!==0||r!==0||n!==0){const c=ue.Matrix[1];ge.IdentityToRef(c),c.setTranslationFromFloats(s,r,n),c.multiplyToRef(o,o)}l&&o.multiplyToRef(l.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,r=this.mesh.position;let n=0;for(let o=0;o=0;n--){const o=e[n],l=o.getParent();if(!l||!this._boneIndices.has(o.getIndex())&&!this.options.useAllBones)continue;let c=this._debugLines[i];c||(c=[O.Zero(),O.Zero()],this._debugLines[i]=c),o.getAbsolutePositionToRef(s,c[0]),l.getAbsolutePositionToRef(s,c[1]),c[0].subtractInPlace(r),c[1].subtractInPlace(r),i++}}_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(ge.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const s=(t=this.utilityLayer)===null||t===void 0?void 0:t.utilityLayerScene,r=this.skeleton.bones,n=[],o=[],l=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,s.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let c=Number.NEGATIVE_INFINITY;const h=this.options.displayOptions||{};for(let f=0;f{const D=new ge;I.getLocalMatrix().multiplyToRef(C,D);const R=new O;D.decompose(void 0,void 0,R);const L=O.Distance(v,R);if(L>c&&(c=L),e)return;const w=R.clone().subtract(v.clone()),N=w.length(),V=w.normalize().scale(N),W=h.midStep||.165,G=h.midStepFactor||.215,ie=V.scale(W),Z=gW("skeletonViewer",{shape:[new O(1,-1,0),new O(1,1,0),new O(-1,1,0),new O(-1,-1,0),new O(1,-1,0)],path:[O.Zero(),ie,V],scaleFunction:H=>{switch(H){case 0:case 2:return 0;case 1:return N*G}return 0},sideOrientation:Oe.DEFAULTSIDE,updatable:!1},s),q=Z.getTotalVertices(),K=[],j=[];for(let H=0;H9?j.push(I.getIndex(),0,0,0):j.push(d.getIndex(),0,0,0);Z.position=v.clone(),Z.setVerticesData(se.MatricesWeightsKind,K,!1),Z.setVerticesData(se.MatricesIndicesKind,j,!1),Z.convertToFlatShadedMesh(),o.push(Z)});const y=h.sphereBaseSize||.2,M=$d("skeletonViewer",{segments:6,diameter:y,updatable:!0},s),b=M.getTotalVertices(),E=[],S=[];for(let I=0;I{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 e,t,i,s,r,n;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,ue.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,this._light.shadowMinZ!==void 0?this._light.shadowMinZ:this._camera.minZ),ue.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,this._light.shadowMaxZ!==void 0?this._light.shadowMaxZ:this._camera.maxZ);const o=this._getInvertViewMatrix();ue.Vector3[2].copyFromFloats(ue.Vector3[1].x,ue.Vector3[1].y,ue.Vector3[0].z),ue.Vector3[3].copyFromFloats(ue.Vector3[1].x,ue.Vector3[0].y,ue.Vector3[0].z),ue.Vector3[4].copyFromFloats(ue.Vector3[0].x,ue.Vector3[0].y,ue.Vector3[0].z),ue.Vector3[5].copyFromFloats(ue.Vector3[0].x,ue.Vector3[1].y,ue.Vector3[0].z),O.TransformCoordinatesToRef(ue.Vector3[2],o,ue.Vector3[2]),O.TransformCoordinatesToRef(ue.Vector3[3],o,ue.Vector3[3]),O.TransformCoordinatesToRef(ue.Vector3[4],o,ue.Vector3[4]),O.TransformCoordinatesToRef(ue.Vector3[5],o,ue.Vector3[5]),ue.Vector3[6].copyFromFloats(ue.Vector3[1].x,ue.Vector3[1].y,ue.Vector3[1].z),ue.Vector3[7].copyFromFloats(ue.Vector3[1].x,ue.Vector3[0].y,ue.Vector3[1].z),ue.Vector3[8].copyFromFloats(ue.Vector3[0].x,ue.Vector3[0].y,ue.Vector3[1].z),ue.Vector3[9].copyFromFloats(ue.Vector3[0].x,ue.Vector3[1].y,ue.Vector3[1].z),O.TransformCoordinatesToRef(ue.Vector3[6],o,ue.Vector3[6]),O.TransformCoordinatesToRef(ue.Vector3[7],o,ue.Vector3[7]),O.TransformCoordinatesToRef(ue.Vector3[8],o,ue.Vector3[8]),O.TransformCoordinatesToRef(ue.Vector3[9],o,ue.Vector3[9]),Ga("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),Ga("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),Ga("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),Ga("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),Ga("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),Ga("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),ue.Vector3[2].toArray(this._nearPlaneVertices,0),ue.Vector3[3].toArray(this._nearPlaneVertices,3),ue.Vector3[4].toArray(this._nearPlaneVertices,6),ue.Vector3[5].toArray(this._nearPlaneVertices,9),(e=this._lightHelperFrustumMeshes[6].geometry)===null||e===void 0||e.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),ue.Vector3[6].toArray(this._farPlaneVertices,0),ue.Vector3[7].toArray(this._farPlaneVertices,3),ue.Vector3[8].toArray(this._farPlaneVertices,6),ue.Vector3[9].toArray(this._farPlaneVertices,9),(t=this._lightHelperFrustumMeshes[7].geometry)===null||t===void 0||t.updateVerticesDataDirectly("position",this._farPlaneVertices,0),ue.Vector3[2].toArray(this._rightPlaneVertices,0),ue.Vector3[6].toArray(this._rightPlaneVertices,3),ue.Vector3[7].toArray(this._rightPlaneVertices,6),ue.Vector3[3].toArray(this._rightPlaneVertices,9),(i=this._lightHelperFrustumMeshes[8].geometry)===null||i===void 0||i.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),ue.Vector3[5].toArray(this._leftPlaneVertices,0),ue.Vector3[9].toArray(this._leftPlaneVertices,3),ue.Vector3[8].toArray(this._leftPlaneVertices,6),ue.Vector3[4].toArray(this._leftPlaneVertices,9),(s=this._lightHelperFrustumMeshes[9].geometry)===null||s===void 0||s.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),ue.Vector3[2].toArray(this._topPlaneVertices,0),ue.Vector3[6].toArray(this._topPlaneVertices,3),ue.Vector3[9].toArray(this._topPlaneVertices,6),ue.Vector3[5].toArray(this._topPlaneVertices,9),(r=this._lightHelperFrustumMeshes[10].geometry)===null||r===void 0||r.updateVerticesDataDirectly("position",this._topPlaneVertices,0),ue.Vector3[3].toArray(this._bottomPlaneVertices,0),ue.Vector3[7].toArray(this._bottomPlaneVertices,3),ue.Vector3[8].toArray(this._bottomPlaneVertices,6),ue.Vector3[4].toArray(this._bottomPlaneVertices,9),(n=this._lightHelperFrustumMeshes[11].geometry)===null||n===void 0||n.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}dispose(){this._lightHelperFrustumMeshes.forEach(e=>{var t;(t=e.material)===null||t===void 0||t.dispose(),e.dispose()}),this._rootNode.dispose()}_createGeometry(){this._rootNode=new Ki("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[O.ZeroReadOnly,O.ZeroReadOnly,O.ZeroReadOnly,O.ZeroReadOnly,O.ZeroReadOnly];const e=Ga("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[O.ZeroReadOnly,O.ZeroReadOnly,O.ZeroReadOnly,O.ZeroReadOnly,O.ZeroReadOnly];const t=Ga("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[O.ZeroReadOnly,O.ZeroReadOnly];const i=Ga("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[O.ZeroReadOnly,O.ZeroReadOnly];const s=Ga("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[O.ZeroReadOnly,O.ZeroReadOnly];const r=Ga("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[O.ZeroReadOnly,O.ZeroReadOnly];const n=Ga("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,s,r,n);const o=(l,c,h)=>{const u=new Oe(l+"plane",this._scene),p=new jt(l+"PlaneMat",this._scene);u.material=p,u.parent=this._rootNode,u.alwaysSelectAsActiveMesh=!0,p.emissiveColor=c,p.alpha=this.transparency,p.backFaceCulling=!1,p.disableLighting=!0;const m=[0,1,2,0,2,3],_=new Jt;_.positions=h,_.indices=m,_.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 Ie(1,0,0),this._nearPlaneVertices),o("far",new Ie(.3,0,0),this._farPlaneVertices),o("right",new Ie(0,1,0),this._rightPlaneVertices),o("left",new Ie(0,.3,0),this._leftPlaneVertices),o("top",new Ie(0,0,1),this._topPlaneVertices),o("bottom",new Ie(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=ue.Vector3[2],this._nearLinesPoints[1]=ue.Vector3[3],this._nearLinesPoints[2]=ue.Vector3[4],this._nearLinesPoints[3]=ue.Vector3[5],this._nearLinesPoints[4]=ue.Vector3[2],this._farLinesPoints[0]=ue.Vector3[6],this._farLinesPoints[1]=ue.Vector3[7],this._farLinesPoints[2]=ue.Vector3[8],this._farLinesPoints[3]=ue.Vector3[9],this._farLinesPoints[4]=ue.Vector3[6],this._trLinesPoints[0]=ue.Vector3[2],this._trLinesPoints[1]=ue.Vector3[6],this._brLinesPoints[0]=ue.Vector3[3],this._brLinesPoints[1]=ue.Vector3[7],this._tlLinesPoints[0]=ue.Vector3[4],this._tlLinesPoints[1]=ue.Vector3[8],this._blLinesPoints[0]=ue.Vector3[5],this._blLinesPoints[1]=ue.Vector3[9]}_getInvertViewMatrix(){return ge.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),O.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}class it{}it.ALPHA_DISABLE=0;it.ALPHA_ADD=1;it.ALPHA_COMBINE=2;it.ALPHA_SUBTRACT=3;it.ALPHA_MULTIPLY=4;it.ALPHA_MAXIMIZED=5;it.ALPHA_ONEONE=6;it.ALPHA_PREMULTIPLIED=7;it.ALPHA_PREMULTIPLIED_PORTERDUFF=8;it.ALPHA_INTERPOLATE=9;it.ALPHA_SCREENMODE=10;it.ALPHA_ONEONE_ONEONE=11;it.ALPHA_ALPHATOCOLOR=12;it.ALPHA_REVERSEONEMINUS=13;it.ALPHA_SRC_DSTONEMINUSSRCALPHA=14;it.ALPHA_ONEONE_ONEZERO=15;it.ALPHA_EXCLUSION=16;it.ALPHA_LAYER_ACCUMULATE=17;it.ALPHA_EQUATION_ADD=0;it.ALPHA_EQUATION_SUBSTRACT=1;it.ALPHA_EQUATION_REVERSE_SUBTRACT=2;it.ALPHA_EQUATION_MAX=3;it.ALPHA_EQUATION_MIN=4;it.ALPHA_EQUATION_DARKEN=5;it.DELAYLOADSTATE_NONE=0;it.DELAYLOADSTATE_LOADED=1;it.DELAYLOADSTATE_LOADING=2;it.DELAYLOADSTATE_NOTLOADED=4;it.NEVER=512;it.ALWAYS=519;it.LESS=513;it.EQUAL=514;it.LEQUAL=515;it.GREATER=516;it.GEQUAL=518;it.NOTEQUAL=517;it.KEEP=7680;it.ZERO=0;it.REPLACE=7681;it.INCR=7682;it.DECR=7683;it.INVERT=5386;it.INCR_WRAP=34055;it.DECR_WRAP=34056;it.TEXTURE_CLAMP_ADDRESSMODE=0;it.TEXTURE_WRAP_ADDRESSMODE=1;it.TEXTURE_MIRROR_ADDRESSMODE=2;it.TEXTURE_CREATIONFLAG_STORAGE=1;it.TEXTUREFORMAT_ALPHA=0;it.TEXTUREFORMAT_LUMINANCE=1;it.TEXTUREFORMAT_LUMINANCE_ALPHA=2;it.TEXTUREFORMAT_RGB=4;it.TEXTUREFORMAT_RGBA=5;it.TEXTUREFORMAT_RED=6;it.TEXTUREFORMAT_R=6;it.TEXTUREFORMAT_RG=7;it.TEXTUREFORMAT_RED_INTEGER=8;it.TEXTUREFORMAT_R_INTEGER=8;it.TEXTUREFORMAT_RG_INTEGER=9;it.TEXTUREFORMAT_RGB_INTEGER=10;it.TEXTUREFORMAT_RGBA_INTEGER=11;it.TEXTUREFORMAT_BGRA=12;it.TEXTUREFORMAT_DEPTH24_STENCIL8=13;it.TEXTUREFORMAT_DEPTH32_FLOAT=14;it.TEXTUREFORMAT_DEPTH16=15;it.TEXTUREFORMAT_DEPTH24=16;it.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17;it.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18;it.TEXTUREFORMAT_STENCIL8=19;it.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492;it.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493;it.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495;it.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494;it.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779;it.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919;it.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778;it.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918;it.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777;it.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776;it.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917;it.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916;it.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808;it.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840;it.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196;it.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492;it.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493;it.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494;it.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495;it.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496;it.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497;it.TEXTURETYPE_UNSIGNED_BYTE=0;it.TEXTURETYPE_UNSIGNED_INT=0;it.TEXTURETYPE_FLOAT=1;it.TEXTURETYPE_HALF_FLOAT=2;it.TEXTURETYPE_BYTE=3;it.TEXTURETYPE_SHORT=4;it.TEXTURETYPE_UNSIGNED_SHORT=5;it.TEXTURETYPE_INT=6;it.TEXTURETYPE_UNSIGNED_INTEGER=7;it.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;it.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;it.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;it.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;it.TEXTURETYPE_UNSIGNED_INT_24_8=12;it.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;it.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;it.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;it.TEXTURETYPE_UNDEFINED=16;it.TEXTURE_2D=3553;it.TEXTURE_2D_ARRAY=35866;it.TEXTURE_CUBE_MAP=34067;it.TEXTURE_CUBE_MAP_ARRAY=3735928559;it.TEXTURE_3D=32879;it.TEXTURE_NEAREST_SAMPLINGMODE=1;it.TEXTURE_NEAREST_NEAREST=1;it.TEXTURE_BILINEAR_SAMPLINGMODE=2;it.TEXTURE_LINEAR_LINEAR=2;it.TEXTURE_TRILINEAR_SAMPLINGMODE=3;it.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;it.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;it.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;it.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;it.TEXTURE_NEAREST_LINEAR=7;it.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;it.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;it.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;it.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;it.TEXTURE_LINEAR_NEAREST=12;it.TEXTURE_EXPLICIT_MODE=0;it.TEXTURE_SPHERICAL_MODE=1;it.TEXTURE_PLANAR_MODE=2;it.TEXTURE_CUBIC_MODE=3;it.TEXTURE_PROJECTION_MODE=4;it.TEXTURE_SKYBOX_MODE=5;it.TEXTURE_INVCUBIC_MODE=6;it.TEXTURE_EQUIRECTANGULAR_MODE=7;it.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;it.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;it.TEXTURE_FILTERING_QUALITY_OFFLINE=4096;it.TEXTURE_FILTERING_QUALITY_HIGH=64;it.TEXTURE_FILTERING_QUALITY_MEDIUM=16;it.TEXTURE_FILTERING_QUALITY_LOW=8;it.SCALEMODE_FLOOR=1;it.SCALEMODE_NEAREST=2;it.SCALEMODE_CEILING=3;it.MATERIAL_TextureDirtyFlag=1;it.MATERIAL_LightDirtyFlag=2;it.MATERIAL_FresnelDirtyFlag=4;it.MATERIAL_AttributesDirtyFlag=8;it.MATERIAL_MiscDirtyFlag=16;it.MATERIAL_PrePassDirtyFlag=32;it.MATERIAL_AllDirtyFlag=63;it.MATERIAL_TriangleFillMode=0;it.MATERIAL_WireFrameFillMode=1;it.MATERIAL_PointFillMode=2;it.MATERIAL_PointListDrawMode=3;it.MATERIAL_LineListDrawMode=4;it.MATERIAL_LineLoopDrawMode=5;it.MATERIAL_LineStripDrawMode=6;it.MATERIAL_TriangleStripDrawMode=7;it.MATERIAL_TriangleFanDrawMode=8;it.MATERIAL_ClockWiseSideOrientation=0;it.MATERIAL_CounterClockWiseSideOrientation=1;it.ACTION_NothingTrigger=0;it.ACTION_OnPickTrigger=1;it.ACTION_OnLeftPickTrigger=2;it.ACTION_OnRightPickTrigger=3;it.ACTION_OnCenterPickTrigger=4;it.ACTION_OnPickDownTrigger=5;it.ACTION_OnDoublePickTrigger=6;it.ACTION_OnPickUpTrigger=7;it.ACTION_OnPickOutTrigger=16;it.ACTION_OnLongPressTrigger=8;it.ACTION_OnPointerOverTrigger=9;it.ACTION_OnPointerOutTrigger=10;it.ACTION_OnEveryFrameTrigger=11;it.ACTION_OnIntersectionEnterTrigger=12;it.ACTION_OnIntersectionExitTrigger=13;it.ACTION_OnKeyDownTrigger=14;it.ACTION_OnKeyUpTrigger=15;it.PARTICLES_BILLBOARDMODE_Y=2;it.PARTICLES_BILLBOARDMODE_ALL=7;it.PARTICLES_BILLBOARDMODE_STRETCHED=8;it.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9;it.MESHES_CULLINGSTRATEGY_STANDARD=0;it.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;it.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;it.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;it.SCENELOADER_NO_LOGGING=0;it.SCENELOADER_MINIMAL_LOGGING=1;it.SCENELOADER_SUMMARY_LOGGING=2;it.SCENELOADER_DETAILED_LOGGING=3;it.PREPASS_IRRADIANCE_TEXTURE_TYPE=0;it.PREPASS_POSITION_TEXTURE_TYPE=1;it.PREPASS_VELOCITY_TEXTURE_TYPE=2;it.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3;it.PREPASS_COLOR_TEXTURE_TYPE=4;it.PREPASS_DEPTH_TEXTURE_TYPE=5;it.PREPASS_NORMAL_TEXTURE_TYPE=6;it.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7;it.BUFFER_CREATIONFLAG_READ=1;it.BUFFER_CREATIONFLAG_WRITE=2;it.BUFFER_CREATIONFLAG_READWRITE=3;it.BUFFER_CREATIONFLAG_UNIFORM=4;it.BUFFER_CREATIONFLAG_VERTEX=8;it.BUFFER_CREATIONFLAG_INDEX=16;it.BUFFER_CREATIONFLAG_STORAGE=32;it.RENDERPASS_MAIN=0;it.INPUT_ALT_KEY=18;it.INPUT_CTRL_KEY=17;it.INPUT_META_KEY1=91;it.INPUT_META_KEY2=92;it.INPUT_META_KEY3=93;it.INPUT_SHIFT_KEY=16;it.SNAPSHOTRENDERING_STANDARD=0;it.SNAPSHOTRENDERING_FAST=1;it.PERSPECTIVE_CAMERA=0;it.ORTHOGRAPHIC_CAMERA=1;it.FOVMODE_VERTICAL_FIXED=0;it.FOVMODE_HORIZONTAL_FIXED=1;it.RIG_MODE_NONE=0;it.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;it.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;it.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;it.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;it.RIG_MODE_STEREOSCOPIC_INTERLACED=14;it.RIG_MODE_VR=20;it.RIG_MODE_WEBVR=21;it.RIG_MODE_CUSTOM=22;it.MAX_SUPPORTED_UV_SETS=6;it.GL_ALPHA_EQUATION_ADD=32774;it.GL_ALPHA_EQUATION_MIN=32775;it.GL_ALPHA_EQUATION_MAX=32776;it.GL_ALPHA_EQUATION_SUBTRACT=32778;it.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779;it.GL_ALPHA_FUNCTION_SRC=768;it.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769;it.GL_ALPHA_FUNCTION_SRC_ALPHA=770;it.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771;it.GL_ALPHA_FUNCTION_DST_ALPHA=772;it.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773;it.GL_ALPHA_FUNCTION_DST_COLOR=774;it.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775;it.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776;it.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769;it.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770;it.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771;it.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772;it.SnippetUrl="https://snippet.babylonjs.com";class Rce{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class Pce extends He{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new Rce){super(null),He.Instances.push(this),e.deterministicLockstep===void 0&&(e.deterministicLockstep=!1),e.lockstepMaxSteps===void 0&&(e.lockstepMaxSteps=4),this._options=e,nu.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,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,_collectUbosUpdatedInFrame:!1},Me.Log(`Babylon.js v${He.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 qb;return t.references=1,t}createIndexBuffer(e){const t=new qb;return t.references=1,t}clear(e,t,i,s=!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,s,r){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=e!==null&&ml.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,s=!1,r,n,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,s){return!0}setBool(e,t){return!0}setFloat4(e,t,i,s,r){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,s){}drawElementsType(e,t,i,s){}drawArraysType(e,t,i,s){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,s,r=3,n=null,o=null,l=null,c=null,h=null,u=null,p){const m=new dn(this,hr.Url),_=String(e);return m.url=_,m.generateMipMaps=!t,m.samplingMode=r,m.invertY=i,m.baseWidth=this._options.textureSize,m.baseHeight=this._options.textureSize,m.width=this._options.textureSize,m.height=this._options.textureSize,h&&(m.format=h),m.isReady=!0,n&&setTimeout(()=>{n(m)}),this._internalTexturesCache.push(m),m}_createHardwareRenderTargetWrapper(e,t,i){const s=new HG(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};t!==void 0&&typeof t=="object"?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=t.generateDepthBuffer===void 0?!0:t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.type=t.type===void 0?0:t.type,s.samplingMode=t.samplingMode===void 0?3:t.samplingMode):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.type=0,s.samplingMode=3);const r=new dn(this,hr.RenderTarget),n=e.width||e,o=e.height||e;return i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,r.baseWidth=n,r.baseHeight=o,r.width=n,r.height=o,r.isReady=!0,r.samples=1,r.generateMipMaps=!!s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,this._internalTexturesCache.push(r),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},t);s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(s.type===1&&!this._caps.textureFloatLinearFiltering||s.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(s.samplingMode=1),i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer;const r=new dn(this,hr.RenderTarget);return r.baseWidth=e,r.baseHeight=e,r.width=e,r.height=e,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=!!s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,this._internalTexturesCache.push(r),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,s,r,n,o,l=null,c=0,h=0,u=!1){const p=new dn(this,hr.Raw);return p.baseWidth=t,p.baseHeight=i,p.width=t,p.height=i,p.format=s,p.generateMipMaps=r,p.samplingMode=o,p.invertY=n,p._compression=l,p.type=c,p._useSRGBBuffer=u,this._doNotHandleContextLost||(p._bufferView=e),p}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r,e.type=n,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,s,r){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!r&&this.setViewport(this._cachedViewport,i,s)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new qb;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,s=!1,r){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,s){}_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,s,r,n=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,s=0){}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){}_uploadImageToTexture(e,t,i=0,s=0){}}Oi.prototype._debugPushGroup=function(a,e){};Oi.prototype._debugPopGroup=function(a){};Oi.prototype._debugInsertMarker=function(a,e){};Oi.prototype._debugFlushPendingCommands=function(){};class Dce{constructor(){this._timeElapsedQueryEnded=!1}}class Oce{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Ir.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Ir.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}He.prototype.createQuery=function(){const a=this._gl.createQuery();if(!a)throw new Error("Unable to create Occlusion Query");return a};He.prototype.deleteQuery=function(a){return this._gl.deleteQuery(a),this};He.prototype.isQueryResultAvailable=function(a){return this._gl.getQueryParameter(a,this._gl.QUERY_RESULT_AVAILABLE)};He.prototype.getQueryResult=function(a){return this._gl.getQueryParameter(a,this._gl.QUERY_RESULT)};He.prototype.beginOcclusionQuery=function(a,e){const t=this._getGlAlgorithmType(a);return this._gl.beginQuery(t,e),!0};He.prototype.endOcclusionQuery=function(a){const e=this._getGlAlgorithmType(a);return this._gl.endQuery(e),this};He.prototype._createTimeQuery=function(){const a=this.getCaps().timerQuery;return a.createQueryEXT?a.createQueryEXT():this.createQuery()};He.prototype._deleteTimeQuery=function(a){const e=this.getCaps().timerQuery;if(e.deleteQueryEXT){e.deleteQueryEXT(a);return}this.deleteQuery(a)};He.prototype._getTimeQueryResult=function(a){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(a,e.QUERY_RESULT_EXT):this.getQueryResult(a)};He.prototype._getTimeQueryAvailability=function(a){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(a,e.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(a)};He.prototype.startTimeQuery=function(){const a=this.getCaps(),e=a.timerQuery;if(!e)return null;const t=new Dce;if(this._gl.getParameter(e.GPU_DISJOINT_EXT),a.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};He.prototype.endTimeQuery=function(a){const e=this.getCaps(),t=e.timerQuery;if(!t||!a)return-1;if(e.canUseTimestampForTimerQuery){if(!a._startTimeQuery)return-1;a._endTimeQuery||(a._endTimeQuery=this._createTimeQuery(),t.queryCounterEXT(a._endTimeQuery,t.TIMESTAMP_EXT))}else if(!a._timeElapsedQueryEnded){if(!a._timeElapsedQuery)return-1;t.endQueryEXT?t.endQueryEXT(t.TIME_ELAPSED_EXT):(this._gl.endQuery(t.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),a._timeElapsedQueryEnded=!0}const i=this._gl.getParameter(t.GPU_DISJOINT_EXT);let s=!1;if(a._endTimeQuery?s=this._getTimeQueryAvailability(a._endTimeQuery):a._timeElapsedQuery&&(s=this._getTimeQueryAvailability(a._timeElapsedQuery)),s&&!i){let r=0;if(e.canUseTimestampForTimerQuery){if(!a._startTimeQuery||!a._endTimeQuery)return-1;const n=this._getTimeQueryResult(a._startTimeQuery);r=this._getTimeQueryResult(a._endTimeQuery)-n,this._deleteTimeQuery(a._startTimeQuery),this._deleteTimeQuery(a._endTimeQuery),a._startTimeQuery=null,a._endTimeQuery=null}else{if(!a._timeElapsedQuery)return-1;r=this._getTimeQueryResult(a._timeElapsedQuery),this._deleteTimeQuery(a._timeElapsedQuery),a._timeElapsedQuery=null,a._timeElapsedQueryEnded=!1}return r}return-1};He.prototype._captureGPUFrameTime=!1;He.prototype._gpuFrameTime=new Tc;He.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime};He.prototype.captureGPUFrameTime=function(a){a!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=a,a?(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))};He.prototype._getGlAlgorithmType=function(a){return a===Ir.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};Object.defineProperty(Ir.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(a){this._occlusionDataStorage.isOcclusionQueryInProgress=a},enumerable:!1,configurable:!0});Object.defineProperty(Ir.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new Oce),this.__occlusionDataStorage},enumerable:!1,configurable:!0});Object.defineProperty(Ir.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(a){this._occlusionDataStorage.isOccluded=a},enumerable:!0,configurable:!0});Object.defineProperty(Ir.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(a){this._occlusionDataStorage.occlusionQueryAlgorithmType=a},enumerable:!0,configurable:!0});Object.defineProperty(Ir.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(a){this._occlusionDataStorage.occlusionType=a},enumerable:!0,configurable:!0});Object.defineProperty(Ir.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(a){this._occlusionDataStorage.occlusionRetryCount=a},enumerable:!0,configurable:!0});Object.defineProperty(Ir.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(a){this._occlusionDataStorage.forceRenderingWhenOccluded=a},enumerable:!0,configurable:!0});Ir.prototype._checkOcclusionQuery=function(){const a=this._occlusionDataStorage;if(a.occlusionType===Ir.OCCLUSION_TYPE_NONE)return a.isOccluded=!1,!1;const e=this.getEngine();if(!e.getCaps().supportOcclusionQuery||!e.isQueryResultAvailable)return a.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery!==null&&this._occlusionQuery!==void 0)if(e.isQueryResultAvailable(this._occlusionQuery)){const s=e.getQueryResult(this._occlusionQuery);a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=!(s>0)}else if(a.occlusionInternalRetryCounter++,a.occlusionRetryCount!==-1&&a.occlusionInternalRetryCounter>a.occlusionRetryCount)a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=a.occlusionType===Ir.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;else return a.occlusionType===Ir.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;const t=this.getScene();if(t.getBoundingBoxRenderer){const i=t.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=e.createQuery()),e.beginOcclusionQuery(a.occlusionQueryAlgorithmType,this._occlusionQuery)&&(i.renderOcclusionBoundingBox(this),e.endOcclusionQuery(a.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return a.isOccluded};var xge=!0;He.prototype.createTransformFeedback=function(){const a=this._gl.createTransformFeedback();if(!a)throw new Error("Unable to create Transform Feedback");return a};He.prototype.deleteTransformFeedback=function(a){this._gl.deleteTransformFeedback(a)};He.prototype.bindTransformFeedback=function(a){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,a)};He.prototype.beginTransformFeedback=function(a=!0){this._gl.beginTransformFeedback(a?this._gl.POINTS:this._gl.TRIANGLES)};He.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()};He.prototype.setTranformFeedbackVaryings=function(a,e){this._gl.transformFeedbackVaryings(a,e,this._gl.INTERLEAVED_ATTRIBS)};He.prototype.bindTransformFeedbackBuffer=function(a){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,a?a.underlyingResource:null)};Oi.prototype.createExternalTexture=function(a){return null};Oi.prototype.setExternalTexture=function(a,e){throw new Error("setExternalTexture: This engine does not support external textures!")};Oi.prototype.updateVideoTexture=function(a,e,t){if(!a||a._isDisabled)return;const i=this._getInternalFormat(a.format),s=this._getRGBABufferInternalSizedFormat(0,a.format),r=this._bindTextureDirectly(this._gl.TEXTURE_2D,a,!0);this._unpackFlipY(!t);try{if(this._videoTextureSupported===void 0&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,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,s,i,this._gl.UNSIGNED_BYTE,e);else{if(!a._workingCanvas){a._workingCanvas=this.createCanvas(a.width,a.height);const n=a._workingCanvas.getContext("2d");if(!n)throw new Error("Unable to get 2d context");a._workingContext=n,a._workingCanvas.width=a.width,a._workingCanvas.height=a.height}a._workingContext.clearRect(0,0,a.width,a.height),a._workingContext.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,a.width,a.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,i,this._gl.UNSIGNED_BYTE,a._workingCanvas)}a.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),a.isReady=!0}catch{a._isDisabled=!0}};Oi.prototype.restoreSingleAttachment=function(){const a=this._gl;this.bindAttachments([a.BACK])};Oi.prototype.restoreSingleAttachmentForRenderTarget=function(){const a=this._gl;this.bindAttachments([a.COLOR_ATTACHMENT0])};Oi.prototype.buildTextureLayout=function(a){const e=this._gl,t=[];for(let i=0;i1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"],i.readBuffer(s[n]),i.drawBuffers(s),i.blitFramebuffer(0,0,o.width,o.height,0,0,o.width,o.height,i.COLOR_BUFFER_BIT,i.NEAREST)}for(let n=0;n1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"];i.drawBuffers(s)}for(let n=0;n1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(l=e.depthTextureFormat));const I=this._gl,D=I.createFramebuffer();this._bindUnboundFramebuffer(D);const R=a.width||a,L=a.height||a,w=[],N=[],V=this.webGLVersion>1&&o&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===18),W=this._setupFramebufferDepthAttachments(!V&&n,!o&&r,R,L);S._framebuffer=D,S._depthStencilBuffer=W,S._generateDepthBuffer=!o&&r,S._generateStencilBuffer=!V&&n,S._attachments=N;for(let G=0;G1||this.isWebGPU);const J=this.webGLVersion>1,te=I[J?"COLOR_ATTACHMENT"+G:"COLOR_ATTACHMENT"+G+"_WEBGL"];if(N.push(te),j===-1)continue;const re=new dn(this,hr.MultiRenderTarget);w[G]=re,I.activeTexture(I["TEXTURE"+G]),I.bindTexture(j,re._hardwareTexture.underlyingResource),I.texParameteri(j,I.TEXTURE_MAG_FILTER,Y.mag),I.texParameteri(j,I.TEXTURE_MIN_FILTER,Y.min),I.texParameteri(j,I.TEXTURE_WRAP_S,I.CLAMP_TO_EDGE),I.texParameteri(j,I.TEXTURE_WRAP_T,I.CLAMP_TO_EDGE);const ee=this._getRGBABufferInternalSizedFormat(Z,K,q),oe=this._getInternalFormat(K),ae=this._getWebGLTextureType(Z);if(J&&(j===35866||j===32879))j===35866?re.is2DArray=!0:re.is3D=!0,re.baseDepth=re.depth=H,I.texImage3D(j,0,ee,R,L,H,0,oe,ae,null);else if(j===34067){for(let fe=0;fe<6;fe++)I.texImage2D(I.TEXTURE_CUBE_MAP_POSITIVE_X+fe,0,ee,R,L,0,oe,ae,null);re.isCube=!0}else I.texImage2D(I.TEXTURE_2D,0,ee,R,L,0,oe,ae,null);s&&I.generateMipmap(j),this._bindTextureDirectly(j,null),re.baseWidth=R,re.baseHeight=L,re.width=R,re.height=L,re.isReady=!0,re.samples=1,re.generateMipMaps=s,re.samplingMode=ie,re.type=Z,re._useSRGBBuffer=q,re.format=K,this._internalTexturesCache.push(re)}if(o&&this._caps.depthTextureExtension){const G=new dn(this,hr.Depth);let ie=5,Z=I.DEPTH_COMPONENT16,q=I.DEPTH_COMPONENT,K=I.UNSIGNED_SHORT,j=I.DEPTH_ATTACHMENT;this.webGLVersion<2?Z=I.DEPTH_COMPONENT:l===14?(ie=1,K=I.FLOAT,Z=I.DEPTH_COMPONENT32F):l===18?(ie=0,K=I.FLOAT_32_UNSIGNED_INT_24_8_REV,Z=I.DEPTH32F_STENCIL8,q=I.DEPTH_STENCIL,j=I.DEPTH_STENCIL_ATTACHMENT):l===16?(ie=0,K=I.UNSIGNED_INT,Z=I.DEPTH_COMPONENT24,j=I.DEPTH_ATTACHMENT):(l===13||l===17)&&(ie=12,K=I.UNSIGNED_INT_24_8,Z=I.DEPTH24_STENCIL8,q=I.DEPTH_STENCIL,j=I.DEPTH_STENCIL_ATTACHMENT),I.activeTexture(I.TEXTURE0),I.bindTexture(I.TEXTURE_2D,G._hardwareTexture.underlyingResource),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MAG_FILTER,I.NEAREST),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MIN_FILTER,I.NEAREST),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_S,I.CLAMP_TO_EDGE),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_T,I.CLAMP_TO_EDGE),I.texImage2D(I.TEXTURE_2D,0,Z,R,L,0,q,K,null),I.framebufferTexture2D(I.FRAMEBUFFER,j,I.TEXTURE_2D,G._hardwareTexture.underlyingResource,0),G.baseWidth=R,G.baseHeight=L,G.width=R,G.height=L,G.isReady=!0,G.samples=1,G.generateMipMaps=s,G.samplingMode=1,G.format=l,G.type=ie,w[c]=G,this._internalTexturesCache.push(G)}return S.setTextures(w),t&&I.drawBuffers(N),this._bindUnboundFramebuffer(null),S.setLayerAndFaceIndices(b,M),this.resetTextureCache(),S};Oi.prototype.updateMultipleRenderTargetTextureSampleCount=function(a,e,t=!0){if(this.webGLVersion<2||!a||!a.texture)return 1;if(a.samples===e)return e;const i=a._attachments.length;if(i===0)return 1;const s=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples);const r=!!a._depthStencilBuffer;if(r&&(s.deleteRenderbuffer(a._depthStencilBuffer),a._depthStencilBuffer=null),a._MSAAFramebuffer&&(s.deleteFramebuffer(a._MSAAFramebuffer),a._MSAAFramebuffer=null),e>1&&typeof s.renderbufferStorageMultisample=="function"){const n=s.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");a._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let l=0;l1?"COLOR_ATTACHMENT"+l:"COLOR_ATTACHMENT"+l+"_WEBGL"],p=this._createRenderBuffer(c.width,c.height,e,-1,this._getRGBAMultiSampleBufferFormat(c.type,c.format),u);if(!p)throw new Error("Unable to create multi sampled framebuffer");h.addMSAARenderBuffer(p),c.samples=e,o.push(u)}t&&s.drawBuffers(o)}else this._bindUnboundFramebuffer(a._framebuffer);return r&&(a._depthStencilBuffer=this._setupFramebufferDepthAttachments(a._generateStencilBuffer,a._generateDepthBuffer,a.texture.width,a.texture.height,e)),this._bindUnboundFramebuffer(null),e};Oi.prototype._createDepthStencilCubeTexture=function(a,e,t){const i=new dn(this,hr.DepthStencil);if(i.isCube=!0,this.webGLVersion===1)return Me.Error("Depth cube texture is not supported by WebGL 1."),i;const s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},e),r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,a,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),t._depthStencilTexture=i,t._depthStencilTextureWithStencil=s.generateStencil;for(let n=0;n<6;n++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,r.DEPTH24_STENCIL8,a,a,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,r.DEPTH_COMPONENT24,a,a,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i};Oi.prototype._partialLoadFile=function(a,e,t,i,s=null){const r=o=>{t[e]=o,t._internalCount++,t._internalCount===6&&i(t)},n=(o,l)=>{s&&o&&s(o.status+" "+o.statusText,l)};this._loadFile(a,r,void 0,void 0,!0,n)};Oi.prototype._cascadeLoadFiles=function(a,e,t,i=null){const s=[];s._internalCount=0;for(let r=0;r<6;r++)this._partialLoadFile(t[r],r,s,e,i)};Oi.prototype._cascadeLoadImgs=function(a,e,t,i,s=null,r){const n=[];n._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(i[o],o,n,a,e,t,s,r)};Oi.prototype._partialLoadImg=function(a,e,t,i,s,r,n=null,o){const l=WL();vF(a,u=>{t[e]=u,t._internalCount++,i&&i.removePendingData(l),t._internalCount===6&&r&&r(s,t)},(u,p)=>{i&&i.removePendingData(l),n&&n(u,p)},i?i.offlineProvider:null,o),i&&i.addPendingData(l)};Oi.prototype._setCubeMapTextureParams=function(a,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),a.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),a._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};Oi.prototype.createCubeTextureBase=function(a,e,t,i,s=null,r=null,n,o=null,l=!1,c=0,h=0,u=null,p=null,m=null,_=!1){const f=u||new dn(this,hr.Cube);f.isCube=!0,f.url=a,f.generateMipMaps=!i,f._lodGenerationScale=c,f._lodGenerationOffset=h,f._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!i),f!==u&&(f.label=a.substring(0,60)),this._doNotHandleContextLost||(f._extension=o,f._files=t);const d=a;this._transformTextureUrl&&!u&&(a=this._transformTextureUrl(a));const C=a.split("?")[0],v=C.lastIndexOf("."),y=o||(v>-1?C.substring(v).toLowerCase():"");let M=null;for(const E of Oi._TextureLoaders)if(E.canLoad(y)){M=E;break}const b=(E,S)=>{a===d?r&&E&&r(E.status+" "+E.statusText,S):(Me.Warn(`Failed to load ${a}, falling back to the ${d}`),this.createCubeTextureBase(d,e,t,!!i,s,r,n,o,l,c,h,f,p,m,_))};if(M){const E=S=>{p&&p(f,S),M.loadCubeData(S,f,l,s,r)};t&&t.length===6?M.supportCascades?this._cascadeLoadFiles(e,S=>E(S.map(I=>new Uint8Array(I))),t,r):r?r("Textures type does not support cascades."):Me.Warn("Texture loader does not support cascades."):this._loadFile(a,S=>E(new Uint8Array(S)),void 0,void 0,!0,b)}else{if(!t)throw new Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(e,f,(E,S)=>{m&&m(E,S)},t,r)}return this._internalTexturesCache.push(f),f};Oi.prototype.createCubeTexture=function(a,e,t,i,s=null,r=null,n,o=null,l=!1,c=0,h=0,u=null,p,m=!1){const _=this._gl;return this.createCubeTextureBase(a,e,t,!!i,s,r,n,o,l,c,h,u,f=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,f,!0),(f,d)=>{const C=this.needPOTTextures?Oi.GetExponentOfTwo(d[0].width,this._caps.maxCubemapTextureSize):d[0].width,v=C,y=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const M=n?this._getInternalFormat(n,f._useSRGBBuffer):f._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA;let b=n?this._getInternalFormat(n):_.RGBA;f._useSRGBBuffer&&this.webGLVersion===1&&(b=M);for(let E=0;E{this.unRegisterView(a)}),s};He.prototype.unRegisterView=function(a){if(!this.views||this.views.length===0)return this;for(const e of this.views)if(e.target===a){const t=this.views.indexOf(e);t!==-1&&this.views.splice(t,1);break}return this};He.prototype._renderViewStep=function(a){const e=a.target,t=e.getContext("2d");if(!t)return!0;const i=this.getRenderingCanvas();wce.notifyObservers(a);const s=a.camera;let r=null,n=null;if(s){if(n=s.getScene(),!n||n.activeCameras&&n.activeCameras.length)return!0;this.activeView=a,r=n.activeCamera,n.activeCamera=s}if(a.customResize)a.customResize(e);else{const o=Math.floor(e.clientWidth/this._hardwareScalingLevel),l=Math.floor(e.clientHeight/this._hardwareScalingLevel),c=o!==e.width||i.width!==e.width||l!==e.height||i.height!==e.height;e.clientWidth&&e.clientHeight&&c&&(e.width=o,e.height=l,this.setSize(o,l))}return!i.width||!i.height?!1:(this._renderFrame(),this.flushFramebuffer(),a.clearBeforeCopy&&t.clearRect(0,0,i.width,i.height),t.drawImage(i,0,0),r&&n&&(n.activeCamera=r),Nce.notifyObservers(a),!0)};He.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)};Oi.prototype.createStorageBuffer=function(a,e){throw new Error("createStorageBuffer: Unsupported method in this engine!")};Oi.prototype.updateStorageBuffer=function(a,e,t,i){};Oi.prototype.readFromStorageBuffer=function(a,e,t,i){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")};Oi.prototype.setStorageBuffer=function(a,e){throw new Error("setStorageBuffer: Unsupported method in this engine!")};function Ege(a){const e=r=>{const n="\\b"+r+"\\b";return a&&(a===r||a.match(new RegExp(n,"g")))};if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(e))return a;const t=a.lastIndexOf("."),i=a.lastIndexOf("?"),s=i>-1?a.substring(i,a.length):"";return(t>-1?a.substring(0,t):a)+this._textureFormatInUse+s}Object.defineProperty(He.prototype,"texturesSupported",{get:function(){const a=new Array;return this._caps.astc&&a.push("-astc.ktx"),this._caps.s3tc&&a.push("-dxt.ktx"),this._caps.pvrtc&&a.push("-pvrtc.ktx"),this._caps.etc2&&a.push("-etc2.ktx"),this._caps.etc1&&a.push("-etc1.ktx"),a},enumerable:!0,configurable:!0});Object.defineProperty(He.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0});He.prototype.setCompressedTextureExclusions=function(a){this._excludedCompressedTextures=a};He.prototype.setTextureFormatToUse=function(a){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}}VL.DEFAULT_BUFFER_SIZE=65536;const vM=[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))],yge=[()=>1,a=>a.y,a=>a.z,a=>a.x,a=>a.x*a.y,a=>a.y*a.z,a=>3*a.z*a.z-1,a=>a.x*a.z,a=>a.x*a.x-a.y*a.y],T9=(a,e)=>vM[a]*yge[a](e),S9=[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 zL{constructor(){this.preScaled=!1,this.l00=O.Zero(),this.l1_1=O.Zero(),this.l10=O.Zero(),this.l11=O.Zero(),this.l2_2=O.Zero(),this.l2_1=O.Zero(),this.l20=O.Zero(),this.l21=O.Zero(),this.l22=O.Zero()}addLight(e,t,i){ue.Vector3[0].set(t.r,t.g,t.b);const s=ue.Vector3[0],r=ue.Vector3[1];s.scaleToRef(i,r),r.scaleToRef(T9(0,e),ue.Vector3[2]),this.l00.addInPlace(ue.Vector3[2]),r.scaleToRef(T9(1,e),ue.Vector3[2]),this.l1_1.addInPlace(ue.Vector3[2]),r.scaleToRef(T9(2,e),ue.Vector3[2]),this.l10.addInPlace(ue.Vector3[2]),r.scaleToRef(T9(3,e),ue.Vector3[2]),this.l11.addInPlace(ue.Vector3[2]),r.scaleToRef(T9(4,e),ue.Vector3[2]),this.l2_2.addInPlace(ue.Vector3[2]),r.scaleToRef(T9(5,e),ue.Vector3[2]),this.l2_1.addInPlace(ue.Vector3[2]),r.scaleToRef(T9(6,e),ue.Vector3[2]),this.l20.addInPlace(ue.Vector3[2]),r.scaleToRef(T9(7,e),ue.Vector3[2]),this.l21.addInPlace(ue.Vector3[2]),r.scaleToRef(T9(8,e),ue.Vector3[2]),this.l22.addInPlace(ue.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(S9[0]),this.l1_1.scaleInPlace(S9[1]),this.l10.scaleInPlace(S9[2]),this.l11.scaleInPlace(S9[3]),this.l2_2.scaleInPlace(S9[4]),this.l2_1.scaleInPlace(S9[5]),this.l20.scaleInPlace(S9[6]),this.l21.scaleInPlace(S9[7]),this.l22.scaleInPlace(S9[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(vM[0]),this.l1_1.scaleInPlace(vM[1]),this.l10.scaleInPlace(vM[2]),this.l11.scaleInPlace(vM[3]),this.l2_2.scaleInPlace(vM[4]),this.l2_1.scaleInPlace(vM[5]),this.l20.scaleInPlace(vM[6]),this.l21.scaleInPlace(vM[7]),this.l22.scaleInPlace(vM[8])}updateFromArray(e){return O.FromArrayToRef(e[0],0,this.l00),O.FromArrayToRef(e[1],0,this.l1_1),O.FromArrayToRef(e[2],0,this.l10),O.FromArrayToRef(e[3],0,this.l11),O.FromArrayToRef(e[4],0,this.l2_2),O.FromArrayToRef(e[5],0,this.l2_1),O.FromArrayToRef(e[6],0,this.l20),O.FromArrayToRef(e[7],0,this.l21),O.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return O.FromFloatsToRef(e[0],e[1],e[2],this.l00),O.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),O.FromFloatsToRef(e[6],e[7],e[8],this.l10),O.FromFloatsToRef(e[9],e[10],e[11],this.l11),O.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),O.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),O.FromFloatsToRef(e[18],e[19],e[20],this.l20),O.FromFloatsToRef(e[21],e[22],e[23],this.l21),O.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new zL().updateFromArray(e)}static FromPolynomial(e){const t=new zL;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 JM{constructor(){this.x=O.Zero(),this.y=O.Zero(),this.z=O.Zero(),this.xx=O.Zero(),this.yy=O.Zero(),this.zz=O.Zero(),this.xy=O.Zero(),this.yz=O.Zero(),this.zx=O.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=zL.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){ue.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=ue.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),ue.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),ue.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(ue.Vector3[0]).addInPlace(ue.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(ue.Vector3[0]).subtractInPlace(ue.Vector3[1]),this.zz.copyFrom(e.l00),ue.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(ue.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 JM().updateFromHarmonics(e)}static FromArray(e){const t=new JM;return O.FromArrayToRef(e[0],0,t.x),O.FromArrayToRef(e[1],0,t.y),O.FromArrayToRef(e[2],0,t.z),O.FromArrayToRef(e[3],0,t.xx),O.FromArrayToRef(e[4],0,t.yy),O.FromArrayToRef(e[5],0,t.zz),O.FromArrayToRef(e[6],0,t.yz),O.FromArrayToRef(e[7],0,t.zx),O.FromArrayToRef(e[8],0,t.xy),t}}const Mge="rgbdDecodePixelShader",Tge=`varying vec2 vUV;uniform sampler2D textureSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;Ue.ShadersStore[Mge]=Tge;function Bce(a,e,t,i=!0){const s=a.getScene(),r=s.getEngine(),n=new Oa("resized"+a.name,{width:e,height:t},s,!a.noMipmap,!0,a._texture.type,!1,a.samplingMode,!1);n.wrapU=a.wrapU,n.wrapV=a.wrapV,n.uOffset=a.uOffset,n.vOffset=a.vOffset,n.uScale=a.uScale,n.vScale=a.vScale,n.uAng=a.uAng,n.vAng=a.vAng,n.wAng=a.wAng,n.coordinatesIndex=a.coordinatesIndex,n.level=a.level,n.anisotropicFilteringLevel=a.anisotropicFilteringLevel,n._texture.isReady=!1,a.wrapU=Te.CLAMP_ADDRESSMODE,a.wrapV=Te.CLAMP_ADDRESSMODE;const o=new l7("pass",1,null,i?Te.BILINEAR_SAMPLINGMODE:Te.NEAREST_SAMPLINGMODE,r,!1,0);return o.externalTextureSamplerBinding=!0,o.getEffect().executeWhenCompiled(()=>{o.onApply=function(c){c.setTexture("textureSampler",a)};const l=n.renderTarget;l&&(s.postProcessManager.directRender([o],l),r.unBindFramebuffer(l),n.disposeFramebufferObjects(),o.dispose(),n.getInternalTexture().isReady=!0)}),n}function QK(a,e,t,i,s,r,n,o){const l=e.getEngine();return e.isReady=!1,s=s??e.samplingMode,i=i??e.type,r=r??e.format,n=n??e.width,o=o??e.height,i===-1&&(i=0),new Promise(c=>{const h=new rs("postprocess",a,null,null,1,null,s,l,!1,void 0,i,void 0,null,!1,r);h.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:n,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:i,format:r});h.getEffect().executeWhenCompiled(()=>{h.onApply=p=>{p._bindTexture("textureSampler",e),p.setFloat2("scale",1,1)},t.postProcessManager.directRender([h],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(e),h&&h.dispose(),u._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,c(e)})})}let hY,Bse;function Vb(a){hY||(hY=new Float32Array(1),Bse=new Int32Array(hY.buffer)),hY[0]=a;const e=Bse[0];let t=e>>16&32768,i=e>>12&2047;const s=e>>23&255;return s<103?t:s>142?(t|=31744,t|=(s==255?0:1)&&e&8388607,t):s<113?(i|=2048,t|=(i>>114-s)+(i>>113-s&1),t):(t|=s-112<<10|i>>1,t+=i&1,t)}function Pb(a){const e=(a&32768)>>15,t=(a&31744)>>10,i=a&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 BY={CreateResizedCopy:Bce,ApplyPostProcess:QK,ToHalfFloat:Vb,FromHalfFloat:Pb};class _X{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let n=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(n=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{if(n){const l=new rs("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);l.externalTextureSamplerBinding=!0;const c=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});l.getEffect().executeWhenCompiled(()=>{l.onApply=h=>{h._bindTexture("textureSampler",t),h.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([l],c,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),l&&l.dispose(),c._swapAndDie(t),t.isReady=!0})}};r?o():e.onLoadObservable.addOnce(o)}static EncodeTextureToRGBD(e,t,i=0){return QK("rgbdEncode",e,t,i,1,5)}}class fN{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class oD{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;if(!e.isCube)return null;(t=e.getScene())===null||t===void 0||t.getEngine().flushFramebuffer();const i=e.getSize().width,s=e.readPixels(0,void 0,void 0,!1),r=e.readPixels(1,void 0,void 0,!1);let n,o;e.isRenderTarget?(n=e.readPixels(3,void 0,void 0,!1),o=e.readPixels(2,void 0,void 0,!1)):(n=e.readPixels(2,void 0,void 0,!1),o=e.readPixels(3,void 0,void 0,!1));const l=e.readPixels(4,void 0,void 0,!1),c=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,u=5;let p=0;return(e.textureType==1||e.textureType==2)&&(p=1),new Promise(m=>{Promise.all([r,s,n,o,l,c]).then(([_,f,d,C,v,y])=>{const M={size:i,right:f,left:_,up:d,down:C,front:v,back:y,format:u,type:p,gammaSpace:h};m(this.ConvertCubeMapToSphericalPolynomial(M))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new zL;let i=0;const s=2/e.size,r=s,n=.5*s,o=n-1;for(let p=0;p<6;p++){const m=this._FileFaces[p],_=e[m.name];let f=o;const d=e.format===5?4:3;for(let C=0;CD){const w=D/L;E*=w,S*=w,I*=w}}else E=Bt.Clamp(E,0,D),S=Bt.Clamp(S,0,D),I=Bt.Clamp(I,0,D);const R=new Ie(E,S,I);t.addLight(M,R,b),i+=b,v+=s}f+=r}}const u=4*Math.PI*6/6/i;return t.scaleInPlace(u),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),JM.FromHarmonics(t)}}oD._FileFaces=[new fN("right",new O(1,0,0),new O(0,0,-1),new O(0,-1,0)),new fN("left",new O(-1,0,0),new O(0,0,1),new O(0,-1,0)),new fN("up",new O(0,1,0),new O(1,0,0),new O(0,0,1)),new fN("down",new O(0,-1,0),new O(1,0,0),new O(0,0,-1)),new fN("front",new O(0,0,1),new O(1,0,0),new O(0,-1,0)),new fN("back",new O(0,0,-1),new O(-1,0,0),new O(0,-1,0))];oD.MAX_HDRI_VALUE=4096;oD.PRESERVE_CLAMPED_COLORS=!1;Sn.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(Sn.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=oD.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(a=>{this._texture._sphericalPolynomial=a,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(a){this._texture&&(this._texture._sphericalPolynomial=a)},enumerable:!0,configurable:!0});const Sge="rgbdEncodePixelShader",Ige=`varying vec2 vUV;uniform sampler2D textureSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;Ue.ShadersStore[Sge]=Ige;const Oee="image/png",Bq=2,Aj=[134,22,135,150,246,214,150,54];function ZK(a){const e=new DataView(a.buffer,a.byteOffset,a.byteLength);let t=0;for(let n=0;nBq)throw new Error(`Unsupported babylon environment map version "${a.version}". Latest supported version is "${Bq}".`);return a.version===2||(a=Object.assign(Object.assign({},a),{version:2,imageType:Oee})),a}async function Fce(a,e={}){var t,i;const s=a.getInternalTexture();if(!s)return Promise.reject("The cube texture is invalid.");const r=(t=e.imageType)!==null&&t!==void 0?t:Oee,n=s.getEngine();if(a.textureType!==2&&a.textureType!==1&&a.textureType!==0&&a.textureType!==0&&a.textureType!==7&&a.textureType!==-1)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let o=1;if(!n.getCaps().textureFloatRender&&(o=2,!n.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");a.sphericalPolynomial;const l=(i=a.getInternalTexture())===null||i===void 0?void 0:i._sphericalPolynomialPromise,c=s.width,h=new oi(n),u={};n.flushFramebuffer();const p=Bt.ILog2(s.width);for(let S=0;S<=p;S++){const I=Math.pow(2,p-S);for(let D=0;D<6;D++){let R=await a.readPixels(D,S,void 0,!1);if(R&&R.byteLength===R.length){const V=new Float32Array(R.byteLength*4);for(let W=0;W{if(t){const m=e.createTexture(null,!0,!0,null,1,null,_=>{p(_)},a);i.getEffect().executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=_=>{_._bindTexture("textureSampler",m),_.setFloat2("scale",1,e._features.needsInvertingBitmap&&a instanceof ImageBitmap?-1:1)},e.scenes.length&&(e.scenes[0].postProcessManager.directRender([i],c,!0,r,n),e.restoreDefaultFramebuffer(),m.dispose(),URL.revokeObjectURL(s),u())})}else{if(e._uploadImageToTexture(h,a,r,n),o){const m=l[n];m&&e._uploadImageToTexture(m._texture,a,r,0)}u()}})}function Uj(a,e,t=Oee){if(!Be.IsExponentOfTwo(a.width))throw new Error("Texture size must be a power of two");const i=Bt.ILog2(a.width)+1,s=a.getEngine();let r=!1,n=!1,o=null,l=null,c=null;const h=s.getCaps();if(a.format=5,a.type=0,a.generateMipMaps=!0,a._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,a),h.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?h.textureHalfFloatRender&&h.textureHalfFloatLinearFiltering?(r=!0,a.type=2):h.textureFloatRender&&h.textureFloatLinearFiltering&&(r=!0,a.type=1):r=!1:(r=!1,n=!0,c={}),r)o=new rs("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,a.type,void 0,null,!1),a._isRGBD=!1,a.invertY=!1,l=s.createRenderTargetCubeTexture(a.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:a.type,format:5});else if(a._isRGBD=!0,a.invertY=!0,n){const m=a._lodGenerationScale,_=a._lodGenerationOffset;for(let f=0;f<3;f++){const C=1-f/2,v=_,y=(i-1)*m+_,M=v+(y-v)*C,b=Math.round(Math.min(Math.max(M,0),y)),E=new dn(s,hr.Temp);E.isCube=!0,E.invertY=!0,E.generateMipMaps=!1,s.updateTextureSamplingMode(2,E);const S=new Sn(null);switch(S._isCube=!0,S._texture=E,c[b]=S,f){case 0:a._lodTextureLow=S;break;case 1:a._lodTextureMid=S;break;case 2:a._lodTextureHigh=S;break}}}const u=[];for(let p=0;p"u"||s._features.forceBitmapOverHTMLImageElement)C=s.createImageBitmap(f,{premultiplyAlpha:"none"}).then(v=>Fse(v,s,r,o,d,m,p,n,c,l,a));else{const v=new Image;v.src=d,C=new Promise((y,M)=>{v.onload=()=>{Fse(v,s,r,o,d,m,p,n,c,l,a).then(()=>y()).catch(b=>{M(b)})},v.onerror=b=>{M(b)}})}u.push(C)}if(e.length{l&&(s._releaseTexture(a),l._swapAndDie(a)),o&&o.dispose(),n&&(a._lodTextureHigh&&a._lodTextureHigh._texture&&(a._lodTextureHigh._texture.isReady=!0),a._lodTextureMid&&a._lodTextureMid._texture&&(a._lodTextureMid._texture.isReady=!0),a._lodTextureLow&&a._lodTextureLow._texture&&(a._lodTextureLow._texture.isReady=!0))})}function JK(a,e){e=AW(e);const t=e.irradiance;if(!t)return;const i=new JM;O.FromArrayToRef(t.x,0,i.x),O.FromArrayToRef(t.y,0,i.y),O.FromArrayToRef(t.z,0,i.z),O.FromArrayToRef(t.xx,0,i.xx),O.FromArrayToRef(t.yy,0,i.yy),O.FromArrayToRef(t.zz,0,i.zz),O.FromArrayToRef(t.yz,0,i.yz),O.FromArrayToRef(t.zx,0,i.zx),O.FromArrayToRef(t.xy,0,i.xy),a._sphericalPolynomial=i}function Vce(a,e,t,i,s){const r=a.getEngine().createRawCubeTexture(null,a.width,a.format,a.type,a.generateMipMaps,a.invertY,a.samplingMode,a._compression),n=Uj(r,e).then(()=>a);return a.onRebuildCallback=o=>({proxy:n,isReady:!0,isAsync:!0}),a._source=hr.CubeRawRGBD,a._bufferViewArrayArray=e,a._lodGenerationScale=i,a._lodGenerationOffset=s,a._sphericalPolynomial=t,Uj(a,e).then(()=>(a.isReady=!0,a))}const Rge={GetEnvInfo:ZK,CreateEnvTextureAsync:Fce,CreateImageDataArrayBufferViews:qK,UploadEnvLevelsAsync:wee,UploadLevelsAsync:Uj,UploadEnvSpherical:JK};function uY(a,e,t,i){let s=i,r=0,n="";for(;s=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e==95}function Fq(a){let e=0,t="",i=!1;const s=[];for(;e=0&&a.charAt(e)!==t;)e--;return e}function Dge(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}class uI{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&&console.log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&console.log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&m.push(C.substring(v+1))}r!=="void"&&m.push("return"),this._functionDescr.push({name:n,type:r,parameters:m,body:u,callIndex:0}),e=h+1;const _=t>0?this._sourceCode.substring(0,t):"",f=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&console.log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:r,body:n}=t;let o=0;for(;o{const M=[];let b=0,E=0;for(;b0?this._sourceCode.substring(0,l):"";const v=h+1{const h=c[0];return yZ(e.charAt(h-1))||yZ(e.charAt(h+n))?t[s]:o})}return e}}uI._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class Oge{get isAsync(){return this.isParallelCompiled}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}_handlesSpectorRebuildCallback(e){throw new Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,s,r,n,o,l){const c=this._engine;if(c.supportsUniformBuffers)for(const p in t)e.bindUniformBlock(p,t[p]);this._engine.getUniforms(this,i).forEach((p,m)=>{s[i[m]]=p}),this._uniforms=s;let u;for(u=0;u{n[p]=m}),l.push(...c.getAttributes(this,o))}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,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,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setInt4(this._uniforms[e],t,i,s,r)||(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,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setUInt4(this._uniforms[e],t,i,s,r)||(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.toArray())||(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,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setFloat3(this._uniforms[e],t,i,s)||(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,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setFloat4(this._uniforms[e],t,i,s,r)||(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 wge extends HG{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,s){super(e,t,i,s),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=s}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class zse{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 MZ(a,e){switch(a){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 nC(`Unsupported texture format or type: format ${a}, type ${e}.`,XM.UnsupportedTextureError)}function QH(a){switch(a){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: ${a}.`)}}function TZ(a){switch(a){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: "+a+".")}}function Nge(a){switch(a){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: ${a}.`)}}function Bge(a){switch(a){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: ${a}.`)}}function Fge(a){switch(a){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: ${a}.`)}}function Vge(a){switch(a){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: ${a}.`)}}function zge(a){switch(a){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: ${a}.`)}}function Uge(a){switch(a){case se.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case se.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case se.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case se.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case se.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${a}.`)}}const zce=new Se;if(typeof self<"u"&&!Object.prototype.hasOwnProperty.call(self,"_native")){let a;Object.defineProperty(self,"_native",{get:()=>a,set:e=>{a=e,a&&zce.notifyObservers(a)}})}function Uce(){return new Promise(a=>{typeof _native>"u"?zce.addOnce(e=>a(e)):a(_native)})}async function kce(a,e){(await Uce())[a]=e}class Use extends qb{}class kge{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=QP._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 QP extends He{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 kge(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!==QP.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${QP.PROTOCOL_VERSION} (JS)`);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,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},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:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,_collectUbosUpdatedInFrame:!1},Be.Log("Babylon Native (v"+He.Version+") launched"),Be.LoadScript=function(s,r,n,o){Be.LoadFile(s,l=>{Function(l).apply(null),r&&r()},void 0,void 0,!1,(l,c)=>{n&&n("LoadScript Error",c)})},typeof URL>"u"&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(window.Blob=function(s){return s}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function s(){const r=isNaN(arguments[0])?1:Number(arguments[0]);return r?Array.prototype.reduce.call(this,function(n,o){return Array.isArray(o)?n.push.apply(n,s.call(o,r-1)):n.push(o),n},[]):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 B$,this.onNewSceneAddedObservable.add(s=>{const r=s.render;s.render=(...n)=>{this._commandBufferEncoder.beginCommandScope(),r.apply(s,n),this._commandBufferEncoder.endCommandScope()}})}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new VL}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_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,s=!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(s?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t){const i=this._normalizeIndexData(e),s=new Use;return s.references=1,s.is32Bits=i.BYTES_PER_ELEMENT===4,i.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(i.buffer,i.byteOffset,i.byteLength,s.is32Bits,t??!1)),s}createVertexBuffer(e,t){const i=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new Use;return s.references=1,i.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(i.buffer,i.byteOffset,i.byteLength,t??!1)),s}_recordVertexArrayObject(e,t,i,s,r){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=s.getAttributesNames();for(let o=0;o=0){const c=n[o];let h=null;if(r&&(h=r[c]),h||(h=t[c]),h){const u=h.getBuffer();u&&u.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,u.nativeVertexBuffer,l,h.byteOffset,h.byteStride,h.getSize(),Uge(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,s){const r=this._engine.createVertexArray();return this._recordVertexArrayObject(r,e,t,i,s),r}_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.nativeProgram,t)}drawElementsType(e,t,i,s){this._drawCalls.addCount(1,!1),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,s){this._drawCalls.addCount(1,!1),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){return new Oge(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,s,r,n,o,l){const c=e;s?c.nativeProgram=this.createRawShaderProgram():c.nativeProgram=this.createShaderProgram(e,t,i,l)}isAsync(e){return!!(e.isAsync&&this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!this.isAsync(e)){t();return}const s=i.onCompiled;s?i.onCompiled=()=>{s(),t()}:i.onCompiled=t}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;if(r.nativeProgram)throw new Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new uI(t);n.processCode(),t=n.code;const o=new uI(i);o.processCode(),i=o.code,t=Oi._ConcatenateShader(t,s),i=Oi._ConcatenateShader(i,s);const l=()=>{var c;r.isCompiled=!0,(c=r.onCompiled)===null||c===void 0||c.call(r),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,l,c=>{r.compilationError=c});try{const c=r.nativeProgram=this._engine.createProgram(t,i);return l(),c}catch(c){const h=c?.message;throw new Error("SHADER ERROR"+(typeof h=="string"?` +`+h:""))}}inlineShaderCode(e){const t=new uI(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.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.nativeProgram,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.nativeProgram);const i=e.getSamplers();for(let s=0;s{}}}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,Bge(this._stencilOpStencilFail),Fge(this._stencilOpDepthFail),Vge(this._stencilOpStencilDepthPass),Nge(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,s,r,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),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,s){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=zge(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,s){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat4(e,t,i,s,r){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),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,s=!1,r){if(s===void 0&&(s=!1),!!e&&!!e._hardwareTexture){const n=t.getCanvasTexture(),o=e._hardwareTexture.underlyingResource;this._engine.copyTexture(o,n),e.isReady=!0}}createDynamicTexture(e,t,i,s){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,s)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const s=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(s,t,i)}}createRawTexture(e,t,i,s,r,n,o,l=null,c=0,h=0,u=!1){const p=new dn(this,hr.Raw);if(p.format=s,p.generateMipMaps=r,p.samplingMode=o,p.invertY=n,p.baseWidth=t,p.baseHeight=i,p.width=p.baseWidth,p.height=p.baseHeight,p._compression=l,p.type=c,p._useSRGBBuffer=this._getUseSRGBBuffer(u,!r),this.updateRawTexture(p,e,s,n,l,c,p._useSRGBBuffer),p._hardwareTexture){const m=p._hardwareTexture.underlyingResource,_=QH(o);this._setTextureSampling(m,_)}return this._internalTexturesCache.push(p),p}createRawTexture2DArray(e,t,i,s,r,n,o,l,c=null,h=0){const u=new dn(this,hr.Raw2DArray);if(u.baseWidth=t,u.baseHeight=i,u.baseDepth=s,u.width=t,u.height=i,u.depth=s,u.format=r,u.type=h,u.generateMipMaps=n,u.samplingMode=l,u.is2DArray=!0,u._hardwareTexture){const p=u._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(p,e,t,i,s,MZ(r,h),n,o);const m=QH(l);this._setTextureSampling(p,m)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){if(!!e){if(t&&e._hardwareTexture){const l=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(l,t,e.width,e.height,MZ(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,o=null,l=null,c=null,h=null,u=null,p,m,_,f=!1){e=e||"";const d=e.substr(0,5)==="data:",C=d&&e.indexOf(";base64,")!==-1,v=c||new dn(this,hr.Url),y=e;this._transformTextureUrl&&!C&&!c&&!l&&(e=this._transformTextureUrl(e));const M=e.lastIndexOf("."),b=u||(M>-1?e.substring(M).toLowerCase():"");let E=null;for(const D of He._TextureLoaders)if(D.canLoad(b)){E=D;break}s&&s.addPendingData(v),v.url=e,v.generateMipMaps=!t,v.samplingMode=r,v.invertY=i,v._useSRGBBuffer=this._getUseSRGBBuffer(f,t),this.doNotHandleContextLost||(v._buffer=l);let S=null;n&&!c&&(S=v.onLoadedObservable.add(n)),c||this._internalTexturesCache.push(v);const I=(D,R)=>{s&&s.removePendingData(v),e===y?(S&&v.onLoadedObservable.remove(S),Ii.UseFallbackTexture&&this.createTexture(Ii.FallbackTexture,t,v.invertY,s,r,null,o,l,v),o&&o((D||"Unknown error")+(Ii.UseFallbackTexture?" - Fallback texture was used":""),R)):(Me.Warn(`Failed to load ${e}, falling back to ${y}`),this.createTexture(y,t,v.invertY,s,r,n,o,l,v,h,u,p,m))};if(E)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const D=R=>{if(!v._hardwareTexture){s&&s.removePendingData(v);return}const L=v._hardwareTexture.underlyingResource;this._engine.loadTexture(L,R,!t,i,v._useSRGBBuffer,()=>{v.baseWidth=this._engine.getTextureWidth(L),v.baseHeight=this._engine.getTextureHeight(L),v.width=v.baseWidth,v.height=v.baseHeight,v.isReady=!0;const w=QH(r);this._setTextureSampling(L,w),s&&s.removePendingData(v),v.onLoadedObservable.notifyObservers(v),v.onLoadedObservable.clear()},()=>{throw new Error("Could not load a native texture.")})};if(d&&l)if(l instanceof ArrayBuffer)D(new Uint8Array(l));else if(ArrayBuffer.isView(l))D(l);else if(typeof l=="string")D(new Uint8Array(Be.DecodeBase64(l)));else throw new Error("Unsupported buffer type");else C?D(new Uint8Array(Be.DecodeBase64(e))):this._loadFile(e,R=>D(new Uint8Array(R)),void 0,void 0,!0,(R,L)=>{I("Unable to load "+(R&&R.responseURL,L))})}return v}wrapNativeTexture(e,t=!1,i=3){const s=new zse(e,this._engine),r=new dn(this,hr.Unknown,!0);return r._hardwareTexture=s,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){var s,r;const n=t.generateStencil||!1,o=t.samples||1,l=i,c=new dn(this,hr.DepthStencil),h=(s=e.width)!==null&&s!==void 0?s:e,u=(r=e.height)!==null&&r!==void 0?r:e,p=this._engine.createFrameBuffer(c._hardwareTexture.underlyingResource,h,u,n,!0,o);return l._framebufferDepthStencil=p,c}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise((s,r)=>{const n=this.createCanvasImage();n.onload=()=>{try{const o=this._engine.createImageBitmap(n);s(o)}catch(o){r(`Error loading image ${n.src} with exception: ${o}`)}},n.onerror=o=>{r(`Error loading image ${n.src} with exception: ${o}`)},n.src=e})}createImageBitmap(e,t){return new Promise((i,s)=>{if(Array.isArray(e)){const r=e;if(r.length){const n=this._engine.createImageBitmap(r[0]);if(n){i(n);return}}}s("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,s,r=null,n=null,o,l=null,c=!1,h=0,u=0,p=null,m,_=!1){const f=p||new dn(this,hr.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!s,f._lodGenerationScale=h,f._lodGenerationOffset=u,f._useSRGBBuffer=this._getUseSRGBBuffer(_,!!s),this._doNotHandleContextLost||(f._extension=l,f._files=i);const d=e.lastIndexOf(".");if((l||(d>-1?e.substring(d).toLowerCase():""))===".env"){const v=y=>{const M=ZK(y);f.width=M.width,f.height=M.width,JK(f,M);const b=M.specular;if(!b)throw new Error("Nothing else parsed so far");f._lodGenerationScale=b.lodGenerationScale;const E=qK(y,M);f.format=5,f.type=0,f.generateMipMaps=!0,f.getEngine().updateTextureSamplingMode(Te.TRILINEAR_SAMPLINGMODE,f),f._isRGBD=!0,f.invertY=!0,this._engine.loadCubeTextureWithMips(f._hardwareTexture.underlyingResource,E,!1,f._useSRGBBuffer,()=>{f.isReady=!0,r&&r()},()=>{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 y=(M,b)=>{n&&M&&n(M.status+" "+M.statusText,b)};this._loadFile(e,M=>v(new Uint8Array(M)),void 0,void 0,!0,y)}}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(y=>Be.LoadFileAsync(y).then(M=>new Uint8Array(M)))).then(y=>new Promise((M,b)=>{this._engine.loadCubeTexture(f._hardwareTexture.underlyingResource,y,!s,!0,f._useSRGBBuffer,M,b)})).then(()=>{f.isReady=!0,r&&r()},y=>{n&&n(`Failed to load cubemap: ${y.message}`,y)})}return this._internalTexturesCache.push(f),f}_createHardwareTexture(){return new zse(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new wge(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=hr.Unknown){var r,n,o;let l=!1,c=0,h=3,u=5,p=!1,m=1,_;t!==void 0&&typeof t=="object"?(l=!!t.generateMipMaps,c=t.type===void 0?0:t.type,h=t.samplingMode===void 0?3:t.samplingMode,u=t.format===void 0?5:t.format,p=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,m=(r=t.samples)!==null&&r!==void 0?r:1,_=t.label):l=!!t,p=this._getUseSRGBBuffer(p,!l),(c===1&&!this._caps.textureFloatLinearFiltering||c===2&&!this._caps.textureHalfFloatLinearFiltering)&&(h=1),c===1&&!this._caps.textureFloat&&(c=0,Me.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const f=new dn(this,s),d=(n=e.width)!==null&&n!==void 0?n:e,C=(o=e.height)!==null&&o!==void 0?o:e,v=e.layers||0;if(v!==0)throw new Error("Texture layers are not supported in Babylon Native");const y=f._hardwareTexture.underlyingResource,M=MZ(u,c);return this._engine.initializeTexture(y,d,C,l,M,!0,p,m),this._setTextureSampling(y,QH(h)),f._useSRGBBuffer=p,f.baseWidth=d,f.baseHeight=C,f.width=d,f.height=C,f.depth=v,f.isReady=!0,f.samples=m,f.generateMipMaps=l,f.samplingMode=h,f.type=c,f.format=u,f.label=_,this._internalTexturesCache.push(f),f}createRenderTargetTexture(e,t){var i,s,r,n;const o=this._createHardwareRenderTargetWrapper(!1,!1,e);let l=!0,c=!1,h=!1,u,p=1;t!==void 0&&typeof t=="object"&&(l=(i=t.generateDepthBuffer)!==null&&i!==void 0?i:!0,c=!!t.generateStencilBuffer,h=!!t.noColorAttachment,u=t.colorAttachment,p=(s=t.samples)!==null&&s!==void 0?s:1);const m=u||(h?null:this._createInternalTexture(e,t,!0,hr.RenderTarget)),_=(r=e.width)!==null&&r!==void 0?r:e,f=(n=e.height)!==null&&n!==void 0?n:e,d=this._engine.createFrameBuffer(m?m._hardwareTexture.underlyingResource:null,_,f,c,l,p);return o._framebuffer=d,o._generateDepthBuffer=l,o._generateStencilBuffer=c,o._samples=p,o.setTextures(m),o}updateRenderTargetTextureSampleCount(e,t){return Me.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=QH(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,s,r){const n=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||s)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");n._framebufferDepthStencil?this._bindUnboundFramebuffer(n._framebufferDepthStencil):this._bindUnboundFramebuffer(n._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 s=e,r=this._normalizeIndexData(t);s.is32Bits=r.BYTES_PER_ELEMENT===4,this._engine.updateDynamicIndexBuffer(s.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i,s){const r=e,n=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,n.buffer,n.byteOffset+(i??0),s??n.byteLength)}_setTexture(e,t,i=!1,s=!1){const r=this._boundUniforms[e];if(!r)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 n;return s?n=t.depthStencilTexture:t.isReady()?n=t.getInternalTexture():t.isCube?n=this.emptyCubeTexture:t.is3D?n=this.emptyTexture3D:t.is2DArray?n=this.emptyTexture2DArray:n=this.emptyTexture,this._activeChannel=e,!n||!n._hardwareTexture?!1:(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,TZ(t.wrapU),TZ(t.wrapV),TZ(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(r,n._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,s){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),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 s=t._hardwareTexture.underlyingResource;this._setTextureCore(i,s)}}_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,s,r,n,o=0,l=0,c=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,s=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,s,r,n,o,l,c,h){var u,p,m,_;if(s!==void 0&&s!==-1)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${s}.`);return this._engine.readTexture((u=e._hardwareTexture)===null||u===void 0?void 0:u.underlyingResource,r??0,c??0,h??0,t,i,(p=n?.buffer)!==null&&p!==void 0?p:null,(m=n?.byteOffset)!==null&&m!==void 0?m:0,(_=n?.byteLength)!==null&&_!==void 0?_:0).then(f=>(n||(n=new Uint8Array(f)),n))}}QP.PROTOCOL_VERSION=8;QP._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new Hce:new VL};class Hce extends VL{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 Vq;(function(a){a.LowPower="low-power",a.HighPerformance="high-performance"})(Vq||(Vq={}));var IM;(function(a){a.DepthClipControl="depth-clip-control",a.Depth32FloatStencil8="depth32float-stencil8",a.TextureCompressionBC="texture-compression-bc",a.TextureCompressionETC2="texture-compression-etc2",a.TextureCompressionASTC="texture-compression-astc",a.TimestampQuery="timestamp-query",a.IndirectFirstInstance="indirect-first-instance",a.ShaderF16="shader-f16",a.RG11B10UFloatRenderable="rg11b10ufloat-renderable",a.BGRA8UnormStorage="bgra8unorm-storage",a.Float32Filterable="float32-filterable"})(IM||(IM={}));var zq;(function(a){a.Unmapped="unmapped",a.Pending="pending",a.Mapped="mapped"})(zq||(zq={}));var Pa;(function(a){a[a.MapRead=1]="MapRead",a[a.MapWrite=2]="MapWrite",a[a.CopySrc=4]="CopySrc",a[a.CopyDst=8]="CopyDst",a[a.Index=16]="Index",a[a.Vertex=32]="Vertex",a[a.Uniform=64]="Uniform",a[a.Storage=128]="Storage",a[a.Indirect=256]="Indirect",a[a.QueryResolve=512]="QueryResolve"})(Pa||(Pa={}));var OL;(function(a){a[a.Read=1]="Read",a[a.Write=2]="Write"})(OL||(OL={}));var nv;(function(a){a.E1d="1d",a.E2d="2d",a.E3d="3d"})(nv||(nv={}));var Oo;(function(a){a[a.CopySrc=1]="CopySrc",a[a.CopyDst=2]="CopyDst",a[a.TextureBinding=4]="TextureBinding",a[a.StorageBinding=8]="StorageBinding",a[a.RenderAttachment=16]="RenderAttachment"})(Oo||(Oo={}));var Ra;(function(a){a.E1d="1d",a.E2d="2d",a.E2dArray="2d-array",a.Cube="cube",a.CubeArray="cube-array",a.E3d="3d"})(Ra||(Ra={}));var kb;(function(a){a.All="all",a.StencilOnly="stencil-only",a.DepthOnly="depth-only"})(kb||(kb={}));var Ae;(function(a){a.R8Unorm="r8unorm",a.R8Snorm="r8snorm",a.R8Uint="r8uint",a.R8Sint="r8sint",a.R16Uint="r16uint",a.R16Sint="r16sint",a.R16Float="r16float",a.RG8Unorm="rg8unorm",a.RG8Snorm="rg8snorm",a.RG8Uint="rg8uint",a.RG8Sint="rg8sint",a.R32Uint="r32uint",a.R32Sint="r32sint",a.R32Float="r32float",a.RG16Uint="rg16uint",a.RG16Sint="rg16sint",a.RG16Float="rg16float",a.RGBA8Unorm="rgba8unorm",a.RGBA8UnormSRGB="rgba8unorm-srgb",a.RGBA8Snorm="rgba8snorm",a.RGBA8Uint="rgba8uint",a.RGBA8Sint="rgba8sint",a.BGRA8Unorm="bgra8unorm",a.BGRA8UnormSRGB="bgra8unorm-srgb",a.RGB9E5UFloat="rgb9e5ufloat",a.RGB10A2Unorm="rgb10a2unorm",a.RG11B10UFloat="rg11b10ufloat",a.RG32Uint="rg32uint",a.RG32Sint="rg32sint",a.RG32Float="rg32float",a.RGBA16Uint="rgba16uint",a.RGBA16Sint="rgba16sint",a.RGBA16Float="rgba16float",a.RGBA32Uint="rgba32uint",a.RGBA32Sint="rgba32sint",a.RGBA32Float="rgba32float",a.Stencil8="stencil8",a.Depth16Unorm="depth16unorm",a.Depth24Plus="depth24plus",a.Depth24PlusStencil8="depth24plus-stencil8",a.Depth32Float="depth32float",a.BC1RGBAUnorm="bc1-rgba-unorm",a.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",a.BC2RGBAUnorm="bc2-rgba-unorm",a.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",a.BC3RGBAUnorm="bc3-rgba-unorm",a.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",a.BC4RUnorm="bc4-r-unorm",a.BC4RSnorm="bc4-r-snorm",a.BC5RGUnorm="bc5-rg-unorm",a.BC5RGSnorm="bc5-rg-snorm",a.BC6HRGBUFloat="bc6h-rgb-ufloat",a.BC6HRGBFloat="bc6h-rgb-float",a.BC7RGBAUnorm="bc7-rgba-unorm",a.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",a.ETC2RGB8Unorm="etc2-rgb8unorm",a.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",a.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",a.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",a.ETC2RGBA8Unorm="etc2-rgba8unorm",a.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",a.EACR11Unorm="eac-r11unorm",a.EACR11Snorm="eac-r11snorm",a.EACRG11Unorm="eac-rg11unorm",a.EACRG11Snorm="eac-rg11snorm",a.ASTC4x4Unorm="astc-4x4-unorm",a.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",a.ASTC5x4Unorm="astc-5x4-unorm",a.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",a.ASTC5x5Unorm="astc-5x5-unorm",a.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",a.ASTC6x5Unorm="astc-6x5-unorm",a.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",a.ASTC6x6Unorm="astc-6x6-unorm",a.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",a.ASTC8x5Unorm="astc-8x5-unorm",a.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",a.ASTC8x6Unorm="astc-8x6-unorm",a.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",a.ASTC8x8Unorm="astc-8x8-unorm",a.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",a.ASTC10x5Unorm="astc-10x5-unorm",a.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",a.ASTC10x6Unorm="astc-10x6-unorm",a.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",a.ASTC10x8Unorm="astc-10x8-unorm",a.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",a.ASTC10x10Unorm="astc-10x10-unorm",a.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",a.ASTC12x10Unorm="astc-12x10-unorm",a.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",a.ASTC12x12Unorm="astc-12x12-unorm",a.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",a.Depth24UnormStencil8="depth24unorm-stencil8",a.Depth32FloatStencil8="depth32float-stencil8"})(Ae||(Ae={}));var vP;(function(a){a.ClampToEdge="clamp-to-edge",a.Repeat="repeat",a.MirrorRepeat="mirror-repeat"})(vP||(vP={}));var Qr;(function(a){a.Nearest="nearest",a.Linear="linear"})(Qr||(Qr={}));var Uq;(function(a){a.Nearest="nearest",a.Linear="linear"})(Uq||(Uq={}));var Fu;(function(a){a.Never="never",a.Less="less",a.Equal="equal",a.LessEqual="less-equal",a.Greater="greater",a.NotEqual="not-equal",a.GreaterEqual="greater-equal",a.Always="always"})(Fu||(Fu={}));var H9;(function(a){a[a.Vertex=1]="Vertex",a[a.Fragment=2]="Fragment",a[a.Compute=4]="Compute"})(H9||(H9={}));var dI;(function(a){a.Uniform="uniform",a.Storage="storage",a.ReadOnlyStorage="read-only-storage"})(dI||(dI={}));var bI;(function(a){a.Filtering="filtering",a.NonFiltering="non-filtering",a.Comparison="comparison"})(bI||(bI={}));var e4;(function(a){a.Float="float",a.UnfilterableFloat="unfilterable-float",a.Depth="depth",a.Sint="sint",a.Uint="uint"})(e4||(e4={}));var gX;(function(a){a.WriteOnly="write-only"})(gX||(gX={}));var kq;(function(a){a.Error="error",a.Warning="warning",a.Info="info"})(kq||(kq={}));var Hq;(function(a){a.Validation="validation",a.Internal="internal"})(Hq||(Hq={}));var kB;(function(a){a.Auto="auto"})(kB||(kB={}));var K3;(function(a){a.PointList="point-list",a.LineList="line-list",a.LineStrip="line-strip",a.TriangleList="triangle-list",a.TriangleStrip="triangle-strip"})(K3||(K3={}));var kj;(function(a){a.CCW="ccw",a.CW="cw"})(kj||(kj={}));var JN;(function(a){a.None="none",a.Front="front",a.Back="back"})(JN||(JN={}));var jq;(function(a){a[a.Red=1]="Red",a[a.Green=2]="Green",a[a.Blue=4]="Blue",a[a.Alpha=8]="Alpha",a[a.All=15]="All"})(jq||(jq={}));var j1;(function(a){a.Zero="zero",a.One="one",a.Src="src",a.OneMinusSrc="one-minus-src",a.SrcAlpha="src-alpha",a.OneMinusSrcAlpha="one-minus-src-alpha",a.Dst="dst",a.OneMinusDst="one-minus-dst",a.DstAlpha="dst-alpha",a.OneMinusDstAlpha="one-minus-dst-alpha",a.SrcAlphaSaturated="src-alpha-saturated",a.Constant="constant",a.OneMinusConstant="one-minus-constant"})(j1||(j1={}));var j9;(function(a){a.Add="add",a.Subtract="subtract",a.ReverseSubtract="reverse-subtract",a.Min="min",a.Max="max"})(j9||(j9={}));var z5;(function(a){a.Keep="keep",a.Zero="zero",a.Replace="replace",a.Invert="invert",a.IncrementClamp="increment-clamp",a.DecrementClamp="decrement-clamp",a.IncrementWrap="increment-wrap",a.DecrementWrap="decrement-wrap"})(z5||(z5={}));var EI;(function(a){a.Uint16="uint16",a.Uint32="uint32"})(EI||(EI={}));var Zo;(function(a){a.Uint8x2="uint8x2",a.Uint8x4="uint8x4",a.Sint8x2="sint8x2",a.Sint8x4="sint8x4",a.Unorm8x2="unorm8x2",a.Unorm8x4="unorm8x4",a.Snorm8x2="snorm8x2",a.Snorm8x4="snorm8x4",a.Uint16x2="uint16x2",a.Uint16x4="uint16x4",a.Sint16x2="sint16x2",a.Sint16x4="sint16x4",a.Unorm16x2="unorm16x2",a.Unorm16x4="unorm16x4",a.Snorm16x2="snorm16x2",a.Snorm16x4="snorm16x4",a.Float16x2="float16x2",a.Float16x4="float16x4",a.Float32="float32",a.Float32x2="float32x2",a.Float32x3="float32x3",a.Float32x4="float32x4",a.Uint32="uint32",a.Uint32x2="uint32x2",a.Uint32x3="uint32x3",a.Uint32x4="uint32x4",a.Sint32="sint32",a.Sint32x2="sint32x2",a.Sint32x3="sint32x3",a.Sint32x4="sint32x4"})(Zo||(Zo={}));var Hj;(function(a){a.Vertex="vertex",a.Instance="instance"})(Hj||(Hj={}));var Gq;(function(a){a.Beginning="beginning",a.End="end"})(Gq||(Gq={}));var Wq;(function(a){a.Beginning="beginning",a.End="end"})(Wq||(Wq={}));var Mh;(function(a){a.Load="load",a.Clear="clear"})(Mh||(Mh={}));var u_;(function(a){a.Store="store",a.Discard="discard"})(u_||(u_={}));var jj;(function(a){a.Occlusion="occlusion",a.Timestamp="timestamp"})(jj||(jj={}));var Gj;(function(a){a.Opaque="opaque",a.Premultiplied="premultiplied"})(Gj||(Gj={}));var Yq;(function(a){a.Unknown="unknown",a.Destroyed="destroyed"})(Yq||(Yq={}));var Xq;(function(a){a.Validation="validation",a.OutOfMemory="out-of-memory",a.Internal="internal"})(Xq||(Xq={}));class el{constructor(){this.shaderLanguage=Ao.GLSL}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let r=0;r=0&&(p.push(o[u]),m.push(_))}this.shaderProcessingContext.attributeNamesFromEffect=p,this.shaderProcessingContext.attributeLocationsFromEffect=m}buildUniformLayout(){if(!!this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new es(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=el.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,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt3(e,t,i,s)}setInt4(e,t,i,s,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt4(e,t,i,s,r)}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,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt3(e,t,i,s)}setUInt4(e,t,i,s,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt4(e,t,i,s,r)}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,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat3(e,t,i,s)}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,s,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat4(e,t,i,s,r)}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||e===void 0?void 0:e.vertex}_getFragmentShaderCode(){var e;return(e=this.sources)===null||e===void 0?void 0:e.fragment}}const jge=4,Gge=1<<16,kse={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class av{static get KnownUBOs(){return av._SimplifiedKnownBindings?av._SimplifiedKnownUBOs:av._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=av.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;s.groupIndex!==-1&&(t[s.groupIndex]===void 0?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.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){var i;const s=this._attributeNextLocation;return this._attributeNextLocation+=((i=kse[e])!==null&&i!==void 0?i:1)*(t||1),s}getVaryingNextLocation(e,t=0){var i;const s=this._varyingNextLocation;return this._varyingNextLocation+=((i=kse[e])!==null&&i!==void 0?i:1)*(t||1),s}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>Gge-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===jge)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}}av._SimplifiedKnownBindings=!0;av._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}}};av._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 Wge extends el{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=Ao.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const o=e.substring(r+1,n);s=+o,isNaN(s)&&(s=+i[o.trim()]),e=e.substr(0,r)}return[e,t,s]}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 ${el.InternalsUBOName} { +float yFactor_; +float textureOutputHeight_; +}; +`,s=e.indexOf("// Internals UBO")!==-1;return t?(this._fragmentIsGLES3=e.indexOf("#version 3")!==-1,this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+`##INJECTCODE## +`+e):(this._vertexIsGLES3=e.indexOf("#version 3")!==-1,this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingCheck(e,t){const i=/(flat\s)?\s*\bout\b/,s=/(flat\s)?\s*\bin\b/,r=/(flat\s)?\s*\bvarying\b/;return(t&&this._fragmentIsGLES3?s:!t&&this._vertexIsGLES3?i:r).test(e)}varyingProcessor(e,t,i){var s;this._preProcessors=i;const r=/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,n=/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,o=/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,c=(t&&this._fragmentIsGLES3?n:!t&&this._vertexIsGLES3?r:o).exec(e);if(c!==null){const h=(s=c[1])!==null&&s!==void 0?s:"",u=c[2],p=c[3];let m;t?(m=this._webgpuProcessingContext.availableVaryings[p],this._missingVaryings[m]="",m===void 0&&Me.Warn(`Invalid fragment shader: The varying named "${p}" is not declared in the vertex shader! This declaration will be ignored.`)):(m=this._webgpuProcessingContext.getVaryingNextLocation(u,this._getArraySize(p,u,i)[2]),this._webgpuProcessingContext.availableVaryings[p]=m,this._missingVaryings[m]=`layout(location = ${m}) ${h} in ${u} ${p};`),e=e.replace(c[0],m===void 0?"":`layout(location = ${m}) ${h} ${t?"in":"out"} ${u} ${p};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=/\s*in\s+(\S+)\s+(\S+)\s*;/gm,s=/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,n=(this._vertexIsGLES3?i:s).exec(e);if(n!==null){const o=n[1],l=n[2],c=this._webgpuProcessingContext.getAttributeNextLocation(o,this._getArraySize(l,o,t)[2]);this._webgpuProcessingContext.availableAttributes[l]=c,this._webgpuProcessingContext.orderedAttributes[c]=l,e=e.replace(n[0],`layout(location = ${c}) in ${o} ${l};`)}return e}uniformProcessor(e,t,i){var s;this._preProcessors=i;const n=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(n!==null){let o=n[1],l=n[2];if(o.indexOf("sampler")===0||o.indexOf("sampler")===1){let c=0;[l,o,c]=this._getArraySize(l,o,i);let h=this._webgpuProcessingContext.availableTextures[l];if(!h){h={autoBindSampler:!0,isTextureArray:c>0,isStorageTexture:!1,textures:[],sampleType:e4.Float};for(let I=0;I<(c||1);++I)h.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const u=(s=el._SamplerTypeByWebGLSamplerType[o])!==null&&s!==void 0?s:"sampler",p=!!el._IsComparisonSamplerByWebGPUSamplerType[u],m=p?bI.Comparison:bI.Filtering,_=l+el.AutoSamplerSuffix;let f=this._webgpuProcessingContext.availableSamplers[_];f||(f={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:m});const d=o.charAt(0)==="u"?"u":o.charAt(0)==="i"?"i":"";d&&(o=o.substr(1));const C=p?e4.Depth:d==="u"?e4.Uint:d==="i"?e4.Sint:e4.Float;h.sampleType=C;const v=c>0,y=f.binding.groupIndex,M=f.binding.bindingIndex,b=el._SamplerFunctionByWebGLSamplerType[o],E=el._TextureTypeByWebGLSamplerType[o],S=el._GpuTextureViewDimensionByWebGPUTextureType[E];if(!v)c=1,e=`layout(set = ${y}, binding = ${M}) uniform ${u} ${_}; + layout(set = ${h.textures[0].groupIndex}, binding = ${h.textures[0].bindingIndex}) uniform ${d}${E} ${l}Texture; + #define ${l} ${d}${b}(${l}Texture, ${_})`;else{const I=[];I.push(`layout(set = ${y}, binding = ${M}) uniform ${d}${u} ${_};`),e=` +`;for(let D=0;D0?` +`:""}#define ${l}${D} ${d}${b}(${l}Texture${D}, ${_})`}e=I.join(` +`)+e,this._textureArrayProcessing.push(l)}this._webgpuProcessingContext.availableTextures[l]=h,this._webgpuProcessingContext.availableSamplers[_]=f,this._addSamplerBindingDescription(_,f,!t);for(let I=0;I=0,c=` + glFragCoord_ = gl_FragCoord; + if (yFactor_ == 1.) { + glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; + } + `,h=l?`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,(n||u?"":`layout(location = 0) out vec4 glFragColor; +`)+"void main(");else{const p=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);p!==null&&(e=e.substring(0,p.index)+"layout(location = 0) "+e.substring(p.index))}e=e.replace(/dFdy/g,"(-yFactor_)*dFdy"),e=e.replace("##INJECTCODE##",h),l&&(e=this._injectStartingAndEndingCode(e,"void main",c))}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 l=e.lastIndexOf("}");e=e.substring(0,l),e+=`gl_Position.y *= yFactor_; +`,r.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 s=i.exec(e);for(;s!==null;){const r=s[1];let n=+r;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[r.trim()]),e=e.replace(s[0],t+n),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { + `;for(const s of this._webgpuProcessingContext.leftOverUniforms)s.length>0?i+=` ${s.type} ${s.name}[${s.length}]; +`:i+=` ${s.type} ${s.name}; +`;return i+=`}; + +`,i}finalizeShaders(e,t){for(let s=0;s0&&(t=r+` +`+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,{vertexCode:e,fragmentCode:t}}}const Yge="bonesDeclaration",Xge=`#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 +`;Ue.IncludesShadersStoreWGSL[Yge]=Xge;const Kge="bonesVertex",Qge=`#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 +`;Ue.IncludesShadersStoreWGSL[Kge]=Qge;const Zge="bakedVertexAnimationDeclaration",qge=`#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 +`;Ue.IncludesShadersStoreWGSL[Zge]=qge;const Jge="bakedVertexAnimation",$ge=`#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 +`;Ue.IncludesShadersStoreWGSL[Jge]=$ge;const e6e="clipPlaneFragment",t6e=`#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 +`;Ue.IncludesShadersStoreWGSL[e6e]=t6e;const i6e="clipPlaneFragmentDeclaration",s6e=`#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 +`;Ue.IncludesShadersStoreWGSL[i6e]=s6e;const r6e="clipPlaneVertex",n6e=`#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 +`;Ue.IncludesShadersStoreWGSL[r6e]=n6e;const a6e="clipPlaneVertexDeclaration",o6e=`#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 +`;Ue.IncludesShadersStoreWGSL[a6e]=o6e;const l6e="instancesDeclaration",c6e=`#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 +`;Ue.IncludesShadersStoreWGSL[l6e]=c6e;const h6e="instancesVertex",u6e=`#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 +`;Ue.IncludesShadersStoreWGSL[h6e]=u6e;const d6e="meshUboDeclaration",f6e=`struct Mesh {world : mat4x4, +visibility : f32,};var mesh : Mesh; +#define WORLD_UBO +`;Ue.IncludesShadersStoreWGSL[d6e]=f6e;const p6e="morphTargetsVertex",m6e=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +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 +#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 +`;Ue.IncludesShadersStoreWGSL[p6e]=m6e;const _6e="morphTargetsVertexDeclaration",g6e=`#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 +#endif +#endif +`;Ue.IncludesShadersStoreWGSL[_6e]=g6e;const v6e="morphTargetsVertexGlobal",C6e=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +var vertexID : f32; +#endif +#endif +`;Ue.IncludesShadersStoreWGSL[v6e]=C6e;const A6e="morphTargetsVertexGlobalDeclaration",x6e=`#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 +`;Ue.IncludesShadersStoreWGSL[A6e]=x6e;const b6e="sceneUboDeclaration",E6e=`struct Scene {viewProjection : mat4x4, +#ifdef MULTIVIEW +viewProjectionR : mat4x4, +#endif +view : mat4x4, +projection : mat4x4, +vEyePosition : vec4,};var scene : Scene; +`;Ue.IncludesShadersStoreWGSL[b6e]=E6e;const Hse="fragmentOutputs.fragDepth",y6e="uniforms",M6e="internals",T6e={texture_1d:Ra.E1d,texture_2d:Ra.E2d,texture_2d_array:Ra.E2dArray,texture_3d:Ra.E3d,texture_cube:Ra.Cube,texture_cube_array:Ra.CubeArray,texture_multisampled_2d:Ra.E2d,texture_depth_2d:Ra.E2d,texture_depth_2d_array:Ra.E2dArray,texture_depth_cube:Ra.Cube,texture_depth_cube_array:Ra.CubeArray,texture_depth_multisampled_2d:Ra.E2d,texture_storage_1d:Ra.E1d,texture_storage_2d:Ra.E2d,texture_storage_2d_array:Ra.E2dArray,texture_storage_3d:Ra.E3d,texture_external:null};class S6e extends el{constructor(){super(...arguments),this.shaderLanguage=Ao.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 s=0;const r=t.lastIndexOf(">");if(t.indexOf("array")>=0&&r>0){let n=r;for(;n>0&&t.charAt(n)!==" "&&t.charAt(n)!==",";)n--;const o=t.substring(n+1,r);for(s=+o,isNaN(s)&&(s=+i[o.trim()]);n>0&&(t.charAt(n)===" "||t.charAt(n)===",");)n--;t=t.substring(t.indexOf("<")+1,n+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesWGSL=[],this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${el.InternalsUBOName} { + yFactor_: f32, + textureOutputHeight_: f32, +}; +var ${M6e} : ${el.InternalsUBOName}; +`+Fq(e)}varyingProcessor(e,t,i){const r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(r!==null){const n=r[2],o=r[1];let l;t?(l=this._webgpuProcessingContext.availableVaryings[o],l===void 0&&Me.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(l=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(o,n,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=l,this._varyingsWGSL.push(` @location(${l}) ${o} : ${n},`),this._varyingNamesWGSL.push(o)),e=""}return e}attributeProcessor(e,t){const s=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(s!==null){const r=s[2],n=s[1],o=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(n,r,t)[2]);this._webgpuProcessingContext.availableAttributes[n]=o,this._webgpuProcessingContext.orderedAttributes[o]=n,this._attributesWGSL.push(`@location(${o}) ${n} : ${r},`),e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(s!==null){const r=s[2],n=s[1];this._addUniformToLeftOverUBO(n,r,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(s!==null){const r=s[1],n=s[2],o=!!s[3],l=s[4],c=l.indexOf("storage")>0,h=s[6],u=c?h.substring(0,h.indexOf(",")).trim():null;let p=o?this._getArraySize(r,n,i)[2]:0,m=this._webgpuProcessingContext.availableTextures[r];if(m)p=m.textures.length;else{m={isTextureArray:p>0,isStorageTexture:c,textures:[],sampleType:e4.Float},p=p||1;for(let C=0;C0,f=T6e[l],d=_?e4.Depth:h==="u32"?e4.Uint:h==="i32"?e4.Sint:e4.Float;if(m.sampleType=d,f===void 0)throw`Can't get the texture dimension corresponding to the texture function "${l}"!`;for(let C=0;C=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 s=this._buildLeftOverUBO();e=s+e,t=s+t,e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let r=`struct VertexInputs { + @builtin(vertex_index) vertexIndex : u32, + @builtin(instance_index) instanceIndex : u32, +`;this._attributesWGSL.length>0&&(r+=this._attributesWGSL.join(` +`)),r+=` +}; +var vertexInputs : VertexInputs; +`;let n=`struct FragmentInputs { + @builtin(position) position : vec4, +`;this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join(` +`)),n+=` +}; +var vertexOutputs : FragmentInputs; +`,e=r+n+e;const o=` + vertexInputs = input; +`,l=` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; + return vertexOutputs;`;e=this._injectStartingAndEndingCode(e,"fn main",o,l),t=t.replace(/#define /g,"//#define "),t=this._processStridedUniformArrays(t),t=t.replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let c=`struct FragmentInputs { + @builtin(position) position : vec4, + @builtin(front_facing) frontFacing : bool, +`;this._varyingsWGSL.length>0&&(c+=this._varyingsWGSL.join(` +`)),c+=` +}; +var fragmentInputs : FragmentInputs; +`;let h=`struct FragmentOutputs { + @location(0) color : vec4, +`,u=!1,p=0;for(;!u&&(p=t.indexOf(Hse,p),!(p<0));){const f=p;for(u=!0;p>1&&t.charAt(p)!==` +`;){if(t.charAt(p)==="/"&&t.charAt(p-1)==="/"){u=!1;break}p--}p=f+Hse.length}u&&(h+=` @builtin(frag_depth) fragDepth: f32, +`),h+=`}; +var fragmentOutputs : FragmentOutputs; +`,t=c+h+t;const m=` fragmentInputs = input; + `+i,_=" return fragmentOutputs;";return t=this._injectStartingAndEndingCode(t,"fn main",m,_),this._collectBindingNames(),this._preCreateBindGroupEntries(),{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s=`struct ${e} { +`;for(const r of this._webgpuProcessingContext.leftOverUniforms){const n=r.type.replace(/^(.*?)(<.*>)?$/,"$1"),o=el.UniformSizes[n];if(r.length>0)if(o<=2){const l=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${l} { + @size(16) + el: ${n}, + }`,this._stridedUniformArrays.push(r.name),s+=` @align(16) ${r.name} : array<${l}, ${r.length}>, +`}else s+=` ${r.name} : array<${r.type}, ${r.length}>, +`;else s+=` ${r.name} : ${r.type}, +`}return s+=`}; +`,s=`${i} +${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var ${y6e} : ${e}; +`,s}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const s=i.exec(e);if(s===null)break;const r=s[1],n=s[2],o=r.indexOf(el.AutoSamplerSuffix)===r.length-el.AutoSamplerSuffix.length?r.substring(0,r.indexOf(el.AutoSamplerSuffix)):null,l=n==="sampler_comparison"?bI.Comparison:bI.Filtering;if(o){const m=this._webgpuProcessingContext.availableTextures[o];m&&(m.autoBindSampler=!0)}let c=this._webgpuProcessingContext.availableSamplers[r];c||(c={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:l},this._webgpuProcessingContext.availableSamplers[r]=c),this._addSamplerBindingDescription(r,c,t);const h=e.substring(0,s.index),u=`@group(${c.binding.groupIndex}) @binding(${c.binding.bindingIndex}) `,p=e.substring(s.index);e=h+u+p,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 s=i.exec(e);if(s===null)break;const r=s[1],n=s[3];let o=s[4];const l=s[5];let c=this._webgpuProcessingContext.availableBuffers[o];if(!c){const f=r==="uniform"?av.KnownUBOs[l]:null;let d;f?(o=l,d=f.binding,d.groupIndex===-1&&(d=this._webgpuProcessingContext.getNextFreeUBOBinding())):d=this._webgpuProcessingContext.getNextFreeUBOBinding(),c={binding:d},this._webgpuProcessingContext.availableBuffers[o]=c}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],n==="read_write"?dI.Storage:r==="storage"?dI.ReadOnlyStorage:dI.Uniform,t);const h=c.binding.groupIndex,u=c.binding.bindingIndex,p=e.substring(0,s.index),m=`@group(${h}) @binding(${u}) `,_=e.substring(s.index);e=p+m+_,i.lastIndex+=m.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 FY{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return(i=(t=this._webgpuMSAATexture)===null||t===void 0?void 0:t[e])!==null&&i!==void 0?i: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?.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=Ae.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,s,r){this.createView({format:this.format,dimension:i?Ra.Cube:Ra.E2d,mipLevelCount:t?Bt.ILog2(Math.max(s,r))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:kb.All})}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===void 0||e.destroy(),this.releaseMSAATexture(),(t=this._copyInvertYTempTexture)===null||t===void 0||t.destroy(),this.reset()}}const I6e=` + 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); + } + `,L6e=` + 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); + } + `,jce=` + #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); + } + `,R6e=` + #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; + } + `,P6e=jce,D6e=` + #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; + } + `,O6e=` + 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); + } + `,w6e=` + layout(set = 0, binding = 0) uniform Uniforms { + uniform vec4 color; + }; + + layout(location = 0) out vec4 outColor; + + void main() { + outColor = color; + } + `,N6e=` + 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; + } + `,B6e=` + @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); + } + `,F6e=` + @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 B5;(function(a){a[a.MipMap=0]="MipMap",a[a.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",a[a.Clear=2]="Clear",a[a.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(B5||(B5={}));var wN;(function(a){a[a.DontInvertY=0]="DontInvertY",a[a.InvertY=1]="InvertY"})(wN||(wN={}));const jse=[{vertex:I6e,fragment:L6e},{vertex:jce,fragment:R6e},{vertex:O6e,fragment:w6e},{vertex:P6e,fragment:D6e}],DM={"":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,rgb10a2unorm:22,rg32uint:23,rg32sint:24,rg32float:25,rgba16uint:26,rgba16sint:27,rgba16float:28,rgba32uint:29,rgba32sint:30,rgba32float:31,stencil8:32,depth16unorm:33,depth24plus:34,"depth24plus-stencil8":35,depth32float:36,"depth32float-stencil8":37};class ho{static ComputeNumMipmapLevels(e,t){return Bt.ILog2(Math.max(e,t))+1}constructor(e,t,i,s,r){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=s,r.indexOf(IM.RG11B10UFloatRenderable)!==-1){const n=Object.keys(DM);DM[Ae.RG11B10UFloat]=DM[n[n.length-1]]+1}this._mipmapSampler=e.createSampler({minFilter:Qr.Linear}),this._videoSampler=e.createSampler({minFilter:Qr.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,Pa.Uniform|Pa.CopyDst).underlyingResource,this._getPipeline(Ae.RGBA8Unorm),this._getVideoPipeline(Ae.RGBA8Unorm)}_getPipeline(e,t=B5.MipMap,i){const s=t===B5.MipMap?1:t===B5.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===B5.Clear?8:t===B5.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let r=this._pipelines[e][s];if(!r){let n=`#version 450 +`;(t===B5.InvertYPremultiplyAlpha||t===B5.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(n+=`#define INVERTY +`),i.premultiplyAlpha&&(n+=`#define PREMULTIPLYALPHA +`));let o=this._compiledShaders[s];if(!o){let c=this._glslang.compileGLSL(n+jse[t].vertex,"vertex"),h=this._glslang.compileGLSL(n+jse[t].fragment,"fragment");this._tintWASM&&(c=this._tintWASM.convertSpirV2WGSL(c),h=this._tintWASM.convertSpirV2WGSL(h));const u=this._device.createShaderModule({code:c}),p=this._device.createShaderModule({code:h});o=this._compiledShaders[s]=[u,p]}const l=this._device.createRenderPipeline({layout:kB.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:K3.TriangleStrip,stripIndexFormat:EI.Uint16}});r=this._pipelines[e][s]=[l,l.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=wN.DontInvertY){const i=t===wN.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let r=this._videoCompiledShaders[i];if(!r){const o=this._device.createShaderModule({code:N6e}),l=this._device.createShaderModule({code:i===0?B6e:F6e});r=this._videoCompiledShaders[i]=[o,l]}const n=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${i===0?"DontInvertY":"InvertY"}`,layout:kB.Auto,vertex:{module:r[0],entryPoint:"main"},fragment:{module:r[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:K3.TriangleStrip,stripIndexFormat:EI.Uint16}});s=this._videoPipelines[e][i]=[n,n.getBindGroupLayout(0)]}return s}static _GetTextureTypeFromFormat(e){switch(e){case Ae.R8Unorm:case Ae.R8Snorm:case Ae.R8Uint:case Ae.R8Sint:case Ae.RG8Unorm:case Ae.RG8Snorm:case Ae.RG8Uint:case Ae.RG8Sint:case Ae.RGBA8Unorm:case Ae.RGBA8UnormSRGB:case Ae.RGBA8Snorm:case Ae.RGBA8Uint:case Ae.RGBA8Sint:case Ae.BGRA8Unorm:case Ae.BGRA8UnormSRGB:case Ae.RGB10A2Unorm:case Ae.RGB9E5UFloat:case Ae.RG11B10UFloat:case Ae.Depth24UnormStencil8:case Ae.Depth32FloatStencil8:case Ae.BC7RGBAUnorm:case Ae.BC7RGBAUnormSRGB:case Ae.BC6HRGBUFloat:case Ae.BC6HRGBFloat:case Ae.BC5RGUnorm:case Ae.BC5RGSnorm:case Ae.BC3RGBAUnorm:case Ae.BC3RGBAUnormSRGB:case Ae.BC2RGBAUnorm:case Ae.BC2RGBAUnormSRGB:case Ae.BC4RUnorm:case Ae.BC4RSnorm:case Ae.BC1RGBAUnorm:case Ae.BC1RGBAUnormSRGB:case Ae.ETC2RGB8Unorm:case Ae.ETC2RGB8UnormSRGB:case Ae.ETC2RGB8A1Unorm:case Ae.ETC2RGB8A1UnormSRGB:case Ae.ETC2RGBA8Unorm:case Ae.ETC2RGBA8UnormSRGB:case Ae.EACR11Unorm:case Ae.EACR11Snorm:case Ae.EACRG11Unorm:case Ae.EACRG11Snorm:case Ae.ASTC4x4Unorm:case Ae.ASTC4x4UnormSRGB:case Ae.ASTC5x4Unorm:case Ae.ASTC5x4UnormSRGB:case Ae.ASTC5x5Unorm:case Ae.ASTC5x5UnormSRGB:case Ae.ASTC6x5Unorm:case Ae.ASTC6x5UnormSRGB:case Ae.ASTC6x6Unorm:case Ae.ASTC6x6UnormSRGB:case Ae.ASTC8x5Unorm:case Ae.ASTC8x5UnormSRGB:case Ae.ASTC8x6Unorm:case Ae.ASTC8x6UnormSRGB:case Ae.ASTC8x8Unorm:case Ae.ASTC8x8UnormSRGB:case Ae.ASTC10x5Unorm:case Ae.ASTC10x5UnormSRGB:case Ae.ASTC10x6Unorm:case Ae.ASTC10x6UnormSRGB:case Ae.ASTC10x8Unorm:case Ae.ASTC10x8UnormSRGB:case Ae.ASTC10x10Unorm:case Ae.ASTC10x10UnormSRGB:case Ae.ASTC12x10Unorm:case Ae.ASTC12x10UnormSRGB:case Ae.ASTC12x12Unorm:case Ae.ASTC12x12UnormSRGB:return 0;case Ae.R16Uint:case Ae.R16Sint:case Ae.RG16Uint:case Ae.RG16Sint:case Ae.RGBA16Uint:case Ae.RGBA16Sint:case Ae.Depth16Unorm:return 5;case Ae.R16Float:case Ae.RG16Float:case Ae.RGBA16Float:return 2;case Ae.R32Uint:case Ae.R32Sint:case Ae.RG32Uint:case Ae.RG32Sint:case Ae.RGBA32Uint:case Ae.RGBA32Sint:return 7;case Ae.R32Float:case Ae.RG32Float:case Ae.RGBA32Float:case Ae.Depth32Float:return 1;case Ae.Stencil8:throw"No fixed size for Stencil8 format!";case Ae.Depth24Plus:throw"No fixed size for Depth24Plus format!";case Ae.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0}static _GetBlockInformationFromFormat(e){switch(e){case Ae.R8Unorm:case Ae.R8Snorm:case Ae.R8Uint:case Ae.R8Sint:return{width:1,height:1,length:1};case Ae.R16Uint:case Ae.R16Sint:case Ae.R16Float:case Ae.RG8Unorm:case Ae.RG8Snorm:case Ae.RG8Uint:case Ae.RG8Sint:return{width:1,height:1,length:2};case Ae.R32Uint:case Ae.R32Sint:case Ae.R32Float:case Ae.RG16Uint:case Ae.RG16Sint:case Ae.RG16Float:case Ae.RGBA8Unorm:case Ae.RGBA8UnormSRGB:case Ae.RGBA8Snorm:case Ae.RGBA8Uint:case Ae.RGBA8Sint:case Ae.BGRA8Unorm:case Ae.BGRA8UnormSRGB:case Ae.RGB9E5UFloat:case Ae.RGB10A2Unorm:case Ae.RG11B10UFloat:return{width:1,height:1,length:4};case Ae.RG32Uint:case Ae.RG32Sint:case Ae.RG32Float:case Ae.RGBA16Uint:case Ae.RGBA16Sint:case Ae.RGBA16Float:return{width:1,height:1,length:8};case Ae.RGBA32Uint:case Ae.RGBA32Sint:case Ae.RGBA32Float:return{width:1,height:1,length:16};case Ae.Stencil8:throw"No fixed size for Stencil8 format!";case Ae.Depth16Unorm:return{width:1,height:1,length:2};case Ae.Depth24Plus:throw"No fixed size for Depth24Plus format!";case Ae.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case Ae.Depth32Float:return{width:1,height:1,length:4};case Ae.Depth24UnormStencil8:return{width:1,height:1,length:4};case Ae.Depth32FloatStencil8:return{width:1,height:1,length:5};case Ae.BC7RGBAUnorm:case Ae.BC7RGBAUnormSRGB:case Ae.BC6HRGBUFloat:case Ae.BC6HRGBFloat:case Ae.BC5RGUnorm:case Ae.BC5RGSnorm:case Ae.BC3RGBAUnorm:case Ae.BC3RGBAUnormSRGB:case Ae.BC2RGBAUnorm:case Ae.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case Ae.BC4RUnorm:case Ae.BC4RSnorm:case Ae.BC1RGBAUnorm:case Ae.BC1RGBAUnormSRGB:return{width:4,height:4,length:8};case Ae.ETC2RGB8Unorm:case Ae.ETC2RGB8UnormSRGB:case Ae.ETC2RGB8A1Unorm:case Ae.ETC2RGB8A1UnormSRGB:case Ae.EACR11Unorm:case Ae.EACR11Snorm:return{width:4,height:4,length:8};case Ae.ETC2RGBA8Unorm:case Ae.ETC2RGBA8UnormSRGB:case Ae.EACRG11Unorm:case Ae.EACRG11Snorm:return{width:4,height:4,length:16};case Ae.ASTC4x4Unorm:case Ae.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case Ae.ASTC5x4Unorm:case Ae.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case Ae.ASTC5x5Unorm:case Ae.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case Ae.ASTC6x5Unorm:case Ae.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case Ae.ASTC6x6Unorm:case Ae.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case Ae.ASTC8x5Unorm:case Ae.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case Ae.ASTC8x6Unorm:case Ae.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case Ae.ASTC8x8Unorm:case Ae.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case Ae.ASTC10x5Unorm:case Ae.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case Ae.ASTC10x6Unorm:case Ae.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case Ae.ASTC10x8Unorm:case Ae.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case Ae.ASTC10x10Unorm:case Ae.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case Ae.ASTC12x10Unorm:case Ae.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case Ae.ASTC12x12Unorm:case Ae.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}setCommandEncoder(e){this._commandEncoderForCreation=e}static IsCompressedFormat(e){switch(e){case Ae.BC7RGBAUnormSRGB:case Ae.BC7RGBAUnorm:case Ae.BC6HRGBFloat:case Ae.BC6HRGBUFloat:case Ae.BC5RGSnorm:case Ae.BC5RGUnorm:case Ae.BC4RSnorm:case Ae.BC4RUnorm:case Ae.BC3RGBAUnormSRGB:case Ae.BC3RGBAUnorm:case Ae.BC2RGBAUnormSRGB:case Ae.BC2RGBAUnorm:case Ae.BC1RGBAUnormSRGB:case Ae.BC1RGBAUnorm:case Ae.ETC2RGB8Unorm:case Ae.ETC2RGB8UnormSRGB:case Ae.ETC2RGB8A1Unorm:case Ae.ETC2RGB8A1UnormSRGB:case Ae.ETC2RGBA8Unorm:case Ae.ETC2RGBA8UnormSRGB:case Ae.EACR11Unorm:case Ae.EACR11Snorm:case Ae.EACRG11Unorm:case Ae.EACRG11Snorm:case Ae.ASTC4x4Unorm:case Ae.ASTC4x4UnormSRGB:case Ae.ASTC5x4Unorm:case Ae.ASTC5x4UnormSRGB:case Ae.ASTC5x5Unorm:case Ae.ASTC5x5UnormSRGB:case Ae.ASTC6x5Unorm:case Ae.ASTC6x5UnormSRGB:case Ae.ASTC6x6Unorm:case Ae.ASTC6x6UnormSRGB:case Ae.ASTC8x5Unorm:case Ae.ASTC8x5UnormSRGB:case Ae.ASTC8x6Unorm:case Ae.ASTC8x6UnormSRGB:case Ae.ASTC8x8Unorm:case Ae.ASTC8x8UnormSRGB:case Ae.ASTC10x5Unorm:case Ae.ASTC10x5UnormSRGB:case Ae.ASTC10x6Unorm:case Ae.ASTC10x6UnormSRGB:case Ae.ASTC10x8Unorm:case Ae.ASTC10x8UnormSRGB:case Ae.ASTC10x10Unorm:case Ae.ASTC10x10UnormSRGB:case Ae.ASTC12x10Unorm:case Ae.ASTC12x10UnormSRGB:case Ae.ASTC12x12Unorm:case Ae.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return Ae.Depth16Unorm;case 16:return Ae.Depth24Plus;case 13:return Ae.Depth24PlusStencil8;case 14:return Ae.Depth32Float;case 17:return Ae.Depth24UnormStencil8;case 18:return Ae.Depth32FloatStencil8;case 19:return Ae.Stencil8;case 36492:return i?Ae.BC7RGBAUnormSRGB:Ae.BC7RGBAUnorm;case 36495:return Ae.BC6HRGBUFloat;case 36494:return Ae.BC6HRGBFloat;case 33779:return i?Ae.BC3RGBAUnormSRGB:Ae.BC3RGBAUnorm;case 33778:return i?Ae.BC2RGBAUnormSRGB:Ae.BC2RGBAUnorm;case 33777:case 33776:return i?Ae.BC1RGBAUnormSRGB:Ae.BC1RGBAUnorm;case 37808:return i?Ae.ASTC4x4UnormSRGB:Ae.ASTC4x4Unorm;case 36196:case 37492:return i?Ae.ETC2RGB8UnormSRGB:Ae.ETC2RGB8Unorm;case 37496:return i?Ae.ETC2RGBA8UnormSRGB:Ae.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return Ae.R8Snorm;case 7:return Ae.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return Ae.R8Sint;case 9:return Ae.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return Ae.RGBA8Sint;default:return Ae.RGBA8Snorm}case 0:switch(t){case 6:return Ae.R8Unorm;case 7:return Ae.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?Ae.RGBA8UnormSRGB:Ae.RGBA8Unorm;case 12:return i?Ae.BGRA8UnormSRGB:Ae.BGRA8Unorm;case 8:return Ae.R8Uint;case 9:return Ae.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return Ae.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 Ae.RGBA8Unorm}case 4:switch(t){case 8:return Ae.R16Sint;case 9:return Ae.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return Ae.RGBA16Sint;default:return Ae.RGBA16Sint}case 5:switch(t){case 8:return Ae.R16Uint;case 9:return Ae.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return Ae.RGBA16Uint;default:return Ae.RGBA16Uint}case 6:switch(t){case 8:return Ae.R32Sint;case 9:return Ae.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return Ae.RGBA32Sint;default:return Ae.RGBA32Sint}case 7:switch(t){case 8:return Ae.R32Uint;case 9:return Ae.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return Ae.RGBA32Uint;default:return Ae.RGBA32Uint}case 1:switch(t){case 6:return Ae.R32Float;case 7:return Ae.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return Ae.RGBA32Float;default:return Ae.RGBA32Float}case 2:switch(t){case 6:return Ae.R16Float;case 7:return Ae.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return Ae.RGBA16Float;default:return Ae.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:return Ae.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return Ae.RG11B10UFloat}case 14:switch(t){case 5:return Ae.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 Ae.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 Ae.RGB10A2Unorm;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV";default:return Ae.RGB10A2Unorm}}return i?Ae.RGBA8UnormSRGB:Ae.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case Ae.R8Unorm:case Ae.R8Snorm:case Ae.R8Uint:case Ae.R8Sint:case Ae.BC4RUnorm:case Ae.BC4RSnorm:case Ae.R16Uint:case Ae.R16Sint:case Ae.Depth16Unorm:case Ae.R16Float:case Ae.R32Uint:case Ae.R32Sint:case Ae.R32Float:case Ae.Depth32Float:case Ae.Stencil8:case Ae.Depth24Plus:case Ae.EACR11Unorm:case Ae.EACR11Snorm:return 1;case Ae.RG8Unorm:case Ae.RG8Snorm:case Ae.RG8Uint:case Ae.RG8Sint:case Ae.Depth24UnormStencil8:case Ae.Depth32FloatStencil8:case Ae.BC5RGUnorm:case Ae.BC5RGSnorm:case Ae.RG16Uint:case Ae.RG16Sint:case Ae.RG16Float:case Ae.RG32Uint:case Ae.RG32Sint:case Ae.RG32Float:case Ae.Depth24PlusStencil8:case Ae.EACRG11Unorm:case Ae.EACRG11Snorm:return 2;case Ae.RGB9E5UFloat:case Ae.RG11B10UFloat:case Ae.BC6HRGBUFloat:case Ae.BC6HRGBFloat:case Ae.ETC2RGB8Unorm:case Ae.ETC2RGB8UnormSRGB:return 3;case Ae.RGBA8Unorm:case Ae.RGBA8UnormSRGB:case Ae.RGBA8Snorm:case Ae.RGBA8Uint:case Ae.RGBA8Sint:case Ae.BGRA8Unorm:case Ae.BGRA8UnormSRGB:case Ae.RGB10A2Unorm:case Ae.BC7RGBAUnorm:case Ae.BC7RGBAUnormSRGB:case Ae.BC3RGBAUnorm:case Ae.BC3RGBAUnormSRGB:case Ae.BC2RGBAUnorm:case Ae.BC2RGBAUnormSRGB:case Ae.BC1RGBAUnorm:case Ae.BC1RGBAUnormSRGB:case Ae.RGBA16Uint:case Ae.RGBA16Sint:case Ae.RGBA16Float:case Ae.RGBA32Uint:case Ae.RGBA32Sint:case Ae.RGBA32Float:case Ae.ETC2RGB8A1Unorm:case Ae.ETC2RGB8A1UnormSRGB:case Ae.ETC2RGBA8Unorm:case Ae.ETC2RGBA8UnormSRGB:case Ae.ASTC4x4Unorm:case Ae.ASTC4x4UnormSRGB:case Ae.ASTC5x4Unorm:case Ae.ASTC5x4UnormSRGB:case Ae.ASTC5x5Unorm:case Ae.ASTC5x5UnormSRGB:case Ae.ASTC6x5Unorm:case Ae.ASTC6x5UnormSRGB:case Ae.ASTC6x6Unorm:case Ae.ASTC6x6UnormSRGB:case Ae.ASTC8x5Unorm:case Ae.ASTC8x5UnormSRGB:case Ae.ASTC8x6Unorm:case Ae.ASTC8x6UnormSRGB:case Ae.ASTC8x8Unorm:case Ae.ASTC8x8UnormSRGB:case Ae.ASTC10x5Unorm:case Ae.ASTC10x5UnormSRGB:case Ae.ASTC10x6Unorm:case Ae.ASTC10x6UnormSRGB:case Ae.ASTC10x8Unorm:case Ae.ASTC10x8UnormSRGB:case Ae.ASTC10x10Unorm:case Ae.ASTC10x10UnormSRGB:case Ae.ASTC12x10Unorm:case Ae.ASTC12x10UnormSRGB:case Ae.ASTC12x12Unorm:case Ae.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case Ae.Stencil8:case Ae.Depth24UnormStencil8:case Ae.Depth32FloatStencil8:case Ae.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case Ae.Depth24UnormStencil8:case Ae.Depth32FloatStencil8:case Ae.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case Ae.Depth16Unorm:return Ae.Depth16Unorm;case Ae.Depth24Plus:return Ae.Depth24Plus;case Ae.Depth24PlusStencil8:return Ae.Depth24Plus;case Ae.Depth24UnormStencil8:return Ae.Depth24Plus;case Ae.Depth32Float:return Ae.Depth32Float;case Ae.Depth32FloatStencil8:return Ae.Depth32Float}return e}copyVideoToTexture(e,t,i,s=!1,r){var n,o,l,c;const h=r===void 0,[u,p]=this._getVideoPipeline(i,s?wN.InvertY:wN.DontInvertY);h&&(r=this._device.createCommandEncoder({})),(o=(n=r).pushDebugGroup)===null||o===void 0||o.call(n,`copy video to texture - invertY=${s}`);const _={colorAttachments:[{view:t._hardwareTexture.underlyingResource.createView({format:i,dimension:Ra.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:kb.All}),loadOp:Mh.Load,storeOp:u_.Store}]},f=r.beginRenderPass(_),d={layout:p,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},C=this._device.createBindGroup(d);f.setPipeline(u),f.setBindGroup(0,C),f.draw(4,1,0,0),f.end(),(c=(l=r).popDebugGroup)===null||c===void 0||c.call(l),h&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,o=0,l=0,c=1,h=0,u=0,p=0,m=0,_,f){var d,C,v,y,M,b;const E=p!==0,S=_===void 0,[I,D]=this._getPipeline(s,E?B5.InvertYPremultiplyAlphaWithOfst:B5.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});o=Math.max(o,0),S&&(_=this._device.createCommandEncoder({})),(C=(d=_).pushDebugGroup)===null||C===void 0||C.call(d,`internal process texture - invertY=${r} premultiplyAlpha=${n}`);let R;if(ho._IsHardwareTexture(e)?(R=e.underlyingResource,r&&!n&&c===1&&o===0||(e=void 0)):(R=e,e=void 0),!R)return;E&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,u,p,m]),0,4*4);const L=e,w=(v=L?._copyInvertYTempTexture)!==null&&v!==void 0?v:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,_,Oo.CopySrc|Oo.RenderAttachment|Oo.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),N=(y=L?._copyInvertYRenderPassDescr)!==null&&y!==void 0?y:{colorAttachments:[{view:w.createView({format:s,dimension:Ra.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Mh.Load,storeOp:u_.Store}]},V=_.beginRenderPass(N);let W=E?L?._copyInvertYBindGroupWithOfst:L?._copyInvertYBindGroup;if(!W){const G={layout:D,entries:[{binding:0,resource:R.createView({format:s,dimension:Ra.E2d,baseMipLevel:l,mipLevelCount:1,arrayLayerCount:c,baseArrayLayer:o})}]};E&&G.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),W=this._device.createBindGroup(G)}V.setPipeline(I),V.setBindGroup(0,W),V.draw(4,1,0,0),V.end(),_.copyTextureToTexture({texture:w},{texture:R,mipLevel:l,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),L?(L._copyInvertYTempTexture=w,L._copyInvertYRenderPassDescr=N,E?L._copyInvertYBindGroupWithOfst=W:L._copyInvertYBindGroup=W):this._deferredReleaseTextures.push([w,null]),(b=(M=_).popDebugGroup)===null||b===void 0||b.call(M),S&&(this._device.queue.submit([_.finish()]),_=null)}copyWithInvertY(e,t,i,s){var r,n,o,l;const c=s===void 0,[h,u]=this._getPipeline(t,B5.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});c&&(s=this._device.createCommandEncoder({})),(n=(r=s).pushDebugGroup)===null||n===void 0||n.call(r,"internal copy texture with invertY");const p=s.beginRenderPass(i),m=this._device.createBindGroup({layout:u,entries:[{binding:0,resource:e}]});p.setPipeline(h),p.setBindGroup(0,m),p.draw(4,1,0,0),p.end(),(l=(o=s).popDebugGroup)===null||l===void 0||l.call(o),c&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,o=Ae.RGBA8Unorm,l=1,c,h=-1,u=0,p){l>1&&(l=4);const m=e.layers||1,_={width:e.width,height:e.height,depthOrArrayLayers:m},f=DM[o]?Oo.RenderAttachment:0,d=ho.IsCompressedFormat(o),C=t?ho.ComputeNumMipmapLevels(e.width,e.height):1,v=h>=0?h:Oo.CopySrc|Oo.CopyDst|Oo.TextureBinding;u|=t&&!d?Oo.CopySrc|f:0,!d&&!n&&(u|=f|Oo.CopyDst);const y=this._device.createTexture({label:`Texture${n?"3D":"2D"}_${p?p+"_":""}${_.width}x${_.height}x${_.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${l}`,size:_,dimension:n?nv.E3d:nv.E2d,format:o,usage:v|u,sampleCount:l,mipLevelCount:C});return ho.IsImageBitmap(e)&&(this.updateTexture(e,y,e.width,e.height,m,o,0,0,s,r,0,0),t&&i&&this.generateMipmaps(y,o,C,0,c)),y}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=Ae.RGBA8Unorm,o=1,l,c=-1,h=0,u){o>1&&(o=4);const p=ho.IsImageBitmapArray(e)?e[0].width:e.width,m=ho.IsImageBitmapArray(e)?e[0].height:e.height,_=DM[n]?Oo.RenderAttachment:0,f=ho.IsCompressedFormat(n),d=t?ho.ComputeNumMipmapLevels(p,m):1,C=c>=0?c:Oo.CopySrc|Oo.CopyDst|Oo.TextureBinding;h|=t&&!f?Oo.CopySrc|_:0,f||(h|=_|Oo.CopyDst);const v=this._device.createTexture({label:`TextureCube_${u?u+"_":""}${p}x${m}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:p,height:m,depthOrArrayLayers:6},dimension:nv.E2d,format:n,usage:C|h,sampleCount:o,mipLevelCount:d});return ho.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,v,p,m,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(v,n,d,l)),v}generateCubeMipmaps(e,t,i,s){var r,n,o,l;const c=s===void 0;c&&(s=this._device.createCommandEncoder({})),(n=(r=s).pushDebugGroup)===null||n===void 0||n.call(r,`create cube mipmaps - ${i} levels`);for(let h=0;h<6;++h)this.generateMipmaps(e,t,i,h,s);(l=(o=s).popDebugGroup)===null||l===void 0||l.call(o),c&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r){var n,o,l,c,h,u,p,m;const _=r===void 0,[f,d]=this._getPipeline(t);s=Math.max(s,0),_&&(r=this._device.createCommandEncoder({})),(o=(n=r).pushDebugGroup)===null||o===void 0||o.call(n,`create mipmaps for face #${s} - ${i} levels`);let C;if(ho._IsHardwareTexture(e)?(C=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(C=e,e=void 0),!C)return;const v=e;for(let y=1;yh;)this._device.queue.writeBuffer(n,t+u,i.buffer,o+u,h),u+=h;this._device.queue.writeBuffer(n,t+u,i.buffer,o+u,r-u)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=Pb(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,o=0,l=0,c=null,h=!0,u=!1){const p=o===1?2:o===2?1:0;return new Promise((m,_)=>{e.mapAsync(OL.Read,l,t).then(()=>{const f=e.getMappedRange(l,t);let d=c;if(u)d===null?d=lX(o,t,!0,f):d=lX(o,d.buffer,void 0,f);else if(d===null)switch(p){case 0:d=new Uint8Array(t),d.set(new Uint8Array(f));break;case 1:d=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,f);break;case 2:d=new Float32Array(t/4),d.set(new Float32Array(f));break}else switch(p){case 0:d=new Uint8Array(d.buffer),d.set(new Uint8Array(f));break;case 1:d=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,f,c);break;case 2:d=new Float32Array(d.buffer),d.set(new Float32Array(f));break}if(r!==n){p===1&&!u&&(r*=2,n*=2);const C=new Uint8Array(d.buffer);let v=r,y=0;for(let M=1;M_(f))})}releaseBuffer(e){return Nee._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 V6e[e.samplingMode]+z6e[(e._comparisonFunction||514)-512+1]+U6e[e.samplingMode]+(((t=e._cachedWrapU)!==null&&t!==void 0?t:1)<<8)+(((i=e._cachedWrapV)!==null&&i!==void 0?i:1)<<10)+(((s=e._cachedWrapR)!==null&&s!==void 0?s:1)<<12)+((e.useMipMaps?1:0)<<14)+(r<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,r,n,o;const l=e.useMipMaps;switch(e.samplingMode){case 11:i=Qr.Linear,s=Qr.Linear,r=Qr.Nearest,l||(n=o=0);break;case 3:case 3:i=Qr.Linear,s=Qr.Linear,l?r=Qr.Linear:(r=Qr.Nearest,n=o=0);break;case 8:i=Qr.Nearest,s=Qr.Nearest,l?r=Qr.Linear:(r=Qr.Nearest,n=o=0);break;case 4:i=Qr.Nearest,s=Qr.Nearest,r=Qr.Nearest,l||(n=o=0);break;case 5:i=Qr.Nearest,s=Qr.Linear,r=Qr.Nearest,l||(n=o=0);break;case 6:i=Qr.Nearest,s=Qr.Linear,l?r=Qr.Linear:(r=Qr.Nearest,n=o=0);break;case 7:i=Qr.Nearest,s=Qr.Linear,r=Qr.Nearest,n=o=0;break;case 1:case 1:i=Qr.Nearest,s=Qr.Nearest,r=Qr.Nearest,n=o=0;break;case 9:i=Qr.Linear,s=Qr.Nearest,r=Qr.Nearest,l||(n=o=0);break;case 10:i=Qr.Linear,s=Qr.Nearest,l?r=Qr.Linear:(r=Qr.Nearest,n=o=0);break;case 2:case 2:i=Qr.Linear,s=Qr.Linear,r=Qr.Nearest,n=o=0;break;case 12:i=Qr.Linear,s=Qr.Nearest,r=Qr.Nearest,n=o=0;break;default:i=Qr.Nearest,s=Qr.Nearest,r=Qr.Nearest,n=o=0;break}return t>1&&(n!==0||o!==0)?{magFilter:Qr.Linear,minFilter:Qr.Linear,mipmapFilter:Qr.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return vP.Repeat;case 0:return vP.ClampToEdge;case 2:return vP.MirrorRepeat}return vP.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e){const t=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,i=this._GetSamplerFilterDescriptor(e,t);return Object.assign(Object.assign(Object.assign({},i),this._GetSamplerWrappingDescriptor(e)),{compare:e._comparisonFunction?bL.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:i.anisotropyEnabled?t:1})}static GetCompareFunction(e){switch(e){case 519:return Fu.Always;case 514:return Fu.Equal;case 516:return Fu.Greater;case 518:return Fu.GreaterEqual;case 513:return Fu.Less;case 515:return Fu.LessEqual;case 512:return Fu.Never;case 517:return Fu.NotEqual;default:return Fu.Less}}getSampler(e,t=!1,i=0){if(this.disabled)return this._device.createSampler(bL._GetSamplerDescriptor(e));t?i=0:i===0&&(i=bL.GetSamplerHashCode(e));let s=t?void 0:this._samplers[i];return s||(s=this._device.createSampler(bL._GetSamplerDescriptor(e)),t||(this._samplers[i]=s)),s}}var bc;(function(a){a[a.StencilReadMask=0]="StencilReadMask",a[a.StencilWriteMask=1]="StencilWriteMask",a[a.DepthBias=2]="DepthBias",a[a.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",a[a.DepthStencilState=4]="DepthStencilState",a[a.MRTAttachments1=5]="MRTAttachments1",a[a.MRTAttachments2=6]="MRTAttachments2",a[a.RasterizationState=7]="RasterizationState",a[a.ColorStates=8]="ColorStates",a[a.ShaderStage=9]="ShaderStage",a[a.TextureStage=10]="TextureStage",a[a.VertexState=11]="VertexState",a[a.NumStates=12]="NumStates"})(bc||(bc={}));const dY={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},pN={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class Jo{constructor(e,t,i){this.mrtTextureCount=0,this._device=e,this._useTextureStage=i,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=[Ae.BGRA8Unorm],this.setColorFormat(Ae.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(Ae.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,s=0){if(i>1&&(i=4),this.disabled){const n=Jo._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,n,i),Jo.NumCacheMiss++,Jo._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,Jo.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return Jo.NumCacheHitWithHash++,this._parameter.pipeline;const r=Jo._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),Jo.NumCacheMiss++,Jo._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){Jo.NumPipelineCreationLastFrame=Jo._NumPipelineCreationCurrentFrame,Jo._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,s,r,n,o,l){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(l??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(r)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[bc.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,bc.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[bc.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,bc.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=DM[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 r=[0,0];let n=0,o=0,l=0;for(let c=0;c=32&&(o=0,n++)}this._mrtFormats.length=l,(this._mrtAttachments1!==r[0]||this._mrtAttachments2!==r[1])&&(this._mrtAttachments1=r[0],this._mrtAttachments2=r[1],this._states[bc.MRTAttachments1]=r[0],this._states[bc.MRTAttachments2]=r[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,bc.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:DM[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:pN[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:pN[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:pN[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[bc.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,bc.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[bc.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,bc.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=i===null?1:pN[i],this._stencilFrontPassOp=s===null?2:pN[s],this._stencilFrontFailOp=r===null?1:pN[r],this.setStencilReadMask(n),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:return K3.TriangleList;case 2:return K3.PointList;case 1:return K3.LineList;case 3:return K3.PointList;case 4:return K3.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return K3.LineStrip;case 7:return K3.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return K3.TriangleList}}static _GetAphaBlendOperation(e){switch(e){case 32774:return j9.Add;case 32778:return j9.Subtract;case 32779:return j9.ReverseSubtract;case 32775:return j9.Min;case 32776:return j9.Max;default:return j9.Add}}static _GetAphaBlendFactor(e){switch(e){case 0:return j1.Zero;case 1:return j1.One;case 768:return j1.Src;case 769:return j1.OneMinusSrc;case 770:return j1.SrcAlpha;case 771:return j1.OneMinusSrcAlpha;case 772:return j1.DstAlpha;case 773:return j1.OneMinusDstAlpha;case 774:return j1.Dst;case 775:return j1.OneMinusDst;case 776:return j1.SrcAlphaSaturated;case 32769:return j1.Constant;case 32770:return j1.OneMinusConstant;case 32771:return j1.Constant;case 32772:return j1.OneMinusConstant;default:return j1.One}}static _GetCompareFunction(e){switch(e){case 0:return Fu.Never;case 1:return Fu.Less;case 2:return Fu.Equal;case 3:return Fu.LessEqual;case 4:return Fu.Greater;case 5:return Fu.NotEqual;case 6:return Fu.GreaterEqual;case 7:return Fu.Always}return Fu.Never}static _GetStencilOpFunction(e){switch(e){case 0:return z5.Zero;case 1:return z5.Keep;case 2:return z5.Replace;case 3:return z5.IncrementClamp;case 4:return z5.DecrementClamp;case 5:return z5.Invert;case 6:return z5.IncrementWrap;case 7:return z5.DecrementWrap}return z5.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case se.BYTE:switch(s){case 1:case 2:return i?Zo.Snorm8x2:Zo.Sint8x2;case 3:case 4:return i?Zo.Snorm8x4:Zo.Sint8x4}break;case se.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?Zo.Unorm8x2:Zo.Uint8x2;case 3:case 4:return i?Zo.Unorm8x4:Zo.Uint8x4}break;case se.SHORT:switch(s){case 1:case 2:return i?Zo.Snorm16x2:Zo.Sint16x2;case 3:case 4:return i?Zo.Snorm16x4:Zo.Sint16x4}break;case se.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?Zo.Unorm16x2:Zo.Uint16x2;case 3:case 4:return i?Zo.Unorm16x4:Zo.Uint16x4}break;case se.INT:switch(s){case 1:return Zo.Sint32;case 2:return Zo.Sint32x2;case 3:return Zo.Sint32x3;case 4:return Zo.Sint32x4}break;case se.UNSIGNED_INT:switch(s){case 1:return Zo.Uint32;case 2:return Zo.Uint32x2;case 3:return Zo.Uint32x3;case 4:return Zo.Uint32x4}break;case se.FLOAT:switch(s){case 1:return Zo.Float32;case 2:return Zo.Float32x2;case 3:return Zo.Float32x3;case 4:return Zo.Float32x4}break}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:Jo._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:Jo._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:Jo._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:Jo._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:Jo._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:Jo._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[bc.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,bc.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace,s=this._cullEnabled?this._cullFace:0,r=this._clampDepth?1:0,n=this._alphaToCoverageEnabled?1:0,o=i-1+(s<<1)+(r<<3)+(n<<4)+(e<<5)+(t<<8);this._rasterizationState!==o&&(this._rasterizationState=o,this._states[bc.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,bc.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:dY[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:dY[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:dY[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:dY[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[bc.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,bc.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[bc.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,bc.DepthStencilState))}_setVertexState(e){var t,i;const s=this._statesLength;let r=bc.VertexState;const n=e._pipelineContext,o=n.shaderProcessingContext.attributeNamesFromEffect,l=n.shaderProcessingContext.attributeLocationsFromEffect;let c,h=0;for(let u=0;u0)for(let d=0;d=this._video.HAVE_CURRENT_DATA}dispose(){}}class $K{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatTextures(){return this._numFloatTextures>0}constructor(){this.uniqueId=$K._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?bL.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){var i,s,r;let n=this.textures[e],o=-1;n?o=(s=(i=n.texture)===null||i===void 0?void 0:i.uniqueId)!==null&&s!==void 0?s:-1:this.textures[e]=n={texture:t,isFloatTexture:!1,isExternalTexture:!1},n.isExternalTexture&&this._numExternalTextures--,n.isFloatTexture&&this._numFloatTextures--,t?(n.isFloatTexture=t.type===1,n.isExternalTexture=Bee.IsExternalTexture(t),n.isFloatTexture&&this._numFloatTextures++,n.isExternalTexture&&this._numExternalTextures++):(n.isFloatTexture=!1,n.isExternalTexture=!1),n.texture=t;const l=o!==((r=t?.uniqueId)!==null&&r!==void 0?r:-1);l&&this.updateId++,this.isDirty||(this.isDirty=l)}}$K._Counter=0;class xW{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,Pa.CopyDst|Pa.Indirect|Pa.Storage),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=xW._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?.uniqueId!==((i=this.buffers[e])===null||i===void 0?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}}xW._Counter=0;class VY{constructor(){this.values={}}}class Il{static get Statistics(){return{totalCreated:Il.NumBindGroupsCreatedTotal,lastFrameCreated:Il.NumBindGroupsCreatedLastFrame,lookupLastFrame:Il.NumBindGroupsLookupLastFrame,noLookupLastFrame:Il.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Il.NumBindGroupsCreatedLastFrame=Il._NumBindGroupsCreatedCurrentFrame,Il.NumBindGroupsLookupLastFrame=Il._NumBindGroupsLookupCurrentFrame,Il.NumBindGroupsNoLookupLastFrame=Il._NumBindGroupsNoLookupCurrentFrame,Il._NumBindGroupsCreatedCurrentFrame=0,Il._NumBindGroupsLookupCurrentFrame=0,Il._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var s,r,n,o,l,c,h,u,p,m;let _,f=Il._Cache;const d=this.disabled||i.forceBindGroupCreation;if(!d){if(!t.isDirty(i.updateId)&&!i.isDirty)return Il._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const v of e.shaderProcessingContext.bufferNames){const y=(r=(s=t.buffers[v])===null||s===void 0?void 0:s.uniqueId)!==null&&r!==void 0?r:0;let M=f.values[y];M||(M=new VY,f.values[y]=M),f=M}for(const v of e.shaderProcessingContext.samplerNames){const y=(o=(n=i.samplers[v])===null||n===void 0?void 0:n.hashCode)!==null&&o!==void 0?o:0;let M=f.values[y];M||(M=new VY,f.values[y]=M),f=M}for(const v of e.shaderProcessingContext.textureNames){const y=(h=(c=(l=i.textures[v])===null||l===void 0?void 0:l.texture)===null||c===void 0?void 0:c.uniqueId)!==null&&h!==void 0?h:0;let M=f.values[y];M||(M=new VY,f.values[y]=M),f=M}_=f.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,_)return t.bindGroups=_,Il._NumBindGroupsLookupCurrentFrame++,_;_=[],t.bindGroups=_,d||(f.bindGroups=_),Il.NumBindGroupsCreatedTotal++,Il._NumBindGroupsCreatedCurrentFrame++;const C=e.bindGroupLayouts[i.textureState];for(let v=0;vw==="texture"?"":N)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}M[E].resource=this._cacheSampler.getSampler(L,!1,R.hashCode)}else Me.Error(`Sampler "${D}" could not be bound. entry=${JSON.stringify(S)}, materialContext=${JSON.stringify(i,(L,w)=>L==="texture"||L==="sampler"?"":w)}`,50)}else if(S.texture||S.storageTexture){const R=i.textures[D];if(R){if(this._engine.dbgSanityChecks&&R.texture===null){Me.Error(`Trying to bind a null texture! entry=${JSON.stringify(S)}, bindingInfo=${JSON.stringify(R,(w,N)=>w==="texture"?"":N)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const L=R.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!L||S.texture&&!L.view||S.storageTexture&&!L.viewForWriting)){Me.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(S)}, name=${D}, bindingInfo=${JSON.stringify(R,(w,N)=>w==="texture"?"":N)}, isReady=${(p=R.texture)===null||p===void 0?void 0:p.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}M[E].resource=S.storageTexture?L.viewForWriting:L.view}else Me.Error(`Texture "${D}" could not be bound. entry=${JSON.stringify(S)}, materialContext=${JSON.stringify(i,(L,w)=>L==="texture"||L==="sampler"?"":w)}`,50)}else if(S.externalTexture){const R=i.textures[D];if(R){if(this._engine.dbgSanityChecks&&R.texture===null){Me.Error(`Trying to bind a null external texture! entry=${JSON.stringify(S)}, name=${D}, bindingInfo=${JSON.stringify(R,(w,N)=>w==="texture"?"":N)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const L=R.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!L){Me.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(S)}, name=${D}, bindingInfo=${JSON.stringify(R,(w,N)=>w==="texture"?"":N)}, isReady=${(m=R.texture)===null||m===void 0?void 0:m.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}M[E].resource=this._device.importExternalTexture({source:L})}else Me.Error(`Texture "${D}" could not be bound. entry=${JSON.stringify(S)}, materialContext=${JSON.stringify(i,(L,w)=>L==="texture"||L==="sampler"?"":w)}`,50)}else if(S.buffer){const R=t.buffers[D];if(R){const L=R.underlyingResource;M[E].resource.buffer=L,M[E].resource.size=R.capacity}else Me.Error(`Can't find buffer "${D}". entry=${JSON.stringify(S)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const b=C[v];_[v]=this._device.createBindGroup({layout:b,entries:M})}return _}}Il.NumBindGroupsCreatedTotal=0;Il.NumBindGroupsCreatedLastFrame=0;Il.NumBindGroupsLookupLastFrame=0;Il.NumBindGroupsNoLookupLastFrame=0;Il._Cache=new VY;Il._NumBindGroupsCreatedCurrentFrame=0;Il._NumBindGroupsLookupCurrentFrame=0;Il._NumBindGroupsNoLookupCurrentFrame=0;const j6e="clearQuadVertexShader",G6e=`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 +} +`;Ue.ShadersStore[j6e]=G6e;const W6e="clearQuadPixelShader",Y6e=`uniform vec4 color;void main() {gl_FragColor=color;} +`;Ue.ShadersStore[W6e]=Y6e;class X6e{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 OM(this._device,i,!t._caps.textureFloatLinearFiltering),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"])}clear(e,t,i,s,r=1){var n,o;let l,c=null,h;const u=!!this._engine._currentRenderTarget;if(e)l=e;else{let v=0;this._keyTemp.length=0;for(let M=0;M1?2**36:0)+y*2**37,h=this._keyTemp.join("_"),c=this._bundleCache[h],c)return c;l=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:r})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&ho.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const p=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),m=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),m.uniformBuffer.update();const _=u?this._engine._ubInvertY:this._engine._ubDontInvertY,f=m.uniformBuffer.getBuffer(),d=f.uniqueId+"-"+_.uniqueId;let C=this._bindGroups[d];if(!C){const v=m.bindGroupLayouts[0];C=this._bindGroups[d]=[],C.push(this._device.createBindGroup({layout:v[0],entries:[]})),av._SimplifiedKnownBindings||C.push(this._device.createBindGroup({layout:v[1],entries:[]})),C.push(this._device.createBindGroup({layout:v[av._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:_.underlyingResource,size:_.capacity}},{binding:1,resource:{buffer:f.underlyingResource,size:f.capacity}}]}))}l.setPipeline(p);for(let v=0;v{t!==null&&t>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(t,!0)),this._measureDurationState=0}))}}class Q6e{constructor(e,t){this._querySet=new Yce(2,jj.Timestamp,e,t)}start(e){e.writeTimestamp(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp(this._querySet.querySet,1),this._querySet.readTwoValuesAndSubtract(0)}dispose(){this._querySet.dispose()}}class Z6e{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;let t=!1;switch(this._engine._getCurrentRenderPassIndex()){case 0:{t=this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet!==void 0;break}case 1:{t=this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet!==void 0;break}}return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,s=50,r=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=r,this._allocateNewIndices(s)}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===void 0||e.dispose(),this._availableIndices.length=0}}class m_{async initTwgsl(e){if(!m_._twgsl)return e=e||{},e=Object.assign(Object.assign({},m_._TWgslDefaultOptions),e),e.twgsl?(m_._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&(ql()?await Be.LoadScriptAsync(e.jsPath):importScripts(e.jsPath)),self.twgsl?(m_._twgsl=await self.twgsl(e.wasmPath),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=m_._twgsl.convertSpirV2WGSL(e);return m_.ShowWGSLShaderCode&&(console.log(i),console.log("***********************************************")),m_.DisableUniformityAnalysis||t?`diagnostic(off, derivative_uniformity); +`+i:i}}m_._TWgslDefaultOptions={jsPath:"https://preview.babylonjs.com/twgsl/twgsl.js",wasmPath:"https://preview.babylonjs.com/twgsl/twgsl.wasm"};m_.ShowWGSLShaderCode=!1;m_.DisableUniformityAnalysis=!1;m_._twgsl=null;class q6e{constructor(e,t,i,s){this._record=!1,this._play=!1,this._mainPassBundleList=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i,this._bundleListRenderTarget=s}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._mainPassBundleList.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}endMainRenderPass(){this._record&&this._mainPassBundleList.push(this._bundleList.clone())}endRenderTargetPass(e,t){var i,s,r,n;if(this._play)(s=(i=t._bundleLists)===null||i===void 0?void 0:i[t._currentLayer])===null||s===void 0||s.run(e),this._mode===1&&this._engine._reportDrawCall((n=(r=t._bundleLists)===null||r===void 0?void 0:r[t._currentLayer])===null||n===void 0?void 0:n.numDrawCalls);else if(this._record)t._bundleLists||(t._bundleLists=[]),t._bundleLists[t._currentLayer]=this._bundleListRenderTarget.clone(),t._bundleLists[t._currentLayer].run(e),this._bundleListRenderTarget.reset();else return!1;return!0}endFrame(e){if(this._record&&(this._mainPassBundleList.push(this._bundleList.clone()),this._record=!1,this._play=!0,this._mode=this._modeSaved),e!==null&&this._play)for(let t=0;t;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 +} +`;Ue.ShadersStoreWGSL[J6e]=$6e;const Wse={label:"TextureView_SwapChain_ResolveTarget",dimension:nv.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Yse={label:"TextureView_SwapChain",dimension:nv.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},fY="/* disable_uniformity_analysis */",eve=new Zt;class Xs extends He{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 Me.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 currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Xs(e,t);return new Promise(s=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>s(i))})}constructor(e,t={}){var i,s;if(super(null,(i=t.antialias)!==null&&i!==void 0?i:!0,t),this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._renderTargetEncoderDescriptor={label:"renderTarget"},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._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,null],this._currentRenderPass=null,this._mainRenderPassWrapper=new Gse,this._rttRenderPassWrapper=new Gse,this._pendingDebugCommands=[],this._onAfterUnbindFrameBufferObservable=new Se,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},{x:0,y:0,w:0,h:0}],this._scissorsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=[-1,-1],this._blendColorsCurrent=[[null,null,null,null],[null,null,null,null]],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=(s=t.enableGPUDebugMarkers)!==null&&s!==void 0?s:!1,Me.Log(`Babylon.js v${He.Version} - ${this.description} engine`),!navigator.gpu){Me.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(e),this._shaderProcessor=new Wge,this._shaderProcessorWGSL=new S6e}initAsync(e,t){var i;return this._initGlslang(e??((i=this._options)===null||i===void 0?void 0:i.glslangOptions)).then(s=>{var r;return this._glslang=s,this._tintWASM=Xs.UseTWGSL?new m_:null,this._tintWASM?this._tintWASM.initTwgsl(t??((r=this._options)===null||r===void 0?void 0:r.twgslOptions)).then(()=>navigator.gpu.requestAdapter(this._options),n=>{throw Me.Error("Can not initialize twgsl!"),Me.Error(n),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},s=>{throw Me.Error("Can not initialize glslang!"),Me.Error(s),Error("WebGPU initializations stopped.")}).then(s=>{var r,n,o;if(s){this._adapter=s,this._adapterSupportedExtensions=[],(r=this._adapter.features)===null||r===void 0||r.forEach(h=>this._adapterSupportedExtensions.push(h)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(h=>{this._adapterInfo=h});const l=(n=this._options.deviceDescriptor)!==null&&n!==void 0?n:{},c=(o=l?.requiredFeatures)!==null&&o!==void 0?o:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(c){const h=c,u=[];for(const p of h)this._adapterSupportedExtensions.indexOf(p)!==-1&&u.push(p);l.requiredFeatures=u}if(this._options.setMaximumLimits&&!l.requiredLimits){l.requiredLimits={};for(const h in this._adapterSupportedLimits)l.requiredLimits[h]=this._adapterSupportedLimits[h]}return this._adapter.requestDevice(l)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(s=>{var r,n;this._device=s,this._deviceEnabledExtensions=[],(r=this._device.features)===null||r===void 0||r.forEach(l=>this._deviceEnabledExtensions.push(l)),this._deviceLimits=s.limits;let o=-1;this._device.addEventListener("uncapturederror",l=>{++o{this._isDisposed||(this._contextWasLost=!0,Me.Warn("WebGPU context lost. "+l),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(this.initAsync.bind(this)))})},s=>{Me.Error("Could not retrieve a WebGPU device."),Me.Error(s)}).then(()=>{this._bufferManager=new Nee(this._device),this._textureHelper=new ho(this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new bL(this._device),this._cacheBindGroups=new Il(this._device,this._cacheSampler,this),this._timestampQuery=new K6e(this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Z6e(this,this._device,this._bufferManager):void 0,this._bundleList=new vX(this._device),this._bundleListRenderTarget=new vX(this._device),this._snapshotRendering=new q6e(this,this._snapshotRenderingMode,this._bundleList,this._bundleListRenderTarget),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),Pa.Uniform|Pa.CopyDst),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),Pa.Uniform|Pa.CopyDst),this.dbgVerboseLogsForFirstFrames&&this._count===void 0&&(this._count=0,console.log("%c frame #"+this._count+" - begin","background: #ffff00")),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._emptyVertexBuffer=new se(this,[0],"",!1,!1,1,!1,0,1),this._initializeLimits(),this._cacheRenderPipeline=new OM(this._device,this._emptyVertexBuffer,!this._caps.textureFloatLinearFiltering),this._depthCullingState=new H6e(this._cacheRenderPipeline),this._stencilStateComposer=new k6e(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 X6e(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(s=>{Me.Error("Can not create WebGPU Device and/or context."),Me.Error(s),console.trace&&console.trace()})}_initGlslang(e){return e=e||{},e=Object.assign(Object.assign({},Xs._GLSLslangDefaultOptions),e),e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?ql()?Be.LoadScriptAsync(e.jsPath).then(()=>self.glslang(e.wasmPath)):(importScripts(e.jsPath),self.glslang(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(IM.TextureCompressionASTC)>=0?!0:void 0,s3tc:this._deviceEnabledExtensions.indexOf(IM.TextureCompressionBC)>=0?!0:void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(IM.TextureCompressionETC2)>=0?!0:void 0,bptc:this._deviceEnabledExtensions.indexOf(IM.TextureCompressionBC)>=0?!0:void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(IM.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(IM.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._caps.parallelShaderCompile=null,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,_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 FY],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(!1),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 r={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:nv.E2d,format:this._options.swapChainFormat,usage:Oo.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(r),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:nv.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Zt(0,0,0,1),loadOp:Mh.Clear,storeOp:u_.Store}]}else t=[{view:void 0,clearValue:new Zt(0,0,0,1),loadOp:Mh.Clear,storeOp:u_.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?Ae.Depth24PlusStencil8:Ae.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:nv.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:Oo.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:nv.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Mh.Clear,depthStoreOp:u_.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Mh.Clear:void 0,stencilStoreOp:this.isStencilEnable?u_.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:Oo.RenderAttachment|Oo.CopySrc,alphaMode:this.premultipliedAlpha?Gj.Premultiplied:Gj.Opaque})}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,r=t.indexOf(fY)>=0,n=i===Ao.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===Ao.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,s,r)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=e.indexOf(fY)>=0,n=t.indexOf(fY)>=0,o=`#version 450 +`,l=s===Ao.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),c=s===Ao.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(l,c,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new uI(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new Hge(e,this)}createMaterialContext(){return new $K}createDrawContext(){return new xW(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,o,l){const c=e,h=c.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(l),console.log(t),console.log(i),console.log("***********************************************")),c.sources={fragment:i,vertex:t,rawVertex:r,rawFragment:n},s?c.stages=this._compileRawPipelineStageDescriptor(t,i,h):c.stages=this._compilePipelineStageDescriptor(t,i,l,h)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let r=0;r0,c._cachedWrapU=0,c._cachedWrapV=0,c._useSRGBBuffer=l.useSRGBBuffer,c.label=l.label,this._internalTexturesCache.push(c),i||this._textureHelper.createGPUTextureForInternalTexture(c,h,u,p||1,l.creationFlags),c}createTexture(e,t,i,s,r=3,n=null,o=null,l=null,c=null,h=null,u=null,p,m,_,f){return this._createTextureBase(e,t,i,s,r,n,o,(d,C,v,y,M,b,E,S)=>{var I;const D=y;if(d.baseWidth=D.width,d.baseHeight=D.height,d.width=D.width,d.height=D.height,d.format=h??5,d.type=0,S(d.width,d.height,D,C,d,()=>{}),!((I=d._hardwareTexture)===null||I===void 0)&&I.underlyingResource)!b&&!E&&this._generateMipmaps(d,this._uploadEncoder);else{const R=this._textureHelper.createGPUTextureForInternalTexture(d,D.width,D.height,void 0,_);ho.IsImageBitmap(D)&&(this._textureHelper.updateTexture(D,d,D.width,D.height,d.depth,R.format,0,0,M,!1,0,0),!b&&!E&&this._generateMipmaps(d,this._uploadEncoder))}v&&v.removePendingData(d),d.isReady=!0,d.onLoadedObservable.notifyObservers(d),d.onLoadedObservable.clear()},()=>!1,l,c,h,u,p,m,f)}wrapWebGPUTexture(e){const t=new FY(e),i=new dn(this,hr.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===void 0)&&t.underlyingResource||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e,e.source===hr.RenderTarget||e.source===hr.MultiRenderTarget?this._renderTargetEncoder:void 0))}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,s=null){t!==null&&(e._cachedWrapU=t),i!==null&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,i,s=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===s)return;const r=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,r)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const r=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),r&&r.autoBindSampler){const n=i+el.AutoSamplerSuffix;this._currentMaterialContext.setSampler(n,t)}}}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let r=0;r0;for(const r in e){const n=e[r],o=i[r],l=o.group,c=o.binding,h=n.type,u=n.object;let p=n.indexInGroupEntries,m=this._bindGroupEntries[l];switch(m||(m=this._bindGroupEntries[l]=[]),h){case go.Sampler:{const _=u;p!==void 0&&s?m[p].resource=this._cacheSampler.getSampler(_):(n.indexInGroupEntries=m.length,m.push({binding:c,resource:this._cacheSampler.getSampler(_)}));break}case go.Texture:case go.TextureWithoutSampler:{const _=u,f=_._texture._hardwareTexture;p!==void 0&&s?(h===go.Texture&&(m[p++].resource=this._cacheSampler.getSampler(_._texture)),m[p].resource=f.view):(n.indexInGroupEntries=m.length,h===go.Texture&&m.push({binding:c-1,resource:this._cacheSampler.getSampler(_._texture)}),m.push({binding:c,resource:f.view}));break}case go.StorageTexture:{const _=u,f=_._texture._hardwareTexture;(f.textureAdditionalUsages&Oo.StorageBinding)===0&&Me.Error(`computeDispatch: The texture (name=${_.name}, uniqueId=${_.uniqueId}) is not a storage texture!`,50),p!==void 0&&s?m[p].resource=f.viewForWriting:(n.indexInGroupEntries=m.length,m.push({binding:c,resource:f.viewForWriting}));break}case go.ExternalTexture:{const f=u.underlyingResource;p!==void 0&&s?m[p].resource=this._device.importExternalTexture({source:f}):(n.indexInGroupEntries=m.length,m.push({binding:c,resource:this._device.importExternalTexture({source:f})}));break}case go.UniformBuffer:case go.StorageBuffer:{const f=(h===go.UniformBuffer,u).getBuffer(),d=f.underlyingResource;p!==void 0&&s?(m[p].resource.buffer=d,m[p].resource.size=f.capacity):(n.indexInGroupEntries=m.length,m.push({binding:c,resource:{buffer:d,offset:0,size:f.capacity}}));break}}}for(let r=0;r{this.computeDispatch(a,e,t,i,s,r,n)});return}const o=a._pipelineContext,l=e;o.computePipeline||(o.computePipeline=this._device.createComputePipeline({layout:kB.Auto,compute:o.stage}));const h=this._renderTargetEncoder.beginComputePass();h.setPipeline(o.computePipeline);const u=l.getBindGroups(t,o.computePipeline,n);for(let p=0;p{const f=_,d=f[0].width,C=d;this._setCubeMapTextureParams(m,!i),m.format=n??-1;const v=this._textureHelper.createGPUTextureForInternalTexture(m,d,C);this._textureHelper.updateCubeTextures(f,v.underlyingResource,d,C,v.format,!1,!1,0,0),i||this._generateMipmaps(m,this._uploadEncoder),m.isReady=!0,m.onLoadedObservable.notifyObservers(m),m.onLoadedObservable.clear(),s&&s()},!!p)};Xs.prototype._setCubeMapTextureParams=function(a,e,t){a.samplingMode=e?3:2,a._cachedWrapU=0,a._cachedWrapV=0,t&&(a._maxLodLevel=t)};Xs.prototype._debugPushGroup=function(a,e){!this._options.enableGPUDebugMarkers||(e===0||e===1?(e===0?this._renderEncoder:this._renderTargetEncoder).pushDebugGroup(a):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(a):this._pendingDebugCommands.push(["push",a]))};Xs.prototype._debugPopGroup=function(a){!this._options.enableGPUDebugMarkers||(a===0||a===1?(a===0?this._renderEncoder:this._renderTargetEncoder).popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))};Xs.prototype._debugInsertMarker=function(a,e){!this._options.enableGPUDebugMarkers||(e===0||e===1?(e===0?this._renderEncoder:this._renderTargetEncoder).insertDebugMarker(a):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(a):this._pendingDebugCommands.push(["insert",a]))};Xs.prototype._debugFlushPendingCommands=function(){for(let a=0;a{e?.removePendingData(p),c&&f&&c(f.status+" "+f.statusText,d)},_=f=>{const d=p.width,C=n(f);if(!C)return;const v=[0,2,4,1,3,5];if(o){const y=i===4,M=o(C),b=p._hardwareTexture,E=[0,1,2,3,4,5];for(let S=0;S>S,D=[];for(let R=0;R<6;R++){let L=M[S][E[R]];y&&(L=bW(L,I,I,s)),D.push(new Uint8Array(L.buffer,L.byteOffset,L.byteLength))}this._textureHelper.updateCubeTextures(D,b.underlyingResource,I,I,b.format,u,!1,0,0)}}else{const y=[];for(let M=0;M<6;M++)y.push(C[v[M]]);this.updateRawCubeTexture(p,y,i,s,u)}p.isReady=!0,e?.removePendingData(p),l&&l()};return this._loadFile(a,f=>{_(f)},void 0,e?.offlineProvider,!0,m),p};Xs.prototype.createRawTexture3D=function(a,e,t,i,s,r,n,o,l=null,c=0,h=0){const u=hr.Raw3D,p=new dn(this,u);return p.baseWidth=e,p.baseHeight=t,p.baseDepth=i,p.width=e,p.height=t,p.depth=i,p.format=s,p.type=c,p.generateMipMaps=r,p.samplingMode=o,p.is3D=!0,this._doNotHandleContextLost||(p._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(p,e,t,void 0,h),this.updateRawTexture3D(p,a,s,n,l,c),this._internalTexturesCache.push(p),p};Xs.prototype.updateRawTexture3D=function(a,e,t,i,s=null,r=0){if(this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.invertY=i,a._compression=s),e){const n=a._hardwareTexture;t===4&&(e=bW(e,a.width,a.height,r));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,a,a.width,a.height,a.depth,n.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};Xs.prototype.createRawTexture2DArray=function(a,e,t,i,s,r,n,o,l=null,c=0,h=0){const u=hr.Raw2DArray,p=new dn(this,u);return p.baseWidth=e,p.baseHeight=t,p.baseDepth=i,p.width=e,p.height=t,p.depth=i,p.format=s,p.type=c,p.generateMipMaps=r,p.samplingMode=o,p.is2DArray=!0,this._doNotHandleContextLost||(p._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(p,e,t,i,h),this.updateRawTexture2DArray(p,a,s,n,l,c),this._internalTexturesCache.push(p),p};Xs.prototype.updateRawTexture2DArray=function(a,e,t,i,s=null,r=0){if(this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.invertY=i,a._compression=s),e){const n=a._hardwareTexture;t===4&&(e=bW(e,a.width,a.height,r));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,a,a.width,a.height,a.depth,n.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};function bW(a,e,t,i){let s,r=1;i===1?s=new Float32Array(e*t*4):i===2?(s=new Uint16Array(e*t*4),r=15360):i===7?s=new Uint32Array(e*t*4):s=new Uint8Array(e*t*4);for(let n=0;n0,a.depth=l,a.isReady=!0,a.samples=r,a.generateMipMaps=!1,a.samplingMode=i?2:1,a.type=1,a._comparisonFunction=s,a._cachedWrapU=0,a._cachedWrapV=0};Xs.prototype.updateRenderTargetTextureSampleCount=function(a,e){return!a||!a.texture||a.samples===e||(e=Math.min(e,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(a.texture,e),a._depthStencilTexture&&(this._textureHelper.createMSAATexture(a._depthStencilTexture,e),a._depthStencilTexture.samples=e),a._samples=e,a.texture.samples=e),e};Xs.prototype.createRenderTargetCubeTexture=function(a,e){var t;const i=this._createHardwareRenderTargetWrapper(!1,!0,a),s=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},e);s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,i.label=(t=s.label)!==null&&t!==void 0?t:"RenderTargetWrapper",i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer;const r=new dn(this,hr.RenderTarget);return r.width=a,r.height=a,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=s.samples,r.generateMipMaps=s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,r.format=s.format,this._internalTexturesCache.push(r),i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,s.samplingMode===void 0||s.samplingMode===2||s.samplingMode===2||s.samplingMode===3||s.samplingMode===3||s.samplingMode===5||s.samplingMode===6||s.samplingMode===7||s.samplingMode===11,i._generateStencilBuffer,i.samples),e&&e.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),e&&e.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1),i};Ws.prototype.setTextureSampler=function(a,e){this._engine.setTextureSampler(a,e)};Xs.prototype.setTextureSampler=function(a,e){var t;(t=this._currentMaterialContext)===null||t===void 0||t.setSampler(a,e)};Ws.prototype.setStorageBuffer=function(a,e){this._engine.setStorageBuffer(a,e)};Xs.prototype.createStorageBuffer=function(a,e){return this._createBuffer(a,e|32)};Xs.prototype.updateStorageBuffer=function(a,e,t,i){const s=a;t===void 0&&(t=0);let r;i===void 0?(e instanceof Array?r=new Float32Array(e):e instanceof ArrayBuffer?r=new Uint8Array(e):r=e,i=r.byteLength):e instanceof Array?r=new Float32Array(e):e instanceof ArrayBuffer?r=new Uint8Array(e):r=e,this._bufferManager.setSubData(s,t,r,0,i)};Xs.prototype.readFromStorageBuffer=function(a,e,t,i){t=t||a.capacity;const s=this._bufferManager.createRawBuffer(t,Pa.MapRead|Pa.CopyDst);return this._renderTargetEncoder.copyBufferToBuffer(a.underlyingResource,e??0,s,0,t),new Promise((r,n)=>{this.onEndFrameObservable.addOnce(()=>{s.mapAsync(OL.Read,0,t).then(()=>{const o=s.getMappedRange(0,t);let l=i;if(l===void 0)l=new Uint8Array(t),l.set(new Uint8Array(o));else{const c=l.constructor;l=new c(l.buffer),l.set(new c(o))}s.unmap(),this._bufferManager.releaseBuffer(s),r(l)},o=>n(o))})})};Xs.prototype.setStorageBuffer=function(a,e){var t,i;(t=this._currentDrawContext)===null||t===void 0||t.setBuffer(a,(i=e?.getBuffer())!==null&&i!==void 0?i:null)};Xs.prototype.createUniformBuffer=function(a){let e;return a instanceof Array?e=new Float32Array(a):e=a,this._bufferManager.createBuffer(e,Pa.Uniform|Pa.CopyDst)};Xs.prototype.createDynamicUniformBuffer=function(a){return this.createUniformBuffer(a)};Xs.prototype.updateUniformBuffer=function(a,e,t,i){t===void 0&&(t=0);const s=a;let r;i===void 0?(e instanceof Float32Array?r=e:r=new Float32Array(e),i=r.byteLength):e instanceof Float32Array?r=e:r=new Float32Array(e),this._bufferManager.setSubData(s,t,r,0,i)};Xs.prototype.bindUniformBufferBase=function(a,e,t){this._currentDrawContext.setBuffer(t,a)};Xs.prototype.bindUniformBlock=function(){};function rve(a){return!!(a&&a.underlyingResource!==void 0)}Xs.prototype.updateVideoTexture=function(a,e,t){var i;if(!a||a._isDisabled)return;this._videoTextureSupported===void 0&&(this._videoTextureSupported=!0);let s=a._hardwareTexture;!((i=a._hardwareTexture)===null||i===void 0)&&i.underlyingResource||(s=this._textureHelper.createGPUTextureForInternalTexture(a)),rve(e)?(this._textureHelper.copyVideoToTexture(e,a,s.format,!t),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder),a.isReady=!0):e&&this.createImageBitmap(e).then(r=>{this._textureHelper.updateTexture(r,a,a.width,a.height,a.depth,s.format,0,0,!t,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder),a.isReady=!0}).catch(()=>{a.isReady=!0})};class nve{static CreateAsync(e,t){return Xs.IsSupportedAsync.then(i=>i?Xs.CreateAsync(e,t):He.IsSupported?new Promise(s=>{s(new He(e,void 0,t))}):new Promise(s=>{s(new Pce(t))}))}}class lv{}lv.COPY=1;lv.CUT=2;lv.PASTE=3;class zY{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return lv.COPY;case 86:return lv.PASTE;case 88:return lv.CUT;default:return-1}}}class yI extends QL{constructor(e){super(e),this.controllerType=s7.DAYDREAM}initControllerMesh(e,t){As.ImportMesh("",yI.MODEL_BASE_URL,yI.MODEL_FILENAME,e,i=>{this._defaultModel=i[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)})}_handleButtonChange(e,t){if(e===0){const i=this.onTriggerStateChangedObservable;i&&i.notifyObservers(t)}else Me.Warn(`Unrecognized Daydream button index: ${e}`)}}yI.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/";yI.MODEL_FILENAME="generic.babylon";yI.GAMEPAD_ID_PREFIX="Daydream";oT._ControllerFactories.push({canCreate:a=>a.id.indexOf(yI.GAMEPAD_ID_PREFIX)===0,create:a=>new yI(a)});class MI extends QL{constructor(e){super(e),this._buttonIndexToObservableNameMap=["onPadStateChangedObservable","onTriggerStateChangedObservable"],this.controllerType=s7.GEAR_VR,this._calculatedPosition=new O(this.hand=="left"?-.15:.15,-.5,.25),this._disableTrackPosition(this._calculatedPosition)}initControllerMesh(e,t){As.ImportMesh("",MI.MODEL_BASE_URL,MI.MODEL_FILENAME,e,i=>{const s=new Oe("",e);i[1].parent=s,i[1].position.z=-.15,this._defaultModel=s,this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)})}_handleButtonChange(e,t){if(ea.id.indexOf(MI.GAMEPAD_ID_PREFIX)===0||a.id.indexOf("Oculus Go")!==-1||a.id.indexOf("Vive Focus")!==-1,create:a=>new MI(a)});class TI extends QL{constructor(e){super(e)}initControllerMesh(e,t){As.ImportMesh("",TI.MODEL_BASE_URL,TI.MODEL_FILENAME,e,i=>{this._defaultModel=i[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)})}_handleButtonChange(e,t){console.log("Button id: "+e+"state: "),console.dir(t)}}TI.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/";TI.MODEL_FILENAME="generic.babylon";oT._DefaultControllerFactory=a=>new TI(a);class W1 extends QL{constructor(e){super(e),this.onSecondaryTriggerStateChangedObservable=new Se,this.onThumbRestChangedObservable=new Se,this.controllerType=s7.OCULUS}initControllerMesh(e,t){let i;this.hand==="left"?i=W1.MODEL_LEFT_FILENAME:i=W1.MODEL_RIGHT_FILENAME,As.ImportMesh("",W1._IsQuest?W1.QUEST_MODEL_BASE_URL:W1.MODEL_BASE_URL,i,e,s=>{this._defaultModel=W1._IsQuest?s[0]:s[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)})}get onAButtonStateChangedObservable(){if(this.hand==="right")return this.onMainButtonStateChangedObservable;throw new Error("No A button on left hand")}get onBButtonStateChangedObservable(){if(this.hand==="right")return this.onSecondaryButtonStateChangedObservable;throw new Error("No B button on left hand")}get onXButtonStateChangedObservable(){if(this.hand==="left")return this.onMainButtonStateChangedObservable;throw new Error("No X button on right hand")}get onYButtonStateChangedObservable(){if(this.hand==="left")return this.onSecondaryButtonStateChangedObservable;throw new Error("No Y button on right hand")}_handleButtonChange(e,t){const i=t,s=this.hand==="right"?-1:1;switch(e){case 0:this.onPadStateChangedObservable.notifyObservers(i);return;case 1:!W1._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[3].rotation.x=-i.value*.2,this._defaultModel.getChildren()[3].position.y=-i.value*.005,this._defaultModel.getChildren()[3].position.z=-i.value*.005),this.onTriggerStateChangedObservable.notifyObservers(i);return;case 2:!W1._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[4].position.x=s*i.value*.0035),this.onSecondaryTriggerStateChangedObservable.notifyObservers(i);return;case 3:!W1._IsQuest&&this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[1].position.y=-.001:this._defaultModel.getChildren()[1].position.y=0),this.onMainButtonStateChangedObservable.notifyObservers(i);return;case 4:!W1._IsQuest&&this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),this.onSecondaryButtonStateChangedObservable.notifyObservers(i);return;case 5:this.onThumbRestChangedObservable.notifyObservers(i);return}}}W1.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/";W1.MODEL_LEFT_FILENAME="left.babylon";W1.MODEL_RIGHT_FILENAME="right.babylon";W1.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/";W1._IsQuest=!1;oT._ControllerFactories.push({canCreate:a=>(Ii.LastCreatedEngine&&Ii.LastCreatedEngine._vrDisplay&&Ii.LastCreatedEngine._vrDisplay.displayName==="Oculus Quest"&&(W1._IsQuest=!0),a.id.indexOf("Oculus Touch")!==-1),create:a=>new W1(a)});class ZP extends QL{constructor(e){super(e),this.controllerType=s7.VIVE,this._invertLeftStickY=!0}initControllerMesh(e,t){As.ImportMesh("",ZP.MODEL_BASE_URL,ZP.MODEL_FILENAME,e,i=>{this._defaultModel=i[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)})}get onLeftButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onRightButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onMenuButtonStateChangedObservable(){return this.onSecondaryButtonStateChangedObservable}_handleButtonChange(e,t){const i=t;switch(e){case 0:this.onPadStateChangedObservable.notifyObservers(i);return;case 1:this._defaultModel&&(this._defaultModel.getChildren()[6].rotation.x=-i.value*.15),this.onTriggerStateChangedObservable.notifyObservers(i);return;case 2:this.onMainButtonStateChangedObservable.notifyObservers(i);return;case 3:this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),this.onSecondaryButtonStateChangedObservable.notifyObservers(i);return}}}ZP.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/";ZP.MODEL_FILENAME="wand.babylon";oT._ControllerFactories.push({canCreate:a=>a.id.toLowerCase().indexOf("openvr")!==-1,create:a=>new ZP(a)});class ave{constructor(){this.buttonMeshes={},this.axisMeshes={}}}class v_ extends QL{constructor(e){super(e),this._mapping={buttons:["thumbstick","trigger","grip","menu","trackpad"],buttonMeshNames:{trigger:"SELECT",menu:"MENU",grip:"GRASP",thumbstick:"THUMBSTICK_PRESS",trackpad:"TOUCHPAD_PRESS"},buttonObservableNames:{trigger:"onTriggerStateChangedObservable",menu:"onSecondaryButtonStateChangedObservable",grip:"onMainButtonStateChangedObservable",thumbstick:"onPadStateChangedObservable",trackpad:"onTrackpadChangedObservable"},axisMeshNames:["THUMBSTICK_X","THUMBSTICK_Y","TOUCHPAD_TOUCH_X","TOUCHPAD_TOUCH_Y"],pointingPoseMeshName:GP.POINTING_POSE},this.onTrackpadChangedObservable=new Se,this.onTrackpadValuesChangedObservable=new Se,this.trackpad={x:0,y:0},this.controllerType=s7.WINDOWS,this._loadedMeshInfo=null}get onTriggerButtonStateChangedObservable(){return this.onTriggerStateChangedObservable}get onMenuButtonStateChangedObservable(){return this.onSecondaryButtonStateChangedObservable}get onGripButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onThumbstickButtonStateChangedObservable(){return this.onPadStateChangedObservable}get onTouchpadButtonStateChangedObservable(){return this.onTrackpadChangedObservable}get onTouchpadValuesChangedObservable(){return this.onTrackpadValuesChangedObservable}_updateTrackpad(){this.browserGamepad.axes&&(this.browserGamepad.axes[2]!=this.trackpad.x||this.browserGamepad.axes[3]!=this.trackpad.y)&&(this.trackpad.x=this.browserGamepad.axes[this._mapping.axisMeshNames.indexOf("TOUCHPAD_TOUCH_X")],this.trackpad.y=this.browserGamepad.axes[this._mapping.axisMeshNames.indexOf("TOUCHPAD_TOUCH_Y")],this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad))}update(){if(super.update(),this.browserGamepad.axes&&(this._updateTrackpad(),this._loadedMeshInfo))for(let e=0;e{this._loadedMeshInfo=this._processModel(e,n),this._loadedMeshInfo&&(this._defaultModel=this._loadedMeshInfo.rootNode,this.attachToMesh(this._defaultModel),t&&t(this._defaultModel))},null,(n,o)=>{Me.Log(o),Me.Warn("Failed to retrieve controller model from the remote server: "+s+r),i||this.initControllerMesh(n,t,!0)})}_processModel(e,t){let i=null;const s=new Oe(this.id+" "+this.hand,e);let r=null;for(let n=0;nl.name===o,!1)[0]}function r(n,o){return n.getChildren(l=>l.name==o,!0)[0]}}getForwardRay(e=100){if(!(this._loadedMeshInfo&&this._loadedMeshInfo.pointingPoseNode))return super.getForwardRay(e);const t=this._loadedMeshInfo.pointingPoseNode.getWorldMatrix(),i=t.getTranslation(),s=new O(0,0,-1),r=O.TransformNormal(s,t),n=O.Normalize(r);return new gr(i,n,e)}dispose(){super.dispose(),this.onTrackpadChangedObservable.clear(),this.onTrackpadValuesChangedObservable.clear()}}v_.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/";v_.MODEL_LEFT_FILENAME="left.glb";v_.MODEL_RIGHT_FILENAME="right.glb";v_.GAMEPAD_ID_PREFIX="Spatial Controller (Spatial Interaction Source) ";v_.GAMEPAD_ID_PATTERN=/([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;class ove extends v_{constructor(e){super(e),this._mapping={buttons:["trigger","grip","trackpad","thumbstick","menu"],buttonMeshNames:{trigger:"SELECT",menu:"MENU",grip:"GRASP",thumbstick:"THUMBSTICK_PRESS",trackpad:"TOUCHPAD_PRESS"},buttonObservableNames:{trigger:"onTriggerStateChangedObservable",menu:"onSecondaryButtonStateChangedObservable",grip:"onMainButtonStateChangedObservable",thumbstick:"onThumbstickStateChangedObservable",trackpad:"onTrackpadChangedObservable"},axisMeshNames:["TOUCHPAD_TOUCH_X","TOUCHPAD_TOUCH_Y","THUMBSTICK_X","THUMBSTICK_Y"],pointingPoseMeshName:GP.POINTING_POSE},this.thumbstickValues={x:0,y:0},this.onThumbstickStateChangedObservable=new Se,this.onThumbstickValuesChangedObservable=new Se,this.onTrackpadChangedObservable=this.onPadStateChangedObservable,this.onTrackpadValuesChangedObservable=this.onPadValuesChangedObservable}get onThumbstickButtonStateChangedObservable(){return this.onThumbstickStateChangedObservable}_updateTrackpad(){this.browserGamepad.axes&&(this.browserGamepad.axes[2]!=this.thumbstickValues.x||this.browserGamepad.axes[3]!=this.thumbstickValues.y)&&(this.trackpad.x=this.browserGamepad.axes[2],this.trackpad.y=this.browserGamepad.axes[3],this.onThumbstickValuesChangedObservable.notifyObservers(this.trackpad))}dispose(){super.dispose(),this.onThumbstickStateChangedObservable.clear(),this.onThumbstickValuesChangedObservable.clear()}}oT._ControllerFactories.push({canCreate:a=>a.id.indexOf(v_.GAMEPAD_ID_PREFIX)===0,create:a=>new v_(a)});class cj extends ua{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Ie.Gray(),i=Mn.DefaultUtilityLayer,s=null,r=1){var n,o,l,c,h,u,p;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Se,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new O(0,0,0),this._parent=s,this._coloredMaterial=new jt("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ie(.1,.1,.1)),this._hoverMaterial=new jt("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=Ie.Yellow(),this._disableMaterial=new jt("",i.utilityLayerScene),this._disableMaterial.diffuseColor=Ie.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new Oe("axis",i.utilityLayerScene);const{arrowMesh:m,arrowTail:_}=this._createGizmoMesh(this._gizmoMesh,r),f=this._createGizmoMesh(this._gizmoMesh,r+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,ua.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const d=m.position.clone(),C=_.position.clone(),v=_.scaling.clone(),y=D=>{const R=D*(3/this._rootMesh.scaling.length())*6;m.position.z+=R/3.5,_.scaling.y+=R,this.dragScale=_.scaling.y,_.position.z=m.position.z/2},M=()=>{m.position.set(d.x,d.y,d.z),_.position.set(C.x,C.y,C.z),_.scaling.set(v.x,v.y,v.z),this.dragScale=_.scaling.y,this._dragging=!1};this.dragBehavior=new uc({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let b=0;const E={snapDistance:0};this.dragBehavior.onDragObservable.add(D=>{if(this.attachedNode){this._handlePivot();const R=this.sensitivity*D.dragDistance*(this.scaleRatio*3/this._rootMesh.scaling.length()),L=this._tmpVector;let w=!1,N=0;this.uniformScaling?L.setAll(.57735):L.copyFrom(e),this.snapDistance==0?L.scaleToRef(R,L):(b+=R,Math.abs(b)>this.snapDistance?(N=Math.floor(Math.abs(b)/this.snapDistance),b<0&&(N*=-1),b=b%this.snapDistance,L.scaleToRef(this.snapDistance*N,L),w=!0):L.scaleInPlace(0)),ge.ScalingToRef(1+L.x,1+L.y,1+L.z,ue.Matrix[2]),ue.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),ue.Matrix[1]);const V=this.attachedNode._isMesh?this.attachedNode:void 0;ue.Matrix[1].decompose(ue.Vector3[1],void 0,void 0,ua.PreserveScaling?V:void 0);const W=1e5;Math.abs(ue.Vector3[1].x){this._dragging=!0}),this.dragBehavior.onDragObservable.add(D=>y(D.dragDistance)),this.dragBehavior.onDragEndObservable.add(M),(l=(o=(n=s?.uniformScaleGizmo)===null||n===void 0?void 0:n.dragBehavior)===null||o===void 0?void 0:o.onDragObservable)===null||l===void 0||l.add(D=>y(D.delta.y)),(u=(h=(c=s?.uniformScaleGizmo)===null||c===void 0?void 0:c.dragBehavior)===null||h===void 0?void 0:h.onDragEndObservable)===null||u===void 0||u.add(M);const S={gizmoMeshes:[m,_],colliderMeshes:[f.arrowMesh,f.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(p=this._parent)===null||p===void 0||p.addToAxisCache(this._gizmoMesh,S),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(D=>{var R;if(!this._customMeshSet&&(this._isHovered=S.colliderMeshes.indexOf((R=D?.pickInfo)===null||R===void 0?void 0:R.pickedMesh)!=-1,!this._parent)){const L=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(S.gizmoMeshes,L)}}),this.dragBehavior.onEnabledObservable.add(D=>{this._setGizmoMeshMaterial(S.gizmoMeshes,D?this._coloredMaterial:this._disableMaterial)});const I=i._getSharedGizmoLight();I.includedOnlyMeshes=I.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const s=pl("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),r=J1("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return s.scaling.scaleInPlace(.1),s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,s.position.z+=.3,r.material=this._coloredMaterial,r.position.z+=.275/2,r.rotation.x=Math.PI/2,i&&(s.visibility=0,r.visibility=0),e.addChild(s),e.addChild(r),{arrowMesh:s,arrowTail:r}}_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)}}class Xce extends ua{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let s=0;s<3;s++)for(let r=0;r<3;r++)for(let n=0;n<3;n++){const o=(s===1?1:0)+(r===1?1:0)+(n===1?1:0);if(!(o===1||o===3)){if(t[i]){const l=new O(s-1,r-1,n-1);l.multiplyInPlace(this._axisFactor),t[i].setEnabled(l.lengthSquared()>Ls)}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}setColor(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new Ie(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach(t=>{t.color&&(t.color=e)})}constructor(e=Ie.Gray(),t=Mn.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new O(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._tmpQuaternion=new ke,this._tmpVector=new O(0,0,0),this._tmpRotationMatrix=new ge,this.ignoreChildren=!1,this.includeChildPredicate=null,this.rotationSphereSize=.1,this.scaleBoxSize=.1,this.fixedDragMeshScreenSize=!1,this.fixedDragMeshBoundsSize=!1,this.fixedDragMeshScreenSizeDistanceFactor=10,this.onDragStartObservable=new Se,this.onScaleBoxDragObservable=new Se,this.onScaleBoxDragEndObservable=new Se,this.onRotationSphereDragObservable=new Se,this.onRotationSphereDragEndObservable=new Se,this.scalePivot=null,this._axisFactor=new O(1,1,1),this._existingMeshScale=new O,this._dragMesh=null,this._pointerDragBehavior=new uc,this.updateScale=!1,this._anchorMesh=new Ir("anchor",t.utilityLayerScene),this._coloredMaterial=new jt("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new jt("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new Ir("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new ke;const i=[];i.push(Ga("lines",{points:[new O(0,0,0),new O(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(0,0,0),new O(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(0,0,0),new O(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(this._boundingDimensions.x,0,0),new O(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(this._boundingDimensions.x,0,0),new O(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(0,this._boundingDimensions.y,0),new O(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(0,this._boundingDimensions.y,0),new O(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(0,0,this._boundingDimensions.z),new O(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(0,0,this._boundingDimensions.z),new O(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new O(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new O(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ga("lines",{points:[new O(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new O(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach(r=>{r.color=e,r.position.addInPlace(new O(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),r.isPickable=!1,this._lineBoundingBox.addChild(r)}),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateSpheresParent=new Ir("",t.utilityLayerScene),this._rotateSpheresParent.rotationQuaternion=new ke;for(let r=0;r<12;r++){const n=$d("",{diameter:1},t.utilityLayerScene);n.rotationQuaternion=new ke,n.material=this._coloredMaterial,n.isNearGrabbable=!0;const o=new uc({});o.moveAttached=!1,o.updateDragPlane=!1,n.addBehavior(o);const l=new O(1,0,0);let c=0;o.onDragStartObservable.add(()=>{l.copyFrom(n.forward),c=0}),o.onDragObservable.add(h=>{if(this.onRotationSphereDragObservable.notifyObservers({}),this.attachedMesh){const u=this.attachedMesh.parent;if(u&&u.scaling&&u.scaling.isNonUniformWithinEpsilon(.001)){Me.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");return}yn._RemoveAndStorePivotPoint(this.attachedMesh);const p=l,m=h.dragPlaneNormal.scale(O.Dot(h.dragPlaneNormal,p)),_=p.subtract(m).normalizeToNew();let f=O.Dot(_,h.delta)<0?Math.abs(h.delta.length()):-Math.abs(h.delta.length());f=f/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=ke.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=ke.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),c+=f,Math.abs(c)<=2*Math.PI&&(r>=8?ke.RotationYawPitchRollToRef(0,0,f,this._tmpQuaternion):r>=4?ke.RotationYawPitchRollToRef(f,0,0,this._tmpQuaternion):ke.RotationYawPitchRollToRef(0,f,0,this._tmpQuaternion),this._anchorMesh.addChild(this.attachedMesh,ua.PreserveScaling),this._anchorMesh.getScene().useRightHandedSystem&&this._tmpQuaternion.conjugateInPlace(),this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion,this._anchorMesh.rotationQuaternion),this._anchorMesh.removeChild(this.attachedMesh,ua.PreserveScaling),this.attachedMesh.setParent(u,ua.PreserveScaling)),this.updateBoundingBox(),yn._RestorePivotPoint(this.attachedMesh)}this._updateDummy()}),o.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({}),this._selectNode(n)}),o.onDragEndObservable.add(h=>{this.onRotationSphereDragEndObservable.notifyObservers({}),this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(h.pointerInfo,n)}),this._rotateSpheresParent.addChild(n)}this._rootMesh.addChild(this._rotateSpheresParent),this._scaleBoxesParent=new Ir("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new ke;for(let r=0;r<3;r++)for(let n=0;n<3;n++)for(let o=0;o<3;o++){const l=(r===1?1:0)+(n===1?1:0)+(o===1?1:0);if(l===1||l===3)continue;const c=pl("",{size:1},t.utilityLayerScene);c.material=this._coloredMaterial,c._internalMetadata=l===2,c.isNearGrabbable=!0;const h=new O(r-1,n-1,o-1).normalize(),u=new uc({dragAxis:h});u.updateDragPlane=!1,u.moveAttached=!1,c.addBehavior(u),u.onDragObservable.add(p=>{if(this.onScaleBoxDragObservable.notifyObservers({}),this.attachedMesh){const m=this.attachedMesh.parent;if(m&&m.scaling&&m.scaling.isNonUniformWithinEpsilon(.001)){Me.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");return}yn._RemoveAndStorePivotPoint(this.attachedMesh);const _=p.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),f=new O(_,_,_);l===2&&(f.x*=Math.abs(h.x),f.y*=Math.abs(h.y),f.z*=Math.abs(h.z)),f.scaleInPlace(this._scaleDragSpeed),f.multiplyInPlace(this._axisFactor),this.updateBoundingBox(),this.scalePivot?(this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix),this._boundingDimensions.scaleToRef(.5,this._tmpVector),O.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),O.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.addInPlace(this._tmpVector)):(c.absolutePosition.subtractToRef(this._anchorMesh.position,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector)),this._anchorMesh.addChild(this.attachedMesh,ua.PreserveScaling),this._anchorMesh.scaling.addInPlace(f),(this._anchorMesh.scaling.x<0||this._anchorMesh.scaling.y<0||this._anchorMesh.scaling.z<0)&&this._anchorMesh.scaling.subtractInPlace(f),this._anchorMesh.removeChild(this.attachedMesh,ua.PreserveScaling),this.attachedMesh.setParent(m,ua.PreserveScaling),yn._RestorePivotPoint(this.attachedMesh)}this._updateDummy()}),u.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({}),this._selectNode(c)}),u.onDragEndObservable.add(p=>{this.onScaleBoxDragEndObservable.notifyObservers({}),this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(p.pointerInfo,c)}),this._scaleBoxesParent.addChild(c)}this._rootMesh.addChild(this._scaleBoxesParent);const s=new Array;this._pointerObserver=t.utilityLayerScene.onPointerObservable.add(r=>{s[r.event.pointerId]?r.pickInfo&&r.pickInfo.pickedMesh!=s[r.event.pointerId]&&(s[r.event.pointerId].material=this._coloredMaterial,delete s[r.event.pointerId]):this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(n=>{r.pickInfo&&r.pickInfo.pickedMesh==n&&(s[r.event.pointerId]=n,n.material=this._hoverColoredMaterial)})}),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),yn._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e,ua.PreserveScaling),this._anchorMesh.removeChild(e,ua.PreserveScaling),e.setParent(t,ua.PreserveScaling),yn._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?.event instanceof PointerEvent&&e?.event.pointerType==="touch"&&(t.material=this._coloredMaterial)}getScaleBoxes(){return this._scaleBoxesParent.getChildMeshes()}updateBoundingBox(){if(this.attachedMesh){yn._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null,ua.PreserveScaling),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=ke.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=ke.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,ua.PreserveScaling)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),yn._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 s=0;s<2;s++){const r=t*4+i*2+s;if(t==0&&(e[r].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*s),e[r].position.addInPlace(new O(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(O.Cross(e[r].position.normalizeToNew(),O.Right()).normalizeToNew().add(e[r].position))),t==1&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*s),e[r].position.addInPlace(new O(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(O.Cross(e[r].position.normalizeToNew(),O.Up()).normalizeToNew().add(e[r].position))),t==2&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*s,this._boundingDimensions.z/2),e[r].position.addInPlace(new O(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(O.Cross(e[r].position.normalizeToNew(),O.Forward()).normalizeToNew().add(e[r].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[r].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const n=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[r].scaling.set(n,n,n)}else this.fixedDragMeshBoundsSize?e[r].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[r].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 s=0;s<3;s++)for(let r=0;r<3;r++){const n=(i===1?1:0)+(s===1?1:0)+(r===1?1:0);if(!(n===1||n===3)){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(s/2),this._boundingDimensions.z*(r/2)),e[t].position.addInPlace(new O(-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.position,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 s=e;t&&i._internalMetadata===!0&&(s=!1),i.setEnabled(s)})}_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=pl("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new ke,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)}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(l=>{t(l)})};t(e),e.rotationQuaternion||(e.rotationQuaternion=ke.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),s=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const r=pl("box",{size:1},e.getScene()),n=e.getHierarchyBoundingVectors();return n.max.subtractToRef(n.min,r.scaling),r.scaling.y===0&&(r.scaling.y=Ls),r.scaling.x===0&&(r.scaling.x=Ls),r.scaling.z===0&&(r.scaling.z=Ls),r.position.set((n.max.x+n.min.x)/2,(n.max.y+n.min.y)/2,(n.max.z+n.min.z)/2),e.addChild(r),e.rotationQuaternion.copyFrom(s),e.position.copyFrom(i),e.removeChild(r),r.addChild(e),r.visibility=0,r}setCustomMesh(){Me.Error("Custom meshes are not supported on this gizmo")}}class $5 extends ua{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Ie.Gray(),i=Mn.DefaultUtilityLayer,s=32,r=null,n=!1,o=1){var l;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Se,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new O,this._parent=r,this._coloredMaterial=new jt("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ie(.1,.1,.1)),this._hoverMaterial=new jt("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=Ie.Yellow(),this._disableMaterial=new jt("",i.utilityLayerScene),this._disableMaterial.diffuseColor=Ie.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new Oe("",i.utilityLayerScene);const{rotationMesh:c,collider:h}=this._createGizmoMesh(this._gizmoMesh,o,s);this._rotationDisplayPlane=Jd("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=Math.PI*.5,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),Ws.ShadersStore.rotationGizmoVertexShader=$5._RotationGizmoVertexShader,Ws.ShadersStore.rotationGizmoFragmentShader=$5._RotationGizmoFragmentShader,this._rotationShaderMaterial=new oh("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles"]}),this._rotationShaderMaterial.backFaceCulling=!1,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,ua.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new uc({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=$5.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const u=new O,p=new ge,m=new O;let _=new O;this.dragBehavior.onDragStartObservable.add(b=>{this.attachedNode&&(u.copyFrom(b.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(p),O.TransformCoordinatesToRef(b.dragPlanePoint,p,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(b.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});const f={snapDistance:0};let d=0;const C=new ge,v=new ke;this.dragBehavior.onDragObservable.add(b=>{if(this.attachedNode){const E=new O(1,1,1),S=new ke(0,0,0,1),I=new O(0,0,0);if(this._handlePivot(),this.attachedNode.getWorldMatrix().decompose(E,S,I),!(Math.abs(Math.abs(E.x)-Math.abs(E.y))<=Ls&&Math.abs(Math.abs(E.x)-Math.abs(E.z))<=Ls)&&this.updateGizmoRotationToMatchAttachedMesh){Me.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}S.normalize();const R=this.updateGizmoPositionToMatchAttachedMesh?I:this._rootMesh.absolutePosition,L=b.dragPlanePoint.subtract(R).normalize(),w=u.subtract(R).normalize(),N=O.Cross(L,w),V=O.Dot(L,w);let W=Math.atan2(N.length(),V)*this.sensitivity;m.copyFrom(e),_.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(S.toRotationMatrix(p),_=O.TransformCoordinates(m,p));let G=!1;if(i.utilityLayerScene.activeCamera){const K=i.utilityLayerScene.activeCamera.position.subtract(R).normalize();O.Dot(K,_)>0&&(m.scaleInPlace(-1),_.scaleInPlace(-1),G=!0)}O.Dot(_,N)>0&&(W=-W);let Z=!1;if(this.snapDistance!=0)if(d+=W,Math.abs(d)>this.snapDistance){let K=Math.floor(Math.abs(d)/this.snapDistance);d<0&&(K*=-1),d=d%this.snapDistance,W=this.snapDistance*K,Z=!0}else W=0;const q=Math.sin(W/2);if(v.set(m.x*q,m.y*q,m.z*q,Math.cos(W/2)),C.determinant()>0){const K=new O;v.toEulerAnglesToRef(K),ke.RotationYawPitchRollToRef(K.y,-K.x,-K.z,v)}if(this.updateGizmoRotationToMatchAttachedMesh)S.multiplyToRef(v,S),ge.ComposeToRef(E,S,I,this.attachedNode.getWorldMatrix());else{v.toRotationMatrix(ue.Matrix[0]);const K=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(ue.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(K)}u.copyFrom(b.dragPlanePoint),Z&&(f.snapDistance=W,this.onSnapObservable.notifyObservers(f)),this._angles.y+=W,this.angle+=G?-W:W,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});const y=i._getSharedGizmoLight();y.includedOnlyMeshes=y.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const M={colliderMeshes:[h],gizmoMeshes:[c],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(l=this._parent)===null||l===void 0||l.addToAxisCache(this._gizmoMesh,M),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(b=>{var E;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=$5.MaxDragAngle,this._isHovered=M.colliderMeshes.indexOf((E=b?.pickInfo)===null||E===void 0?void 0:E.pickedMesh)!=-1,!this._parent)){const S=M.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(M.gizmoMeshes,S)}}),this.dragBehavior.onEnabledObservable.add(b=>{this._setGizmoMeshMaterial(M.gizmoMeshes,b?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){const s=r7("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);s.visibility=0;const r=r7("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,s.rotation.x=Math.PI/2,e.addChild(r,ua.PreserveScaling),e.addChild(s,ua.PreserveScaling),{rotationMesh:r,collider:s}}_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()}}$5.MaxDragAngle=Math.PI*9/20;$5._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; + }`;$5._RotationGizmoFragmentShader=` + precision highp float; + varying vec2 vUV; + varying vec3 vPosition; + uniform vec3 angles; + #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(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity; + }`;class Kce extends ua{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&&console.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(){let e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{e=e||t.isHovered}),e}constructor(e=Mn.DefaultUtilityLayer,t=32,i=!1,s=1,r,n){super(e),this.onDragStartObservable=new Se,this.onDragEndObservable=new Se,this._observables=[],this._sensitivity=1,this._gizmoAxisCache=new Map;const o=n&&n.xOptions&&n.xOptions.color?n.xOptions.color:Ie.Red().scale(.5),l=n&&n.yOptions&&n.yOptions.color?n.yOptions.color:Ie.Green().scale(.5),c=n&&n.zOptions&&n.zOptions.color?n.zOptions.color:Ie.Blue().scale(.5);this.xGizmo=new $5(new O(1,0,0),o,e,t,this,i,s),this.yGizmo=new $5(new O(0,1,0),l,e,t,this,i,s),this.zGizmo=new $5(new O(0,0,1),c,e,t,this,i,s),[this.xGizmo,this.yGizmo,this.zGizmo].forEach(h=>{n&&n.updateScale!=null&&(h.updateScale=n.updateScale),h.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),h.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,this.attachedNode=null,r?r.addToAxisCache(this._gizmoAxisCache):ua.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}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}dispose(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach(e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})}setCustomMesh(){Me.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 $N extends ua{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new Ki("plane",e),s=Jd("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return s.material=t,s.parent=i,i}constructor(e,t=Ie.Gray(),i=Mn.DefaultUtilityLayer,s=null){var r;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Se,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=s,this._coloredMaterial=new jt("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ie(.1,.1,.1)),this._hoverMaterial=new jt("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=Ie.Yellow(),this._disableMaterial=new jt("",i.utilityLayerScene),this._disableMaterial.diffuseColor=Ie.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=$N._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 n=0;const o=new O,l={snapDistance:0};this.dragBehavior=new uc({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add(u=>{if(this.attachedNode){if(this._handlePivot(),this.snapDistance==0)this.attachedNode.getWorldMatrix().getTranslationToRef(ue.Vector3[0]),ue.Vector3[0].addToRef(u.delta,ue.Vector3[0]),this.dragBehavior.validateDrag(ue.Vector3[0])&&this.attachedNode.getWorldMatrix().addTranslationFromFloats(u.delta.x,u.delta.y,u.delta.z);else if(n+=u.dragDistance,Math.abs(n)>this.snapDistance){const p=Math.floor(Math.abs(n)/this.snapDistance);n=n%this.snapDistance,u.delta.normalizeToRef(o),o.scaleInPlace(this.snapDistance*p),this.attachedNode.getWorldMatrix().getTranslationToRef(ue.Vector3[0]),ue.Vector3[0].addToRef(o,ue.Vector3[0]),this.dragBehavior.validateDrag(ue.Vector3[0])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(o.x,o.y,o.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 c=i._getSharedGizmoLight();c.includedOnlyMeshes=c.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const h={gizmoMeshes:this._gizmoMesh.getChildMeshes(),colliderMeshes:this._gizmoMesh.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(r=this._parent)===null||r===void 0||r.addToAxisCache(this._gizmoMesh,h),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(u=>{var p;if(!this._customMeshSet&&(this._isHovered=h.colliderMeshes.indexOf((p=u?.pickInfo)===null||p===void 0?void 0:p.pickedMesh)!=-1,!this._parent)){const m=h.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(h.gizmoMeshes,m)}}),this.dragBehavior.onEnabledObservable.add(u=>{this._setGizmoMeshMaterial(h.gizmoMeshes,u?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 Qce extends ua{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(){let e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{e=e||t.isHovered}),e}constructor(e=Mn.DefaultUtilityLayer,t=1,i){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new Se,this.onDragEndObservable=new Se,this._planarGizmoEnabled=!1,this.xGizmo=new tv(new O(1,0,0),Ie.Red().scale(.5),e,this,t),this.yGizmo=new tv(new O(0,1,0),Ie.Green().scale(.5),e,this,t),this.zGizmo=new tv(new O(0,0,1),Ie.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new $N(new O(1,0,0),Ie.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new $N(new O(0,1,0),Ie.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new $N(new O(0,0,1),Ie.Blue().scale(.5),this.gizmoLayer,this),[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(s=>{s.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),s.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):ua.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}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)}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.onDragEndObservable.clear()}setCustomMesh(){Me.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 Zce extends ua{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(){let e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{e=e||t.isHovered}),e}constructor(e=Mn.DefaultUtilityLayer,t=1,i){super(e),this._meshAttached=null,this._nodeAttached=null,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new Se,this.onDragEndObservable=new Se,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new cj(new O(1,0,0),Ie.Red().scale(.5),e,this,t),this.yGizmo=new cj(new O(0,1,0),Ie.Green().scale(.5),e,this,t),this.zGizmo=new cj(new O(0,0,1),Ie.Blue().scale(.5),e,this,t),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(s=>{s.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),s.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):ua.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new jt("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=Ie.Gray(),this._hoverMaterial=new jt("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=Ie.Yellow(),this._disableMaterial=new jt("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=Ie.Gray(),this._disableMaterial.alpha=.4;const e=new cj(new O(0,1,0),Ie.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=KP("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=KP("",{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)})):Me.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}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t.coordinatesMode=e})}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 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)}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.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach(e=>{e&&e.dispose()}),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()})}}class lve{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}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}constructor(e,t=1,i=Mn.DefaultUtilityLayer,s=Mn.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new Se,this.onAttachedToNodeObservable=new Se,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=Ie.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=UB.Local,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new Z$,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=s,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const r=this._attachToMeshPointerObserver(e),n=ua.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[r,n]}_attachToMeshPointerObserver(e){return e.onPointerObservable.add(i=>{if(!!this.usePointerToAttachGizmos&&i.type==mi.POINTERDOWN)if(i.pickInfo&&i.pickInfo.pickedMesh){if(this.enableAutoPicking){let s=i.pickInfo.pickedMesh;if(this.attachableMeshes==null)for(;s&&s.parent!=null;)s=s.parent;else{let r=!1;this.attachableMeshes.forEach(n=>{s&&(s==n||s.isDescendantOf(n))&&(s=n,r=!0)}),r||(s=null)}s instanceof Ir?this._attachedMesh!=s&&this.attachToMesh(s):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 Qce(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}get positionGizmoEnabled(){return this._gizmosEnabled.positionGizmo}set rotationGizmoEnabled(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new Kce(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}get rotationGizmoEnabled(){return this._gizmosEnabled.rotationGizmo}set scaleGizmoEnabled(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new Zce(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}get scaleGizmoEnabled(){return this._gizmosEnabled.scaleGizmo}set boundingBoxGizmoEnabled(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new Xce(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}get boundingBoxGizmoEnabled(){return this._gizmosEnabled.boundingBoxGizmo}addToAxisCache(e){e.size>0&&e.forEach((t,i)=>{this._gizmoAxisCache.set(i,t)})}dispose(){var e,t;this._pointerObservers.forEach(i=>{this._scene.onPointerObservable.remove(i)});for(const i in this.gizmos){const s=this.gizmos[i];s&&s.dispose()}this._defaultKeepDepthUtilityLayer!==Mn._DefaultKeepDepthUtilityLayer&&((e=this._defaultKeepDepthUtilityLayer)===null||e===void 0||e.dispose()),this._defaultUtilityLayer!==Mn._DefaultUtilityLayer&&((t=this._defaultUtilityLayer)===null||t===void 0||t.dispose()),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}class wI extends pr{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0}_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=O.Zero()),O.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=O.Zero()),O.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=O.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=O.Cross(this.direction,Fo.Y),t=O.Cross(e,this.direction);return O.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=O.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=ge.Identity()),ge.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)}}z([bo()],wI.prototype,"position",null);z([bo()],wI.prototype,"direction",null);z([X()],wI.prototype,"shadowMinZ",null);z([X()],wI.prototype,"shadowMaxZ",null);pn.AddNodeConstructor("Light_Type_1",(a,e)=>()=>new c4(a,O.Zero(),e));class c4 extends wI{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 pr.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||ge.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 s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const h=O.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,p=-Number.MAX_VALUE;for(let m=0;mthis._orthoRight&&(this._orthoRight=h.x),h.y>this._orthoTop&&(this._orthoTop=h.y),this.autoCalcShadowZBounds&&(h.zp&&(p=h.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=u,this._shadowMaxZ=p)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,l=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,c=this.getScene().getEngine().useReverseDepthBuffer;ge.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,c?l:o,c?o:l,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}}z([X()],c4.prototype,"shadowFrustumSize",null);z([X()],c4.prototype,"shadowOrthoScale",null);z([X()],c4.prototype,"autoUpdateExtends",void 0);z([X()],c4.prototype,"autoCalcShadowZBounds",void 0);z([X("orthoLeft")],c4.prototype,"_orthoLeft",void 0);z([X("orthoRight")],c4.prototype,"_orthoRight",void 0);z([X("orthoTop")],c4.prototype,"_orthoTop",void 0);z([X("orthoBottom")],c4.prototype,"_orthoBottom",void 0);function Wj(a,e={},t){e.diameter||(e.diameter=1),e.segments||(e.segments=16);const i=$d("",{slice:.5,diameter:e.diameter,segments:e.segments},t),s=RF("",{radius:e.diameter/2,tessellation:e.segments*3+(4-e.segments)},t);s.rotation.x=-Math.PI/2,s.parent=i;const r=Oe.MergeMeshes([s,i],!0);return r.name=a,r}const cve={CreateHemisphere:Wj};Oe.CreateHemisphere=(a,e,t,i)=>Wj(a,{segments:e,diameter:t},i);pn.AddNodeConstructor("Light_Type_2",(a,e)=>()=>new tp(a,O.Zero(),O.Zero(),0,0,e));class tp extends wI{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()&&(tp._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):tp._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,s,r,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=ge.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=O.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=O.Zero(),this._projectionTextureViewLightMatrix=ge.Zero(),this._projectionTextureProjectionLightMatrix=ge.Zero(),this._projectionTextureScalingMatrix=ge.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=s,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return pr.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,o=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;ge.PerspectiveFovLHToRef(r,1,l?o:n,l?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.direction,this._projectionTextureViewTargetVector),ge.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),s=-i*t,r=1/Math.tan(this._angle/2),n=1;ge.FromValuesToRef(r/n,0,0,0,0,r,0,0,0,0,i,1,0,0,s,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Te){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;ge.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=O.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=O.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=O.Normalize(this.transformedDirection):i=O.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())}}z([X()],tp.prototype,"angle",null);z([X()],tp.prototype,"innerAngle",null);z([X()],tp.prototype,"shadowAngleScale",null);z([X()],tp.prototype,"exponent",void 0);z([X()],tp.prototype,"projectionTextureLightNear",null);z([X()],tp.prototype,"projectionTextureLightFar",null);z([X()],tp.prototype,"projectionTextureUpDirection",null);z([xs("projectedLightTexture")],tp.prototype,"_projectionTexture",void 0);class j5 extends ua{constructor(e=Mn.DefaultUtilityLayer){super(e),this._cachedPosition=new O,this._cachedForward=new O(0,0,1),this._pointerObserver=null,this.onClickedObservable=new Se,this._light=null,this.attachedMesh=new Ir("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new Ki("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new jt("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Ie(.5,.5,.5),this._material.specularColor=new Ie(.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))},mi.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){console.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 gn?this._lightMesh=j5._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof c4?this._lightMesh=j5._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof tp?this._lightMesh=j5._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=j5._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 ke,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(ue.Vector3[0]),e=ue.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 O(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(O.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new O(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else O.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 Oe("hemisphereLight",e),i=Wj(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;const s=this._CreateLightLines(3,e);return s.parent=t,t.scaling.scaleInPlace(j5._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new Oe("pointLight",e),i=$d(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;const s=this._CreateLightLines(5,e);return s.parent=t,t.scaling.scaleInPlace(j5._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new Oe("spotLight",e),i=$d(t.name,{segments:10,diameter:1},e);i.parent=t;const s=Wj(t.name,{segments:10,diameter:2},e);s.parent=t,s.rotation.x=-Math.PI/2;const r=this._CreateLightLines(2,e);return r.parent=t,t.scaling.scaleInPlace(j5._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new Oe("directionalLight",e),i=new Oe(t.name,e);i.parent=t;const s=$d(t.name,{diameter:1.2,segments:10},e);s.parent=i;const r=J1(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);r.parent=i;let n=r.clone(t.name);n.scaling.y=.5,n.position.x+=1.25;let o=r.clone(t.name);o.scaling.y=.5,o.position.x+=-1.25;const l=J1(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return l.position.y+=3,l.parent=i,n=l.clone(t.name),n.position.y=1.5,n.position.x+=1.25,o=l.clone(t.name),o.position.y=1.5,o.position.x+=-1.25,i.scaling.scaleInPlace(j5._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}j5._Scale=.007;j5._CreateLightLines=(a,e)=>{const i=new Oe("root",e);i.rotation.x=Math.PI/2;const s=new Oe("linePivot",e);s.parent=i;const r=J1("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},e);if(r.position.y=r.scaling.y/2+1.2,r.parent=s,a<2)return s;for(let o=0;o<4;o++){const l=s.clone("lineParentClone");l.rotation.z=Math.PI/4,l.rotation.y=Math.PI/2+Math.PI/2*o,l.getChildMeshes()[0].scaling.y=.5,l.getChildMeshes()[0].scaling.x=l.getChildMeshes()[0].scaling.z=.8,l.getChildMeshes()[0].position.y=l.getChildMeshes()[0].scaling.y/2+1.2}if(a<3)return i;for(let o=0;o<4;o++){const l=s.clone("linePivotClone");l.rotation.z=Math.PI/2,l.rotation.y=Math.PI/2*o}if(a<4)return i;for(let o=0;o<4;o++){const l=s.clone("linePivotClone");l.rotation.z=Math.PI+Math.PI/4,l.rotation.y=Math.PI/2+Math.PI/2*o,l.getChildMeshes()[0].scaling.y=.5,l.getChildMeshes()[0].scaling.x=l.getChildMeshes()[0].scaling.z=.8,l.getChildMeshes()[0].position.y=l.getChildMeshes()[0].scaling.y/2+1.2}if(a<5)return i;const n=s.clone("linePivotClone");return n.rotation.z=Math.PI,i};class eB extends ua{constructor(e=Mn.DefaultUtilityLayer){super(e),this._pointerObserver=null,this.onClickedObservable=new Se,this._camera=null,this._invProjection=new ge,this._material=new jt("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Ie(.5,.5,.5),this._material.specularColor=new Ie(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(t=>{!this._camera||(this._isHovered=!!(t.pickInfo&&this._rootMesh.getChildMeshes().indexOf(t.pickInfo.pickedMesh)!=-1),this._isHovered&&t.event.button===0&&this.onClickedObservable.notifyObservers(this._camera))},mi.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._cameraMesh=eB._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraLinesMesh=eB._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach(i=>{i.material=this._material}),this._cameraMesh.parent=this._rootMesh,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 +}`;Ue.ShadersStore[vve]=Cve;const Ave="kernelBlurVertex",xve="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";Ue.IncludesShadersStore[Ave]=xve;const bve="kernelBlurVertexShader",Eve=`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 +}`;Ue.ShadersStore[bve]=Eve;class Rh extends rs{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,s,r,n=Te.BILINEAR_SAMPLINGMODE,o,l,c=0,h="",u=!1,p=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,o,l,null,c,"kernelBlur",{varyingCount:0,depCount:0},!0,p),this._blockCompilation=u,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add(m=>{this._outputTexture?m.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):m.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)}),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],o=0;for(let d=0;d0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){const t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,s=-(e*e/(2*t*t));return 1/i*Math.exp(s)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return Kt.Parse(()=>new Rh(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,s)}}z([X("kernel")],Rh.prototype,"_kernel",void 0);z([X("packedFloat")],Rh.prototype,"_packedFloat",void 0);z([FG()],Rh.prototype,"direction",void 0);$e("BABYLON.BlurPostProcess",Rh);class EW extends Oa{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,s,r=0,n=Te.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,s,!0,r,!1,n,o),this.mirrorPlane=new Zd(0,1,0,1),this._transformMatrix=ge.Zero(),this._mirrorMatrix=ge.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 l=i.getEngine();l.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add(()=>{var h;(h=l._debugPushGroup)===null||h===void 0||h.call(l,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var h;(h=l._debugPopGroup)===null||h===void 0||h.call(l,1)});let c;this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),ge.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),c=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=O.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=c})}_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 Rh("horizontal blur",new lt(1,0),this._blurKernelX,this._blurRatio,null,Te.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 Rh("vertical blur",new lt(0,1),this._blurKernelY,this._blurRatio,null,Te.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 EW(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 e;super.dispose();const t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),(e=this._sceneUBO)===null||e===void 0||e.dispose()}}Te._CreateMirror=(a,e,t,i)=>new EW(a,e,t,i);class Ic extends Sn{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(ge.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";return e.forEach(r=>s+=r),new Ic(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new Ic(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=r,n}constructor(e,t,i=null,s=!1,r=null,n=null,o=null,l=5,c=!1,h=null,u=!1,p=.8,m=0,_,f){var d;super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new Se,this.boundingBoxPosition=O.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new ge,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=l,this.isCube=!0,this._textureMatrix=ge.Identity(),this._createPolynomials=u,this.coordinatesMode=Te.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=h,this._loaderOptions=_,this._useSRGBBuffer=f,this._lodScale=p,this._lodOffset=m,!(!e&&!r)&&this.updateURL(e,h,n,c,o,i,(d=this.getScene())===null||d===void 0?void 0:d.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,o=!1,l=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);const c=e.lastIndexOf("."),h=t||(c>-1?e.substring(c).toLowerCase():""),u=h.indexOf(".dds")===0,p=h.indexOf(".env")===0,m=h.indexOf(".basis")===0;if(p?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),l)this._files=l;else if(!m&&!p&&!u&&!n&&(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let _=0;_o.getActiveTextures().indexOf(this)!==-1)),this._textureMatrix=e,!(!((i=this.getScene())===null||i===void 0)&&i.useRightHandedSystem)))return;const s=ue.Vector3[0],r=ue.Quaternion[0],n=ue.Vector3[1];this._textureMatrix.decompose(s,r,n),r.z*=-1,r.w*=-1,ge.ComposeToRef(s,r,n,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return!((e=this.getScene())===null||e===void 0)&&e.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var i;const s=this.getScene(),r=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const n=()=>{var l;this.onLoadObservable.notifyObservers(this),r&&(r.dispose(),(l=this.getScene())===null||l===void 0||l.markAllMaterialsAsDirty(1)),e&&e()},o=(l,c)=>{this._loadingError=!0,this._errorObject={message:l,exception:c},t&&t(l,c),Te.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Be.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(()=>n()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,s,this._lodScale,this._lodOffset,e,o,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,s,this._files,this._noMipmap,e,o,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),(i=this._texture)===null||i===void 0||i.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){const s=Kt.Parse(()=>{var r;let n=!1;return e.prefiltered&&(n=e.prefiltered),new Ic(i+((r=e.url)!==null&&r!==void 0?r:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,n,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=O.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=O.FromArray(e.boundingBoxSize)),e.animations)for(let r=0;r{const i=new Ic(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=i.uniqueId,i},this);return t.uniqueId=e,t}}z([X()],Ic.prototype,"url",void 0);z([bo()],Ic.prototype,"boundingBoxPosition",void 0);z([bo()],Ic.prototype,"boundingBoxSize",null);z([X("rotationY")],Ic.prototype,"rotationY",null);z([X("files")],Ic.prototype,"_files",void 0);z([X("forcedExtension")],Ic.prototype,"_forcedExtension",void 0);z([X("extensions")],Ic.prototype,"_extensions",void 0);z([vK("textureMatrix")],Ic.prototype,"_textureMatrix",void 0);z([vK("textureMatrixRefraction")],Ic.prototype,"_textureMatrixRefraction",void 0);Te._CubeTextureParser=Ic.Parse;$e("BABYLON.CubeTexture",Ic);const yve="backgroundFragmentDeclaration",Mve=`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 +`;Ue.IncludesShadersStore[yve]=Mve;const Tve="backgroundUboDeclaration",Sve=`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; +#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) +uniform vec3 vBackgroundCenter; +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 vReflectionControl; +#endif +}; +#include +`;Ue.IncludesShadersStore[Tve]=Sve;const Ive="backgroundPixelShader",Lve=`#ifdef TEXTURELODSUPPORT +#extension GL_EXT_shader_texture_lod : enable +#endif +precision highp float; +#include<__decl__backgroundFragment> +#include +#define RECIPROCAL_PI2 0.15915494 +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 +#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 +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +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 +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#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 +#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 +} +`;Ue.ShadersStore[Ive]=Lve;const Rve="backgroundVertexDeclaration",Pve=`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 +`;Ue.IncludesShadersStore[Rve]=Pve;const Dve="backgroundVertexShader",Ove=`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 +#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 +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[Dve]=Ove;class wve extends ta{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.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 Ur extends Bl{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=Ur.StandardReflectance0*t,this.reflectionReflectance90=Ur.StandardReflectance90*t):(t=t*2-1,this.reflectionReflectance0=Ur.StandardReflectance0+(1-Ur.StandardReflectance0)*t,this.reflectionReflectance90=Ur.StandardReflectance90+(1-Ur.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=Ie.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=O.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._renderTargets=new Sc(16),this._reflectionControls=Ui.Zero(),this._white=Ie.White(),this._primaryShadowColor=Ie.Black(),this._primaryHighlightColor=Ie.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){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new wve);const s=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if(ze.PrepareDefinesForLights(s,e,r,!1,this._maxSimultaneousLights),r._needNormals=!0,ze.PrepareDefinesForMultiview(s,r),r._areTexturesDirty){if(r._needUVs=!1,s.texturesEnabled){if(s.getEngine().getCaps().textureLOD&&(r.TEXTURELODSUPPORT=!0),this._diffuseTexture&&Xt.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;ze.PrepareDefinesForMergedUV(this._diffuseTexture,r,"DIFFUSE"),r.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,r.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,r.OPACITYFRESNEL=this._opacityFresnel}else r.DIFFUSE=!1,r.DIFFUSEDIRECTUV=0,r.DIFFUSEHASALPHA=!1,r.GAMMADIFFUSE=!1,r.OPACITYFRESNEL=!1;const o=this._reflectionTexture;if(o&&Xt.ReflectionTextureEnabled){if(!o.isReadyOrNotBlocking())return!1;switch(r.REFLECTION=!0,r.GAMMAREFLECTION=o.gammaSpace,r.RGBDREFLECTION=o.isRGBD,r.REFLECTIONBLUR=this._reflectionBlur>0,r.LODINREFLECTIONALPHA=o.lodLevelInAlpha,r.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,r.REFLECTIONBGR=this.switchToBGR,o.coordinatesMode===Te.INVCUBIC_MODE&&(r.INVERTCUBICMAP=!0),r.REFLECTIONMAP_3D=o.isCube,r.REFLECTIONMAP_OPPOSITEZ=r.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!o.invertZ:o.invertZ,o.coordinatesMode){case Te.EXPLICIT_MODE:r.REFLECTIONMAP_EXPLICIT=!0;break;case Te.PLANAR_MODE:r.REFLECTIONMAP_PLANAR=!0;break;case Te.PROJECTION_MODE:r.REFLECTIONMAP_PROJECTION=!0;break;case Te.SKYBOX_MODE:r.REFLECTIONMAP_SKYBOX=!0;break;case Te.SPHERICAL_MODE:r.REFLECTIONMAP_SPHERICAL=!0;break;case Te.EQUIRECTANGULAR_MODE:r.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Te.FIXED_EQUIRECTANGULAR_MODE:r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Te.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Te.CUBIC_MODE:case Te.INVCUBIC_MODE:default:r.REFLECTIONMAP_CUBIC=!0;break}this.reflectionFresnel?(r.REFLECTIONFRESNEL=!0,r.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):(r.REFLECTIONFRESNEL=!1,r.REFLECTIONFALLOFF=!1)}else r.REFLECTION=!1,r.REFLECTIONFRESNEL=!1,r.REFLECTIONFALLOFF=!1,r.REFLECTIONBLUR=!1,r.REFLECTIONMAP_3D=!1,r.REFLECTIONMAP_SPHERICAL=!1,r.REFLECTIONMAP_PLANAR=!1,r.REFLECTIONMAP_CUBIC=!1,r.REFLECTIONMAP_PROJECTION=!1,r.REFLECTIONMAP_SKYBOX=!1,r.REFLECTIONMAP_EXPLICIT=!1,r.REFLECTIONMAP_EQUIRECTANGULAR=!1,r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,r.INVERTCUBICMAP=!1,r.REFLECTIONMAP_OPPOSITEZ=!1,r.LODINREFLECTIONALPHA=!1,r.GAMMAREFLECTION=!1,r.RGBDREFLECTION=!1}r.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,r.USERGBCOLOR=this._useRGBColor,r.NOISE=this._enableNoise}if(r._areLightsDirty&&(r.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(this._primaryColorShadowLevel!==0||this._primaryColorHighlightLevel!==0),r.BACKMAT_SHADOWONLY=this._shadowOnly),r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r)}if(ze.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),ze.PrepareDefinesForFrameBoundValues(s,n,this,r,i,null,t.getRenderingMesh().hasThinInstances),ze.PrepareDefinesForAttributes(e,r,!1,!0,!1)&&e&&!s.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(se.NormalKind)&&(e.createNormals(!0),Me.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const o=new Fl;r.FOG&&o.addFallback(0,"FOG"),r.POINTSIZE&&o.addFallback(1,"POINTSIZE"),r.MULTIVIEW&&o.addFallback(0,"MULTIVIEW"),ze.HandleFallbacksForShadows(r,o,this._maxSimultaneousLights);const l=[se.PositionKind];r.NORMAL&&l.push(se.NormalKind),r.UV1&&l.push(se.UVKind),r.UV2&&l.push(se.UV2Kind),ze.PrepareAttributesForBones(l,e,r,o),ze.PrepareAttributesForInstances(l,r);const c=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"];lh(c);const h=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],u=["Material","Scene"];Dr&&(Dr.PrepareUniforms(c,r),Dr.PrepareSamplers(h,r)),ze.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:u,samplers:h,defines:r,maxSimultaneousLights:this._maxSimultaneousLights});const p=r.toString(),m=s.getEngine().createEffect("background",{attributes:l,uniformsNames:c,uniformBuffersNames:u,samplers:h,defines:p,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},n);t.setEffect(m,r,this._materialContext),this.buildUniformLayout()}return!t.effect||!t.effect.isReady()?!1:(r._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._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.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 s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),ze.BindBonesParameters(t,this._activeEffect);const o=this._mustRebind(s,n,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const l=this._reflectionTexture;(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync)&&(s.texturesEnabled&&(this._diffuseTexture&&Xt.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ze.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&&Xt.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.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),s.texturesEnabled&&(this._diffuseTexture&&Xt.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&&Xt.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",l):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)):this._uniformBuffer.setTexture("reflectionSampler",l),r.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)))),wc(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&ze.BindLights(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),ze.BindFogParameters(s,t,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),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 Kt.Clone(()=>new Ur(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new Ur(e.name,t),e,t,i)}}Ur.StandardReflectance0=.05;Ur.StandardReflectance90=.5;z([Br()],Ur.prototype,"_primaryColor",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],Ur.prototype,"primaryColor",void 0);z([Br()],Ur.prototype,"__perceptualColor",void 0);z([X()],Ur.prototype,"_primaryColorShadowLevel",void 0);z([X()],Ur.prototype,"_primaryColorHighlightLevel",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],Ur.prototype,"primaryColorHighlightLevel",null);z([xs()],Ur.prototype,"_reflectionTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"reflectionTexture",void 0);z([X()],Ur.prototype,"_reflectionBlur",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"reflectionBlur",void 0);z([xs()],Ur.prototype,"_diffuseTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"diffuseTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"shadowLights",void 0);z([X()],Ur.prototype,"_shadowLevel",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"shadowLevel",void 0);z([bo()],Ur.prototype,"_sceneCenter",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"sceneCenter",void 0);z([X()],Ur.prototype,"_opacityFresnel",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"opacityFresnel",void 0);z([X()],Ur.prototype,"_reflectionFresnel",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"reflectionFresnel",void 0);z([X()],Ur.prototype,"_reflectionFalloffDistance",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"reflectionFalloffDistance",void 0);z([X()],Ur.prototype,"_reflectionAmount",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"reflectionAmount",void 0);z([X()],Ur.prototype,"_reflectionReflectance0",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"reflectionReflectance0",void 0);z([X()],Ur.prototype,"_reflectionReflectance90",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"reflectionReflectance90",void 0);z([X()],Ur.prototype,"_useRGBColor",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"useRGBColor",void 0);z([X()],Ur.prototype,"_enableNoise",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"enableNoise",void 0);z([X()],Ur.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"maxSimultaneousLights",void 0);z([X()],Ur.prototype,"_shadowOnly",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],Ur.prototype,"shadowOnly",void 0);z([U$()],Ur.prototype,"_imageProcessingConfiguration",void 0);$e("BABYLON.BackgroundMaterial",Ur);class UL{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Ie(.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 Ie(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:O.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,s)=>{this.onErrorObservable.notifyObservers({message:i,exception:s})},this._options=Object.assign(Object.assign({},UL._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new Se,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t=Object.assign(Object.assign({},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 Zt(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 Sn){this._scene.environmentTexture=this._options.environmentTexture;return}const e=Ic.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new Oe("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 s=this._scene.getWorldExtends(n=>n!==this._ground&&n!==this._rootMesh&&n!==this._skybox),r=s.max.subtract(s.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof dr&&this._scene.activeCamera.upperRadiusLimit&&(e=this._scene.activeCamera.upperRadiusLimit*2,t=e);const n=r.length();n>e&&(e=n*2,t=e),e*=1.1,t*=1.5,i=s.min.add(r.scale(.5)),i.y=s.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=Jd("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 Ur("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 Sn){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new Te(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=Te.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new EW("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Te.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Zd(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let s=0;s{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){!this._skybox||(this._skyboxMaterial||(this._skyboxMaterial=new Ur("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 Sn){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new Ic(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Te.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)}}UL._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png";UL._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds";UL._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class m0 extends Ki{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Te.CLAMP_ADDRESSMODE,this._texture.wrapV=Te.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Te.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Te.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,s,r=null){super(e,s),this.onError=r,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=m0.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new Se,this.onLoadObservable=new Se,s=this.getScene(),e=e||"textureDome",i.resolution=Math.abs(i.resolution)|0||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=i.autoPlay===void 0?!0:Boolean(i.autoPlay),i.loop=i.loop===void 0?!0:Boolean(i.loop),i.size=Math.abs(i.size)||(s.activeCamera?s.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=$d(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:Oe.BACKSIDE},s);const n=this._material=new Ur(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,s,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=$d("",{slice:.5,diameter:i.size*.98,segments:i.resolution*2,sideOrientation:Oe.BACKSIDE},s),this._halfDomeMask.rotate(Fo.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&&s.activeCamera){const l=s.activeCamera,c=O.Forward(),h=O.TransformNormal(c,l.getViewMatrix());h.normalize(),this.rotation.y=Math.acos(O.Dot(c,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 m0.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case m0.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(s=>{let r=s.isRightCamera;this._crossEye&&(r=!r),r?this._texture.uOffset=t:this._texture.uOffset=i});break}case m0.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)}}m0.MODE_MONOSCOPIC=0;m0.MODE_TOPBOTTOM=1;m0.MODE_SIDEBYSIDE=2;class tQ extends m0{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 Te(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,()=>{this.onLoadObservable.notifyObservers()},(s,r)=>{this.onLoadErrorObservable.notifyObservers(s||"Unknown error occured"),this.onError&&this.onError(s,r)})}}tQ.MODE_MONOSCOPIC=m0.MODE_MONOSCOPIC;tQ.MODE_TOPBOTTOM=m0.MODE_TOPBOTTOM;tQ.MODE_SIDEBYSIDE=m0.MODE_SIDEBYSIDE;const Nve="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 Bve=0;const yW=a=>{if(!a.environmentBRDFTexture){const e=a.useDelayedTextureLoading;a.useDelayedTextureLoading=!1;const t=a._blockEntityCollection;a._blockEntityCollection=!1;const i=Te.CreateFromBase64String(Nve,"EnvironmentBRDFTexture"+Bve++,a,!0,!1,Te.BILINEAR_SAMPLINGMODE);a._blockEntityCollection=t;const s=a.getEngine().getLoadedTexturesCache(),r=s.indexOf(i.getInternalTexture());r!==-1&&s.splice(r,1),i.isRGBD=!0,i.wrapU=Te.CLAMP_ADDRESSMODE,i.wrapV=Te.CLAMP_ADDRESSMODE,a.environmentBRDFTexture=i,a.useDelayedTextureLoading=e,_X.ExpandRGBDTexture(i);const n=a.getEngine().onContextRestoredObservable.add(()=>{i.isRGBD=!0;const o=()=>{i.isReady()?_X.ExpandRGBDTexture(i):Be.SetImmediate(o)};o()});a.onDisposeObservable.add(()=>{a.getEngine().onContextRestoredObservable.remove(n)})}return a.environmentBRDFTexture},Fve={GetEnvironmentBRDFTexture:yW};class Vve extends ta{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 Y1 extends l4{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new Vve,t),this._useEnergyConservation=Y1.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Y1.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Y1.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Y1.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Y1.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Y1.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Y1.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Y1.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"}}Y1.DEFAULT_USE_ENERGY_CONSERVATION=!0;Y1.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;Y1.DEFAULT_USE_SPHERICAL_HARMONICS=!0;Y1.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;z([X(),_t("_markAllSubMeshesAsMiscDirty")],Y1.prototype,"useEnergyConservation",void 0);z([X(),_t("_markAllSubMeshesAsMiscDirty")],Y1.prototype,"useSmithVisibilityHeightCorrelated",void 0);z([X(),_t("_markAllSubMeshesAsMiscDirty")],Y1.prototype,"useSphericalHarmonics",void 0);z([X(),_t("_markAllSubMeshesAsMiscDirty")],Y1.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);const zve="pbrFragmentDeclaration",Uve=`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 +#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 +`;Ue.IncludesShadersStore[zve]=Uve;const kve="pbrUboDeclaration",Hve=`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 +`;Ue.IncludesShadersStore[kve]=Hve;const jve="pbrFragmentExtraDeclaration",Gve=`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 +`;Ue.IncludesShadersStore[jve]=Gve;const Wve="samplerFragmentAlternateDeclaration",Yve=`#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 +`;Ue.IncludesShadersStore[Wve]=Yve;const Xve="pbrFragmentSamplersDeclaration",Kve=`#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 +`;Ue.IncludesShadersStore[Xve]=Kve;const Qve="subSurfaceScatteringFunctions",Zve=`bool testLightingForSSS(float diffusionProfile) +{return diffusionProfile<1.;}`;Ue.IncludesShadersStore[Qve]=Zve;const qve="importanceSampling",Jve=`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);}`;Ue.IncludesShadersStore[qve]=Jve;const $ve="pbrHelperFunctions",e8e=`#define RECIPROCAL_PI2 0.15915494 +#define RECIPROCAL_PI 0.31830988618 +#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 +`;Ue.IncludesShadersStore[$ve]=e8e;const t8e="harmonicsFunctions",i8e=`#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 +`;Ue.IncludesShadersStore[t8e]=i8e;const s8e="pbrDirectLightingSetupFunctions",r8e=`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;}`;Ue.IncludesShadersStore[s8e]=r8e;const n8e="pbrDirectLightingFalloffFunctions",a8e=`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 +}`;Ue.IncludesShadersStore[n8e]=a8e;const o8e="pbrBRDFFunctions",l8e=`#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);if (alphaG==0.) {vec3 c=textureCube(inputTexture,n).rgb; +#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 +`;Ue.IncludesShadersStore[c8e]=h8e;const u8e="pbrDirectLightingFunctions",d8e=`#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 +`;Ue.IncludesShadersStore[u8e]=d8e;const f8e="pbrIBLFunctions",p8e=`#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 +`;Ue.IncludesShadersStore[f8e]=p8e;const m8e="pbrBlockAlbedoOpacity",_8e=`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;} +`;Ue.IncludesShadersStore[g8e]=v8e;const C8e="pbrBlockAmbientOcclusion",A8e=`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;} +`;Ue.IncludesShadersStore[C8e]=A8e;const x8e="pbrBlockAlphaFresnel",b8e=`#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 +`;Ue.IncludesShadersStore[E8e]=y8e;const M8e="pbrBlockReflection",T8e=`#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 +`;Ue.IncludesShadersStore[M8e]=T8e;const S8e="pbrBlockSheen",I8e=`#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 +`;Ue.IncludesShadersStore[S8e]=I8e;const L8e="pbrBlockClearcoat",R8e=`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 +`;Ue.IncludesShadersStore[L8e]=R8e;const P8e="pbrBlockIridescence",D8e=`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 +`;Ue.IncludesShadersStore[P8e]=D8e;const O8e="pbrBlockSubSurface",w8e=`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 +#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 +#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 ANISOTROPIC +vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y); +#else +vec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y); +#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 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 +#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 +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 +`;Ue.IncludesShadersStore[O8e]=w8e;const N8e="pbrBlockNormalGeometric",B8e=`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 +`;Ue.IncludesShadersStore[N8e]=B8e;const F8e="pbrBlockNormalFinal",V8e=`#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 +`;Ue.IncludesShadersStore[F8e]=V8e;const z8e="pbrBlockLightmapInit",U8e=`#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 +`;Ue.IncludesShadersStore[z8e]=U8e;const k8e="pbrBlockGeometryInfo",H8e=`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 +`;Ue.IncludesShadersStore[k8e]=H8e;const j8e="pbrBlockReflectance0",G8e=`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 +`;Ue.IncludesShadersStore[j8e]=G8e;const W8e="pbrBlockReflectance",Y8e=`#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 +`;Ue.IncludesShadersStore[W8e]=Y8e;const X8e="pbrBlockDirectLighting",K8e=`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 +`;Ue.IncludesShadersStore[X8e]=K8e;const Q8e="pbrBlockFinalLitComponents",Z8e=`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 +`;Ue.IncludesShadersStore[Q8e]=Z8e;const q8e="pbrBlockFinalUnlitComponents",J8e=`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; +`;Ue.IncludesShadersStore[q8e]=J8e;const $8e="pbrBlockFinalColorComposition",e5e=`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); +`;Ue.IncludesShadersStore[$8e]=e5e;const t5e="pbrBlockImageProcessing",i5e=`#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 +`;Ue.IncludesShadersStore[t5e]=i5e;const s5e="pbrDebug",r5e=`#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 +`;Ue.IncludesShadersStore[s5e]=r5e;const n5e="pbrPixelShader",a5e=`#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 +#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 +} +`;Ue.ShadersStore[n5e]=a5e;const o5e="pbrVertexDeclaration",l5e=`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 +`;Ue.IncludesShadersStore[o5e]=l5e;const c5e="pbrVertexShader",h5e=`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 +}`;Ue.ShadersStore[c5e]=h5e;class qce extends ta{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 Ph extends l4{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new qce,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=Ph._DefaultIndexOfRefraction,this.indexOfRefraction=Ph._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=Ie.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 s=this._material._disableBumpMap;return!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Xt.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&Xt.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&&Xt.ClearCoatBumpTextureEnabled&&!s&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&Xt.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||i===void 0?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Xt.ClearCoatTextureEnabled?ze.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&Xt.ClearCoatTextureEnabled?ze.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&Xt.ClearCoatBumpTextureEnabled?ze.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===Ph._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&Xt.ClearCoatTintTextureEnabled?(ze.PrepareDefinesForMergedUV(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,s){var r,n,o,l,c,h,u,p;if(!this._isEnabled)return;const m=s.materialDefines,_=this._material.isFrozen,f=this._material._disableBumpMap,d=this._material._invertNormalMapX,C=this._material._invertNormalMapY,v=m.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!_||!e.isSync){v&&Xt.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),ze.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&Xt.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",(n=(r=this._texture)===null||r===void 0?void 0:r.coordinatesIndex)!==null&&n!==void 0?n:0,(l=(o=this._texture)===null||o===void 0?void 0:o.level)!==null&&l!==void 0?l:0,(h=(c=this._textureRoughness)===null||c===void 0?void 0:c.coordinatesIndex)!==null&&h!==void 0?h:0,(p=(u=this._textureRoughness)===null||u===void 0?void 0:u.level)!==null&&p!==void 0?p:0),this._texture&&ze.BindTextureMatrix(this._texture,e,"clearCoat"),this._textureRoughness&&!v&&!m.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&ze.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&Xt.ClearCoatTextureEnabled&&!f&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),ze.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",d?1:-1,C?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",d?-1:1,C?-1:1)),this._tintTexture&&Xt.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),ze.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const y=1-this._indexOfRefraction,M=1+this._indexOfRefraction,b=Math.pow(-y/M,2),E=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",b,E,y,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&&Xt.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!v&&!m.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Xt.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&Xt.ClearCoatBumpTextureEnabled&&!f&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&Xt.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,s,r;e&&((t=this._texture)===null||t===void 0||t.dispose(),(i=this._textureRoughness)===null||i===void 0||i.dispose(),(s=this._bumpTexture)===null||s===void 0||s.dispose(),(r=this._tintTexture)===null||r===void 0||r.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"}]}}}Ph._DefaultIndexOfRefraction=1.5;z([X(),_t("_markAllSubMeshesAsTexturesDirty")],Ph.prototype,"isEnabled",void 0);z([X()],Ph.prototype,"intensity",void 0);z([X()],Ph.prototype,"roughness",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],Ph.prototype,"indexOfRefraction",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],Ph.prototype,"texture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],Ph.prototype,"useRoughnessFromMainTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],Ph.prototype,"textureRoughness",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],Ph.prototype,"remapF0OnInterfaceChange",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],Ph.prototype,"bumpTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],Ph.prototype,"isTintEnabled",void 0);z([Br()],Ph.prototype,"tintColor",void 0);z([X()],Ph.prototype,"tintColorAtDistance",void 0);z([X()],Ph.prototype,"tintThickness",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],Ph.prototype,"tintTexture",void 0);class Jce extends ta{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 $1 extends l4{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new Jce,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=$1._DefaultMinimumThickness,this.maximumThickness=$1._DefaultMaximumThickness,this.indexOfRefraction=$1._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&&Xt.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&&Xt.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||i===void 0?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Xt.IridescenceTextureEnabled?ze.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&Xt.IridescenceTextureEnabled?ze.PrepareDefinesForMergedUV(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,s){var r,n,o,l,c,h,u,p;if(!this._isEnabled)return;const m=s.materialDefines,_=this._material.isFrozen,f=m.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;(!e.useUbo||!_||!e.isSync)&&(f&&Xt.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),ze.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&Xt.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",(n=(r=this._texture)===null||r===void 0?void 0:r.coordinatesIndex)!==null&&n!==void 0?n:0,(l=(o=this._texture)===null||o===void 0?void 0:o.level)!==null&&l!==void 0?l:0,(h=(c=this._thicknessTexture)===null||c===void 0?void 0:c.coordinatesIndex)!==null&&h!==void 0?h:0,(p=(u=this._thicknessTexture)===null||u===void 0?void 0:u.level)!==null&&p!==void 0?p:0),this._texture&&ze.BindTextureMatrix(this._texture,e,"iridescence"),this._thicknessTexture&&!f&&!m.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&ze.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&Xt.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!f&&!m.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&Xt.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===void 0||t.dispose(),(i=this._thicknessTexture)===null||i===void 0||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"}]}}}$1._DefaultMinimumThickness=100;$1._DefaultMaximumThickness=400;$1._DefaultIndexOfRefraction=1.3;z([X(),_t("_markAllSubMeshesAsTexturesDirty")],$1.prototype,"isEnabled",void 0);z([X()],$1.prototype,"intensity",void 0);z([X()],$1.prototype,"minimumThickness",void 0);z([X()],$1.prototype,"maximumThickness",void 0);z([X()],$1.prototype,"indexOfRefraction",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],$1.prototype,"texture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],$1.prototype,"thicknessTexture",void 0);class $ce extends ta{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class ZL extends l4{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 $ce,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new lt(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&&Xt.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(se.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Xt.AnisotropicTextureEnabled?ze.PrepareDefinesForMergedUV(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&&Xt.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),ze.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&Xt.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)}}z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ZL.prototype,"isEnabled",void 0);z([X()],ZL.prototype,"intensity",void 0);z([FG()],ZL.prototype,"direction",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ZL.prototype,"texture",void 0);z([X(),_t("_markAllSubMeshesAsMiscDirty")],ZL.prototype,"legacy",void 0);class ehe extends ta{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 _C extends l4{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new ehe,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Ie.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&&Xt.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&Xt.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||i===void 0?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Xt.SheenTextureEnabled?(ze.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&Xt.SheenTextureEnabled?ze.PrepareDefinesForMergedUV(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,s){var r,n,o,l,c,h,u,p;if(!this._isEnabled)return;const m=s.materialDefines,_=this._material.isFrozen,f=m.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;(!e.useUbo||!_||!e.isSync)&&(f&&Xt.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),ze.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&Xt.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",(n=(r=this._texture)===null||r===void 0?void 0:r.coordinatesIndex)!==null&&n!==void 0?n:0,(l=(o=this._texture)===null||o===void 0?void 0:o.level)!==null&&l!==void 0?l:0,(h=(c=this._textureRoughness)===null||c===void 0?void 0:c.coordinatesIndex)!==null&&h!==void 0?h:0,(p=(u=this._textureRoughness)===null||u===void 0?void 0:u.level)!==null&&p!==void 0?p:0),this._texture&&ze.BindTextureMatrix(this._texture,e,"sheen"),this._textureRoughness&&!f&&!m.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ze.BindTextureMatrix(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&&Xt.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!f&&!m.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Xt.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===void 0||t.dispose(),(i=this._textureRoughness)===null||i===void 0||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"}]}}}z([X(),_t("_markAllSubMeshesAsTexturesDirty")],_C.prototype,"isEnabled",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],_C.prototype,"linkSheenWithAlbedo",void 0);z([X()],_C.prototype,"intensity",void 0);z([Br()],_C.prototype,"color",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],_C.prototype,"texture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],_C.prototype,"useRoughnessFromMainTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],_C.prototype,"roughness",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],_C.prototype,"textureRoughness",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],_C.prototype,"albedoScaling",void 0);class the extends ta{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_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 ec extends l4{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 the,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!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=Ie.White(),this.tintColorAtDistance=1,this.diffusionDistance=Ie.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&&Xt.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const i=this._getRefractionTexture(t);if(i&&Xt.RefractionTextureEnabled&&!i.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){e.SUBSURFACE=!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_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,s=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,r=(i||!this._refractionIntensityTexture)&&(s||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&Xt.ThicknessTextureEnabled&&ze.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&Xt.RefractionIntensityTextureEnabled&&!r&&ze.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&Xt.TranslucencyIntensityTextureEnabled&&!r&&ze.PrepareDefinesForMergedUV(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)&&r,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&r,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&r,this._isRefractionEnabled&&t.texturesEnabled){const n=this._getRefractionTexture(t);n&&Xt.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=n.isCube,e.SS_GAMMAREFRACTION=n.gammaSpace,e.SS_RGBDREFRACTION=n.isRGBD,e.SS_LINEARSPECULARREFRACTION=n.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&n.isCube?!n.invertZ:n.invertZ,e.SS_LODINREFRACTIONALPHA=n.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=n.isCube&&n.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;s.getRenderingMesh().getWorldMatrix().decompose(ue.Vector3[0]);const r=Math.max(Math.abs(ue.Vector3[0].x),Math.abs(ue.Vector3[0].y),Math.abs(ue.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*r,(this.maximumThickness-this.minimumThickness)*r)}bindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,l=r.LODBASEDMICROSFURACE,c=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&Xt.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),ze.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&Xt.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),ze.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&Xt.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),ze.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),c&&Xt.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",c.getRefractionTextureMatrix());let h=1;c.isCube||c.depth&&(h=c.depth);const u=c.getSize().width,p=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",c.level,1/p,h,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",u,c.lodGenerationScale,c.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",u,Bt.Log2(u)),c.boundingBoxSize){const m=c;e.updateVector3("vRefractionPosition",m.boundingBoxPosition),e.updateVector3("vRefractionSize",m.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)}t.texturesEnabled&&(this._thicknessTexture&&Xt.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&Xt.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&Xt.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),c&&Xt.RefractionTextureEnabled&&(l?e.setTexture("refractionSampler",c):(e.setTexture("refractionSampler",c._lodTextureMid||c),e.setTexture("refractionSamplerLow",c._lodTextureLow||c),e.setTexture("refractionSamplerHigh",c._lodTextureHigh||c))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){Xt.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!(Xt.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"}]}}}z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"isRefractionEnabled",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"isTranslucencyEnabled",void 0);z([X(),_t("_markScenePrePassDirty")],ec.prototype,"isScatteringEnabled",void 0);z([X()],ec.prototype,"_scatteringDiffusionProfileIndex",void 0);z([X()],ec.prototype,"refractionIntensity",void 0);z([X()],ec.prototype,"translucencyIntensity",void 0);z([X()],ec.prototype,"useAlbedoToTintRefraction",void 0);z([X()],ec.prototype,"useAlbedoToTintTranslucency",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"thicknessTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"refractionTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"indexOfRefraction",void 0);z([X()],ec.prototype,"_volumeIndexOfRefraction",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"volumeIndexOfRefraction",null);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"invertRefractionY",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"linkRefractionWithTransparency",void 0);z([X()],ec.prototype,"minimumThickness",void 0);z([X()],ec.prototype,"maximumThickness",void 0);z([X()],ec.prototype,"useThicknessAsDepth",void 0);z([Br()],ec.prototype,"tintColor",void 0);z([X()],ec.prototype,"tintColorAtDistance",void 0);z([Br()],ec.prototype,"diffusionDistance",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"useMaskFromThicknessTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"refractionIntensityTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"translucencyIntensityTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ec.prototype,"useGltfStyleTextures",void 0);const mN={effect:null,subMesh:null};class Kq extends ta{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 Fr extends Bl{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 Ui(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Fr.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=Ie.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Ie(0,0,0),this._albedoColor=new Ie(1,1,1),this._reflectivityColor=new Ie(1,1,1),this._reflectionColor=new Ie(1,1,1),this._emissiveColor=new Ie(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=Fr.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 Sc(16),this._globalAmbientColor=new Ie(0,0,0),this._useLogarithmicDepth=!1,this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Y1(this),this.clearCoat=new Ph(this),this.iridescence=new $1(this),this.anisotropy=new ZL(this),this.sheen=new _C(this),this.subSurface=new ec(this),this.detailMap=new lT(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Xt.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=yW(this.getScene()),this.prePassConfiguration=new fX}get hasRenderTargetTextures(){return Xt.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}get _disableAlphaBlending(){var e;return this._transparencyMode===Fr.PBRMATERIAL_OPAQUE||this._transparencyMode===Fr.PBRMATERIAL_ALPHATEST||((e=this.subSurface)===null||e===void 0?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===void 0)&&e.disableAlphaBlending?!1:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===Fr.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Fr.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var s;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(zu.GetDefineNames,this._eventInfo),t.materialDefines=new Kq(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&Xt.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&Xt.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&Xt.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const p=this._getReflectionTexture();if(p&&Xt.ReflectionTextureEnabled){if(!p.isReadyOrNotBlocking())return!1;if(p.irradianceTexture){if(!p.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!p.sphericalPolynomial&&((s=p.getInternalTexture())===null||s===void 0?void 0:s._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&Xt.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&Xt.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(Xt.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&&Xt.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&Xt.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;!o.getCaps().standardDerivatives&&!e.isVerticesDataPresent(se.NormalKind)&&(e.createNormals(!0),Me.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const l=t.effect,c=r._areLightsDisposed;let h=this._prepareEffect(e,r,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),u=!1;if(h)if(this._onEffectCreatedObservable&&(mN.effect=h,mN.subMesh=t,this._onEffectCreatedObservable.notifyObservers(mN)),this.allowShaderHotSwapping&&l&&!h.isReady()){if(h=l,r.markAsUnprocessed(),u=this.isFrozen,c)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,r,this._materialContext);return!t.effect||!t.effect.isReady()?!1:(r._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!u,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!!(this._metallic!=null||this._roughness!=null||this._metallicTexture)}_prepareEffect(e,t,i=null,s=null,r=null,n=null,o){if(this._prepareDefines(e,t,r,n,o),!t.isDirty)return null;t.markAsProcessed();const c=this.getScene().getEngine(),h=new Fl;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=ze.HandleFallbacksForShadows(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 p=[se.PositionKind];t.NORMAL&&p.push(se.NormalKind),t.TANGENT&&p.push(se.TangentKind);for(let b=1;b<=6;++b)t["UV"+b]&&p.push(`uv${b===1?"":b}`);t.VERTEXCOLOR&&p.push(se.ColorKind),t.INSTANCESCOLOR&&p.push(se.ColorInstanceKind),ze.PrepareAttributesForBones(p,e,t,h),ze.PrepareAttributesForInstances(p,t),ze.PrepareAttributesForMorphTargets(p,e,t),ze.PrepareAttributesForBakedVertexAnimation(p,e,t);let m="pbr";const _=["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"],f=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],C={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=u,this._eventInfo.defines=t,this._eventInfo.uniforms=_,this._eventInfo.attributes=p,this._eventInfo.samplers=f,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=C,this._callbackPluginEventGeneric(zu.PrepareEffect,this._eventInfo),fX.AddUniforms(_),lh(_),Dr&&(Dr.PrepareUniforms(_,t),Dr.PrepareSamplers(f,t)),ze.PrepareUniformsAndSamplersList({uniformsNames:_,uniformBuffersNames:d,samplers:f,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const v={};this.customShaderNameResolve&&(m=this.customShaderNameResolve(m,_,d,f,t,p,v));const y=t.toString(),M=c.createEffect(m,{attributes:p,uniformsNames:_,uniformBuffersNames:d,samplers:f,defines:y,fallbacks:h,onCompiled:i,onError:s,indexParameters:C,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},c);return this._eventInfo.customCode=void 0,M}_prepareDefines(e,t,i=null,s=null,r=!1){var n;const o=this.getScene(),l=o.getEngine();ze.PrepareDefinesForLights(o,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,ze.PrepareDefinesForMultiview(o,t);const c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(ze.PrepareDefinesForPrePass(o,t,this.canRenderToMRT&&!c),ze.PrepareDefinesForOIT(o,t,c),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let h=1;h<=6;++h)t["MAINUV"+h]=!1;if(o.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,l.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&Xt.DiffuseTextureEnabled?(ze.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&Xt.AmbientTextureEnabled?(ze.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&Xt.OpacityTextureEnabled?(ze.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const h=this._getReflectionTexture();if(h&&Xt.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,l._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=h.coordinatesMode===Te.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 Te.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Te.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Te.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Te.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Te.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Te.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Te.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Te.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Te.CUBIC_MODE:case Te.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!h.boundingBoxSize;break}h.coordinatesMode!==Te.SKYBOX_MODE&&(h.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):h.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||l.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&&Xt.LightmapTextureEnabled?(ze.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&Xt.EmissiveTextureEnabled?(ze.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,Xt.SpecularTextureEnabled){if(this._metallicTexture?(ze.PrepareDefinesForMergedUV(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?(ze.PrepareDefinesForMergedUV(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===((n=this._reflectanceTexture)===null||n===void 0?void 0:n._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!u,this._metallicReflectanceTexture?(ze.PrepareDefinesForMergedUV(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)?(ze.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?ze.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;l.getCaps().standardDerivatives&&this._bumpTexture&&Xt.BumpTextureEnabled&&!this._disableBumpMap?(ze.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&Xt.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=o.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&&Xt.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===Fr.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Fr.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=l.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&&(ze.PrepareDefinesForMisc(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(se.NormalKind),t.DEBUGMODE=this._debugMode),ze.PrepareDefinesForFrameBoundValues(o,l,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ze.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==Fr.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(zu.GetDefineNames,this._eventInfo);const r=new Kq(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(mN.effect=n,mN.subMesh=null,this._onEffectCreatedObservable.notifyObservers(mN)),n.isReady()?t&&t(this):n.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 s,r,n,o;const l=this.getScene(),c=i.materialDefines;if(!c)return;const h=i.effect;if(!h)return;this._activeEffect=h,t.getMeshUniformBuffer().bindToEffect(h,"Mesh"),t.transferToEffect(e);const u=l.getEngine();this._uniformBuffer.bindToEffect(h,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,l,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),c.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const p=h._forceRebindOnNextCall||this._mustRebind(l,h,t.visibility);ze.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let m=null;const _=this._uniformBuffer;if(p){if(this.bindViewProjection(h),m=this._getReflectionTexture(),!_.useUbo||!this.isFrozen||!_.isSync||h._forceRebindOnNextCall){if(l.texturesEnabled){if(this._albedoTexture&&Xt.DiffuseTextureEnabled&&(_.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),ze.BindTextureMatrix(this._albedoTexture,_,"albedo")),this._ambientTexture&&Xt.AmbientTextureEnabled&&(_.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),ze.BindTextureMatrix(this._ambientTexture,_,"ambient")),this._opacityTexture&&Xt.OpacityTextureEnabled&&(_.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ze.BindTextureMatrix(this._opacityTexture,_,"opacity")),m&&Xt.ReflectionTextureEnabled){if(_.updateMatrix("reflectionMatrix",m.getReflectionTextureMatrix()),_.updateFloat2("vReflectionInfos",m.level,0),m.boundingBoxSize){const f=m;_.updateVector3("vReflectionPosition",f.boundingBoxPosition),_.updateVector3("vReflectionSize",f.boundingBoxSize)}if(this.realTimeFiltering){const f=m.getSize().width;_.updateFloat2("vReflectionFilteringInfo",f,Bt.Log2(f))}if(!c.USEIRRADIANCEMAP){const f=m.sphericalPolynomial;if(c.USESPHERICALFROMREFLECTIONMAP&&f)if(c.SPHERICAL_HARMONICS){const d=f.preScaledHarmonics;_.updateVector3("vSphericalL00",d.l00),_.updateVector3("vSphericalL1_1",d.l1_1),_.updateVector3("vSphericalL10",d.l10),_.updateVector3("vSphericalL11",d.l11),_.updateVector3("vSphericalL2_2",d.l2_2),_.updateVector3("vSphericalL2_1",d.l2_1),_.updateVector3("vSphericalL20",d.l20),_.updateVector3("vSphericalL21",d.l21),_.updateVector3("vSphericalL22",d.l22)}else _.updateFloat3("vSphericalX",f.x.x,f.x.y,f.x.z),_.updateFloat3("vSphericalY",f.y.x,f.y.y,f.y.z),_.updateFloat3("vSphericalZ",f.z.x,f.z.y,f.z.z),_.updateFloat3("vSphericalXX_ZZ",f.xx.x-f.zz.x,f.xx.y-f.zz.y,f.xx.z-f.zz.z),_.updateFloat3("vSphericalYY_ZZ",f.yy.x-f.zz.x,f.yy.y-f.zz.y,f.yy.z-f.zz.z),_.updateFloat3("vSphericalZZ",f.zz.x,f.zz.y,f.zz.z),_.updateFloat3("vSphericalXY",f.xy.x,f.xy.y,f.xy.z),_.updateFloat3("vSphericalYZ",f.yz.x,f.yz.y,f.yz.z),_.updateFloat3("vSphericalZX",f.zx.x,f.zx.y,f.zx.z)}_.updateFloat3("vReflectionMicrosurfaceInfos",m.getSize().width,m.lodGenerationScale,m.lodGenerationOffset)}this._emissiveTexture&&Xt.EmissiveTextureEnabled&&(_.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ze.BindTextureMatrix(this._emissiveTexture,_,"emissive")),this._lightmapTexture&&Xt.LightmapTextureEnabled&&(_.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ze.BindTextureMatrix(this._lightmapTexture,_,"lightmap")),Xt.SpecularTextureEnabled&&(this._metallicTexture?(_.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),ze.BindTextureMatrix(this._metallicTexture,_,"reflectivity")):this._reflectivityTexture&&(_.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),ze.BindTextureMatrix(this._reflectivityTexture,_,"reflectivity")),this._metallicReflectanceTexture&&(_.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),ze.BindTextureMatrix(this._metallicReflectanceTexture,_,"metallicReflectance")),this._reflectanceTexture&&c.REFLECTANCE&&(_.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),ze.BindTextureMatrix(this._reflectanceTexture,_,"reflectance")),this._microSurfaceTexture&&(_.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),ze.BindTextureMatrix(this._microSurfaceTexture,_,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&Xt.BumpTextureEnabled&&!this._disableBumpMap&&(_.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),ze.BindTextureMatrix(this._bumpTexture,_,"bump"),l._mirroredCameraPosition?_.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):_.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&_.updateFloat("pointSize",this.pointSize),c.METALLICWORKFLOW){hn.Color3[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,hn.Color3[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness,_.updateColor4("vReflectivityColor",hn.Color3[0],1);const f=(r=(s=this.subSurface)===null||s===void 0?void 0:s._indexOfRefraction)!==null&&r!==void 0?r:1.5,d=1,C=Math.pow((f-d)/(f+d),2);this._metallicReflectanceColor.scaleToRef(C*this._metallicF0Factor,hn.Color3[0]);const v=this._metallicF0Factor;_.updateColor4("vMetallicReflectanceFactors",hn.Color3[0],v)}else _.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);_.updateColor3("vEmissiveColor",Xt.EmissiveTextureEnabled?this._emissiveColor:Ie.BlackReadOnly),_.updateColor3("vReflectionColor",this._reflectionColor),!c.SS_REFRACTION&&((n=this.subSurface)===null||n===void 0?void 0:n._linkRefractionWithTransparency)?_.updateColor4("vAlbedoColor",this._albedoColor,1):_.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*l.environmentIntensity,this._lightingInfos.w=this._specularIntensity,_.updateVector4("vLightingIntensity",this._lightingInfos),l.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),_.updateColor3("vAmbientColor",this._globalAmbientColor),_.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}l.texturesEnabled&&(this._albedoTexture&&Xt.DiffuseTextureEnabled&&_.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&Xt.AmbientTextureEnabled&&_.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Xt.OpacityTextureEnabled&&_.setTexture("opacitySampler",this._opacityTexture),m&&Xt.ReflectionTextureEnabled&&(c.LODBASEDMICROSFURACE?_.setTexture("reflectionSampler",m):(_.setTexture("reflectionSampler",m._lodTextureMid||m),_.setTexture("reflectionSamplerLow",m._lodTextureLow||m),_.setTexture("reflectionSamplerHigh",m._lodTextureHigh||m)),c.USEIRRADIANCEMAP&&_.setTexture("irradianceSampler",m.irradianceTexture)),c.ENVIRONMENTBRDF&&_.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&Xt.EmissiveTextureEnabled&&_.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Xt.LightmapTextureEnabled&&_.setTexture("lightmapSampler",this._lightmapTexture),Xt.SpecularTextureEnabled&&(this._metallicTexture?_.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&_.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&_.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&c.REFLECTANCE&&_.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&_.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&Xt.BumpTextureEnabled&&!this._disableBumpMap&&_.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(h),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),wc(this._activeEffect,this,l),this.bindEyePosition(h)}else l.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(p||!this.isFrozen)&&(l.lightsEnabled&&!this._disableLighting&&ze.BindLights(l,t,this._activeEffect,c,this._maxSimultaneousLights),(l.fogEnabled&&t.applyFog&&l.fogMode!==oi.FOGMODE_NONE||m||t.receiveShadows||c.PREPASS)&&this.bindView(h),ze.BindFogParameters(l,t,this._activeEffect,!0),c.NUM_MORPH_INFLUENCERS&&ze.BindMorphTargetParameters(t,this._activeEffect),c.BAKED_VERTEX_ANIMATION_TEXTURE&&((o=t.bakedVertexAnimationManager)===null||o===void 0||o.bind(h,c.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),ze.BindLogDepth(c,this._activeEffect,l)),this._afterBind(t,this._activeEffect),_.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 e;if(!(!((e=this.subSurface)===null||e===void 0)&&e.isScatteringEnabled))return!1;const t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,s,r,n,o,l,c,h,u,p,m,_;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)===null||i===void 0||i.dispose(),(s=this._ambientTexture)===null||s===void 0||s.dispose(),(r=this._opacityTexture)===null||r===void 0||r.dispose(),(n=this._reflectionTexture)===null||n===void 0||n.dispose(),(o=this._emissiveTexture)===null||o===void 0||o.dispose(),(l=this._metallicTexture)===null||l===void 0||l.dispose(),(c=this._reflectivityTexture)===null||c===void 0||c.dispose(),(h=this._bumpTexture)===null||h===void 0||h.dispose(),(u=this._lightmapTexture)===null||u===void 0||u.dispose(),(p=this._metallicReflectanceTexture)===null||p===void 0||p.dispose(),(m=this._reflectanceTexture)===null||m===void 0||m.dispose(),(_=this._microSurfaceTexture)===null||_===void 0||_.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Fr.PBRMATERIAL_OPAQUE=Lt.MATERIAL_OPAQUE;Fr.PBRMATERIAL_ALPHATEST=Lt.MATERIAL_ALPHATEST;Fr.PBRMATERIAL_ALPHABLEND=Lt.MATERIAL_ALPHABLEND;Fr.PBRMATERIAL_ALPHATESTANDBLEND=Lt.MATERIAL_ALPHATESTANDBLEND;Fr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;Fr.LIGHTFALLOFF_PHYSICAL=0;Fr.LIGHTFALLOFF_GLTF=1;Fr.LIGHTFALLOFF_STANDARD=2;z([U$()],Fr.prototype,"_imageProcessingConfiguration",void 0);z([_t("_markAllSubMeshesAsMiscDirty")],Fr.prototype,"debugMode",void 0);z([X()],Fr.prototype,"useLogarithmicDepth",null);class ji extends Fr{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===Fr.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Fr.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=Fr.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Fr.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Fr.LIGHTFALLOFF_GLTF:this._lightFalloff=Fr.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=ji.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Ie.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Ie(0,0,0),this.albedoColor=new Ie(1,1,1),this.reflectivityColor=new Ie(1,1,1),this.reflectionColor=new Ie(1,1,1),this.emissiveColor=new Ie(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=yW(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=Kt.Clone(()=>new ji(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const s=Kt.Parse(()=>new ji(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Lt._parsePlugins(e,s,t,i),e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}ji.PBRMATERIAL_OPAQUE=Fr.PBRMATERIAL_OPAQUE;ji.PBRMATERIAL_ALPHATEST=Fr.PBRMATERIAL_ALPHATEST;ji.PBRMATERIAL_ALPHABLEND=Fr.PBRMATERIAL_ALPHABLEND;ji.PBRMATERIAL_ALPHATESTANDBLEND=Fr.PBRMATERIAL_ALPHATESTANDBLEND;ji.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Fr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"directIntensity",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"emissiveIntensity",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"environmentIntensity",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"specularIntensity",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"disableBumpMap",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"albedoTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"ambientTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"ambientTextureStrength",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesAndMiscDirty")],ji.prototype,"opacityTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"reflectionTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"emissiveTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"reflectivityTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"metallicTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"metallic",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"roughness",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"metallicF0Factor",void 0);z([Br(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"metallicReflectanceColor",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"metallicReflectanceTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"reflectanceTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"microSurfaceTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"bumpTexture",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty",null)],ji.prototype,"lightmapTexture",void 0);z([Br("ambient"),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"ambientColor",void 0);z([Br("albedo"),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"albedoColor",void 0);z([Br("reflectivity"),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"reflectivityColor",void 0);z([Br("reflection"),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"reflectionColor",void 0);z([Br("emissive"),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"emissiveColor",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"microSurface",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useLightmapAsShadowmap",void 0);z([X(),_t("_markAllSubMeshesAsTexturesAndMiscDirty")],ji.prototype,"useAlphaFromAlbedoTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesAndMiscDirty")],ji.prototype,"forceAlphaTest",void 0);z([X(),_t("_markAllSubMeshesAsTexturesAndMiscDirty")],ji.prototype,"alphaCutOff",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useSpecularOverAlpha",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useRoughnessFromMetallicTextureGreen",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useMetallnessFromMetallicTextureBlue",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useAmbientInGrayScale",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);z([X()],ji.prototype,"usePhysicalLightFalloff",null);z([X()],ji.prototype,"useGLTFLightFalloff",null);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useRadianceOverAlpha",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useObjectSpaceNormalMap",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useParallax",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useParallaxOcclusion",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"parallaxScaleBias",void 0);z([X(),_t("_markAllSubMeshesAsLightsDirty")],ji.prototype,"disableLighting",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"forceIrradianceInFragment",void 0);z([X(),_t("_markAllSubMeshesAsLightsDirty")],ji.prototype,"maxSimultaneousLights",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"invertNormalMapX",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"invertNormalMapY",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"twoSidedLighting",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useAlphaFresnel",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useLinearAlphaFresnel",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"environmentBRDFTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"forceNormalForward",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"enableSpecularAntiAliasing",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useHorizonOcclusion",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ji.prototype,"useRadianceOcclusion",void 0);z([X(),_t("_markAllSubMeshesAsMiscDirty")],ji.prototype,"unlit",void 0);z([X(),_t("_markAllSubMeshesAsMiscDirty")],ji.prototype,"applyDecalMapAfterDetailMap",void 0);$e("BABYLON.PBRMaterial",ji);const u5e=542327876,Xse=131072,Kse=512,Qse=4,Zse=64,qse=131072;function iQ(a){return a.charCodeAt(0)+(a.charCodeAt(1)<<8)+(a.charCodeAt(2)<<16)+(a.charCodeAt(3)<<24)}function d5e(a){return String.fromCharCode(a&255,a>>8&255,a>>16&255,a>>24&255)}const Jse=iQ("DXT1"),$se=iQ("DXT3"),ere=iQ("DXT5"),SZ=iQ("DX10"),tre=113,ire=116,sre=2,rre=10,f5e=88,IZ=31,p5e=0,m5e=1,nre=2,are=3,LZ=4,ore=7,RZ=20,lre=21,_5e=22,g5e=23,v5e=24,C5e=25,A5e=26,x5e=28,b5e=32;class la{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,IZ),i=new Int32Array(e.buffer,e.byteOffset,IZ+4);let s=1;t[nre]&Xse&&(s=Math.max(1,t[ore]));const r=t[lre],n=r===SZ?i[b5e]:0;let o=0;switch(r){case tre:o=2;break;case ire:o=1;break;case SZ:if(n===rre){o=2;break}if(n===sre){o=1;break}}return{width:t[LZ],height:t[are],mipmapCount:s,isFourCC:(t[RZ]&Qse)===Qse,isRGB:(t[RZ]&Zse)===Zse,isLuminance:(t[RZ]&qse)===qse,isCube:(t[x5e]&Kse)===Kse,isCompressed:r===Jse||r===$se||r===ere,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const o=new Float32Array(s),l=new Uint16Array(r,i);let c=0;for(let h=0;h>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,o,l){const c=new Uint8Array(s),h=new Uint8Array(r,i);let u=0;for(let p=0;p0?s.sphericalPolynomial=oD.ConvertCubeMapToSphericalPolynomial({size:p[LZ],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):s.sphericalPolynomial=void 0}}la.StoreLODInAlphaChannel=!1;Oi.prototype.createPrefilteredCubeTexture=function(a,e,t,i,s=null,r=null,n,o=null,l=!0){const c=h=>{if(!h){s&&s(null);return}const u=h.texture;if(l?h.info.sphericalPolynomial&&(u._sphericalPolynomial=h.info.sphericalPolynomial):u._sphericalPolynomial=new JM,u._source=hr.CubePrefiltered,this.getCaps().textureLOD){s&&s(u);return}const p=3,m=this._gl,_=h.width;if(!_)return;const f=[];for(let d=0;d1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),la.UploadDDSLevels(r,t,h,n,o,6,-1,c),!n.isFourCC&&n.mipmapCount===1?r.generateMipMapsForCubemap(t):l=n.mipmapCount-1}else{const c=e;n=la.GetDDSInfo(c),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new JM),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),la.UploadDDSLevels(r,t,c,n,o,6),!n.isFourCC&&n.mipmapCount===1?r.generateMipMapsForCubemap(t,!1):l=n.mipmapCount-1}r._setCubeMapTextureParams(t,o,l),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s({isDDS:!0,width:t.width,info:n,data:e,texture:t})}loadData(e,t,i){const s=la.GetDDSInfo(e),r=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps&&s.width>>s.mipmapCount-1===1;i(s.width,s.height,r,s.isFourCC,()=>{la.UploadDDSLevels(t.getEngine(),t,e,s,r,1)})}}He._TextureLoaders.push(new ihe);class she{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=ZK(e);if(n){t.width=n.width,t.height=n.width;try{JK(t,n),wee(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()},o=>{r?.("Can not upload environment levels",o)})}catch(o){r?.("Can not upload environment file",o)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}He._TextureLoaders.push(new she);class Zf{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Zf.IsValid(e)){this.isInvalid=!0,Me.Error("texture missing KTX identifier");return}const i=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),n=s.getUint32(0,!0)===67305985;if(this.glType=s.getUint32(1*i,n),this.glTypeSize=s.getUint32(2*i,n),this.glFormat=s.getUint32(3*i,n),this.glInternalFormat=s.getUint32(4*i,n),this.glBaseInternalFormat=s.getUint32(5*i,n),this.pixelWidth=s.getUint32(6*i,n),this.pixelHeight=s.getUint32(7*i,n),this.pixelDepth=s.getUint32(8*i,n),this.numberOfArrayElements=s.getUint32(9*i,n),this.numberOfFaces=s.getUint32(10*i,n),this.numberOfMipmapLevels=s.getUint32(11*i,n),this.bytesOfKeyValueData=s.getUint32(12*i,n),this.glType!==0){Me.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){Me.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){Me.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){Me.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=Zf.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case Zf.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break;case Zf.TEX_2D:case Zf.COMPRESSED_3D:case Zf.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=Zf.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=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}}Zf.HEADER_LEN=12+13*4;Zf.COMPRESSED_2D=0;Zf.COMPRESSED_3D=1;Zf.TEX_2D=2;Zf.TEX_3D=3;class rhe{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 s=this._pendingActions.shift();s?this._execute(e,s):e.idle=!0})})}}class PF extends rhe{constructor(e,t,i=PF.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,()=>{s(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(n=>{n.terminate()});const r=this._workerInfos.indexOf(e);r!==-1&&this._workerInfos.splice(r,1)},this._options.idleTimeElapsedBeforeRelease))})})}}PF.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};var Qq;(function(a){a[a.ETC1S=0]="ETC1S",a[a.UASTC4x4=1]="UASTC4x4"})(Qq||(Qq={}));var tB;(function(a){a[a.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",a[a.BC7_RGBA=1]="BC7_RGBA",a[a.BC3_RGBA=2]="BC3_RGBA",a[a.BC1_RGB=3]="BC1_RGB",a[a.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",a[a.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",a[a.ETC2_RGBA=6]="ETC2_RGBA",a[a.ETC1_RGB=7]="ETC1_RGB",a[a.RGBA32=8]="RGBA32",a[a.R8=9]="R8",a[a.RG8=10]="RG8"})(tB||(tB={}));var CX;(function(a){a[a.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",a[a.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",a[a.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",a[a.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",a[a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",a[a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",a[a.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",a[a.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",a[a.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",a[a.RGBA8Format=32856]="RGBA8Format",a[a.R8Format=33321]="R8Format",a[a.RG8Format=33323]="RG8Format"})(CX||(CX={}));function I9(a){return a?Be.GetAbsoluteUrl(a):null}function Zq(a){a.wasmUASTCToASTC!==null&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=a.wasmUASTCToASTC),a.wasmUASTCToBC7!==null&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=a.wasmUASTCToBC7),a.wasmUASTCToRGBA_UNORM!==null&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=a.wasmUASTCToRGBA_UNORM),a.wasmUASTCToRGBA_SRGB!==null&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=a.wasmUASTCToRGBA_SRGB),a.wasmUASTCToR8_UNORM!==null&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=a.wasmUASTCToR8_UNORM),a.wasmUASTCToRG8_UNORM!==null&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=a.wasmUASTCToRG8_UNORM),a.jsMSCTranscoder!==null&&(KTX2DECODER.MSCTranscoder.JSModuleURL=a.jsMSCTranscoder),a.wasmMSCTranscoder!==null&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=a.wasmMSCTranscoder),a.wasmZSTDDecoder!==null&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=a.wasmZSTDDecoder)}class nhe{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:[tB.BC1_RGB,tB.BC3_RGBA],yes:{transcodeFormat:tB.RGBA32,engineFormat:CX.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class Ou{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(Ou._WorkerPoolPromise||Ou._DecoderModulePromise)return;const t={jsDecoderModule:Be.GetAbsoluteUrl(this.URLConfig.jsDecoderModule),wasmUASTCToASTC:I9(this.URLConfig.wasmUASTCToASTC),wasmUASTCToBC7:I9(this.URLConfig.wasmUASTCToBC7),wasmUASTCToRGBA_UNORM:I9(this.URLConfig.wasmUASTCToRGBA_UNORM),wasmUASTCToRGBA_SRGB:I9(this.URLConfig.wasmUASTCToRGBA_SRGB),wasmUASTCToR8_UNORM:I9(this.URLConfig.wasmUASTCToR8_UNORM),wasmUASTCToRG8_UNORM:I9(this.URLConfig.wasmUASTCToRG8_UNORM),jsMSCTranscoder:I9(this.URLConfig.jsMSCTranscoder),wasmMSCTranscoder:I9(this.URLConfig.wasmMSCTranscoder),wasmZSTDDecoder:I9(this.URLConfig.wasmZSTDDecoder)};e&&typeof Worker=="function"&&typeof URL<"u"?Ou._WorkerPoolPromise=new Promise(i=>{const s=`${Zq}(${E5e})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new PF(e,()=>new Promise((n,o)=>{const l=new Worker(r),c=u=>{l.removeEventListener("error",c),l.removeEventListener("message",h),o(u)},h=u=>{u.data.action==="init"&&(l.removeEventListener("error",c),l.removeEventListener("message",h),n(l))};l.addEventListener("error",c),l.addEventListener("message",h),l.postMessage({action:"init",urls:t})})))}):typeof KTX2DECODER>"u"?Ou._DecoderModulePromise=Be.LoadScriptAsync(t.jsDecoderModule).then(()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Zq(t),new KTX2DECODER.KTX2Decoder)):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Ou._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=Ou.DefaultNumWorkers){this._engine=e,Ou._Initialize(t)}uploadAsync(e,t,i){const s=this._engine.getCaps(),r={astc:!!s.astc,bptc:!!s.bptc,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,etc1:!!s.etc1};if(Ou._WorkerPoolPromise)return Ou._WorkerPoolPromise.then(n=>new Promise((o,l)=>{n.push((c,h)=>{const u=_=>{c.removeEventListener("error",u),c.removeEventListener("message",p),l(_),h()},p=_=>{if(_.data.action==="decoded"){if(c.removeEventListener("error",u),c.removeEventListener("message",p),!_.data.success)l({message:_.data.msg});else try{this._createTexture(_.data.decodedData,t,i),o()}catch(f){l({message:f})}h()}};c.addEventListener("error",u),c.addEventListener("message",p),c.postMessage({action:"setDefaultDecoderOptions",options:Ou.DefaultDecoderOptions._getKTX2DecoderOptions()});const m=new Uint8Array(e.byteLength);m.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),c.postMessage({action:"decode",data:m,caps:r,options:i},[m.buffer])})}));if(Ou._DecoderModulePromise)return Ou._DecoderModulePromise.then(n=>(Ou.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=Ou.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((o,l)=>{n.decode(e,s).then(c=>{this._createTexture(c,t),o()}).catch(c=>{l({message:c})})})));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 r=!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,r=!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 n=0;n=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}}Ou.URLConfig={jsDecoderModule:"https://preview.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};Ou.DefaultNumWorkers=Ou.GetDefaultNumWorkers();Ou.DefaultDecoderOptions=new nhe;function E5e(){let a;onmessage=e=>{if(!!e.data)switch(e.data.action){case"init":{const t=e.data.urls;importScripts(t.jsDecoderModule),Zq(t),a=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=e.data.options;break}case"decode":a.decode(e.data.data,e.data.caps,e.data.options).then(t=>{const i=[];for(let s=0;s{postMessage({action:"decoded",success:!1,msg:t})});break}}}function y5e(a){switch(a){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 ahe{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||t==="image/ktx"||t==="image/ktx2"}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),n=new Zf(e,6),o=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,o,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(Zf.IsValid(e)){t._invertVScale=!t.invertY;const r=new Zf(e,1),n=y5e(r.glInternalFormat);n?(t.format=n,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=r.glInternalFormat,i(r.pixelWidth,r.pixelHeight,t.generateMipMaps,!0,()=>{r.uploadLevels(t,t.generateMipMaps)},r.isInvalid)}else Ou.IsValid(e)?new Ou(t.getEngine()).uploadAsync(e,t,s).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},n=>{Me.Warn(`Failed to load KTX2 texture data: ${n.message}`),i(0,0,!1,!1,()=>{},!0)}):(Me.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}He._TextureLoaders.unshift(new ahe);class HB extends q1{constructor(e,t,i){super(e,O.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=ke.Identity(),this._referencedPosition=new O,this._trackingState=gP.NOT_TRACKING,this.onXRCameraInitializedObservable=new Se,this.onBeforeCameraTeleport=new Se,this.onAfterCameraTeleport=new Se,this.onTrackingStateChanged=new Se,this.compensateOnFirstFrame=!0,this._rotate180=new ke(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new ke,this.cameraRigMode=Pi.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.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:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new hu(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new hu(.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,ke.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){const t=ue.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),ke.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(gP.NOT_TRACKING);return}const t=e.emulatedPosition?gP.TRACKING_LOST:gP.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){const i={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(i),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(e.transform){const i=e.transform.orientation;if(e.transform.orientation.x===void 0)return;const s=e.transform.position;this._referencedPosition.set(s.x,s.y,s.z),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,s)=>{var r;const n=this.rigCameras[s];!n.isLeftCamera&&!n.isRightCamera&&(i.eye==="right"?n._isRightCamera=!0:i.eye==="left"&&(n._isLeftCamera=!0));const o=i.transform.position,l=i.transform.orientation;n.parent=this.parent,n.position.set(o.x,o.y,o.z),n.rotationQuaternion.set(l.x,l.y,l.z,l.w),this._scene.useRightHandedSystem?n.rotationQuaternion.multiplyInPlace(this._rotate180):(n.position.z*=-1,n.rotationQuaternion.z*=-1,n.rotationQuaternion.w*=-1),ge.FromFloat32ArrayToRefScaled(i.projectionMatrix,0,1,n._projectionMatrix),this._scene.useRightHandedSystem||n._projectionMatrix.toggleProjectionMatrixHandInPlace(),s===0&&this._projectionMatrix.copyFrom(n._projectionMatrix);const c=this._xrSessionManager.getRenderTargetTextureForView(i);this._renderingMultiview=((r=c?._texture)===null||r===void 0?void 0:r.isMultiview)||!1,this._renderingMultiview?s==0&&(this._xrSessionManager.trySetViewportForView(this.viewport,i),this.outputRenderTarget=c):(this._xrSessionManager.trySetViewportForView(n.viewport,i),n.outputRenderTarget=c||this._xrSessionManager.getRenderTargetTextureForView(i)),n.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.lengthe;){const t=this.rigCameras.pop();t&&t.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=ue.Matrix[0],t=ue.Matrix[1],i=ue.Matrix[2];ge.ComposeToRef(HB._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),ge.ComposeToRef(HB._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 s=new XRRigidTransform({x:this._referencedPosition.x,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(s)}}}HB._ScaleReadOnly=O.One();class sQ{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 Se,this.onStateChangedObservable=new Se,this.state=Ih.NOT_IN_XR,this.sessionManager=new hW(e),this.camera=new HB("webxr",e,this.sessionManager),this.featuresManager=new _l(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){const t=new sQ(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(i=>{throw t._setState(Ih.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===void 0||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),s={}){var r,n,o;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(Ih.ENTERING_XR),t!=="viewer"&&t!=="local"&&(s.optionalFeatures=s.optionalFeatures||[],s.optionalFeatures.push(t)),s=await this.featuresManager._extendXRSessionInitObject(s),e==="immersive-ar"&&t!=="unbounded"&&Me.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,s),await this.sessionManager.setReferenceSpaceTypeAsync(t);const l=await i.initializeXRLayerAsync(this.sessionManager.session),c={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature($r.LAYERS)||(c.baseLayer=l),this.sessionManager.updateRenderState(c),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(!((n=(r=this._nonVRCamera)===null||r===void 0?void 0:r.inputs)===null||n===void 0)&&n.attachedToElement),(o=this._nonVRCamera)===null||o===void 0||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!==Ih.EXITING_XR&&this._setState(Ih.EXITING_XR),this.camera.rigCameras.forEach(h=>{h.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(Ih.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(Ih.IN_XR)}),this.sessionManager}catch(l){throw console.log(l),console.log(l.message),this._setState(Ih.NOT_IN_XR),l}}exitXRAsync(){return this.state!==Ih.IN_XR?Promise.resolve():(this._setState(Ih.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?.fps?e.fps:1e3)*1e3,s=e?.preferredCameraIndex?e?.preferredCameraIndex:0,r=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[s].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[s].absoluteRotation))};if(this._spectatorMode){if(s>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const n=()=>{this.state===Ih.IN_XR?(this._spectatorCamera=new XL("webxr-spectator",O.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new ke,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(r),this._scene.onAfterRenderCameraObservable.add(o=>{o===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===Ih.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(r),this._scene.activeCameras=null)};this.onStateChangedObservable.add(n),n()}else this.sessionManager.onXRFrameObservable.removeCallback(r),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 i4{constructor(e,t,i=-1,s=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=s,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new Se,this.onButtonStateChangedObservable=new Se}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 s=e.buttons[this._buttonIndex];if(!s)return;this._currentValue!==s.value&&(this.changes.value={current:s.value,previous:this._currentValue},t=!0,this._currentValue=s.value),this._touched!==s.touched&&(this.changes.touched={current:s.touched,previous:this._touched},t=!0,this._touched=s.touched),this._pressed!==s.pressed&&(this.changes.pressed={current:s.pressed,previous:this._pressed},t=!0,this._pressed=s.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))}}i4.BUTTON_TYPE="button";i4.SQUEEZE_TYPE="squeeze";i4.THUMBSTICK_TYPE="thumbstick";i4.TOUCHPAD_TYPE="touchpad";i4.TRIGGER_TYPE="trigger";class lD{constructor(e,t,i,s,r=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=s,this._doNotLoadControllerMesh=r,this._controllerCache=n,this._initComponent=o=>{if(!o)return;const l=this.layout.components[o],c=l.type,h=l.gamepadIndices.button,u=[];l.gamepadIndices.xAxis!==void 0&&l.gamepadIndices.yAxis!==void 0&&u.push(l.gamepadIndices.xAxis,l.gamepadIndices.yAxis),this.components[o]=new i4(o,c,h,u)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new Se,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?Me.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,s)=>{const r=n=>{e?this._getGenericParentMesh(n):this._setRootMesh(n),this._processLoadedModel(n),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const n=this._controllerCache.filter(o=>o.filename===t.filename&&o.path===t.path);if(n[0]){n[0].meshes.forEach(o=>o.setEnabled(!0)),r(n[0].meshes);return}}As.ImportMesh("",t.path,t.filename,this.scene,n=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:n})),r(n)},null,(n,o)=>{Me.Log(o),Me.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(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 s=i?t*.5+.5:t;ke.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),O.LerpToRef(e.minMesh.position,e.maxMesh.position,s,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 Oe(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.parent||(t.isPickable=!1,t.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=ke.FromEulerAngles(0,Math.PI,0)}}class jB extends lD{constructor(e,t,i){super(e,M5e[i],t,i),this.profileId=jB.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new Oe(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1,t.parent||t.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=ke.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}jB.ProfileId="generic-trigger";const M5e={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 ohe extends lD{constructor(e,t,i,s,r){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,r),this._repositoryUrl=s,this.controllerCache=r,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=As.IsPluginForExtensionAvailable(".glb");return e||Me.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(s=>{const r=i.visualResponses[s];if(r.valueNodeProperty==="transform")this._buttonMeshMapping[t].states[s]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{const n=i.type===i4.TOUCHPAD_TYPE&&i.touchPointNodeName?i.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[t].states[s]={valueMesh:this._getChildByName(this.rootMesh,n)},i.type===i4.TOUCHPAD_TYPE&&!this._touchDots[s]){const o=$d(s+"dot",{diameter:.0015,segments:8},this.scene);o.material=new jt(s+"mat",this.scene),o.material.diffuseColor=Ie.Red(),o.parent=this._buttonMeshMapping[t].states[s].valueMesh||null,o.isVisible=!1,this._touchDots[s]=o}}})})}_setRootMesh(e){this.rootMesh=new Oe(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 s=this._buttonMeshMapping[t],r=this.layout.components[t];Object.keys(r.visualResponses).forEach(n=>{const o=r.visualResponses[n];let l=i.value;if(o.componentProperty==="xAxis"?l=i.axes.x:o.componentProperty==="yAxis"&&(l=i.axes.y),o.valueNodeProperty==="transform")this._lerpTransform(s.states[n],l,o.componentProperty!=="button");else{const c=s.states[n].valueMesh;c&&(c.isVisible=i.touched||i.pressed),this._touchDots[n]&&(this._touchDots[n].isVisible=i.touched||i.pressed)}})})}}const PZ=[];class ou{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 s=[];if(i&&s.push(i),s.push(...e.profiles||[]),s.length&&!s[0]&&s.pop(),e.gamepad&&e.gamepad.id)switch(e.gamepad.id){case(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0):s.push("oculus-touch-v2");break}const r=s.indexOf("windows-mixed-reality");if(r!==-1&&s.splice(r,0,"microsoft-mixed-reality"),s.length||s.push("generic-trigger"),this.UseOnlineRepository){const n=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,o=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return n.call(this,s,e,t).catch(()=>o.call(this,s,e,t))}else return this._LoadProfilesFromAvailableControllers(s,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=Be.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e.toString())),this._ProfilesList}static ClearControllerCache(){PZ.forEach(e=>{e.meshes.forEach(t=>{t.dispose(!1,!0)})}),PZ.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(s=>{for(let r=0;r(this._ProfileLoadingPromises[s]||(this._ProfileLoadingPromises[s]=Be.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${s}/profile.json`,!1).then(r=>JSON.parse(r))),this._ProfileLoadingPromises[s])).then(s=>new ohe(i,t,s,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:PZ))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;snew jB(e,a.gamepad,a.handedness));ou.DefaultFallbacks();let T5e=0;class lhe{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new O,this._disposed=!1,this.onDisposeObservable=new Se,this.onMeshLoadedObservable=new Se,this.onMotionControllerInitObservable=new Se,this._uniqueId=`controller-${T5e++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Ir(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new ke,this.inputSource.gripSpace&&(this.grip=new Ir(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new ke),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&this.inputSource.targetRayMode==="tracked-pointer"&&ou.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(s=>{this.motionController=s,this.onMotionControllerInitObservable.notifyObservers(s),!this._options.doNotLoadControllerMesh&&!this.motionController._doNotLoadControllerMesh&&this.motionController.loadModel().then(r=>{var n;r&&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&&((n=this.motionController)===null||n===void 0||n.dispose())})},()=>{Be.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;O.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){const s=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=s,s){const r=s.transform.position;this.pointer.position.set(r.x,r.y,r.z);const n=s.transform.orientation;this.pointer.rotationQuaternion.set(n.x,n.y,n.z,n.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){const r=e.getPose(this.inputSource.gripSpace,t);if(r){const n=r.transform.position,o=r.transform.orientation;this.grip.position.set(n.x,n.y,n.z),this.grip.rotationQuaternion.set(o.x,o.y,o.z,o.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.motionController&&this.motionController.updateFromXRFrame(e)}}class che{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new Se,this.onControllerRemovedObservable=new Se,this._onInputSourcesChange=s=>{this._addAndRemoveControllers(s.added,s.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(()=>{this._addAndRemoveControllers([],this.controllers.map(s=>s.inputSource))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(s=>{s.addEventListener("inputsourceschange",this._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(s=>{this.controllers.forEach(r=>{r.updateFromXRFrame(s,this.xrSessionManager.referenceSpace,this.xrCamera)})}),this._options.customControllersRepositoryURL&&(ou.BaseRepositoryUrl=this._options.customControllersRepositoryURL),ou.UseOnlineRepository=!this._options.disableOnlineControllerRepository,ou.UseOnlineRepository)try{ou.UpdateProfilesList().catch(()=>{ou.UseOnlineRepository=!1})}catch{ou.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map(n=>n.inputSource);for(const n of e)if(i.indexOf(n)===-1){const o=new lhe(this.xrSessionManager.scene,n,Object.assign(Object.assign({},this._options.controllerOptions||{}),{forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation}));this.controllers.push(o),this.onControllerAddedObservable.notifyObservers(o)}const s=[],r=[];this.controllers.forEach(n=>{t.indexOf(n.inputSource)===-1?s.push(n):r.push(n)}),this.controllers=s,r.forEach(n=>{this.onControllerRemovedObservable.notifyObservers(n),n.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(),ou.ClearControllerCache()}}class $b extends ku{constructor(e,t){super(e),this._options=t,this._attachController=i=>{if(this._controllers[i.uniqueId])return;const{laserPointer:s,selectionMesh:r}=this._generateNewMeshPair(i.pointer);switch(this._controllers[i.uniqueId]={xrController:i,laserPointer:s,selectionMesh:r,meshUnderPointer:null,pick:null,tmpRay:new gr(new O,new O),disabledByNearInteraction:!1,id:$b._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":return this._attachScreenRayMode(i)}},this._controllers={},this._tmpVectorForPickCompare=new O,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Ie(.9,.9,.9),this.laserPointerDefaultColor=new Ie(.7,.7,.7),this.selectionMeshDefaultColor=new Ie(.8,.8,.8),this.selectionMeshPickedColor=new Ie(.3,.3,1),this._identityMatrix=ge.Identity(),this._screenCoordinatesRef=O.Zero(),this._viewportRef=new hu(0,0,0,0),this._scene=this._xrSessionManager.scene}attach(){if(!super.attach())return!1;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._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 gr(new O,new O),disabledByNearInteraction:!1,id:$b._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{const i=this._controllers[t];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 s;if(i.xrController)s=i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay);else if(i.webXRCamera)s=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay);else return;if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&s){const l=this._xrSessionManager.scene,c=this._options.xrInput.xrCamera;c&&(c.viewport.toGlobalToRef(l.getEngine().getRenderWidth(),l.getEngine().getRenderHeight(),this._viewportRef),O.ProjectToRef(s,this._identityMatrix,l.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),typeof this._screenCoordinatesRef.x=="number"&&typeof this._screenCoordinatesRef.y=="number"&&!isNaN(this._screenCoordinatesRef.x)&&!isNaN(this._screenCoordinatesRef.y)&&(l.pointerX=this._screenCoordinatesRef.x,l.pointerY=this._screenCoordinatesRef.y,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const n=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);!r||!r.hit?i.pick=n:!n||!n.hit||r.distance{if(!!t.pick){if(this._augmentPointerInit(c,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(r,t.pick))l&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,c)),l=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,c),l=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,c),n.isVisible=!1;else{const h=1-o/i;n.scaling.set(h,h,h)}else l=!1,o=0;this._scene.simulatePointerMove(t.pick,c),r=t.pick}}),this._options.renderingGroupId!==void 0&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&l&&(this._scene.simulatePointerUp(t.pick,c),t.finalPointerUpTriggered=!0),n.dispose()})}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const s={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),!(!t.pick||this._options.disablePointerUpOnTouchOut&&i)&&(i?this._scene.simulatePointerMove(t.pick,s):(this._scene.simulatePointerDown(t.pick,s),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,s)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,s),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 s=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(n=>{if(n.changes.pressed){const o=n.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?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const s=n=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&n.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)},r=n=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&n.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:r,selectstart:s},this._xrSessionManager.session.addEventListener("selectstart",s),this._xrSessionManager.session.addEventListener("selectend",r)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(O.Dot(e,t.direction)){const s=t.eventListeners&&t.eventListeners[i];s&&this._xrSessionManager.session.removeEventListener(i,s)}),!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 cu,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{Be.Warn("controller already detached.")}})}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Mn.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():J1("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const s=new jt("laserPointerMat",t);s.emissiveColor=this.laserPointerDefaultColor,s.alpha=.7,i.material=s,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const r=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():r7("gazeTracker",{diameter:.0035*3,thickness:.0025*3,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const n=new jt("targetMat",t);return n.specularColor=Ie.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,r.material=n,this._options.renderingGroupId!==void 0&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;(i=e.pickedPoint)===null||i===void 0||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const s=(this._options.gazeModePointerMovedFactor||1)*.01*t.distance;return this._tmpVectorForPickCompare.length()>s}_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}}$b._IdCounter=200;$b.Name=$r.POINTER_SELECTION;$b.Version=1;_l.AddWebXRFeature($b.Name,(a,e)=>()=>new $b(a,e),$b.Version,!0);_d.prototype._projectOnTrianglesToRef=function(a,e,t,i,s,r){const n=ue.Vector3[0],o=ue.Vector3[1];let l=1/0;for(let c=this.indexStart;c{if(this._controllers[i.uniqueId])return;const{touchCollisionMesh:s,touchCollisionMeshFunction:r,hydrateCollisionMeshFunction:n}=this._generateNewTouchPointMesh(),o=this._generateVisualCue();switch(this._controllers[i.uniqueId]={xrController:i,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:s,touchCollisionMeshFunction:r,hydrateCollisionMeshFunction:n,currentAnimationState:n_.DEHYDRATED,grabRay:new gr(new O,new O),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:e7._IdCounter++,pickedPointVisualCue:o},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 Ie(.8,.8,.8),this.selectionMeshPickedColor=new Ie(.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=gL.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 n_.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===n_.HOVER)break;case n_.HOVER:if(e.touchCollisionMeshFunction(!0),t===n_.TOUCH)break}else switch(e.currentAnimationState){case n_.TOUCH:if(e.touchCollisionMeshFunction(!1),t===n_.HOVER)break;case n_.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===n_.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var s;const r=this._controllers[e];r.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(ue.Vector3[0]),r.grabRay.direction.copyFrom(ue.Vector3[0]),this._options.nearInteractionControllerMode===gL.CENTERED_IN_FRONT&&!(!((s=r.xrController)===null||s===void 0)&&s.inputSource.hand)&&(r.xrController.getWorldPointerRayToRef(this._tmpRay),r.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),r.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,r.touchCollisionMesh.position.copyFrom(r.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var i;const s=this._controllers[t],r=(i=s.xrController)===null||i===void 0?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!s.xrController||!r&&(!this._options.nearInteractionControllerMode||!s.xrController.inputSource.gamepad)){s.pick=null;return}if(s.hoverInteraction=!1,s.nearInteraction=!1,s.xrController){if(r){const c=r.get("index-finger-tip");if(c){const h=e.getJointPose(c,this._xrSessionManager.referenceSpace);if(h&&h.transform){const u=this._scene.useRightHandedSystem?1:-1;ue.Vector3[0].set(h.transform.position.x,h.transform.position.y,h.transform.position.z*u),ue.Quaternion[0].set(h.transform.orientation.x,h.transform.orientation.y,h.transform.orientation.z*u,h.transform.orientation.w*u),this._processTouchPoint(t,ue.Vector3[0],ue.Quaternion[0])}}}else if(s.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==gL.DISABLED){let c=s.xrController.pointer;s.xrController.grip&&this._options.nearInteractionControllerMode===gL.CENTERED_ON_CONTROLLER&&(c=s.xrController.grip),this._processTouchPoint(t,c.position,c.rotationQuaternion)}}else return;const n=(c,h)=>{let u=null;return!h||!h.hit?u=c:!c||!c.hit||h.distance{let h=new cu,u=!1;const p=c&&c.pickedPoint&&c.hit;return c?.pickedPoint&&(u=c.pickedPoint.x===0&&c.pickedPoint.y===0&&c.pickedPoint.z===0),p&&!u&&(h=c),h};if(!s.grabInteraction){let c=null,h=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(h=this._pickWithSphere(s,this._hoverRadius,this._utilityLayerScene,m=>this._nearInteractionPredicate(m)));const u=this._pickWithSphere(s,this._hoverRadius,this._scene,m=>this._nearInteractionPredicate(m)),p=n(u,h);if(p&&p.hit&&(c=o(p),c.hit&&(s.hoverInteraction=!0)),s.hoverInteraction){let m=null;const _=r?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(m=this._pickWithSphere(s,_,this._utilityLayerScene,v=>this._nearPickPredicate(v)));const f=this._pickWithSphere(s,_,this._scene,v=>this._nearPickPredicate(v)),d=n(f,m),C=o(d);C.hit&&(c=C,s.nearInteraction=!0)}s.stalePick=s.pick,s.pick=c,s.pick&&s.pick.pickedPoint&&s.pick.hit?(s.meshUnderPointer=s.pick.pickedMesh,s.pickedPointVisualCue.position.copyFrom(s.pick.pickedPoint),s.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(s.id,!0)):(s.meshUnderPointer=null,s.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(s.id,!1))}let l=n_.DEHYDRATED;s.grabInteraction||s.nearInteraction?l=n_.TOUCH:s.hoverInteraction&&(l=n_.HOVER),this._handleTransitionAnimation(s,l)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Mn.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Mn.DefaultUtilityLayer.utilityLayerScene:this._scene,t=$d("nearInteraction",{diameter:.0035*3},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=ke.Identity();const i=new jt("targetMat",e);return i.specularColor=Ie.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.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.nearInteractionTargetMesh=null))});const s=r=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),r&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):r&&!this._options.enableNearInteractionOnAllControllers&&!this._options.disableSwitchOnClick&&(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const r=n=>{t.squeezeComponent=n.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const l=o.changes.pressed.current;s(l)}}):(t.selectionComponent=n.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const l=o.changes.pressed.current;s(l)}}))};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{const r=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))},n=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.eventListeners={selectend:n,selectstart:r},this._xrSessionManager.session.addEventListener("selectstart",r),this._xrSessionManager.session.addEventListener("selectend",n)}}_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 s=t.eventListeners&&t.eventListeners[i];s&&this._xrSessionManager.session.removeEventListener(i,s)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{const i={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new cu,i)}),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._options.useUtilityLayer?this._options.customUtilityLayerScene||Mn.DefaultUtilityLayer.utilityLayerScene:this._scene,t=$d("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:Pl.ParseFromSnippetAsync("8RUNKL#3",e).then(S=>{t.material=S});const i=new Ele;i.setEasingMode(Pc.EASINGMODE_EASEINOUT);const s=new O(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),r=this._controllerPickRadius*(4/3),n=new O(r,r,r),o=this._controllerPickRadius*(7/6),l=new O(o,o,o),c=this._controllerPickRadius*(4/5),h=new O(c,c,c),u=this._controllerPickRadius*(3/2),p=new O(u,u,u),m=[{frame:0,value:s},{frame:10,value:p},{frame:18,value:n}],_=[{frame:0,value:n},{frame:10,value:h},{frame:18,value:s}],f=[{frame:0,value:O.ZeroReadOnly},{frame:12,value:l},{frame:15,value:s}],d=[{frame:0,value:s},{frame:10,value:O.ZeroReadOnly},{frame:15,value:O.ZeroReadOnly}],C=new at("touch","scaling",60,at.ANIMATIONTYPE_VECTOR3,at.ANIMATIONLOOPMODE_CONSTANT),v=new at("release","scaling",60,at.ANIMATIONTYPE_VECTOR3,at.ANIMATIONLOOPMODE_CONSTANT),y=new at("hydrate","scaling",60,at.ANIMATIONTYPE_VECTOR3,at.ANIMATIONLOOPMODE_CONSTANT),M=new at("dehydrate","scaling",60,at.ANIMATIONTYPE_VECTOR3,at.ANIMATIONLOOPMODE_CONSTANT);return C.setEasingFunction(i),v.setEasingFunction(i),y.setEasingFunction(i),M.setEasingFunction(i),C.setKeys(m),v.setKeys(_),y.setKeys(f),M.setKeys(d),{touchCollisionMesh:t,touchCollisionMeshFunction:S=>{const I=S?C:v;e.beginDirectAnimation(t,[I],0,18,!1,1)},hydrateCollisionMeshFunction:S=>{const I=S?y:M;S&&(t.isVisible=!0),e.beginDirectAnimation(t,[I],0,15,!1,1,()=>{S||(t.isVisible=!1)})}}}_pickWithSphere(e,t,i,s){const r=new cu;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=Jb.CreateFromCenterAndRadius(n,t);for(let l=0;lu&&(h=0,l.copyFrom(t.center)),h!==-1&&h()=>new e7(a,e),e7.Version,!0);class hhe{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class S5e{}class rQ{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new Se,this._onSessionGranted=s=>{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 Be.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 s=t.sessionMode||"immersive-vr",r=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 l=document.createElement("style");l.appendChild(document.createTextNode(o)),document.getElementsByTagName("head")[0].appendChild(l);const c=document.createElement("button");c.className="babylonVRicon",c.title=`${s} - ${r}`,this._buttons.push(new hhe(c,s,r)),this._buttons[this._buttons.length-1].update=function(h){this.element.style.display=h===null||h===this?"":"none",c.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(r=>e.sessionManager.isSessionSupportedAsync(r.sessionMode));e.onStateChangedObservable.add(r=>{r==Ih.NOT_IN_XR&&this._updateButtons(null)}),(await Promise.all(i)).forEach((r,n)=>{r?(this.overlay.appendChild(this._buttons[n].element),this._buttons[n].element.onclick=this._enterXRWithButtonIndex.bind(this,n)):Be.Warn(`Session mode "${this._buttons[n].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){const s=new rQ(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==Ih.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==Ih.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,s=i.title;i.title="Error entering XR session : "+s,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 vL;(function(a){a[a.INIT=0]="INIT",a[a.STARTED=1]="STARTED",a[a.ENDED=2]="ENDED"})(vL||(vL={}));function qq(a){var e;let t=0;const i=Date.now();a.observableParameters=(e=a.observableParameters)!==null&&e!==void 0?e:{};const s=a.contextObservable.add(r=>{const n=Date.now();t=n-i;const o={startTime:i,currentTime:n,deltaTime:t,completeRate:t/a.timeout,payload:r};a.onTick&&a.onTick(o),a.breakCondition&&a.breakCondition()&&(a.contextObservable.remove(s),a.onAborted&&a.onAborted(o)),t>=a.timeout&&(a.contextObservable.remove(s),a.onEnded&&a.onEnded(o))},a.observableParameters.mask,a.observableParameters.insertFirst,a.observableParameters.scope);return s}class uhe{constructor(e){var t,i;this.onEachCountObservable=new Se,this.onTimerAbortedObservable=new Se,this.onTimerEndedObservable=new Se,this.onStateChangedObservable=new Se,this._observer=null,this._breakOnNextTick=!1,this._tick=s=>{const r=Date.now();this._timer=r-this._startTime;const n={startTime:this._startTime,currentTime:r,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:s},o=this._breakOnNextTick||this._breakCondition(n);o||this._timer>=this._timeToEnd?this._stop(n,o):this.onEachCountObservable.notifyObservers(n)},this._setState(vL.INIT),this._contextObservable=e.contextObservable,this._observableParameters=(t=e.observableParameters)!==null&&t!==void 0?t:{},this._breakCondition=(i=e.breakCondition)!==null&&i!==void 0?i:()=>!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===vL.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(vL.STARTED)}stop(){this._state===vL.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(vL.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class IP extends ku{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 Zt(1,1,1,1),this._tmpRay=new gr(new O,new O),this._tmpVector=new O,this._tmpQuaternion=new ke,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 Se,this.teleportationEnabled=!0,this._rotationEnabled=!0,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}};const s=this._controllers[i.uniqueId];if(s.xrController.inputSource.targetRayMode==="tracked-pointer"&&s.xrController.inputSource.gamepad){const r=()=>{if(i.motionController){const n=i.motionController.getComponentOfType(i4.THUMBSTICK_TYPE)||i.motionController.getComponentOfType(i4.TOUCHPAD_TYPE);if(!n||this._options.useMainComponentOnly){const o=i.motionController.getMainComponent();if(!o)return;s.teleportationComponent=o,s.onButtonChangedObserver=o.onButtonStateChangedObservable.add(()=>{if(!!this.teleportationEnabled&&o.changes.pressed)if(o.changes.pressed.current){s.teleportationState.forward=!0,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,s.teleportationState.currentRotation=0;const l=this._options.timeToTeleport||3e3;qq({timeout:l,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!o.pressed,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&s.teleportationState.forward&&this._teleportForward(i.uniqueId)}})}else s.teleportationState.forward=!1,this._currentTeleportationControllerId=""})}else s.teleportationComponent=n,s.onAxisChangedObserver=n.onAxisValueChangedObservable.add(o=>{if(o.y<=.7&&s.teleportationState.backwards&&(s.teleportationState.backwards=!1),o.y>.7&&!s.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!s.teleportationState.backwards){s.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,ke.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 l=this._xrSessionManager.scene.pickWithRay(this._tmpRay,c=>this._floorMeshes.indexOf(c)!==-1);l&&l.pickedPoint&&(this._options.xrInput.xrCamera.position.x=l.pickedPoint.x,this._options.xrInput.xrCamera.position.z=l.pickedPoint.z)}if(o.y<-.7&&!this._currentTeleportationControllerId&&!s.teleportationState.rotating&&this.teleportationEnabled&&(s.teleportationState.forward=!0,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),o.x){if(s.teleportationState.forward)this._currentTeleportationControllerId===s.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{s.teleportationState.currentRotation=Math.atan2(o.x,o.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):s.teleportationState.currentRotation=0);else if(!s.teleportationState.rotating&&Math.abs(o.x)>.7){s.teleportationState.rotating=!0;const l=this.rotationAngle*(o.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);ke.FromEulerAngles(0,l,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion)}}else s.teleportationState.rotating=!1;o.x===0&&o.y===0&&(s.teleportationState.blocked&&(s.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),s.teleportationState.forward&&this._teleportForward(i.uniqueId))})}};i.motionController?r():i.onMotionControllerInitObservable.addOnce(()=>{r()})}else this._xrSessionManager.scene.onPointerObservable.add(r=>{if(r.type===mi.POINTERDOWN){s.teleportationState.forward=!0,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,s.teleportationState.currentRotation=0;const n=this._options.timeToTeleport||3e3;qq({timeout:n,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&s.teleportationState.forward&&this._teleportForward(i.uniqueId)}})}else r.type===mi.POINTERUP&&(s.teleportationState.forward=!1,this._currentTeleportationControllerId="")})},this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new Zt(1,0,0,.75),this._setTargetMeshVisibility(!1)}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)}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.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(l)!==-1)return!0;const c=this._floorMeshes.indexOf(l);return c===-1?!1:this._floorMeshes[c].absolutePosition.ythis._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(u)!==-1?!0:this._floorMeshes.indexOf(u)!==-1);if(h&&h.pickedMesh&&this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(h.pickedMesh)!==-1){r.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(h);return}else h&&h.pickedPoint&&(r.teleportationState.blocked=!1,n=!0,this._setTargetMeshPosition(h),this._setTargetMeshVisibility(!0),this._showParabolicPath(h))}this._setTargetMeshVisibility(n)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Mn.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=aD("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const n=new ep("teleportationPlaneDynamicTexture",512,e,!0);n.hasAlpha=!0;const o=n.getContext(),l=512/2,c=512/2,h=200;o.beginPath(),o.arc(l,c,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(),n.update();const u=new jt("teleportationPlaneMaterial",e);u.diffuseTexture=n,t.material=u}const i=r7("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const r=new at("animationInnerCircle","position.y",30,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),r.setKeys(n);const o=new W$;o.setEasingMode(Pc.EASINGMODE_EASEINOUT),r.setEasingFunction(o),i.animations=[],i.animations.push(r),e.beginAnimation(i,0,60,!0)}const s=J1("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(Fo.X,Math.PI/2),s.position.z=.6,s.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,s.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const r=new jt("torusConsMat",e);r.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,r.disableLighting?r.emissiveColor=new Ie(.3,.3,1):r.diffuseColor=new Ie(.3,.3,1),r.alpha=.9,i.material=r,s.material=r,this._teleportationRingMaterial=r}this._options.renderingGroupId!==void 0&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,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,s=Number.MAX_VALUE;if(this._snapToPositions.length){const r=t*t;this._snapToPositions.forEach(n=>{const o=O.DistanceSquared(n,e);o<=r&&o{i.isVisible=e}),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&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||Mn.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=Ob.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=new Array(26).fill(r||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=Ga("teleportation path line",{points:s.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:n},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._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=i,ke.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._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}}IP.Name=$r.TELEPORTATION;IP.Version=1;_l.AddWebXRFeature(IP.Name,(a,e)=>()=>new IP(a,e),IP.Version,!0);class I5e{}class nQ{constructor(){}static CreateAsync(e,t={}){const i=new nQ;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){const s=Object.assign({renderTarget:i.renderTarget},t.uiOptions||{});t.optionalFeatures&&(typeof t.optionalFeatures=="boolean"?s.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:s.optionalFeatures=t.optionalFeatures),i.enterExitUI=new rQ(e,s)}return sQ.CreateAsync(e).then(s=>{if(i.baseExperience=s,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new che(s.sessionManager,s.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){const r=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature($b.Name,t.useStablePlugins?"stable":"latest",r),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(IP.Name,t.useStablePlugins?"stable":"latest",Object.assign({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(e7.Name,t.useStablePlugins?"stable":"latest",Object.assign({xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0},t.nearInteractionOptions))),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),!t.disableDefaultUI)return i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)}).then(()=>i).catch(s=>(Me.Error("Error initializing XR"),Me.Error(s),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var L5e=!0;oi.prototype.createDefaultLight=function(a=!1){if(a&&this.lights)for(let e=0;el.isVisible&&l.isEnabled()),s=i.max.subtract(i.min),r=i.min.add(s.scale(.5));let n,o=s.length()*1.5;if(isFinite(o)||(o=1,r.copyFromFloats(0,0,0)),a){const l=new dr("default camera",-(Math.PI/2),Math.PI/2,o,r,this);l.lowerRadiusLimit=o*.01,l.wheelPrecision=100/o,n=l}else{const l=new q1("default camera",new O(r.x,r.y,-o),this);l.setTarget(r),n=l}n.minZ=o*.01,n.maxZ=o*1e3,n.speed=o*.2,this.activeCamera=n,t&&n.attachControl()}};oi.prototype.createDefaultCameraOrLight=function(a=!1,e=!1,t=!1){this.createDefaultLight(e),this.createDefaultCamera(a,e,t)};oi.prototype.createDefaultSkybox=function(a,e=!1,t=1e3,i=0,s=!0){if(!a)return Me.Warn("Can not create default skybox without environment texture."),null;s&&a&&(this.environmentTexture=a);const r=pl("hdrSkyBox",{size:t},this);if(e){const n=new ji("skyBox",this);n.backFaceCulling=!1,n.reflectionTexture=a.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=Te.SKYBOX_MODE),n.microSurface=1-i,n.disableLighting=!0,n.twoSidedLighting=!0,r.material=n}else{const n=new jt("skyBox",this);n.backFaceCulling=!1,n.reflectionTexture=a.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=Te.SKYBOX_MODE),n.disableLighting=!0,r.material=n}return r.isPickable=!1,r.infiniteDistance=!0,r.ignoreCameraMaxZ=!0,r};oi.prototype.createDefaultEnvironment=function(a){return UL?new UL(a,this):null};oi.prototype.createDefaultVRExperience=function(a={}){return new WP(this,a)};oi.prototype.createDefaultXRExperienceAsync=function(a={}){return nQ.CreateAsync(this,a).then(e=>e)};function cre(a){for(;a.firstChild;)a.removeChild(a.firstChild);a.srcObject=null,a.src="",a.removeAttribute("src")}class Yj extends Te{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new Se),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e?.message):Me.Error(e?.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if(e?.name==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}else if(!this.video.muted){Me.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,s=!1,r=!1,n=Te.TRILINEAR_SAMPLINGMODE,o={},l,c=5){var h,u;super(null,i,!s,r),this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this._resizeInternalTexture=()=>{var m;this._texture!=null&&this._texture.dispose(),!this._getEngine().needPOTTextures||Be.IsExponentOfTwo(this.video.videoWidth)&&Be.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Te.WRAP_ADDRESSMODE,this.wrapV=Te.WRAP_ADDRESSMODE):(this.wrapU=Te.CLAMP_ADDRESSMODE,this.wrapV=Te.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=(m=this._format)!==null&&m!==void 0?m: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 m=this.video.onplaying,_=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=_,this.video.onplaying=m,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||!p)?(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0):p&&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 Be.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return typeof e=="string"?(Be.SetCorsBehavior(e,t),t.src=e):(Be.SetCorsBehavior(e[0],t),e.forEach(i=>{const s=document.createElement("source");s.src=i,t.appendChild(s)})),this.onDisposeObservable.addOnce(()=>{cre(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 Yj(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("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),(e=this._externalTexture)===null||e===void 0||e.dispose()}static CreateFromStreamAsync(e,t,i,s=!0){const r=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(r),r.style.transform="scale(0.0001, 0.0001)",r.style.opacity="0",r.style.position="fixed",r.style.bottom="0px",r.style.right="0px"),r.setAttribute("autoplay",""),r.setAttribute("muted","true"),r.setAttribute("playsinline",""),r.muted=!0,r.isNative||(r.mozSrcObject!==void 0?r.mozSrcObject=t:typeof r.srcObject=="object"?r.srcObject=t:r.src=window.URL&&window.URL.createObjectURL(t)),new Promise(n=>{const o=()=>{const l=new Yj("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&l.onDisposeObservable.addOnce(()=>{r.remove()}),l.onDisposeObservable.addOnce(()=>{cre(r)}),n(l),r.removeEventListener("playing",o)};r.addEventListener("playing",o),r.play()})}static async CreateFromWebCamAsync(e,t,i=!1,s=!0){if(navigator.mediaDevices){const r=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,r,t,s);return n.onDisposeObservable.addOnce(()=>{r.getTracks().forEach(o=>{o.stop()})}),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,s=!1,r=!0){this.CreateFromWebCamAsync(e,i,s,r).then(function(n){t&&t(n)}).catch(function(n){Me.Error(n.name)})}}class aQ extends m0{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const s={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},r=new Yj((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Te.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(n=>{var o;((o=n.pickInfo)===null||o===void 0?void 0:o.pickedMesh)===this.mesh&&this._texture.video.play()},mi.POINTERDOWN)),this._textureObserver=r.onLoadObservable.add(()=>{this.onLoadObservable.notifyObservers()}),r}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}aQ.MODE_MONOSCOPIC=m0.MODE_MONOSCOPIC;aQ.MODE_TOPBOTTOM=m0.MODE_TOPBOTTOM;aQ.MODE_SIDEBYSIDE=m0.MODE_SIDEBYSIDE;class dhe{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 Tc,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 fhe{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(()=>{Be.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()}),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add(()=>{Be.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(()=>{Be.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()}),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add(()=>{Be.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(()=>{Be.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()}),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add(()=>{Be.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(()=>{Be.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()}),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add(()=>{Be.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(()=>{Be.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()}),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add(()=>{Be.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(),Be.StartPerformanceCounter("Main render")}),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add(()=>{this._renderTime.endMonitoring(!1),Be.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(),Be.StartPerformanceCounter(`Rendering camera ${t.name}`)}),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add(t=>{this._cameraRenderTime.endMonitoring(!1),Be.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 Tc,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new Tc,this._captureFrameTime=!1,this._frameTime=new Tc,this._captureRenderTime=!1,this._renderTime=new Tc,this._captureInterFrameTime=!1,this._interFrameTime=new Tc,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new Tc,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new Tc,this._capturePhysicsTime=!1,this._physicsTime=new Tc,this._captureAnimationsTime=!1,this._animationsTime=new Tc,this._captureCameraRenderTime=!1,this._cameraRenderTime=new Tc,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&&(Be.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&&(Be.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 R5e="glowMapGenerationPixelShader",P5e=`#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 +}`;Ue.ShadersStore[D5e]=O5e;class T_{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 s=0;s{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let r;const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{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 s;const r=this._scene.getEngine(),n=e.getMesh(),o=(s=n._internalAbstractMeshDataInfo._materialForRenderPass)===null||s===void 0?void 0:s[r.currentRenderPassId];if(o)return o.isReadyForSubMesh(n,e,t);const l=e.getMaterial();if(!l)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return l.isReadyForSubMesh(e.getMesh(),e,t);const c=[],h=[se.PositionKind];let u=!1,p=!1;if(l){const y=l.needAlphaTesting(),M=l.getAlphaTestTexture(),b=M&&M.hasAlpha&&(l.useAlphaFromDiffuseTexture||l._useAlphaFromAlbedoTexture);M&&(y||b)&&(c.push("#define DIFFUSE"),n.isVerticesDataPresent(se.UV2Kind)&&M.coordinatesIndex===1?(c.push("#define DIFFUSEUV2"),p=!0):n.isVerticesDataPresent(se.UVKind)&&(c.push("#define DIFFUSEUV1"),u=!0),y&&(c.push("#define ALPHATEST"),c.push("#define ALPHATESTVALUE 0.4")),M.gammaSpace||c.push("#define DIFFUSE_ISLINEAR"));const E=l.opacityTexture;E&&(c.push("#define OPACITY"),n.isVerticesDataPresent(se.UV2Kind)&&E.coordinatesIndex===1?(c.push("#define OPACITYUV2"),p=!0):n.isVerticesDataPresent(se.UVKind)&&(c.push("#define OPACITYUV1"),u=!0))}i&&(c.push("#define EMISSIVE"),n.isVerticesDataPresent(se.UV2Kind)&&i.coordinatesIndex===1?(c.push("#define EMISSIVEUV2"),p=!0):n.isVerticesDataPresent(se.UVKind)&&(c.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||c.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent(se.ColorKind)&&n.hasVertexAlpha&&l.transparencyMode!==Lt.MATERIAL_OPAQUE&&(h.push(se.ColorKind),c.push("#define VERTEXALPHA")),u&&(h.push(se.UVKind),c.push("#define UV1")),p&&(h.push(se.UV2Kind),c.push("#define UV2"));const m=new Fl;if(n.useBones&&n.computeBonesUsingShaders){h.push(se.MatricesIndicesKind),h.push(se.MatricesWeightsKind),n.numBoneInfluencers>4&&(h.push(se.MatricesIndicesExtraKind),h.push(se.MatricesWeightsExtraKind)),c.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);const y=n.skeleton;y&&y.isUsingTextureForMatrices?c.push("#define BONETEXTURE"):c.push("#define BonesPerMesh "+(y?y.bones.length+1:0)),n.numBoneInfluencers>0&&m.addCPUSkinningFallback(0,n)}else c.push("#define NUM_BONE_INFLUENCERS 0");const _=n.morphTargetManager;let f=0;_&&_.numInfluencers>0&&(c.push("#define MORPHTARGETS"),f=_.numInfluencers,c.push("#define NUM_MORPH_INFLUENCERS "+f),_.isUsingTextureForTargets&&c.push("#define MORPHTARGETS_TEXTURE"),ze.PrepareAttributesForMorphTargetsInfluencers(h,n,f)),t&&(c.push("#define INSTANCES"),ze.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&c.push("#define THIN_INSTANCES")),PI(l,this._scene,c),this._addCustomEffectDefines(c);const d=e._getDrawWrapper(void 0,!0),C=d.defines,v=c.join(` +`);if(C!==v){const y=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];lh(y),d.setEffect(this._engine.createEffect("glowMapGeneration",h,y,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],v,m,void 0,void 0,{maxSimultaneousMorphTargets:f}),v)}return d.effect.isReady()}render(){for(let n=0;ny.setMatrix("world",b))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(n)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[se.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 Be.Instantiate(e.customType).Parse(e,t,i)}}T_._SceneComponentInitialization=a=>{throw Ys("EffectLayerSceneComponent")};z([X()],T_.prototype,"name",void 0);z([bF()],T_.prototype,"neutralColor",void 0);z([X()],T_.prototype,"isEnabled",void 0);z([Joe()],T_.prototype,"camera",null);z([X()],T_.prototype,"renderingGroupId",null);z([X()],T_.prototype,"disableBoundingBoxesFromEffectLayer",void 0);pc.AddParser(ai.NAME_EFFECTLAYER,(a,e,t,i)=>{if(a.effectLayers){t.effectLayers||(t.effectLayers=new Array);for(let s=0;s{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,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const n=r._mainTexture;this._engine.currentRenderPassId=n.renderPassId;for(const o of e.subMeshes)if(!r.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 s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===Pi.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==Pi.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const r=s._mainTexture;r._shouldRender()&&(this.scene.incrementRenderId(),r.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=a._getComponent(ai.NAME_EFFECTLAYER);e||(e=new phe(a),a._addComponent(e))};const w5e="glowMapMergePixelShader",N5e=`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 +}`;Ue.ShadersStore[w5e]=N5e;const B5e="glowMapMergeVertexShader",F5e=`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 +}`;Ue.ShadersStore[B5e]=F5e;pc.prototype.getGlowLayerByName=function(a){var e;for(let t=0;t<((e=this.effectLayers)===null||e===void 0?void 0:e.length);t++)if(this.effectLayers[t].name===a&&this.effectLayers[t].getEffectName()===x_.EffectName)return this.effectLayers[t];return null};class x_ extends T_{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 Zt(0,0,0,1),this._options=Object.assign({mainTextureRatio:x_.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 x_.EffectName}_createMergeEffect(){let e=`#define EMISSIVE +`;return this._options.ldrMerge&&(e+=`#define LDR +`),this._engine.createEffect("glowMapMerge",[se.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?He.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?He.GetExponentOfTwo(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture1=new Oa("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=Te.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=Te.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(Te.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const s=Math.floor(e/2),r=Math.floor(t/2);this._blurTexture2=new Oa("GlowLayerBlurRTT2",{width:s,height:r},this._scene,!1,!0,i),this._blurTexture2.wrapU=Te.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=Te.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(Te.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new Rh("GlowLayerHBP1",new lt(1,0),n,{width:e,height:t},null,Te.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 Rh("GlowLayerVBP1",new lt(0,1),n,{width:e,height:t},null,Te.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new Rh("GlowLayerHBP2",new lt(1,0),n,{width:s,height:r},null,Te.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(o=>{o.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new Rh("GlowLayerVBP2",new lt(0,1),n,{width:s,height:r},null,Te.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 l=this._blurTexture2.renderTarget;l&&this._scene.postProcessManager.directRender(this._postProcesses2,l,!0),this._engine.unBindFramebuffer(l??o,!0)}}),this._postProcesses.map(o=>{o.autoClear=!1})}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}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(Lt.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var s;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 n=(s=i.emissiveIntensity)!==null&&s!==void 0?s:1;r*=n,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=Kt.Serialize(this);e.customType="BABYLON.GlowLayer";let t;if(e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew x_(e.name,t,e.options),e,t,i);let r;for(r=0;r{c.setFloat2("screenSize",this.width,this.height),c.setVector2("direction",this.direction),c.setFloat("blurWidth",this.kernel)})}}class j2 extends T_{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 Se,this.onAfterBlurObservable=new Se,this._instanceGlowingMeshStencilReference=j2.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=j2.NeutralColor,this._engine.isStencilEnable||Me.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options=Object.assign({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 j2.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[se.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?He.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?He.GetExponentOfTwo(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new Oa("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=Te.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Te.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Te.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new l7("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Te.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new hre("HighlightLayerHBP",new lt(1,0),this._options.blurHorizontalSize,1,null,Te.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new hre("HighlightLayerVBP",new lt(0,1),this._options.blurVerticalSize,1,null,Te.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new Rh("HighlightLayerHBP",new lt(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,Te.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new Rh("HighlightLayerVBP",new lt(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,Te.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);const s=this._blurTexture.renderTarget;s&&(this._scene.postProcessManager.directRender(this._postProcesses,s,!0),this._engine.unBindFramebuffer(s,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(s=>{s.autoClear=!1})}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s||!this._meshes)return!1;let r=null;const n=this._meshes[s.uniqueId];return n&&n.glowEmissiveOnly&&i&&(r=i.emissiveTexture),super._isReady(e,t,r)}_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(Lt.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Lt.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 s=this._meshes[e.uniqueId];s?this._emissiveTextureAndColor.color.set(s.color.r,s.color.g,s.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),s&&s.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(s=>{i.stencilState=s.getEngine().getStencilBuffer(),s.getEngine().setStencilBuffer(!1)}),i.afterRender=e.onAfterRenderObservable.add(s=>{s.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 s=this._meshes[e.uniqueId];s?s.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(r=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[r.uniqueId]?this._defaultStencilReference(r):r.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(r=>{this.isEnabled&&this._defaultStencilReference(r)}),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(j2.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=Kt.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 s=Kt.Parse(()=>new j2(e.name,t,e.options),e,t,i);let r;for(r=0;rthis._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,s,r){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(r)>-1&&(e.layerMask&s)!==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 s=this.scene.layers.indexOf(i);s!==-1&&this.scene.layers.splice(s,1),t&&i.dispose()})}}const U5e="layerPixelShader",k5e=`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 +}`;Ue.ShadersStore[U5e]=k5e;const H5e="layerVertexShader",j5e=`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 +}`;Ue.ShadersStore[H5e]=j5e;class _he{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,s,r){this.name=e,this._applyPostProcess=!0,this.scale=new lt(1,1),this.offset=new lt(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new Se,this.onBeforeRenderObservable=new Se,this.onAfterRenderObservable=new Se,this.texture=t?new Te(t,i,!0):null,this.isBackground=s===void 0?!0:s,this.color=r===void 0?new Zt(1,1,1,1):r,this._scene=i||Ii.LastCreatedScene;let n=this._scene._getComponent(ai.NAME_LAYER);n||(n=new mhe(this._scene),this._scene._addComponent(n)),this._scene.layers.push(this);const o=this._scene.getEngine();this._drawWrapper=new ml(o);const l=[];l.push(1,1),l.push(-1,1),l.push(-1,-1),l.push(1,-1);const c=new se(o,l,se.PositionKind,!1,!1,2);this._vertexBuffers[se.PositionKind]=c,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[se.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){var e;const t=this._scene.getEngine();let i="";this.alphaTest&&(i="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(i+=` +#define LINEAR`),this._previousDefines!==i&&(this._previousDefines=i,this._drawWrapper.effect=t.createEffect("layer",[se.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],i));const s=this._drawWrapper.effect;return s?.isReady()&&((e=this.texture)===null||e===void 0?void 0:e.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(Lt.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(Lt.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[se.PositionKind];e&&(e.dispose(),this._vertexBuffers[se.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 oQ{static AddFlare(e,t,i,s,r){return new oQ(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Ie(1,1,1),this.texture=s?new Te(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new ml(n),this._drawWrapper.effect=n.createEffect("lensFlare",[se.PositionKind],["color","viewportMatrix"],["textureSampler"],""),r.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}const G5e="lensFlarePixelShader",W5e=`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 +}`;Ue.ShadersStore[G5e]=W5e;const Y5e="lensFlareVertexShader",X5e=`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 +}`;Ue.ShadersStore[Y5e]=X5e;class qP{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=new Array,this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||Ii.LastCreatedScene,qP._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=n=>i.activeCamera&&n.material&&n.isVisible&&n.isEnabled()&&n.isBlocker&&(n.layerMask&i.activeCamera.layerMask)!=0;const s=i.getEngine(),r=[];r.push(1,1),r.push(-1,1),r.push(-1,-1),r.push(1,-1),this._vertexBuffers[se.PositionKind]=new se(s,r,se.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=O.Project(t,ge.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=O.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 s,r;this._positionXi.x+i.width-this.borderLimit?s=this._positionX-i.x-i.width+this.borderLimit:s=0,this._positionYi.y+i.height-this.borderLimit?r=this._positionY-i.y-i.height+this.borderLimit:r=0;let n=s>r?s:r;n-=this.viewportBorder,n>this.borderLimit&&(n=this.borderLimit);let o=1-Bt.Clamp(n/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 l=i.x+i.width/2,c=i.y+i.height/2,h=l-this._positionX,u=c-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let p=0;p{throw Ys("LensFlareSystemSceneComponent")};pc.AddParser(ai.NAME_LENSFLARESYSTEM,(a,e,t,i)=>{if(a.lensFlareSystems!==void 0&&a.lensFlareSystems!==null){t.lensFlareSystems||(t.lensFlareSystems=new Array);for(let s=0,r=a.lensFlareSystems.length;s{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;Be.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)(e.layerMask&i.layerMask)!==0&&i.render();Be.EndPerformanceCounter("Lens flares",t.length>0)}}}qP._SceneComponentInitialization=a=>{let e=a._getComponent(ai.NAME_LENSFLARESYSTEM);e||(e=new ghe(a),a._addComponent(e))};const K5e="bayerDitherFunctions",Q5e=`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);} +`;Ue.IncludesShadersStore[K5e]=Q5e;const Z5e="shadowMapFragmentExtraDeclaration",q5e=`#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 +`;Ue.IncludesShadersStore[Z5e]=q5e;const J5e="shadowMapFragment",$5e=`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;`;Ue.IncludesShadersStore[J5e]=$5e;const eCe="shadowMapPixelShader",tCe=`#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 +}`;Ue.ShadersStore[eCe]=tCe;const iCe="sceneVertexDeclaration",sCe=`uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; +`;Ue.IncludesShadersStore[iCe]=sCe;const rCe="meshVertexDeclaration",nCe=`uniform mat4 world;uniform float visibility; +`;Ue.IncludesShadersStore[rCe]=nCe;const aCe="shadowMapVertexDeclaration",oCe=`#include +#include +`;Ue.IncludesShadersStore[aCe]=oCe;const lCe="shadowMapUboDeclaration",cCe=`layout(std140,column_major) uniform; +#include +#include +`;Ue.IncludesShadersStore[lCe]=cCe;const hCe="shadowMapVertexExtraDeclaration",uCe=`#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 +`;Ue.IncludesShadersStore[hCe]=uCe;const dCe="shadowMapVertexNormalBias",fCe=`#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 +`;Ue.IncludesShadersStore[dCe]=fCe;const pCe="shadowMapVertexMetric",mCe=`#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 +`;Ue.IncludesShadersStore[pCe]=mCe;const _Ce="shadowMapVertexShader",gCe=`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 +}`;Ue.ShadersStore[_Ce]=gCe;const vCe="depthBoxBlurPixelShader",CCe=`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)));}`;Ue.ShadersStore[vCe]=CCe;const ACe="shadowMapFragmentSoftTransparentShadow",xCe=`#if SM_SOFTTRANSPARENTSHADOW==1 +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; +#endif +`;Ue.IncludesShadersStore[ACe]=xCe;class Us{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===Us.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===Us.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===Us.FILTER_PCF||e===Us.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===Us.FILTER_PCF||e===Us.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===Us.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(Us.FILTER_POISSONSAMPLING);!e&&this.filter!==Us.FILTER_POISSONSAMPLING||(this.filter=e?t:Us.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===Us.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(Us.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==Us.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:Us.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===Us.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(Us.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==Us.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:Us.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===Us.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(Us.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==Us.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:Us.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===Us.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(Us.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==Us.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:Us.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===Us.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(Us.FILTER_PCF);!e&&this.filter!==Us.FILTER_PCF||(this.filter=e?t:Us.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===Us.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(Us.FILTER_PCSS);!e&&this.filter!==Us.FILTER_PCSS||(this.filter=e?t:Us.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 Us.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 s of e.getChildren())this.removeShadowCaster(s);return this}getLight(){return this._light}_getCamera(){var e;return(e=this._camera)!==null&&e!==void 0?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,s,r){this.onBeforeShadowMapRenderObservable=new Se,this.onAfterShadowMapRenderObservable=new Se,this.onBeforeShadowMapRenderMeshObservable=new Se,this.onAfterShadowMapRenderMeshObservable=new Se,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=Us.FILTER_NONE,this._filteringQuality=Us.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=O.Zero(),this._viewMatrix=ge.Zero(),this._projectionMatrix=ge.Zero(),this._transformMatrix=ge.Zero(),this._cachedPosition=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=ge.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.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}")`))),Us._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 Oa(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 Oa(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=Te.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Te.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Te.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var s;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),(s=e._debugPushGroup)===null||s===void 0||s.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)}),this._shadowMap.onBeforeRenderObservable.add(s=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=s,this._filter===Us.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,r;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===Us.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(s=e._debugPopGroup)===null||s===void 0||s.call(e,1);return}const n=this.getShadowMapForRendering();n&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,n.renderTarget,!0),e.unBindFramebuffer(n.renderTarget,!0),(r=e._debugPopGroup)===null||r===void 0||r.call(e,1))});const t=new Zt(0,0,0,0),i=new Zt(1,1,1,1);this._shadowMap.onClearObservable.add(s=>{this._filter===Us.FILTER_PCF?s.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?s.clear(t,!0,!0,!1):s.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(s=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=s.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let s=pd.MIN_RENDERINGGROUPS;s{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new Rh(this._light.name+"KernelBlurY",new lt(0,1),this.blurKernel,1,null,Te.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 rs(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Te.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,s){let r;if(s.length)for(r=0;r{n!==r&&!M?(r.getMeshUniformBuffer().bindToEffect(C,"Mesh"),r.transferToEffect(b)):(n.getMeshUniformBuffer().bindToEffect(C,"Mesh"),n.transferToEffect(M?b:y))}),this.forceBackFacesOnly&&l.setState(!0,0,!1,!1,c.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(C),this.onAfterShadowMapRenderMeshObservable.notifyObservers(r)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){!this._shadowMap||(this.filter===Us.FILTER_NONE||this.filter===Us.FILTER_PCSS?this._shadowMap.updateSamplingMode(Te.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Te.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i=Object.assign({useInstances:!1},t),s=this.getShadowMap();if(!s){e&&e(this);return}const r=s.renderList;if(!r){e&&e(this);return}const n=new Array;for(const c of r)n.push(...c.subMeshes);if(n.length===0){e&&e(this);return}let o=0;const l=()=>{var c,h;if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(n[o],i.useInstances,(h=(c=n[o].getMaterial())===null||c===void 0?void 0:c.needAlphaBlendingForMesh(n[o].getMesh()))!==null&&h!==void 0?h:!1);)if(o++,o>=n.length){e&&e(this);return}setTimeout(l,16)}};l()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){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 r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(se.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===pr.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var s;const r=e.getMaterial(),n=r?.shadowDepthWrapper;if(this._opacityTexture=null,!r)return!1;const o=[];if(this._prepareShadowDefines(e,t,o,i),n){if(!n.isReadyForSubMesh(e,o,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const l=e._getDrawWrapper(void 0,!0);let c=l.effect,h=l.defines;const u=[se.PositionKind],p=e.getMesh();this.normalBias&&p.isVerticesDataPresent(se.NormalKind)&&(u.push(se.NormalKind),o.push("#define NORMAL"),p.nonUniformScaling&&o.push("#define NONUNIFORMSCALING"));const m=r.needAlphaTesting();if((m||r.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=r.opacityTexture:this._opacityTexture=r.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const v=(s=r.alphaCutOff)!==null&&s!==void 0?s:Us.DEFAULT_ALPHA_CUTOFF;o.push("#define ALPHATEXTURE"),m&&o.push(`#define ALPHATESTVALUE ${v}${v%1===0?".":""}`),p.isVerticesDataPresent(se.UVKind)&&(u.push(se.UVKind),o.push("#define UV1")),p.isVerticesDataPresent(se.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(u.push(se.UV2Kind),o.push("#define UV2"))}const _=new Fl;if(p.useBones&&p.computeBonesUsingShaders&&p.skeleton){u.push(se.MatricesIndicesKind),u.push(se.MatricesWeightsKind),p.numBoneInfluencers>4&&(u.push(se.MatricesIndicesExtraKind),u.push(se.MatricesWeightsExtraKind));const v=p.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+p.numBoneInfluencers),p.numBoneInfluencers>0&&_.addCPUSkinningFallback(0,p),v.isUsingTextureForMatrices?o.push("#define BONETEXTURE"):o.push("#define BonesPerMesh "+(v.bones.length+1))}else o.push("#define NUM_BONE_INFLUENCERS 0");const f=p.morphTargetManager;let d=0;if(f&&f.numInfluencers>0&&(o.push("#define MORPHTARGETS"),d=f.numInfluencers,o.push("#define NUM_MORPH_INFLUENCERS "+d),f.isUsingTextureForTargets&&o.push("#define MORPHTARGETS_TEXTURE"),ze.PrepareAttributesForMorphTargetsInfluencers(u,p,d)),PI(r,this._scene,o),t&&(o.push("#define INSTANCES"),ze.PushAttributesForInstances(u),e.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const v of this.customShaderOptions.defines)o.indexOf(v)===-1&&o.push(v);const C=o.join(` +`);if(h!==C){h=C;let v="shadowMap";const y=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],M=["diffuseSampler","boneSampler","morphTargets"],b=["Scene","Mesh"];if(lh(y),this.customShaderOptions){if(v=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const S of this.customShaderOptions.attributes)u.indexOf(S)===-1&&u.push(S);if(this.customShaderOptions.uniforms)for(const S of this.customShaderOptions.uniforms)y.indexOf(S)===-1&&y.push(S);if(this.customShaderOptions.samplers)for(const S of this.customShaderOptions.samplers)M.indexOf(S)===-1&&M.push(S)}const E=this._scene.getEngine();c=E.createEffect(v,{attributes:u,uniformsNames:y,uniformBuffersNames:b,samplers:M,defines:C,fallbacks:_,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d}},E),l.setEffect(c,h)}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,s=this._light;!i.shadowsEnabled||!s.shadowEnabled||(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===Us.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Us.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===Us.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Us.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),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const r=this._getCamera();if(!r)return;const n=this.getShadowMap();!n||(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===Us.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n.getSize().width,1/n.getSize().width,this.frustumEdgeFalloff,e)):this._filter===Us.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/n.getSize().width,this._contactHardeningLightSizeUVRatio*n.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/n.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(r),this.getLight().getDepthMinZ(r)+this.getLight().getDepthMaxZ(r),e))}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),O.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(O.Dot(this._lightDirection,O.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),ge.LookAtLHToRef(t,t.add(this._lightDirection),O.Up(),this._viewMatrix);const i=this.getShadowMap();if(i){const s=i.renderList;s&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,s)}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,s]=t.value;s===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 e;const t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=(e=this._camera)===null||e===void 0?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(let s=0;s{throw Ys("ShadowGeneratorSceneComponent")};const bCe="depthPixelShader",ECe=`#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 +}`;Ue.ShadersStore[bCe]=ECe;const yCe="depthVertexShader",MCe=`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 +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 +} +`;Ue.ShadersStore[yCe]=MCe;class qL{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=Te.TRILINEAR_SAMPLINGMODE,n=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=t===0,this.isPacked?this.clearColor=new Zt(1,1,1,1):this.clearColor=new Zt(n?1e8:1,0,0,1),qL._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,r!==Te.NEAREST_SAMPLINGMODE&&(t===1&&!l._caps.textureFloatLinearFiltering&&(r=Te.NEAREST_SAMPLINGMODE),t===2&&!l._caps.textureHalfFloatLinearFiltering&&(r=Te.NEAREST_SAMPLINGMODE));const c=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=new Oa(o??"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,c),this._depthMap.wrapU=Te.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Te.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=l._debugPushGroup)===null||u===void 0||u.call(l,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var u;(u=l._debugPopGroup)===null||u===void 0||u.call(l,1)}),this._depthMap.customIsReadyFunction=(u,p,m)=>{if((m||p===0)&&u.subMeshes)for(let _=0;_{var p,m;const _=u.getRenderingMesh(),f=u.getEffectiveMesh(),d=this._scene,C=d.getEngine(),v=u.getMaterial();if(f._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!v||f.infiniteDistance||v.disableDepthWrite||u.verticesCount===0||u._renderId===d.getRenderId())return;const y=f._getWorldMatrixDeterminant()<0;let M=(p=_.overrideMaterialSideOrientation)!==null&&p!==void 0?p:v.sideOrientation;y&&(M=M===0?1:0);const b=M===0;C.setState(v.backFaceCulling,0,!1,b,this.reverseCulling?!v.cullBackFaces:v.cullBackFaces);const E=_._getInstancesRenderList(u._id,!!u.getReplacementMesh());if(E.mustReturn)return;const S=C.getCaps().instancedArrays&&(E.visibleInstances[u._id]!==null&&E.visibleInstances[u._id]!==void 0||_.hasThinInstances),I=this._camera||d.activeCamera;if(this.isReady(u,S)&&I){u._renderId=d.getRenderId();const D=(m=f._internalAbstractMeshDataInfo._materialForRenderPass)===null||m===void 0?void 0:m[C.currentRenderPassId];let R=u._getDrawWrapper();!R&&D&&(R=D._getDrawWrapper());const L=I.mode===Pi.ORTHOGRAPHIC_CAMERA;if(!R)return;const w=R.effect;C.enableEffect(R),S||_._bind(u,w,v.fillMode),D?D.bindForSubMesh(f.getWorldMatrix(),f,u):(w.setMatrix("viewProjection",d.getTransformMatrix()),w.setMatrix("world",f.getWorldMatrix()),this._storeCameraSpaceZ&&w.setMatrix("view",d.getViewMatrix()));let N,V;if(L?(N=!C.useReverseDepthBuffer&&C.isNDCHalfZRange?0:1,V=C.useReverseDepthBuffer&&C.isNDCHalfZRange?0:1):(N=C.useReverseDepthBuffer&&C.isNDCHalfZRange?I.minZ:C.isNDCHalfZRange?0:I.minZ,V=C.useReverseDepthBuffer&&C.isNDCHalfZRange?0:I.maxZ),w.setFloat2("depthValues",N,N+V),!D){if(v.needAlphaTesting()){const W=v.getAlphaTestTexture();W&&(w.setTexture("diffuseSampler",W),w.setMatrix("diffuseMatrix",W.getTextureMatrix()))}if(_.useBones&&_.computeBonesUsingShaders&&_.skeleton){const W=_.skeleton;if(W.isUsingTextureForMatrices){const G=W.getTransformMatrixTexture(_);if(!G)return;w.setTexture("boneSampler",G),w.setFloat("boneTextureWidth",4*(W.bones.length+1))}else w.setMatrices("mBones",W.getTransformMatrices(_))}wc(w,v,d),ze.BindMorphTargetParameters(_,w),_.morphTargetManager&&_.morphTargetManager.isUsingTextureForTargets&&_.morphTargetManager._bind(w)}_._processRendering(f,u,w,v.fillMode,E,S,(W,G)=>w.setMatrix("world",G))}};this._depthMap.customRenderFunction=(u,p,m,_)=>{let f;if(_.length)for(f=0;f<_.length;f++)h(_.data[f]);for(f=0;f4&&(h.push(se.MatricesIndicesExtraKind),h.push(se.MatricesWeightsExtraKind)),c.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),c.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0));const d=e.getRenderingMesh().skeleton;d?.isUsingTextureForMatrices&&c.push("#define BONETEXTURE")}else c.push("#define NUM_BONE_INFLUENCERS 0");const u=r.morphTargetManager;let p=0;u&&u.numInfluencers>0&&(p=u.numInfluencers,c.push("#define MORPHTARGETS"),c.push("#define NUM_MORPH_INFLUENCERS "+p),u.isUsingTextureForTargets&&c.push("#define MORPHTARGETS_TEXTURE"),ze.PrepareAttributesForMorphTargetsInfluencers(h,r,p)),t&&(c.push("#define INSTANCES"),ze.PushAttributesForInstances(h),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"),PI(l,n,c);const m=e._getDrawWrapper(void 0,!0),_=m.defines,f=c.join(` +`);if(_!==f){const d=["world","mBones","boneTextureWidth","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];lh(d),m.setEffect(s.createEffect("depth",h,d,["diffuseSampler","morphTargets","boneSampler"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:p}),f)}return m.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]}}}qL._SceneComponentInitialization=a=>{throw Ys("DepthRendererSceneComponent")};const TCe="minmaxReduxPixelShader",SCe=`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 +`;Ue.ShadersStore[TCe]=SCe;class vhe{constructor(e){this.onAfterReductionPerformed=new Se,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new wj(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new rs("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?` +#define DEPTH_REDUX`:""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let o=this._sourceTexture.getRenderWidth(),l=this._sourceTexture.getRenderHeight();n.onApply=((h,u)=>p=>{p.setTexture("sourceTexture",this._sourceTexture),p.setFloat2("texSize",h,u)})(o,l),this._reductionSteps.push(n);let c=1;for(;o>1||l>1;){o=Math.max(Math.round(o/2),1),l=Math.max(Math.round(l/2),1);const h=new rs("Reduction phase "+c,"minmaxRedux",["texSize"],null,{width:o,height:l},null,1,r.getEngine(),!1,"#define "+(o==1&&l==1?"LAST":o==1||l==1?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(h.autoClear=!1,h.forceFullscreenViewport=s,h.onApply=((u,p)=>m=>{u==1||p==1?m.setInt2("texSize",u,p):m.setFloat2("texSize",u,p)})(o,l),this._reductionSteps.push(h),c++,o==1&&l==1){const u=(p,m,_)=>{const f=new Float32Array(4*p*m),d={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(_.inputTexture.texture,p,m,-1,0,f,!1),d.min=f[0],d.max=f[1],this.onAfterReductionPerformed.notifyObservers(d)}};h.onAfterRenderObservable.add(u(o,l,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 e,t;const i=this._camera.getScene().getEngine();(e=i._debugPushGroup)===null||e===void 0||e.call(i,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),i.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),(t=i._debugPopGroup)===null||t===void 0||t.call(i,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;tt&&(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 wu.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ||(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 s=i.min,r=i.max;s>=r&&(s=0,r=1),(s!=this._minDistance||r!=this._maxDistance)&&this.setMinMaxDistance(s,r)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return(i=(t=(e=this._depthReducer)===null||e===void 0?void 0:e.depthRenderer)===null||t===void 0?void 0:t.getDepthMap().refreshRate)!==null&&i!==void 0?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;!((t=this._depthReducer)===null||t===void 0)&&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,s=i-t,r=this._minDistance,n=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,o=t+r*s,l=t+n*s,c=l-o,h=l/o;for(let u=0;u{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===Us.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===void 0||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!==Us.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.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 r=this._getCamera();if(!r)return;const n=this.getShadowMap();if(!n)return;const o=n.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===Us.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===Us.FILTER_PCSS){for(let l=0;lnew wu(s,r,void 0,n));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}}wu._FrustumCornersNDCSpace=[new O(-1,1,-1),new O(1,1,-1),new O(1,-1,-1),new O(-1,-1,-1),new O(-1,1,1),new O(1,1,1),new O(1,-1,1),new O(-1,-1,1)];wu.CLASSNAME="CascadedShadowGenerator";wu.DEFAULT_CASCADES_COUNT=4;wu.MIN_CASCADES_COUNT=2;wu.MAX_CASCADES_COUNT=4;wu._SceneComponentInitialization=a=>{throw Ys("ShadowGeneratorSceneComponent")};pc.AddParser(ai.NAME_SHADOWGENERATOR,(a,e)=>{if(a.shadowGenerators!==void 0&&a.shadowGenerators!==null)for(let t=0,i=a.shadowGenerators.length;t{let e=a._getComponent(ai.NAME_SHADOWGENERATOR);e||(e=new Ahe(a),a._addComponent(e))};pn.AddNodeConstructor("Light_Type_0",(a,e)=>()=>new cD(a,O.Zero(),e));class cD extends wI{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 s=i.next();s.done!==!0;s=i.next())s.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return pr.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new O(1,0,0);case 1:return new O(-1,0,0);case 2:return new O(0,-1,0);case 3:return new O(0,1,0);case 4:return new O(0,0,1);case 5:return new O(0,0,-1)}return O.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,n=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;ge.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:r,o?r:n,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}}z([X()],cD.prototype,"shadowAngle",null);class rI{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const s=this._renderingCanvas.getBoundingClientRect(),r=window.getComputedStyle(this._renderingCanvas).position;!this._loadingDiv||(this._loadingDiv.style.position=r==="fixed"?"fixed":"absolute",this._loadingDiv.style.left=s.left+"px",this._loadingDiv.style.top=s.top+"px",this._loadingDiv.style.width=s.width+"px",this._loadingDiv.style.height=s.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;rI.DefaultLogoUrl?i.src=rI.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 s=document.createElement("div");s.style.width="300px",s.style.gridColumn="1",s.style.gridRow="1",s.style.top="50%",s.style.left="50%",s.style.transform="translate(-50%, -50%)",s.style.position="absolute";const r=new Image;if(rI.DefaultSpinnerUrl?r.src=rI.DefaultSpinnerUrl:r.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",r.style.animation="spin1 0.75s infinite linear",r.style.webkitAnimation="spin1 0.75s infinite linear",r.style.transformOrigin="50% 50%",r.style.webkitTransformOrigin="50% 50%",!t){const n={w:16,h:18.5},o={w:30,h:30};i.style.width=`${n.w}vh`,i.style.height=`${n.h}vh`,i.style.left=`calc(50% - ${n.w/2}vh)`,i.style.top=`calc(50% - ${n.h/2}vh)`,r.style.width=`${o.w}vh`,r.style.height=`${o.h}vh`,r.style.left=`calc(50% - ${o.w/2}vh)`,r.style.top=`calc(50% - ${o.h/2}vh)`}s.appendChild(r),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(s),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)}}rI.DefaultLogoUrl="";rI.DefaultSpinnerUrl="";He.DefaultLoadingScreenFactory=a=>new rI(a);class NI{static ConvertPanoramaToCubemap(e,t,i,s,r=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";const n=this.CreateCubemapTexture(s,this.FACE_FRONT,e,t,i,r),o=this.CreateCubemapTexture(s,this.FACE_BACK,e,t,i,r),l=this.CreateCubemapTexture(s,this.FACE_LEFT,e,t,i,r),c=this.CreateCubemapTexture(s,this.FACE_RIGHT,e,t,i,r),h=this.CreateCubemapTexture(s,this.FACE_UP,e,t,i,r),u=this.CreateCubemapTexture(s,this.FACE_DOWN,e,t,i,r);return{front:n,back:o,left:l,right:c,up:h,down:u,size:s,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,s,r,n=!1){const o=new ArrayBuffer(e*e*4*3),l=new Float32Array(o),c=n?Math.max(1,Math.round(s/4/e)):1,h=1/c,u=h*h,p=t[1].subtract(t[0]).scale(h/e),m=t[3].subtract(t[2]).scale(h/e),_=1/e;let f=0;for(let d=0;dMath.PI;)r-=2*Math.PI;let o=r/Math.PI;const l=n/Math.PI;o=o*.5+.5;let c=Math.round(o*i);c<0?c=0:c>=i&&(c=i-1);let h=Math.round(l*s);h<0?h=0:h>=s&&(h=s-1);const u=s-h-1,p=t[u*i*3+c*3+0],m=t[u*i*3+c*3+1],_=t[u*i*3+c*3+2];return{r:p,g:m,b:_}}}NI.FACE_LEFT=[new O(-1,-1,-1),new O(1,-1,-1),new O(-1,1,-1),new O(1,1,-1)];NI.FACE_RIGHT=[new O(1,-1,1),new O(-1,-1,1),new O(1,1,1),new O(-1,1,1)];NI.FACE_FRONT=[new O(1,-1,-1),new O(1,-1,1),new O(1,1,-1),new O(1,1,1)];NI.FACE_BACK=[new O(-1,-1,1),new O(-1,-1,-1),new O(-1,1,1),new O(-1,1,-1)];NI.FACE_DOWN=[new O(1,1,-1),new O(1,1,1),new O(-1,1,-1),new O(-1,1,1)];NI.FACE_UP=[new O(-1,-1,-1),new O(-1,-1,1),new O(1,-1,-1),new O(1,-1,1)];class AX{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,s,r,n){r>0?(r=this._Ldexp(1,r-(128+8)),e[n+0]=t*r,e[n+1]=i*r,e[n+2]=s*r):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",s="";for(let r=t;r32767)throw"HDR Bad header format, unsupported size";return o+=s.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return NI.ConvertPanoramaToCubemap(n,r.width,r.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const s=t.width;let r,n,o,l,c,h=t.dataPosition,u=0,p=0,m=0;const _=new ArrayBuffer(s*4),f=new Uint8Array(_),d=new ArrayBuffer(t.width*t.height*4*3),C=new Float32Array(d);for(;i>0;){if(r=e[h++],n=e[h++],o=e[h++],l=e[h++],r!=2||n!=2||o&128||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|l)!=s)throw"HDR Bad header format, wrong scan line width";for(u=0,m=0;m<4;m++)for(p=(m+1)*s;u128){if(c=r-128,c==0||c>p-u)throw"HDR Bad Format, bad scanline data (run)";for(;c-- >0;)f[u++]=n}else{if(c=r,c==0||c>p-u)throw"HDR Bad Format, bad scanline data (non-run)";if(f[u++]=n,--c>0)for(let v=0;v0;){for(c=0;c +#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);}`;Ue.ShadersStore[PCe]=DCe;class xhe{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=Bt.ILog2(t)+1,s=this._effectWrapper.effect,r=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();const n=e.getInternalTexture();n&&this._engine.updateTextureSamplingMode(3,n,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);const o=[[new O(0,0,-1),new O(0,-1,0),new O(1,0,0)],[new O(0,0,1),new O(0,-1,0),new O(-1,0,0)],[new O(1,0,0),new O(0,0,1),new O(0,1,0)],[new O(1,0,0),new O(0,0,-1),new O(0,-1,0)],[new O(1,0,0),new O(0,-1,0),new O(0,0,1)],[new O(-1,0,0),new O(0,-1,0),new O(0,0,-1)]];s.setFloat("hdrScale",this.hdrScale),s.setFloat2("vFilteringInfo",e.getSize().width,i),s.setTexture("inputTexture",e);for(let h=0;h<6;h++){s.setVector3("up",o[h][0]),s.setVector3("right",o[h][1]),s.setVector3("front",o[h][2]);for(let u=0;u{this._effectRenderer=new QG(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(Me.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 fI extends Sn{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(ge.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,s=!1,r=!0,n=!1,o=!1,l=null,c=null,h=!1){var u;super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=O.Zero(),this.onLoadObservable=new Se,e&&(this._coordinatesMode=Te.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=ge.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),l&&l()},this._onError=c,this.gammaSpace=n,this._noMipmap=s,this._size=i,this._supersample=h,this._generateHarmonics=r,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Be.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):!((u=this.getScene())===null||u===void 0)&&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 s=r=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const n=AX.GetCubeMapTextureData(r,this._size,this._supersample);if(this._generateHarmonics){const h=oD.ConvertCubeMapToSphericalPolynomial(n);this.sphericalPolynomial=h}const o=[];let l=null,c=null;for(let h=0;h<6;h++){i===2?c=new Uint16Array(this._size*this._size*3):i===0&&(l=new Uint8Array(this._size*this._size*3));const u=n[fI._FacesMapping[h]];if(this.gammaSpace||c||l){for(let p=0;p255){const C=255/d;m*=C,_*=C,f*=C}l[p*3+0]=m,l[p*3+1]=_,l[p*3+2]=f}}c?o.push(c):l?o.push(l):o.push(u)}return o};if(e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const r=this._onLoad,n=new xhe(e);this._onLoad=()=>{n.prefilter(this,r)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,s,null,this._onLoad,this._onError)}clone(){const e=new fI(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===void 0||t.markAllMaterialsAsDirty(1,i=>i.getActiveTextures().indexOf(this)!==-1))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let s=null;return e.name&&!e.isRenderTarget&&(s=new fI(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),s.name=e.name,s.hasAlpha=e.hasAlpha,s.level=e.level,s.coordinatesMode=e.coordinatesMode,s.isBlocking=e.isBlocking),s&&(e.boundingBoxPosition&&(s.boundingBoxPosition=O.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=O.FromArray(e.boundingBoxSize)),e.rotationY&&(s.rotationY=e.rotationY)),s}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}}fI._FacesMapping=["right","left","up","down","front","back"];$e("BABYLON.HDRCubeTexture",fI);class t7{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=new Array,this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new Se,this._onDataLayoutChanged=new Se,this._animationPropertiesOverride=null,this._scene=i||Ii.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=Kt.Clone(()=>new t7(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())),Kt.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new t7(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 s=0;s0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Sc(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._useTextureToStoreTargets=!0,e||(e=Ii.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 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 eC.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(!((e=this._scene)===null||e===void 0)&&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)}clone(){const e=new eC(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 s of this._targets){if(i++,s.influence===0&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=eC.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(s),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=s.influence,this._supportsNormals=this._supportsNormals&&s.hasNormals,this._supportsTangents=this._supportsTangents&&s.hasTangents,this._supportsUVs=this._supportsUVs&&s.hasUVs;const r=s.getPositions();if(r){const n=r.length/3;if(this._vertexCount===0)this._vertexCount=n;else if(this._vertexCount!==n){Me.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 s=0;se&&(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,s=new Float32Array(i*this._textureWidth*this._textureHeight*4);let r=0;for(let n=0;n-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 eC(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(t7.Parse(s,t));return i}}eC.EnableTextureStorage=!0;eC.MaxActiveMorphTargetsInVertexAttributeMode=8;class MW{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=O.Zero(),this._hitPointWorld=O.Zero(),this._rayFromWorld=O.Zero(),this._rayToWorld=O.Zero(),this._triangleIndex=-1}get hasHit(){return this._hasHit}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormalWorld}get hitPointWorld(){return this._hitPointWorld}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormalWorld.set(e.x,e.y,e.z),this._hitPointWorld.set(t.x,t.y,t.z),this._triangleIndex=i??-1}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=O.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=O.Zero(),t=O.Zero()){this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld.setAll(0),this._hitPointWorld.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0}}class TW{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw Ys("CannonJSPlugin")}constructor(e,t=TW.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 O(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 s={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(s),this._physicsPlugin.generateJoint(s)}removeJoint(e,t,i){const s=this._joints.filter(function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e});s.length&&this._physicsPlugin.removeJoint(s[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 s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,s)}applyForce(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,s)}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){Me.Warn("It was not possible to create a physics body for this object.");return}const i=e.physicsBody;i&&this.removePhysicsBody(e);const s=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:s},n=e.getParam("nativeOptions");for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o]);e.physicsBody=new this.BJSCANNON.Body(r),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 l=i[o];e.physicsBody[o].set(l.x,l.y,l.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 s=r=>{if(!r.rotationQuaternion)return;const n=r.getPhysicsImpostor();if(n&&n.parent!==e&&r.parent){const l=r.getAbsolutePosition().subtract(r.parent.getAbsolutePosition()),c=r.rotationQuaternion.multiply(this._tmpQuaternion);n.physicsBody&&(this.removePhysicsBody(n),n.physicsBody=null),n.parent=e,n.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(n),new this.BJSCANNON.Vec3(l.x,l.y,l.z),new this.BJSCANNON.Quaternion(c.x,c.y,c.z,c.w)),e.physicsBody.mass+=n.getParam("mass")}r.getChildMeshes(!0).filter(o=>!!o.physicsImpostor).forEach(s)};t.filter(r=>!!r.physicsImpostor).forEach(s)}}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 s;const r=e.joint.jointData,n={pivotA:r.mainPivot?new this.BJSCANNON.Vec3().set(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z):null,pivotB:r.connectedPivot?new this.BJSCANNON.Vec3().set(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z):null,axisA:r.mainAxis?new this.BJSCANNON.Vec3().set(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z):null,axisB:r.connectedAxis?new this.BJSCANNON.Vec3().set(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case $n.HingeJoint:case $n.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case $n.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case $n.SpringJoint:{const o=r;s=new this.BJSCANNON.Spring(t,i,{restLength:o.length,stiffness:o.stiffness,damping:o.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case $n.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case $n.PointToPointJoint:case $n.BallAndSocketJoint:default:s=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce);break}s.collideConnected=!!r.collision,e.joint.physicsJoint=s,e.joint.type!==$n.SpringJoint?this.world.addConstraint(s):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){s.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==$n.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;si*1e3));p++);this.time+=s;const c=this.time%i/i,h=e,u=this.bodies;for(let p=0;p!==u.length;p++){const m=u[p];m.type!==t.Body.STATIC&&m.sleepState!==t.Body.SLEEPING?(m.position.vsub(m.previousPosition,h),h.scale(c,h),m.position.vadd(h,m.interpolatedPosition)):(m.interpolatedPosition.set(m.position.x,m.position.y,m.position.z),m.interpolatedQuaternion.set(m.quaternion.x,m.quaternion.y,m.quaternion.z,m.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))}}TW.DefaultPluginFactory=()=>new xX;class Jq{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=O.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new MW}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(s){s.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach(s=>{s.afterStep(),this._tmpImpostorsArray[s.uniqueId]=s});let i=this.world.contacts;for(;i!==null;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const s=this._tmpImpostorsArray[+i.body1.name],r=this._tmpImpostorsArray[+i.body2.name];if(!s||!r){i=i.next;continue}s.onCollide({body:r.physicsBody,point:null,distance:0,impulse:0,normal:null}),r.onCollide({body:s.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next}}applyImpulse(e,t,i){const s=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*s))}applyForce(e,t,i){Me.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(l){l.physicsImpostor&&i.push(l.physicsImpostor)})})(e.object);const r=o=>Math.max(o,Ls),n=new ke;i.forEach(o=>{if(!o.object.rotationQuaternion)return;const l=o.object.rotationQuaternion;n.copyFrom(l),o.object.rotationQuaternion.set(0,0,0,1),o.object.computeWorldMatrix(!0);const c=n.toEulerAngles(),h=o.getObjectExtents(),u=57.29577951308232;if(o===e){const p=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(p,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),t.pos.push(p.x),t.pos.push(p.y),t.pos.push(p.z),t.posShape.push(0,0,0),t.rotShape.push(0,0,0)}else{const p=o.object.position.clone();t.posShape.push(p.x),t.posShape.push(p.y),t.posShape.push(p.z),t.rotShape.push(c.x*u,c.y*u,c.z*u)}switch(o.object.rotationQuaternion.copyFrom(n),o.type){case ys.ParticleImpostor:Me.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case ys.SphereImpostor:{const p=h.x,m=h.y,_=h.z,f=Math.max(r(p),r(m),r(_))/2;t.type.push("sphere"),t.size.push(f),t.size.push(f),t.size.push(f);break}case ys.CylinderImpostor:{const p=r(h.x)/2,m=r(h.y);t.type.push("cylinder"),t.size.push(p),t.size.push(m),t.size.push(m);break}case ys.PlaneImpostor:case ys.BoxImpostor:default:{const p=r(h.x),m=r(h.y),_=r(h.z);t.type.push("box"),t.size.push(p),t.size.push(m),t.size.push(_);break}}o.object.rotationQuaternion=l}),e.physicsBody=this.world.add(t),e.physicsBody.resetQuaternion(n),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 s=e.joint.jointData,r=s.nativeParams||{};let n;const o={body1:t,body2:i,axe1:r.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:r.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:r.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:r.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:r.min,max:r.max,collision:r.collision||s.collision,spring:r.spring,world:this.world};switch(e.joint.type){case $n.BallAndSocketJoint:n="jointBall";break;case $n.SpringJoint:{Me.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const l=s;o.min=l.length||o.min,o.max=Math.max(o.min,o.max)}case $n.DistanceJoint:n="jointDistance",o.max=s.maxDistance;break;case $n.PrismaticJoint:n="jointPrisme";break;case $n.SliderJoint:n="jointSlide";break;case $n.WheelJoint:n="jointWheel";break;case $n.HingeJoint:default:n="jointHinge";break}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(t){Me.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 s=e.physicsBody;e.physicsBody.shapes.next||(s.position.set(t.x,t.y,t.z),s.orientation.set(i.x,i.y,i.z,i.w),s.syncShapes(),s.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 O(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new O(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,s){i!==void 0?Me.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)}setLimit(e,t,i,s){const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.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 Me.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){Me.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class Qb{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 ke,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new O,this._tmpContactNormal=new O,this._tmpVec3=new O,this._tmpMatrix=new ge,typeof t=="function"){Me.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}else this.bjsAMMO=t;if(!this.isSupported()){Me.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=s=>{s=this.bjsAMMO.wrapPointer(s,this.bjsAMMO.btManifoldPoint);const r=s.getPositionWorldOnA(),n=s.m_normalWorldOnB;this._tmpContactPoint.x=r.x(),this._tmpContactPoint.y=r.y(),this._tmpContactPoint.z=r.z(),this._tmpContactNormal.x=n.x(),this._tmpContactNormal.y=n.y(),this._tmpContactNormal.z=n.z(),this._tmpContactImpulse=s.getAppliedImpulse(),this._tmpContactDistance=s.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new MW,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 s of i._onPhysicsCollideCallbacks)for(const r of s.otherImpostors)(i.physicsBody.isActive()||r.physicsBody.isActive())&&this._isImpostorPairInContact(i,r)&&(i.onCollide({body:r.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),r.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===ys.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,o,l;const c=new Array;for(let p=0;p{this.bjsAMMO.destroy(t)}),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData;s.mainPivot||(s.mainPivot=new O(0,0,0)),s.connectedPivot||(s.connectedPivot=new O(0,0,0));let r;switch(e.joint.type){case $n.DistanceJoint:{const n=s.maxDistance;n&&(s.mainPivot=new O(0,-n/2,0),s.connectedPivot=new O(0,n/2,0)),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case $n.HingeJoint:{s.mainAxis||(s.mainAxis=new O(0,0,0)),s.connectedAxis||(s.connectedAxis=new O(0,0,0));const n=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),o=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);r=new this.bjsAMMO.btHingeConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),n,o);break}case $n.BallAndSocketJoint:r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:Me.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}this.world.addConstraint(r,!e.joint.jointData.collision),e.joint.physicsJoint=r}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(se.PositionKind);n||(n=[]);let o;if(t&&t!==i){let c;t.rotationQuaternion?c=t.rotationQuaternion:t.rotation?c=ke.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):c=ke.Identity(),ge.Compose(O.One(),c,t.position).invertToRef(this._tmpMatrix),o=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else ge.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),o=this._tmpMatrix;const l=r.length/3;for(let c=0;c{s+=this._addMeshVerts(e,t,c)})}return s}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){t.getIndices();let i=t.getVerticesData(se.PositionKind);i||(i=[]);let s=t.getVerticesData(se.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let l=0;lp*p),l=(p,m)=>p+m;if(o.reduce(l)===0)t=r.length,i=t/3-1,this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[t-3],r[t-2],r[t-1]);else{e._isFromLine=!1;const p=e.getParam("path");if(e.getParam("shape")===null)return Me.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=p.length,i=t-1,this._tmpAmmoVectorA.setValue(p[0].x,p[0].y,p[0].z),this._tmpAmmoVectorB.setValue(p[t-1].x,p[t-1].y,p[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 s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(se.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=r.length/3;for(let l=0;l{s+=this._addHullVerts(e,t,l)})}return s}_createShape(e,t=!1){const i=e.object;let s;const r=e.getObjectExtents();if(!t){const n=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];s=new this.bjsAMMO.btCompoundShape;let o=0;if(n.forEach(l=>{const c=l.getPhysicsImpostor();if(c){if(c.type==ys.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const h=this._createShape(c),u=l.parent.getWorldMatrix().clone(),p=new O;u.decompose(p),this._tmpAmmoTransform.getOrigin().setValue(l.position.x*p.x,l.position.y*p.y,l.position.z*p.z),this._tmpAmmoQuaternion.setValue(l.rotationQuaternion.x,l.rotationQuaternion.y,l.rotationQuaternion.z,l.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,h),c.dispose(),o++}}),o>0){if(e.type!=ys.NoImpostor){const l=this._createShape(e,!0);l&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,l))}return s}else this.bjsAMMO.destroy(s),s=null}switch(e.type){case ys.SphereImpostor:if(Bt.WithinEpsilon(r.x,r.y,1e-4)&&Bt.WithinEpsilon(r.x,r.z,1e-4))s=new this.bjsAMMO.btSphereShape(r.x/2);else{const n=[new this.bjsAMMO.btVector3(0,0,0)],o=[1];s=new this.bjsAMMO.btMultiSphereShape(n,o,1),s.setLocalScaling(new this.bjsAMMO.btVector3(r.x/2,r.y/2,r.z/2))}break;case ys.CapsuleImpostor:{const n=r.x/2;s=new this.bjsAMMO.btCapsuleShape(n,r.y-n*2)}break;case ys.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case ys.PlaneImpostor:case ys.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case ys.MeshImpostor:if(e.getParam("mass")==0){if(this.onCreateCustomMeshImpostor)s=this.onCreateCustomMeshImpostor(e);else{const n=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(n),this._addMeshVerts(n,i,i)==0?s=new this.bjsAMMO.btCompoundShape:s=new this.bjsAMMO.btBvhTriangleMeshShape(n)}break}case ys.ConvexHullImpostor:{if(this.onCreateCustomConvexHullImpostor)s=this.onCreateCustomConvexHullImpostor(e);else{const n=new this.bjsAMMO.btConvexHullShape;this._addHullVerts(n,i,i)==0?(e._pluginData.toDispose.push(n),s=new this.bjsAMMO.btCompoundShape):s=n}break}case ys.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case ys.CustomImpostor:s=this._createCustom(e);break;case ys.SoftbodyImpostor:s=this._createSoftbody(e);break;case ys.ClothImpostor:s=this._createCloth(e);break;case ys.RopeImpostor:s=this._createRope(e);break;default:Me.Warn("The impostor type is not currently supported by the ammo plugin.");break}return s}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 s=e.physicsBody.getWorldTransform();if(Math.abs(s.getOrigin().x()-t.x)>Ls||Math.abs(s.getOrigin().y()-t.y)>Ls||Math.abs(s.getOrigin().z()-t.z)>Ls||Math.abs(s.getRotation().x()-i.x)>Ls||Math.abs(s.getRotation().y()-i.y)>Ls||Math.abs(s.getRotation().z()-i.z)>Ls||Math.abs(s.getRotation().w()-i.w)>Ls)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),s.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),s.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(s),e.mass==0){const r=e.physicsBody.getMotionState();r&&r.setWorldTransform(s)}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 O(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 O(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:(Me.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===ys.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):Me.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(Me.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):Me.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(Me.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):Me.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(Me.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):Me.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const o=e.segments,l=Math.round((o-1)*i),c=Math.round((o-1)*s),h=o-1-c,u=l+o*h;e.physicsBody.appendAnchor(u,t.physicsBody,n,r)}appendHook(e,t,i,s=1,r=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,r,s)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){Me.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){Me.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 s=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,s),i.reset(e,t),s.hasHit()&&(i.setHitData({x:s.get_m_hitNormalWorld().x(),y:s.get_m_hitNormalWorld().y(),z:s.get_m_hitNormalWorld().z()},{x:s.get_m_hitPointWorld().x(),y:s.get_m_hitPointWorld().y(),z:s.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(s),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}Qb._DISABLE_COLLISION_FLAG=4;Qb._KINEMATIC_FLAG=2;Qb._DISABLE_DEACTIVATION_FLAG=4;pc.prototype.removeReflectionProbe=function(a){if(!this.reflectionProbes)return-1;const e=this.reflectionProbes.indexOf(a);return e!==-1&&this.reflectionProbes.splice(e,1),e};pc.prototype.addReflectionProbe=function(a){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(a)};class hD{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=ge.Identity(),this._target=O.Zero(),this._add=O.Zero(),this._invertYAxis=!1,this.position=O.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=new Array),this._scene.reflectionProbes.push(this);let o=0;if(r){const h=this._scene.getEngine().getCaps();h.textureHalfFloatRender?o=2:h.textureFloatRender&&(o=1)}this._renderTargetTexture=new Oa(e,t,i,s,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const l=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?ge.LookAtRHToRef:ge.LookAtLHToRef,p=i.useRightHandedSystem?ge.PerspectiveFovRH:ge.PerspectiveFovLH;u(this.position,this._target,O.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=p(Math.PI/2,1,l?i.activeCamera.maxZ:i.activeCamera.minZ,l?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 c;this._renderTargetTexture.onBeforeBindObservable.add(()=>{var h,u;this._currentSceneUBO=i.getSceneUniformBuffer(),(u=(h=i.getEngine())._debugPushGroup)===null||u===void 0||u.call(h,`reflection probe generation for ${e}`,1),c=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var h,u;i.imageProcessingConfiguration.applyByPostProcess=c,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),(u=(h=i.getEngine())._debugPopGroup)===null||u===void 0||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=Kt.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let s=null;if(t.reflectionProbes)for(let r=0;rs||new hD(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i),s.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&s.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(s.metadata=e.metadata),s}}z([xF()],hD.prototype,"_attachedMesh",void 0);z([bo()],hD.prototype,"position",void 0);var OCe=!0;class Ej{}Ej.LoaderInjectedPhysicsEngine=void 0;let IN={},EL={};const dre=(a,e,t,i)=>{if(!e.materials)return null;for(let s=0,r=e.materials.length;s{for(const i in e)if(a.name===e[i])return t.push(a.id),!0;return a.parentId!==void 0&&t.indexOf(a.parentId)!==-1?(t.push(a.id),!0):!1},NN=(a,e)=>a+" of "+(e?e.file+" from "+e.name+" version: "+e.version+", exporter version: "+e.exporter_version:"unknown"),bhe=(a,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,s=t.isEnabled(!1);if(e._waitingData.lods.distances){const r=e._waitingData.lods.distances;if(r.length>=i.length){const n=r.length>i.length?r[r.length-1]:0;t.setEnabled(!1);for(let o=0;o0&&t.addLODLevel(n,null),s===!0&&t.setEnabled(!0)}else Be.Warn("Invalid level of detail distances for "+e.name)}}e._waitingData.lods=null}},mY=(a,e,t)=>{if(typeof a!="number"){const s=t.getLastEntryById(a);return s&&e!==void 0&&e!==null?s.instances[parseInt(e)]:s}const i=IN[a];return i&&e!==void 0&&e!==null?i.instances[parseInt(e)]:i},bX=(a,e)=>typeof a!="number"?e.getLastMaterialById(a,!0):EL[a],fre=(a,e,t,i,s=!1)=>{const r=new kG(a);let n="importScene has failed JSON parse";try{var o=JSON.parse(e);n="";const l=As.loggingLevel===As.DETAILED_LOGGING;let c,h;if(o.environmentTexture!==void 0&&o.environmentTexture!==null){const p=o.isPBR!==void 0?o.isPBR:!0;if(o.environmentTextureType&&o.environmentTextureType==="BABYLON.HDRCubeTexture"){const m=o.environmentTextureSize?o.environmentTextureSize:128,_=new fI((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,a,m,!0,!p,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(_.rotationY=o.environmentTextureRotationY),a.environmentTexture=_}else if(typeof o.environmentTexture=="object"){const m=Ic.Parse(o.environmentTexture,a,t);a.environmentTexture=m}else if(o.environmentTexture.endsWith(".env")){const m=new Ic((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,a,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(m.rotationY=o.environmentTextureRotationY),a.environmentTexture=m}else{const m=Ic.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,a,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(m.rotationY=o.environmentTextureRotationY),a.environmentTexture=m}if(o.createDefaultSkybox===!0){const m=a.activeCamera!==void 0&&a.activeCamera!==null?(a.activeCamera.maxZ-a.activeCamera.minZ)/2:1e3,_=o.skyboxBlurLevel||0;a.createDefaultSkybox(a.environmentTexture,p,m,_)}r.environmentTexture=a.environmentTexture}if(o.environmentIntensity!==void 0&&o.environmentIntensity!==null&&(a.environmentIntensity=o.environmentIntensity),o.lights!==void 0&&o.lights!==null)for(c=0,h=o.lights.length;c{r.textures.indexOf(f)==-1&&(r.textures.push(f),f._parentContainer=r)}))}if(o.multiMaterials!==void 0&&o.multiMaterials!==null)for(c=0,h=o.multiMaterials.length;c{r.textures.indexOf(f)==-1&&(r.textures.push(f),f._parentContainer=r)})}if(o.morphTargetManagers!==void 0&&o.morphTargetManagers!==null)for(const p of o.morphTargetManagers){const m=eC.Parse(p,a);r.morphTargetManagers.push(m),m._parentContainer=r}if(o.skeletons!==void 0&&o.skeletons!==null)for(c=0,h=o.skeletons.length;c{_&&(r.geometries.push(_),_._parentContainer=r)})}if(o.transformNodes!==void 0&&o.transformNodes!==null)for(c=0,h=o.transformNodes.length;c{p._waitingSubMaterialsUniqueIds.forEach(m=>{p.subMaterials.push(bX(m,a))}),p._waitingSubMaterialsUniqueIds=[]}),a.meshes.forEach(p=>{p._waitingMaterialId!==null&&(p.material=bX(p._waitingMaterialId,a),p._waitingMaterialId=null)}),c=0,h=a.skeletons.length;c{if(m._waitingTransformNodeId){const _=a.getLastEntryById(m._waitingTransformNodeId);_&&m.linkTransformNode(_),m._waitingTransformNodeId=null}}),p._hasWaitingData=null)}for(c=0,h=a.meshes.length;c0){for(let m=0;m0){for(let m=0;m{p._loadedUniqueId=""}),pc.Parse(o,a,r,t),c=0,h=a.meshes.length;ca.indexOf("babylon")!==-1,importMesh:(a,e,t,i,s,r,n,o)=>{var l;let c="importMesh has failed JSON parse";try{var h=JSON.parse(t);c="";const u=As.loggingLevel===As.DETAILED_LOGGING;a?Array.isArray(a)||(a=[a]):a=null;const p=new Array,m=new Map,_=[];if(h.transformNodes!==void 0&&h.transformNodes!==null)for(let f=0,d=h.transformNodes.length;f{I===!0||!h.geometries[D]||!Array.isArray(h.geometries[D])||h.geometries[D].forEach(R=>{if(R.id===E.geometryId){switch(D){case"vertexData":au.Parse(R,e,i);break}I=!0}})}),I===!1&&Me.Warn("Geometry not found for mesh "+E.id)}if(E.materialUniqueId||E.materialId){const I=E.materialUniqueId?C:d;let D=I.indexOf(E.materialUniqueId||E.materialId)!==-1;if(D===!1&&h.multiMaterials!==void 0&&h.multiMaterials!==null){const R=(L,w)=>{I.push(L);const N=dre(w,h,e,i);N&&N.material&&(EL[N.parsedMaterial.uniqueId||N.parsedMaterial.id]=N.material,c+=` + Material `+N.material.toString(u))};for(let L=0,w=h.multiMaterials.length;LR(W,G=>G.uniqueId===W)):N.materials.forEach(W=>R(W,G=>G.id===W)),I.push(N.uniqueId||N.id);const V=g0.ParseMultiMaterial(N,e);EL[N.uniqueId||N.id]=V,V&&(D=!0,c+=` + Multi-Material `+V.toString(u));break}}}if(D===!1){I.push(E.materialUniqueId||E.materialId);const R=dre(L=>E.materialUniqueId&&L.uniqueId===E.materialUniqueId||L.id===E.materialId,h,e,i);!R||!R.material?Me.Warn("Material not found for mesh "+E.id):(EL[R.parsedMaterial.uniqueId||R.parsedMaterial.id]=R.material,c+=` + Material `+R.material.toString(u))}}if(E.skeletonId!==null&&E.skeletonId!==void 0&&h.skeletonId!==-1&&h.skeletons!==void 0&&h.skeletons!==null&&!(f.indexOf(E.skeletonId)>-1))for(let D=0,R=h.skeletons.length;D-1&&h.morphTargetManagers!==void 0&&h.morphTargetManagers!==null&&!(v.indexOf(E.morphTargetManagerId)>-1))for(let D=0,R=h.morphTargetManagers.length;D{M._waitingSubMaterialsUniqueIds.forEach(b=>{M.subMaterials.push(bX(b,e))}),M._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(M=>{M._waitingMaterialId!==null&&(M.material=bX(M._waitingMaterialId,e),M._waitingMaterialId=null)});for(let M=0,b=e.transformNodes.length;M-1&&_.splice(I,1)}y._waitingParentId=null}y._waitingData.lods&&bhe(e,y)}for(const M of _)M.dispose();for(let M=0,b=e.skeletons.length;M{if(S._waitingTransformNodeId){const I=e.getLastEntryById(S._waitingTransformNodeId);I&&S.linkTransformNode(I),S._waitingTransformNodeId=null}}),E._hasWaitingData=null)}for(let M=0,b=e.meshes.length;M{f._loadedUniqueId=""}),!0}catch(u){const p=NN("importMesh",h?h.producer:"Unknown")+c;if(o)o(p,u);else throw Me.Log(p),u}finally{c!==null&&As.loggingLevel!==As.NO_LOGGING&&Me.Log(NN("importMesh",h?h.producer:"Unknown")+(As.loggingLevel!==As.MINIMAL_LOGGING?c:"")),EL={}}return!1},load:(a,e,t,i)=>{let s="importScene has failed JSON parse";try{var r=JSON.parse(e);if(s="",r.useDelayedTextureLoading!==void 0&&r.useDelayedTextureLoading!==null&&(a.useDelayedTextureLoading=r.useDelayedTextureLoading&&!As.ForceFullSceneLoadingForIncremental),r.autoClear!==void 0&&r.autoClear!==null&&(a.autoClear=r.autoClear),r.clearColor!==void 0&&r.clearColor!==null&&(a.clearColor=Zt.FromArray(r.clearColor)),r.ambientColor!==void 0&&r.ambientColor!==null&&(a.ambientColor=Ie.FromArray(r.ambientColor)),r.gravity!==void 0&&r.gravity!==null&&(a.gravity=O.FromArray(r.gravity)),r.useRightHandedSystem!==void 0&&(a.useRightHandedSystem=!!r.useRightHandedSystem),r.fogMode&&r.fogMode!==0)switch(a.fogMode=r.fogMode,a.fogColor=Ie.FromArray(r.fogColor),a.fogStart=r.fogStart,a.fogEnd=r.fogEnd,a.fogDensity=r.fogDensity,s+=" Fog mode for scene: ",a.fogMode){case 1:s+=`exp +`;break;case 2:s+=`exp2 +`;break;case 3:s+=`linear +`;break}if(r.physicsEnabled){let o;r.physicsEngine==="cannon"||r.physicsEngine===xX.name?o=new xX(void 0,void 0,Ej.LoaderInjectedPhysicsEngine):r.physicsEngine==="oimo"||r.physicsEngine===Jq.name?o=new Jq(void 0,Ej.LoaderInjectedPhysicsEngine):(r.physicsEngine==="ammo"||r.physicsEngine===Qb.name)&&(o=new Qb(void 0,Ej.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(r.physicsEngine?r.physicsEngine:"oimo")+` enabled +`;const l=r.physicsGravity?O.FromArray(r.physicsGravity):null;a.enablePhysics(l,o)}return r.metadata!==void 0&&r.metadata!==null&&(a.metadata=r.metadata),r.collisionsEnabled!==void 0&&r.collisionsEnabled!==null&&(a.collisionsEnabled=r.collisionsEnabled),fre(a,e,t,i,!0)?(r.autoAnimate&&a.beginAnimation(a,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1),r.activeCameraID!==void 0&&r.activeCameraID!==null&&a.setActiveCameraById(r.activeCameraID),!0):!1}catch(n){const o=NN("importScene",r?r.producer:"Unknown")+s;if(i)i(o,n);else throw Me.Log(o),n}finally{s!==null&&As.loggingLevel!==As.NO_LOGGING&&Me.Log(NN("importScene",r?r.producer:"Unknown")+(As.loggingLevel!==As.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(a,e,t,i)=>fre(a,e,t,i)});class Xj{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,He.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||Ie.White(),this.rightColor=e.rightColor||Ie.Black(),e.isEnabled===!1&&(this.isEnabled=!1)}clone(){const e=new Xj;return e2.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 Xj({isEnabled:e.isEnabled,leftColor:Ie.FromArray(e.leftColor),rightColor:Ie.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}Kt._FresnelParametersParser=Xj.Parse;class NCe extends oh{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new Zt(0,0,0,1))}}class ip extends Fr{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 Ie(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}z([X(),_t("_markAllSubMeshesAsLightsDirty")],ip.prototype,"maxSimultaneousLights",void 0);z([X(),_t("_markAllSubMeshesAsLightsDirty")],ip.prototype,"disableLighting",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],ip.prototype,"environmentTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ip.prototype,"invertNormalMapX",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ip.prototype,"invertNormalMapY",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],ip.prototype,"normalTexture",void 0);z([Br("emissive"),_t("_markAllSubMeshesAsTexturesDirty")],ip.prototype,"emissiveColor",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty")],ip.prototype,"emissiveTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],ip.prototype,"occlusionStrength",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],ip.prototype,"occlusionTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],ip.prototype,"alphaCutOff",void 0);z([X()],ip.prototype,"doubleSided",null);z([xs(),_t("_markAllSubMeshesAsTexturesDirty",null)],ip.prototype,"lightmapTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],ip.prototype,"useLightmapAsShadowmap",void 0);class $M extends ip{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=Kt.Clone(()=>new $M(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=Kt.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 s=Kt.Parse(()=>new $M(e.name,t),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}z([Br(),_t("_markAllSubMeshesAsTexturesDirty","_albedoColor")],$M.prototype,"baseColor",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],$M.prototype,"baseTexture",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],$M.prototype,"metallic",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],$M.prototype,"roughness",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],$M.prototype,"metallicRoughnessTexture",void 0);$e("BABYLON.PBRMetallicRoughnessMaterial",$M);class eT extends ip{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=Kt.Clone(()=>new eT(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=Kt.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 s=Kt.Parse(()=>new eT(e.name,t),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}z([Br("diffuse"),_t("_markAllSubMeshesAsTexturesDirty","_albedoColor")],eT.prototype,"diffuseColor",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],eT.prototype,"diffuseTexture",void 0);z([Br("specular"),_t("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],eT.prototype,"specularColor",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty","_microSurface")],eT.prototype,"glossiness",void 0);z([xs(),_t("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],eT.prototype,"specularGlossinessTexture",void 0);$e("BABYLON.PBRSpecularGlossinessMaterial",eT);class LP extends Sn{constructor(e,t,i=null){if(super(t),!!e)if(this._textureMatrix=ge.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const s=this.getScene();s?s.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=r=>{if(typeof r!="string")return;let n=null,o=null,l;const c=r.split(` +`);let h=0,u=0,p=0,m=0,_=0;for(let f=0;f0&&(f+1)%4===0)n[f]=255;else{const d=o[f];n[f]=d/_*255}t.is3D?(t.updateSize(h,h,h),e.updateRawTexture3D(t,n,5,!1)):(t.updateSize(h*h,h),e.updateRawTexture(t,n,5,!1)),t.isReady=!0,this._triggerOnLoad()},s=this.getScene();return s?s._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 LP(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 LP(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}}LP._NoneEmptyLineRegex=/\S+/;$e("BABYLON.ColorGradingTexture",LP);class GB extends Sn{constructor(e,t,i,s=!1,r=!0,n=null,o=null,l=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Te.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=l,this._noMipmap=s,this.gammaSpace=r,this._onLoad=n,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?n&&(this._texture.isReady?Be.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(this._loadTexture.bind(this),this._onError)}_loadImage(e,t){const i=document.createElement("canvas");vF(this.url,s=>{this._width=s.width,this._height=s.height,i.width=this._width,i.height=this._height;const r=i.getContext("2d");r.drawImage(s,0,0);const n=r.getImageData(0,0,s.width,s.height);this._buffer=n.data.buffer,i.remove(),e()},(s,r)=>{t&&t(`${this.getClassName()} could not be loaded`,r)},null)}_loadTexture(){const e=this.getScene(),t=()=>{const i=this._getFloat32ArrayFromArrayBuffer(this._buffer),s=NI.ConvertPanoramaToCubemap(i,this._width,this._height,this._size,this._supersample),r=[];for(let n=0;n<6;n++){const o=s[GB._FacesMapping[n]];r.push(o)}return r};!e||(this._texture=e.getEngine().createRawCubeTextureFromUrl(this.url,e,this._size,4,e.getEngine().getCaps().textureFloat?1:7,this._noMipmap,t,null,this._onLoad,this._onError))}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(e.byteLength*3/4);let s=0;for(let r=0;re.length){Me.Error("Unable to load TGA file - Not enough data");return}t+=i.id_length;let s=!1,r=!1,n=!1;switch(i.image_type){case zCe:s=!0;case BCe:r=!0;break;case UCe:s=!0;case FCe:break;case kCe:s=!0;case VCe:n=!0;break}let o;const l=i.pixel_size>>3,c=i.width*i.height*l;let h;if(r&&(h=e.subarray(t,t+=i.colormap_length*(i.colormap_size>>3))),s){o=new Uint8Array(c);let M,b,E,S=0;const I=new Uint8Array(l);for(;t>jCe){default:case YCe:u=0,m=1,d=i.width,p=0,_=1,f=i.height;break;case GCe:u=0,m=1,d=i.width,p=i.height-1,_=-1,f=-1;break;case XCe:u=i.width-1,m=-1,d=-1,p=0,_=1,f=i.height;break;case WCe:u=i.width-1,m=-1,d=-1,p=i.height-1,_=-1,f=-1;break}const C="_getImageData"+(n?"Grey":"")+i.pixel_size+"bits",v=Ehe[C](i,h,o,p,_,f,u,m,d);a.getEngine()._uploadDataToTextureDirectly(a,v)}function KCe(a,e,t,i,s,r,n,o,l){const c=t,h=e,u=a.width,p=a.height;let m,_=0,f,d;const C=new Uint8Array(u*p*4);for(d=i;d!==r;d+=s)for(f=n;f!==l;f+=o,_++)m=c[_],C[(f+u*d)*4+3]=255,C[(f+u*d)*4+2]=h[m*3+0],C[(f+u*d)*4+1]=h[m*3+1],C[(f+u*d)*4+0]=h[m*3+2];return C}function QCe(a,e,t,i,s,r,n,o,l){const c=t,h=a.width,u=a.height;let p,m=0,_,f;const d=new Uint8Array(h*u*4);for(f=i;f!==r;f+=s)for(_=n;_!==l;_+=o,m+=2){p=c[m+0]+(c[m+1]<<8);const C=((p&31744)>>10)*255/31|0,v=((p&992)>>5)*255/31|0,y=(p&31)*255/31|0;d[(_+h*f)*4+0]=C,d[(_+h*f)*4+1]=v,d[(_+h*f)*4+2]=y,d[(_+h*f)*4+3]=p&32768?0:255}return d}function ZCe(a,e,t,i,s,r,n,o,l){const c=t,h=a.width,u=a.height;let p=0,m,_;const f=new Uint8Array(h*u*4);for(_=i;_!==r;_+=s)for(m=n;m!==l;m+=o,p+=3)f[(m+h*_)*4+3]=255,f[(m+h*_)*4+2]=c[p+0],f[(m+h*_)*4+1]=c[p+1],f[(m+h*_)*4+0]=c[p+2];return f}function qCe(a,e,t,i,s,r,n,o,l){const c=t,h=a.width,u=a.height;let p=0,m,_;const f=new Uint8Array(h*u*4);for(_=i;_!==r;_+=s)for(m=n;m!==l;m+=o,p+=4)f[(m+h*_)*4+2]=c[p+0],f[(m+h*_)*4+1]=c[p+1],f[(m+h*_)*4+0]=c[p+2],f[(m+h*_)*4+3]=c[p+3];return f}function JCe(a,e,t,i,s,r,n,o,l){const c=t,h=a.width,u=a.height;let p,m=0,_,f;const d=new Uint8Array(h*u*4);for(f=i;f!==r;f+=s)for(_=n;_!==l;_+=o,m++)p=c[m],d[(_+h*f)*4+0]=p,d[(_+h*f)*4+1]=p,d[(_+h*f)*4+2]=p,d[(_+h*f)*4+3]=255;return d}function $Ce(a,e,t,i,s,r,n,o,l){const c=t,h=a.width,u=a.height;let p=0,m,_;const f=new Uint8Array(h*u*4);for(_=i;_!==r;_+=s)for(m=n;m!==l;m+=o,p+=2)f[(m+h*_)*4+0]=c[p+0],f[(m+h*_)*4+1]=c[p+0],f[(m+h*_)*4+2]=c[p+0],f[(m+h*_)*4+3]=c[p+1];return f}const Ehe={GetTGAHeader:SW,UploadContent:Hee,_getImageData8bits:KCe,_getImageData16bits:QCe,_getImageData24bits:ZCe,_getImageData32bits:qCe,_getImageDataGrey8bits:JCe,_getImageDataGrey16bits:$Ce};class yhe{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=SW(s);i(r.width,r.height,t.generateMipMaps,!1,()=>{Hee(t,s)})}}He._TextureLoaders.push(new yhe);class Mhe{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=AX.RGBE_ReadHeader(s),n=AX.RGBE_ReadPixels(s,r),o=r.width*r.height,l=new Float32Array(o*4);for(let c=0;c{const c=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,c._uploadDataToTextureDirectly(t,l)})}}He._TextureLoaders.push(new Mhe);class eAe{}var G9;(function(a){a[a.cTFETC1=0]="cTFETC1",a[a.cTFETC2=1]="cTFETC2",a[a.cTFBC1=2]="cTFBC1",a[a.cTFBC3=3]="cTFBC3",a[a.cTFBC4=4]="cTFBC4",a[a.cTFBC5=5]="cTFBC5",a[a.cTFBC7=6]="cTFBC7",a[a.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",a[a.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",a[a.cTFASTC_4x4=10]="cTFASTC_4x4",a[a.cTFATC_RGB=11]="cTFATC_RGB",a[a.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",a[a.cTFRGBA32=13]="cTFRGBA32",a[a.cTFRGB565=14]="cTFRGB565",a[a.cTFBGR565=15]="cTFBGR565",a[a.cTFRGBA4444=16]="cTFRGBA4444",a[a.cTFFXT1_RGB=17]="cTFFXT1_RGB",a[a.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",a[a.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",a[a.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",a[a.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(G9||(G9={}));const SI={JSModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.js",WasmModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.wasm"},The=(a,e)=>{let t;switch(a){case G9.cTFETC1:t=36196;break;case G9.cTFBC1:t=33776;break;case G9.cTFBC4:t=33779;break;case G9.cTFASTC_4x4:t=37808;break;case G9.cTFETC2:t=37496;break;case G9.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t};let DZ=null,xM=null,tAe=0;const iAe=!1,sAe=()=>(DZ||(DZ=new Promise((a,e)=>{xM?a(xM):Be.LoadFileAsync(SI.WasmModuleURL).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");const i=URL.createObjectURL(new Blob([`(${rAe})()`],{type:"application/javascript"}));xM=new Worker(i);const s=r=>{r.data.action==="init"?(xM.removeEventListener("message",s),a(xM)):r.data.action==="error"&&e(r.data.error||"error initializing worker")};xM.addEventListener("message",s),xM.postMessage({action:"init",url:SI.JSModuleURL,wasmBinary:t})}).catch(e)})),DZ),EX=(a,e)=>{const t=a instanceof ArrayBuffer?new Uint8Array(a):a;return new Promise((i,s)=>{sAe().then(()=>{const r=tAe++,n=l=>{l.data.action==="transcode"&&l.data.id===r&&(xM.removeEventListener("message",n),l.data.success?i(l.data):s("Transcode is not supported on this device"))};xM.addEventListener("message",n);const o=new Uint8Array(t.byteLength);o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),xM.postMessage({action:"transcode",id:r,imageData:o,config:e,ignoreSupportedFormats:iAe},[o.buffer])},r=>{s(r)})})},_Y=(a,e)=>{var t,i;let s=(t=e._gl)===null||t===void 0?void 0:t.TEXTURE_2D;a.isCube&&(s=(i=e._gl)===null||i===void 0?void 0:i.TEXTURE_CUBE_MAP),e._bindTextureDirectly(s,a,!0)},yX=(a,e)=>{const t=a.getEngine();for(let i=0;i{t._releaseTexture(r),_Y(a,t)})}else a._invertVScale=!a.invertY,a.width=s.width+3&-4,a.height=s.height+3&-4,a.samplingMode=2,_Y(a,t),t._uploadDataToTextureDirectly(a,new Uint16Array(s.transcodedPixels.buffer),i,0,4,!0);else{a.width=s.width,a.height=s.height,a.generateMipMaps=e.fileInfo.images[i].levels.length>1;const r=hQ.GetInternalFormatFromBasisFormat(e.format,t);a.format=r,_Y(a,t),e.fileInfo.images[i].levels.forEach((n,o)=>{t._uploadCompressedDataToTextureDirectly(a,r,n.width,n.height,n.transcodedPixels,i,o)}),t._features.basisNeedsPOT&&(Bt.Log2(a.width)%1!==0||Bt.Log2(a.height)%1!==0)&&(Be.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."),a._cachedWrapU=Te.CLAMP_ADDRESSMODE,a._cachedWrapV=Te.CLAMP_ADDRESSMODE)}}},hQ={JSModuleURL:SI.JSModuleURL,WasmModuleURL:SI.WasmModuleURL,GetInternalFormatFromBasisFormat:The,TranscodeAsync:EX,LoadTextureFromTranscodeResult:yX};function rAe(){const a={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=n=>{if(n.data.action==="init"){if(!e){try{importScripts(n.data.url)}catch(o){postMessage({action:"error",error:o})}e=BASIS({wasmBinary:n.data.wasmBinary})}e!==null&&e.then(o=>{BASIS=o,o.initializeBasis(),postMessage({action:"init"})})}else if(n.data.action==="transcode"){const o=n.data.config,l=n.data.imageData,c=new BASIS.BasisFile(l),h=i(c);let u=n.data.ignoreSupportedFormats?null:t(n.data.config,h),p=!1;u===null&&(p=!0,u=h.hasAlpha?a.cTFBC3:a.cTFBC1);let m=!0;c.startTranscoding()||(m=!1);const _=[];for(let f=0;f>2&3],u[y++]=h[v>>4&3],u[y++]=h[v>>6&3]}}return u}}Object.defineProperty(hQ,"JSModuleURL",{get:function(){return SI.JSModuleURL},set:function(a){SI.JSModuleURL=a}});Object.defineProperty(hQ,"WasmModuleURL",{get:function(){return SI.WasmModuleURL},set:function(a){SI.WasmModuleURL=a}});class She{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};EX(e,o).then(l=>{const c=l.fileInfo.images[0].levels.length>1&&t.generateMipMaps;yX(t,l),t.getEngine()._setCubeMapTextureParams(t,c),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}).catch(l=>{const c="Failed to transcode Basis file, transcoding may not be supported on this device";Be.Warn(c),t.isReady=!0,r&&r(l)})}loadData(e,t,i){const s=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!s.etc1,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,astc:!!s.astc,bc7:!!s.bptc}};EX(e,r).then(n=>{const o=n.fileInfo.images[0].levels[0],l=n.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(o.width,o.height,l,n.format!==-1,()=>{yX(t,n)})}).catch(n=>{Be.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),Be.Warn(`Failed to transcode Basis file: ${n}`),i(0,0,!1,!1,()=>{},!0)})}}He._TextureLoaders.push(new She);class CL extends Oa{get isSupported(){var e,t;return(t=(e=this._engine)===null||e===void 0?void 0:e.getCaps().drawBuffersExtension)!==null&&t!==void 0?t:!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(n))}_initTypes(e,t,i,s,r,n,o,l,c,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 e,t;const i=(e=this._renderTarget)===null||e===void 0?void 0:e.textures;if(!!i){for(let s=i.length-1;s>=0;s--)this._textures[s]._texture=null;(t=this._renderTarget)===null||t===void 0||t.dispose(),this._renderTarget=null}}}class $q{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class tC{constructor(e,t,i,s){var r,n,o,l,c,h,u,p,m,_,f,d,C;return this.name=e,this.meshes=t,this.scene=s,this.options=i,this.options.map=(r=this.options.map)!==null&&r!==void 0?r:["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=(n=this.options.uvsIn)!==null&&n!==void 0?n:se.UVKind,this.options.uvsOut=(o=this.options.uvsOut)!==null&&o!==void 0?o:se.UVKind,this.options.layout=(l=this.options.layout)!==null&&l!==void 0?l:tC.LAYOUT_STRIP,this.options.layout===tC.LAYOUT_COLNUM&&(this.options.colnum=(c=this.options.colnum)!==null&&c!==void 0?c:8),this.options.updateInputMeshes=(h=this.options.updateInputMeshes)!==null&&h!==void 0?h:!0,this.options.disposeSources=(u=this.options.disposeSources)!==null&&u!==void 0?u:!0,this._expecting=0,this.options.fillBlanks=(p=this.options.fillBlanks)!==null&&p!==void 0?p:!0,this.options.fillBlanks===!0&&(this.options.customFillColor=(m=this.options.customFillColor)!==null&&m!==void 0?m:"black"),this.options.frameSize=(_=this.options.frameSize)!==null&&_!==void 0?_:256,this.options.paddingRatio=(f=this.options.paddingRatio)!==null&&f!==void 0?f:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!==0&&this._paddingValue++,this.options.paddingMode=(d=this.options.paddingMode)!==null&&d!==void 0?d:tC.SUBUV_WRAP,this.options.paddingMode===tC.SUBUV_COLOR&&(this.options.paddingColor=(C=this.options.paddingColor)!==null&&C!==void 0?C:new Zt(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new lt(1,1).divide(t);let s=0;const r=this._expecting,n=this.meshes.length,o=Object.keys(this.sets);for(let p=0;p{this._calculateMeshUVFrames(l,c,t,i,this.options.updateInputMeshes||!1)};for(let p=0;p{s++,d.update(!1);const b=C.getImageData(0,0,h,h),E=this.sets[M];if(E.getContext().putImageData(b,t.x*v.x,t.y*v.y),d.dispose(),E.update(!1),s==r){u(),e();return}},M=o[f]||"_blank";if(!_||_[M]===null)C.fillStyle="rgba(0,0,0,0)",this.options.fillBlanks&&(C.fillStyle=this.options.customFillColor),C.fillRect(0,0,h,h),y();else{const b=_[M],E=new Image;b instanceof ep?E.src=b.getContext().canvas.toDataURL("image/png"):E.src=b.url,Be.SetCorsBehavior(E.src,E),E.onload=()=>{C.fillStyle="rgba(0,0,0,0)",C.fillRect(0,0,h,h),d.update(!1),C.setTransform(1,0,0,-1,0,0);const S=[0,0,1,0,1,1,0,1,-1,1,-1,0,-1-1,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let I=0;I<9;I++)C.drawImage(E,0,0,E.width,E.height,c+l*S[I],c+l*S[I+1]-h,l,l);break;case 1:for(let I=0;I{n.dispose&&n.dispose()};for(let n=0;n{try{if(this.meshes.length===0){e();return}let i=0;const s=r=>{if(i++,this.options.map){for(let n=0;n{s(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:[]},s=Object.keys(this.sets),r=Object.keys(this.options);try{for(let l=0;l{try{this.setFragment(this._texturePath)}catch{Me.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",s=new wl;s.open("GET",i),s.addEventListener("load",()=>{if(s.status===200||s.responseText&&s.responseText.length>0)try{this._config=JSON.parse(s.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),s.addEventListener("error",()=>{t()},!1);try{s.send()}catch{Me.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 Kt.Clone(()=>{const e=this.getScene(),t=this._texture,i=new uQ(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===hr.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i},this)}}class oAe extends Te{constructor(e,t,i,s,r,n,o=!0,l=!1,c=Te.TRILINEAR_SAMPLINGMODE,h=0,u){super(null,n,!o,l),this.format=r,this._texture=n.getEngine().createRawTexture3D(e,t,i,s,r,o,l,c,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 jee extends Oa{constructor(e,t,i,s){super(e,t,i,s,!0),this.refractionPlane=new Zd(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 jee(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 lAe extends eI{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===void 0||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===void 0||t.dispose(!0),this._renderTarget=null,e||super.dispose()}}class fl extends jP{constructor(e,t,i,s,r){super(e,t,i),this._blockType=s,this._blockName=r,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof fl&&e._blockName===this._blockName?c_.Compatible:c_.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class Lhe extends os{constructor(e){super(e,Pe.Vertex),this.registerInput("matricesIndices",he.Vector4),this.registerInput("matricesWeights",he.Vector4),this.registerInput("matricesIndicesExtra",he.Vector4,!0),this.registerInput("matricesWeightsExtra",he.Vector4,!0),this.registerInput("world",he.Matrix),this.registerOutput("output",he.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(s=>s.isAttribute&&s.name==="matricesIndices"&&t(s));i||(i=new Er("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="matricesWeights"&&t(s));i||(i=new Er("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Rr.World&&t(s));i||(i=new Er("world"),i.setAsSystemValue(Rr.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){ze.BindBonesParameters(i,e)}prepareDefines(e,t,i){!i._areAttributesDirty||ze.PrepareDefinesForBones(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 s=this._outputs[0],r=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 +`,e.compilationString+=this._declareOutput(s,e)+` = ${r.associatedVariableName} * ${i}; +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(s,e)+` = ${r.associatedVariableName}; +`,e.compilationString+=`#endif +`,this}}$e("BABYLON.BonesBlock",Lhe);class Rhe extends os{constructor(e){super(e,Pe.Vertex),this.registerInput("world0",he.Vector4),this.registerInput("world1",he.Vector4),this.registerInput("world2",he.Vector4),this.registerInput("world3",he.Vector4),this.registerInput("world",he.Matrix,!0),this.registerOutput("output",he.Matrix),this.registerOutput("instanceID",he.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(s=>s.isAttribute&&s.name==="world0"&&t(s));i||(i=new Er("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world1"&&t(s));i||(i=new Er("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world2"&&t(s));i||(i=new Er("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world3"&&t(s));i||(i=new Er("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world"&&t(s));i||(i=new Er("world"),i.setAsSystemValue(Rr.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,s=!1,r){let n=!1;i.INSTANCES!==s&&(i.setValue("INSTANCES",s),n=!0),r&&i.THIN_INSTANCES!==!!r?.getRenderingMesh().hasThinInstances&&(i.setValue("THIN_INSTANCES",!!r?.getRenderingMesh().hasThinInstances),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],s=this._outputs[1],r=this.world0,n=this.world1,o=this.world2,l=this.world3;return e.compilationString+=`#ifdef INSTANCES +`,e.compilationString+=this._declareOutput(i,e)+` = mat4(${r.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}, ${l.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(s,e)+` = float(gl_InstanceID); +`:e.compilationString+=this._declareOutput(s,e)+` = 0.0; +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName}; +`,e.compilationString+=this._declareOutput(s,e)+` = 0.0; +`,e.compilationString+=`#endif +`,this}}$e("BABYLON.InstancesBlock",Rhe);class Gee extends os{constructor(e){super(e,Pe.Vertex),this.registerInput("position",he.Vector3),this.registerInput("normal",he.Vector3),this.registerInput("tangent",he.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(he.Color4|he.Vector4|he.Vector3),this.registerInput("uv",he.Vector2),this.registerOutput("positionOutput",he.Vector3),this.registerOutput("normalOutput",he.Vector3),this.registerOutput("tangentOutput",he.Vector4),this.registerOutput("uvOutput",he.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(s=>s.isAttribute&&s.name==="position"&&t(s));i||(i=new Er("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="normal"&&t(s));i||(i=new Er("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="tangent"&&t(s));i||(i=new Er("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="uv"&&t(s));i||(i=new Er("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const s=e.morphTargetManager;s?.isUsingTextureForTargets&&s.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}!i._areAttributesDirty||ze.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(ze.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,o=this.tangent,l=this.uv,c=this.positionOutput,h=this.normalOutput,u=this.tangentOutput,p=this.uvOutput,m=e,_=s.NUM_MORPH_INFLUENCERS,f=i.morphTargetManager,d=f&&f.supportsNormals&&s.NORMAL,C=f&&f.supportsTangents&&s.TANGENT,v=f&&f.supportsUVs&&s.UV1;let y="";f?.isUsingTextureForTargets&&_>0&&(y+=`float vertexID; +`);for(let M=0;M<_;M++)y+=`#ifdef MORPHTARGETS +`,f?.isUsingTextureForTargets?(y+=`vertexID = float(gl_VertexID) * morphTargetTextureInfo.x; +`,y+=`${c.associatedVariableName} += (readVector3FromRawSampler(${M}, vertexID) - ${r.associatedVariableName}) * morphTargetInfluences[${M}]; +`,y+=`vertexID += 1.0; +`):y+=`${c.associatedVariableName} += (position${M} - ${r.associatedVariableName}) * morphTargetInfluences[${M}]; +`,d&&(y+=`#ifdef MORPHTARGETS_NORMAL +`,f?.isUsingTextureForTargets?(y+=`${h.associatedVariableName} += (readVector3FromRawSampler(${M}, vertexID) - ${n.associatedVariableName}) * morphTargetInfluences[${M}]; +`,y+=`vertexID += 1.0; +`):y+=`${h.associatedVariableName} += (normal${M} - ${n.associatedVariableName}) * morphTargetInfluences[${M}]; +`,y+=`#endif +`),v&&(y+=`#ifdef MORPHTARGETS_UV +`,f?.isUsingTextureForTargets?(y+=`${p.associatedVariableName} += (readVector3FromRawSampler(${M}, vertexID).xy - ${l.associatedVariableName}) * morphTargetInfluences[${M}]; +`,y+=`vertexID += 1.0; +`):y+=`${p.associatedVariableName}.xy += (uv_${M} - ${l.associatedVariableName}.xy) * morphTargetInfluences[${M}]; +`,y+=`#endif +`),C&&(y+=`#ifdef MORPHTARGETS_TANGENT +`,f?.isUsingTextureForTargets?y+=`${u.associatedVariableName}.xyz += (readVector3FromRawSampler(${M}, vertexID) - ${o.associatedVariableName}.xyz) * morphTargetInfluences[${M}]; +`:y+=`${u.associatedVariableName}.xyz += (tangent${M} - ${o.associatedVariableName}.xyz) * morphTargetInfluences[${M}]; +`,o.type===he.Vector4?y+=`${u.associatedVariableName}.w = ${o.associatedVariableName}.w; +`:y+=`${u.associatedVariableName}.w = 1.; +`,y+=`#endif +`),y+=`#endif +`;if(m.compilationString=m.compilationString.replace(this._repeatableContentAnchor,y),_>0)for(let M=0;M<_;M++)m.attributes.push(se.PositionKind+M),d&&m.attributes.push(se.NormalKind+M),C&&m.attributes.push(se.TangentKind+M),v&&m.attributes.push(se.UVKind+"_"+M)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);const t=this.position,i=this.normal,s=this.tangent,r=this.uv,n=this.positionOutput,o=this.normalOutput,l=this.tangentOutput,c=this.uvOutput,h=`//${this.name}`;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",h),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",h,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=`${this._declareOutput(n,e)} = ${t.associatedVariableName}; +`,e.compilationString+=`#ifdef NORMAL +`,e.compilationString+=`${this._declareOutput(o,e)} = ${i.associatedVariableName}; +`,e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(o,e)} = vec3(0., 0., 0.); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef TANGENT +`,e.compilationString+=`${this._declareOutput(l,e)} = ${s.associatedVariableName}; +`,e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(l,e)} = vec4(0., 0., 0., 0.); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef UV1 +`,e.compilationString+=`${this._declareOutput(c,e)} = ${r.associatedVariableName}; +`,e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(c,e)} = vec2(0., 0.); +`,e.compilationString+=`#endif +`,this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this}}$e("BABYLON.MorphTargetsBlock",Gee);class Phe extends os{constructor(e){super(e,Pe.Vertex),this.registerInput("worldPosition",he.Vector4,!1,Pe.Vertex),this.registerOutput("direction",he.Vector3),this.registerOutput("color",he.Color3),this.registerOutput("intensity",he.Float),this.registerOutput("shadowBias",he.Float),this.registerOutput("shadowNormalBias",he.Float),this.registerOutput("shadowDepthScale",he.Float),this.registerOutput("shadowDepthRange",he.Vector2)}getClassName(){return"LightInformationBlock"}get worldPosition(){return this._inputs[0]}get direction(){return this._outputs[0]}get color(){return this._outputs[1]}get intensity(){return this._outputs[2]}get shadowBias(){return this._outputs[3]}get shadowNormalBias(){return this._outputs[4]}get shadowDepthScale(){return this._outputs[5]}get shadowDepthRange(){return this._outputs[6]}bind(e,t,i){if(!i)return;this.light&&this.light.isDisposed()&&(this.light=null);let s=this.light;const r=t.getScene();if(!s&&r.lights.length&&(s=this.light=r.lights[0],this._forcePrepareDefines=!0),!s||!s.isEnabled){e.setFloat3(this._lightDataUniformName,0,0,0),e.setFloat4(this._lightColorUniformName,0,0,0,0);return}s.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,s.diffuse,s.intensity);const n=s.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(n?e.setFloat3(this._lightShadowUniformName,n.bias,n.normalBias,n.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange)if(n&&r.activeCamera){const o=s;e.setFloat2(this._lightShadowExtraUniformName,o.getDepthMinZ(r.activeCamera),o.getDepthMinZ(r.activeCamera)+o.getDepthMaxZ(r.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}prepareDefines(e,t,i){if(!i._areLightsDirty&&!this._forcePrepareDefines)return;this._forcePrepareDefines=!1;const s=this.light;i.setValue(this._lightTypeDefineName,!!(s&&s instanceof cD),!0)}_buildBlock(e){super._buildBlock(e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=this.direction,i=this.color,s=this.intensity,r=this.shadowBias,n=this.shadowNormalBias,o=this.shadowDepthScale,l=this.shadowDepthRange;return this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightShadowUniformName=e._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=e._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE"),e._emitUniformFromString(this._lightDataUniformName,"vec3"),e._emitUniformFromString(this._lightColorUniformName,"vec4"),e.compilationString+=`#ifdef ${this._lightTypeDefineName} +`,e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName}); +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(t,e)+` = ${this._lightDataUniformName}; +`,e.compilationString+=`#endif +`,e.compilationString+=this._declareOutput(i,e)+` = ${this._lightColorUniformName}.rgb; +`,e.compilationString+=this._declareOutput(s,e)+` = ${this._lightColorUniformName}.a; +`,(r.hasEndpoints||n.hasEndpoints||o.hasEndpoints)&&(e._emitUniformFromString(this._lightShadowUniformName,"vec3"),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${this._lightShadowUniformName}.x; +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${this._lightShadowUniformName}.y; +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${this._lightShadowUniformName}.z; +`)),l.hasEndpoints&&(e._emitUniformFromString(this._lightShadowExtraUniformName,"vec2"),e.compilationString+=this._declareOutput(l,e)+` = ${this._lightShadowUniformName}; +`),this}serialize(){const e=super.serialize();return 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))}}$e("BABYLON.LightInformationBlock",Phe);class Wee extends os{constructor(e){super(e,Pe.Fragment),this.convertInputToLinearSpace=!0,this.registerInput("color",he.AutoDetect),this.registerOutput("output",he.Color4),this.registerOutput("rgb",he.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(he.Color3|he.Color4|he.Vector3|he.Vector4)}getClassName(){return"ImageProcessingBlock"}get color(){return this._inputs[0]}get output(){return this._outputs[0]}get rgb(){return this._outputs[1]}initialize(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")}isReady(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){!i||!t.imageProcessingConfiguration||t.imageProcessingConfiguration.bind(e)}_buildBlock(e){var t;super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),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");const i=this.color,s=this._outputs[0],r=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",r),e._emitFunctionFromInclude("imageProcessingDeclaration",r),e._emitFunctionFromInclude("imageProcessingFunctions",r),!((t=i.connectedPoint)===null||t===void 0)&&t.isConnected&&(i.connectedPoint.type===he.Color4||i.connectedPoint.type===he.Vector4?e.compilationString+=`${this._declareOutput(s,e)} = ${i.associatedVariableName}; +`:e.compilationString+=`${this._declareOutput(s,e)} = vec4(${i.associatedVariableName}, 1.0); +`,e.compilationString+=`#ifdef IMAGEPROCESSINGPOSTPROCESS +`,this.convertInputToLinearSpace&&(e.compilationString+=`${s.associatedVariableName}.rgb = toLinearSpace(${i.associatedVariableName}.rgb); +`),e.compilationString+=`#else +`,e.compilationString+=`#ifdef IMAGEPROCESSING +`,this.convertInputToLinearSpace&&(e.compilationString+=`${s.associatedVariableName}.rgb = toLinearSpace(${i.associatedVariableName}.rgb); +`),e.compilationString+=`${s.associatedVariableName} = applyImageProcessing(${s.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#endif +`,this.rgb.hasEndpoints&&(e.compilationString+=this._declareOutput(this.rgb,e)+` = ${this.output.associatedVariableName}.xyz; +`)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace}; +`,e}serialize(){const e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){var s;super._deserialize(e,t,i),this.convertInputToLinearSpace=(s=e.convertInputToLinearSpace)!==null&&s!==void 0?s:!0}}z([ws("Convert input to linear space",Ms.Boolean,"ADVANCED")],Wee.prototype,"convertInputToLinearSpace",void 0);$e("BABYLON.ImageProcessingBlock",Wee);class uD extends os{constructor(e){super(e,Pe.Fragment,!0),this.registerInput("normal",he.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(he.Color4|he.Vector4|he.Vector3),this.registerInput("tangent",he.Vector4,!1),this.registerInput("world",he.Matrix,!1),this.registerOutput("TBN",he.Object,Pe.Fragment,new fl("TBN",this,xo.Output,uD,"TBNBlock")),this.registerOutput("row0",he.Vector3,Pe.Fragment),this.registerOutput("row1",he.Vector3,Pe.Fragment),this.registerOutput("row2",he.Vector3,Pe.Fragment)}getClassName(){return"TBNBlock"}initialize(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")}get normal(){return this._inputs[0]}get tangent(){return this._inputs[1]}get world(){return this._inputs[2]}get TBN(){return this._outputs[0]}get row0(){return this._outputs[1]}get row1(){return this._outputs[2]}get row2(){return this._outputs[3]}get target(){return Pe.Fragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.isSystemValue&&s.systemValue===Rr.World&&t(s));i||(i=new Er("world"),i.setAsSystemValue(Rr.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="normal"&&t(s));i||(i=new Er("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="tangent"&&s.type===he.Vector4&&t(s));i||(i=new Er("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var s,r,n,o;const l=this.normal,c=this.tangent;let h=l.isConnected;((s=l.connectInputBlock)===null||s===void 0?void 0:s.isAttribute)&&!e.isVerticesDataPresent((r=l.connectInputBlock)===null||r===void 0?void 0:r.name)&&(h=!1);let u=c.isConnected;((n=c.connectInputBlock)===null||n===void 0?void 0:n.isAttribute)&&!e.isVerticesDataPresent((o=c.connectInputBlock)===null||o===void 0?void 0:o.name)&&(u=!1);const p=h&&u;i.setValue("TBNBLOCK",p,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,o=this.row1,l=this.row2;return e.target===Pe.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 ${r.associatedVariableName} = mat3(${s.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); + `,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${r.associatedVariableName}[0][0], ${r.associatedVariableName}[0][1], ${r.associatedVariableName}[0][2]); +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${r.associatedVariableName}[1[0], ${r.associatedVariableName}[1][1], ${r.associatedVariableName}[1][2]); +`),l.hasEndpoints&&(e.compilationString+=this._declareOutput(l,e)+` = vec3(${r.associatedVariableName}[2][0], ${r.associatedVariableName}[2][1], ${r.associatedVariableName}[2][2]); +`),e.sharedData.blocksWithDefines.push(this)),this}}$e("BABYLON.TBNBlock",uD);class DF extends os{constructor(e){super(e,Pe.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",he.Vector4,!1),this.registerInput("worldNormal",he.Vector4,!1),this.registerInput("worldTangent",he.Vector4,!0),this.registerInput("uv",he.Vector2,!1),this.registerInput("normalMapColor",he.Color3,!1),this.registerInput("strength",he.Float,!1),this.registerInput("viewDirection",he.Vector3,!0),this.registerInput("parallaxScale",he.Float,!0),this.registerInput("parallaxHeight",he.Float,!0),this.registerInput("TBN",he.Object,!0,Pe.VertexAndFragment,new fl("TBN",this,xo.Input,uD,"TBNBlock")),this.registerInput("world",he.Matrix,!0),this.registerOutput("output",he.Vector4),this.registerOutput("uvOffset",he.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 s=this.normalMapColor.connectedPoint._ownerBlock.samplerName,r=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&s||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",r,!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(s=>s.isAttribute&&s.name==="uv"&&t(s));i||(i=new Er("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const i=new Er("strength");i.value=1,i.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,s=this.worldPosition,r=this.worldNormal,n=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 l=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&o||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),c=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:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},p={search:/varying mat3 vTBN;/g,replace:""},m={search:/uniform mat4 normalMatrix;/g,replace:""},_=this.TBN;_.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${_.associatedVariableName}; + #endif + `:n.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${r.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnTangent = normalize(${n.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,p,m]}),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 f=!l||!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:`${f}`},{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, ${f}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${l&&this.useParallaxOcclusion?o:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${l?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:c},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:s.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:r.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:l?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}}z([ws("Invert X axis",Ms.Boolean,"PROPERTIES",{notifiers:{update:!1}})],DF.prototype,"invertX",void 0);z([ws("Invert Y axis",Ms.Boolean,"PROPERTIES",{notifiers:{update:!1}})],DF.prototype,"invertY",void 0);z([ws("Use parallax occlusion",Ms.Boolean)],DF.prototype,"useParallaxOcclusion",void 0);z([ws("Object Space Mode",Ms.Boolean,"PROPERTIES",{notifiers:{update:!1}})],DF.prototype,"useObjectSpaceNormalMap",void 0);$e("BABYLON.PerturbNormalBlock",DF);class Dhe extends os{constructor(e){super(e,Pe.Fragment,!0),this.registerInput("value",he.Float,!0),this.registerInput("cutoff",he.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}}$e("BABYLON.DiscardBlock",Dhe);class Ohe extends os{constructor(e){super(e,Pe.Fragment),this.registerOutput("output",he.Float,Pe.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===Pe.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}}$e("BABYLON.FrontFacingBlock",Ohe);class whe extends os{constructor(e){super(e,Pe.Fragment),this.registerInput("input",he.AutoDetect,!1),this.registerOutput("dx",he.BasedOnInput),this.registerOutput("dy",he.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}}$e("BABYLON.DerivativeBlock",whe);class Nhe extends os{constructor(e){super(e,Pe.Fragment),this.registerOutput("xy",he.Vector2,Pe.Fragment),this.registerOutput("xyz",he.Vector3,Pe.Fragment),this.registerOutput("xyzw",he.Vector4,Pe.Fragment),this.registerOutput("x",he.Float,Pe.Fragment),this.registerOutput("y",he.Float,Pe.Fragment),this.registerOutput("z",he.Float,Pe.Fragment),this.registerOutput("w",he.Float,Pe.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===Pe.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}$e("BABYLON.FragCoordBlock",Nhe);class Bhe extends os{constructor(e){super(e,Pe.Fragment),this.registerOutput("xy",he.Vector2,Pe.Fragment),this.registerOutput("x",he.Float,Pe.Fragment),this.registerOutput("y",he.Float,Pe.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 s of this._outputs)s.hasEndpoints&&(i+=`${this._declareOutput(s,e)} = ${t}.${s.name}; +`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===Pe.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}}$e("BABYLON.ScreenSizeBlock",Bhe);class Fhe extends os{constructor(e){super(e,Pe.Fragment),this.registerInput("vector",he.AutoDetect),this.registerInput("worldViewProjection",he.Matrix),this.registerOutput("output",he.Vector2),this.registerOutput("x",he.Float),this.registerOutput("y",he.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(he.Color3|he.Vector3|he.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(s=>s.systemValue===Rr.WorldViewProjection&&t(s));i||(i=new Er("worldViewProjection"),i.setAsSystemValue(Rr.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const s=i.associatedVariableName,r=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case he.Vector3:e.compilationString+=`vec4 ${r} = ${s} * vec4(${t.associatedVariableName}, 1.0); +`;break;case he.Vector4:e.compilationString+=`vec4 ${r} = ${s} * ${t.associatedVariableName}; +`;break}return e.compilationString+=`${r}.xy /= ${r}.w;`,e.compilationString+=`${r}.xy = ${r}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${r}.xy; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${r}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${r}.y; +`),this}}$e("BABYLON.ScreenSpaceBlock",Fhe);class Vhe extends os{constructor(e){super(e,Pe.Fragment),this.registerInput("input",he.Vector2),this.registerInput("strength",he.Float),this.registerInput("center",he.Vector2),this.registerInput("offset",he.Vector2),this.registerOutput("output",he.Vector2),this.registerOutput("x",he.Float),this.registerOutput("y",he.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 Er("center");e.value=new lt(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Er("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Er("offset");e.value=new lt(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),s=e._getFreeVariableName("x"),r=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` + vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; + float ${i} = ${this.strength.associatedVariableName} * length(${t}); + float ${s} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; + float ${r} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; + vec2 ${n} = vec2(${s} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${r} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); + `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${n}; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${n}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${n}.y; +`),this}}$e("BABYLON.TwirlBlock",Vhe);class IW extends os{constructor(e){super(e,Pe.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",he.Float),this.registerInput("worldPosition",he.Vector3),this.registerInput("worldNormal",he.Vector3),this.registerInput("worldTangent",he.AutoDetect,!0),this.registerOutput("output",he.Vector4),this.registerOutput("xyz",he.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(he.Color3|he.Vector3|he.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&&console.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); + `,s=this.generateInWorldSpace?"":` + result = TBN * result; + result = result * vec3(0.5) + vec3(0.5); + `,r=` + vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { + ${i} + ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""} + ${this.automaticNormalizationNormal?"normal = normalize(normal);":""} + 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); + ${s} + return vec4(result, 0.); + }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",r,"// 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}}z([ws("Generate in world space instead of tangent space",Ms.Boolean,"PROPERTIES",{notifiers:{update:!0}})],IW.prototype,"generateInWorldSpace",void 0);z([ws("Force normalization for the worldNormal input",Ms.Boolean,"PROPERTIES",{notifiers:{update:!0}})],IW.prototype,"automaticNormalizationNormal",void 0);z([ws("Force normalization for the worldTangent input",Ms.Boolean,"PROPERTIES",{notifiers:{update:!0}})],IW.prototype,"automaticNormalizationTangent",void 0);$e("BABYLON.HeightToNormalBlock",IW);class zhe extends os{constructor(e){super(e,Pe.Fragment,!0),this.registerInput("depth",he.Float,!0),this.registerInput("worldPos",he.Vector4,!0),this.registerInput("viewProjection",he.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; + + `:console.warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}$e("BABYLON.FragDepthBlock",zhe);class Uhe extends os{constructor(e){super(e,Pe.Fragment),this.registerInput("worldPosition",he.Vector4,!1),this.registerInput("viewProjection",he.Matrix,!1),this.registerInput("worldNormal",he.AutoDetect,!0),this.registerOutput("depth",he.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(he.Color3|he.Vector3|he.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}}$e("BABYLON.ShadowMapBlock",Uhe);class khe extends os{constructor(e){super(e,Pe.Fragment,!0),this.registerInput("viewDepth",he.Float,!0),this.registerInput("worldPosition",he.AutoDetect,!0),this.registerInput("viewNormal",he.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(he.Vector3|he.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(he.Vector3|he.Vector4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,s=this.viewDepth;e.sharedData.blocksWithDefines.push(this);const r=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",r),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`#ifdef PREPASS_DEPTH\r +`,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${s.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===he.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===he.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+=`#endif\r +`,this}}$e("BABYLON.PrePassOutputBlock",khe);class Hhe extends os{constructor(e){super(e,Pe.VertexAndFragment,!1),this.registerInput("worldPosition",he.Vector4,!1,Pe.Vertex),this.registerInput("view",he.Matrix,!1,Pe.Vertex),this.registerInput("input",he.AutoDetect,!1,Pe.Fragment),this.registerInput("fogColor",he.AutoDetect,!1,Pe.Fragment),this.registerOutput("output",he.Color3,Pe.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(he.Color3|he.Vector3|he.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(he.Color3|he.Vector3|he.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(s=>s.systemValue===Rr.View&&t(s));i||(i=new Er("view"),i.setAsSystemValue(Rr.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Rr.FogColor&&t(s));i||(i=new Er("fogColor",void 0,he.Color3),i.setAsSystemValue(Rr.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&ze.GetFogState(e,s))}bind(e,t,i){if(!i)return;const s=i.getScene();e.setFloat4(this._fogParameters,s.fogMode,s.fogStart,s.fogEnd,s.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===Pe.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,s=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const r=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(r,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${s.associatedVariableName}.rgb; +`,e.compilationString+=`#else +${this._declareOutput(r,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}}$e("BABYLON.FogBlock",Hhe);class MX extends os{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Pe.Fragment:Pe.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Pe.Fragment:Pe.Vertex}constructor(e){super(e,Pe.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",he.Vector4,!1,Pe.Vertex),this.registerInput("worldNormal",he.Vector4,!1,Pe.Fragment),this.registerInput("cameraPosition",he.Vector3,!1,Pe.Fragment),this.registerInput("glossiness",he.Float,!0,Pe.Fragment),this.registerInput("glossPower",he.Float,!0,Pe.Fragment),this.registerInput("diffuseColor",he.Color3,!0,Pe.Fragment),this.registerInput("specularColor",he.Color3,!0,Pe.Fragment),this.registerInput("view",he.Matrix,!0),this.registerOutput("diffuseOutput",he.Color3,Pe.Fragment),this.registerOutput("specularOutput",he.Color3,Pe.Fragment),this.registerOutput("shadow",he.Float,Pe.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(s=>s.systemValue===Rr.CameraPosition&&t(s));i||(i=new Er("cameraPosition"),i.setAsSystemValue(Rr.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(!this.light)ze.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights);else{const r={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};ze.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,r),r.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;ze.PrepareUniformsAndSamplersForLight(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,n)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?ze.BindLight(this.light,this._lightId,s,e,!0):ze.BindLights(s,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 s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,"vec4")&&(e.compilationString+=`${s} = ${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!==Pe.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 s=i.associatedVariableName;this.generateOnlyFragmentCode?(s=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${s}; +`,t),e.compilationString+=`${s} = ${i.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):s="v_"+s+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:s}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:s}]}),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} - ${s}); +`),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()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights"}),this._lightId===0&&(e.compilationString+=`aggShadow = aggShadow / numLights; +`);const r=this.diffuseOutput,n=this.specularOutput;return e.compilationString+=this._declareOutput(r,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; +`,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,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()}}z([ws("Generate only fragment code",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:MX._OnGenerateOnlyFragmentCodeChanged}})],MX.prototype,"generateOnlyFragmentCode",void 0);$e("BABYLON.LightBlock",MX);class aC extends os{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e?.getScene())!==null&&t!==void 0?t:Ii.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}get samplerName(){return this._samplerName}constructor(e){super(e,Pe.VertexAndFragment),this.registerOutput("source",he.Object,Pe.VertexAndFragment,new fl("source",this,xo.Output,aC,"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===Pe.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&&!Pl.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=Te.Parse(e.texture,t,i))}}$e("BABYLON.ImageSourceBlock",aC);class Qj extends os{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)===null||e===void 0?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e?.getScene())!==null&&t!==void 0?t:Ii.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}static _IsPrePassTextureBlock(e){return e?.getClassName()==="PrePassTextureBlock"}get _isSourcePrePass(){return Qj._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!Qj._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){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:Ii.LastCreatedScene;i?.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:Ii.LastCreatedScene;i?.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?Pe.Fragment:Pe.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",he.AutoDetect,!1,Pe.VertexAndFragment),this.registerInput("source",he.Object,!0,Pe.VertexAndFragment,new fl("source",this,xo.Input,aC,"ImageSourceBlock")),this.registerInput("layer",he.Float,!0),this.registerInput("lod",he.Float,!0),this.registerOutput("rgba",he.Color4,Pe.Neutral),this.registerOutput("rgb",he.Color3,Pe.Neutral),this.registerOutput("r",he.Float,Pe.Neutral),this.registerOutput("g",he.Float,Pe.Neutral),this.registerOutput("b",he.Float,Pe.Neutral),this.registerOutput("a",he.Float,Pe.Neutral),this.registerOutput("level",he.Float,Pe.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(he.Vector2|he.Vector3|he.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 Pe.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return Pe.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===Pe.Fragment)return Pe.Fragment;if(e.target===Pe.Vertex)return Pe.VertexAndFragment;if(e.target===Pe.Neutral||e.target===Pe.VertexAndFragment){const t=e.ownerBlock;if(t.target===Pe.Fragment)return Pe.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return Pe.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected)if(e.mode===Gf.PostProcess){const i=e.getBlockByPredicate(s=>s.name==="uv"&&t(s));i&&i.connectTo(this)}else{const i=e.mode===Gf.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name===i&&t(r));s||(s=new Er("uv"),s.setAsAttribute(i)),s.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 s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!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!==Pe.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 t,i,s;let r=e;if((s=(i=(t=this._texture)===null||t===void 0?void 0:t._texture)===null||i===void 0?void 0:i.is2DArray)!==null&&s!==void 0?s:!1){const o=this.layer.isConnected?this.layer.associatedVariableName:"0";r=`vec3(${e}, ${o})`}return r}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===Pe.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===Pe.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,s=!1){if(s){if(e.target===Pe.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===Pe.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r}; +`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,s,r;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===Pe.Vertex||this._fragmentOnly||e.target===Pe.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===Pe.Fragment||this._isMixed&&e.target===Pe.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),!((i=(t=this._texture)===null||t===void 0?void 0:t._texture)===null||i===void 0)&&i.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!==Pe.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(o=>o.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&(!((r=(s=this._texture)===null||s===void 0?void 0:s._texture)===null||r===void 0)&&r.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),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&&!Pl.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=Te.Parse(e.texture,t,i))}}$e("BABYLON.TextureBlock",Qj);class Zj extends os{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e?.getScene())!==null&&t!==void 0?t:Ii.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Pe.Fragment:Pe.VertexAndFragment)}constructor(e){super(e,Pe.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="position"&&t(s));i||(i=new Er("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Rr.World&&t(s));i||(i=new Er("world"),i.setAsSystemValue(Rr.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Rr.View&&t(s));i||(i=new Er("view"),i.setAsSystemValue(Rr.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this._getTexture();!s||!s.getTextureMatrix||(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLocalCubicName,!!s.boundingBoxSize,!0),i.setValue(this._defineExplicitName,s.coordinatesMode===0,!0),i.setValue(this._defineSkyboxName,s.coordinatesMode===5,!0),i.setValue(this._defineCubicName,s.coordinatesMode===3||s.coordinatesMode===6,!0),i.setValue("INVERTCUBICMAP",s.coordinatesMode===6,!0),i.setValue(this._defineSphericalName,s.coordinatesMode===1,!0),i.setValue(this._definePlanarName,s.coordinatesMode===2,!0),i.setValue(this._defineProjectionName,s.coordinatesMode===4,!0),i.setValue(this._defineEquirectangularName,s.coordinatesMode===7,!0),i.setValue(this._defineEquirectangularFixedName,s.coordinatesMode===8,!0),i.setValue(this._defineMirroredEquirectangularFixedName,s.coordinatesMode===9,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){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 r=s;e.setVector3(this._reflectionPositionName,r.boundingBoxPosition),e.setVector3(this._reflectionSizeName,r.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===Pe.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._emitFunction("ReciprocalPI","#define RECIPROCAL_PI2 0.15915494",""),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,s=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const r=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,l=`${this.cameraPosition.associatedVariableName}`,c=`${this.view.associatedVariableName}`;e+=".xyz";let h=` + #ifdef ${this._defineMirroredEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n}); + #endif + + #ifdef ${this._defineEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n}); + #endif + + #ifdef ${this._defineEquirectangularName} + vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${l}.xyz, ${r}); + #endif + + #ifdef ${this._defineSphericalName} + vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${c}, ${r}); + #endif + + #ifdef ${this._definePlanarName} + vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${l}.xyz, ${r}); + #endif + + #ifdef ${this._defineCubicName} + #ifdef ${this._defineLocalCubicName} + vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${l}.xyz, ${r}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); + #else + vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${l}.xyz, ${r}); + #endif + #endif + + #ifdef ${this._defineProjectionName} + vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${c}, ${r}); + #endif + + #ifdef ${this._defineSkyboxName} + vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${r}); + #endif + + #ifdef ${this._defineExplicitName} + vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); + #endif +`;return s||(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 s=`${"vec"+(t.length===0?"4":t.length-1)} ${this._reflectionColorName}; + #ifdef ${this._define3DName} +`;return e?s+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t}; +`:s+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t}; +`,s+=` + #else +`,e?s+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t}; +`:s+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t}; +`,s+=`#endif +`,s}writeOutputs(e,t){let i="";if(e.target===Pe.Fragment)for(const s of this._outputs)s.hasEndpoints&&(i+=`${this._declareOutput(s,e)} = ${t}.${s.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&&!Pl.IgnoreTexturesAtLoadTime&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=Ic.Parse(e.texture,t,i):this.texture=Te.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}z([ws("Generate only fragment code",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Zj._OnGenerateOnlyFragmentCodeChanged}})],Zj.prototype,"generateOnlyFragmentCode",void 0);$e("BABYLON.ReflectionTextureBaseBlock",Zj);class jhe extends Zj{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.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?Pe.Fragment:Pe.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Pe.Fragment:Pe.Vertex}constructor(e){super(e),this.registerInput("position",he.AutoDetect,!1,Pe.Vertex),this.registerInput("worldPosition",he.Vector4,!1,Pe.Vertex),this.registerInput("worldNormal",he.Vector4,!1,Pe.Fragment),this.registerInput("world",he.Matrix,!1,Pe.Vertex),this.registerInput("cameraPosition",he.Vector3,!1,Pe.Fragment),this.registerInput("view",he.Matrix,!1,Pe.Fragment),this.registerOutput("rgb",he.Color3,Pe.Fragment),this.registerOutput("rgba",he.Color4,Pe.Fragment),this.registerOutput("r",he.Float,Pe.Fragment),this.registerOutput("g",he.Float,Pe.Fragment),this.registerOutput("b",he.Float,Pe.Fragment),this.registerOutput("a",he.Float,Pe.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(he.Color3|he.Vector3|he.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(s=>s.systemValue===Rr.CameraPosition&&t(s));i||(i=new Er("cameraPosition"),i.setAsSystemValue(Rr.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!==Pe.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}}$e("BABYLON.ReflectionTextureBlock",jhe);class LW extends os{constructor(e){super(e,Pe.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",he.AutoDetect,!1,Pe.VertexAndFragment),this.registerOutput("depth",he.Float,Pe.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(he.Vector2|he.Vector3|he.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?Pe.VertexAndFragment:Pe.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===he.Vector3?"3":t.type===he.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===Pe.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}if(this.uv.ownerBlock.target===Pe.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,s=!1){if(s){if(e.target===Pe.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===Pe.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!==Pe.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}}z([ws("Use non linear depth",Ms.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(a,e)=>{const t=e;let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),a&&a.disableDepthRenderer(),i}}})],LW.prototype,"useNonLinearDepth",void 0);z([ws("Store Camera space Z",Ms.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(a,e)=>{const t=e;let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),a&&a.disableDepthRenderer(),i}}})],LW.prototype,"storeCameraSpaceZ",void 0);z([ws("Force 32 bits float",Ms.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:a=>a?.disableDepthRenderer()}})],LW.prototype,"force32itsFloat",void 0);$e("BABYLON.SceneDepthBlock",LW);class Ghe extends os{constructor(e){super(e,Pe.VertexAndFragment,!0),this.registerInput("worldPosition",he.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 Pe.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var s,r,n,o,l,c;const h=e.getScene(),u=!!((s=t.clipPlane)!==null&&s!==void 0?s:h.clipPlane),p=!!((r=t.clipPlane2)!==null&&r!==void 0?r:h.clipPlane2),m=!!((n=t.clipPlane3)!==null&&n!==void 0?n:h.clipPlane3),_=!!((o=t.clipPlane4)!==null&&o!==void 0?o:h.clipPlane4),f=!!((l=t.clipPlane5)!==null&&l!==void 0?l:h.clipPlane5),d=!!((c=t.clipPlane6)!==null&&c!==void 0?c:h.clipPlane6);i.setValue("CLIPPLANE",u,!0),i.setValue("CLIPPLANE2",p,!0),i.setValue("CLIPPLANE3",m,!0),i.setValue("CLIPPLANE4",_,!0),i.setValue("CLIPPLANE5",f,!0),i.setValue("CLIPPLANE6",d,!0)}bind(e,t,i){if(!i)return;const s=i.getScene();wc(e,t,s)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==Pe.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}}$e("BABYLON.ClipPlanesBlock",Ghe);class Whe extends os{get texture(){return null}set texture(e){}constructor(e,t=Pe.VertexAndFragment){super(e,t,!1),this.registerOutput("position",he.Object,Pe.VertexAndFragment,new fl("position",this,xo.Output,aC,"ImageSourceBlock")),this.registerOutput("depth",he.Object,Pe.VertexAndFragment,new fl("depth",this,xo.Output,aC,"ImageSourceBlock")),this.registerOutput("normal",he.Object,Pe.VertexAndFragment,new fl("normal",this,xo.Output,aC,"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!==Pe.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 s=t.getScene().enablePrePassRenderer();if(!s)return;const r=s.defaultRT;!r.textures||(this.position.isConnected&&e.setTexture(this._positionSamplerName,r.textures[s.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,r.textures[s.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,r.textures[s.getIndex(6)]))}}$e("BABYLON.PrePassTextureBlock",Whe);class Yhe extends os{get endpoints(){return this._endpoints}constructor(e){super(e,Pe.Neutral),this._endpoints=[],this.registerInput("input",he.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 s of this.endpoints)t.indexOf(s)===-1&&(i+=s._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=[]}}$e("BABYLON.NodeMaterialTeleportInBlock",Yhe);class Xhe extends os{constructor(e){super(e,Pe.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",he.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)===0&&(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 e,t;const i=super.serialize();return i.entryPoint=(t=(e=this.entryPoint)===null||e===void 0?void 0:e.uniqueId)!==null&&t!==void 0?t:"",i}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}$e("BABYLON.NodeMaterialTeleportOutBlock",Xhe);class Khe extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("left",he.AutoDetect),this.registerInput("right",he.AutoDetect),this.registerOutput("output",he.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(he.Float),this._inputs[1].acceptedConnectionPointTypes.push(he.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}}$e("BABYLON.AddBlock",Khe);class Qhe extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("input",he.AutoDetect),this.registerInput("factor",he.Float),this.registerOutput("output",he.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}}$e("BABYLON.ScaleBlock",Qhe);class dQ extends os{constructor(e){super(e,Pe.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",he.AutoDetect),this.registerOutput("output",he.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}}z([ws("Minimum",Ms.Float)],dQ.prototype,"minimum",void 0);z([ws("Maximum",Ms.Float)],dQ.prototype,"maximum",void 0);$e("BABYLON.ClampBlock",dQ);class Zhe extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("left",he.AutoDetect),this.registerInput("right",he.AutoDetect),this.registerOutput("output",he.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(he.Float),this._inputs[0].excludedConnectionPointTypes.push(he.Matrix),this._inputs[0].excludedConnectionPointTypes.push(he.Vector2),this._inputs[1].excludedConnectionPointTypes.push(he.Float),this._inputs[1].excludedConnectionPointTypes.push(he.Matrix),this._inputs[1].excludedConnectionPointTypes.push(he.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}}$e("BABYLON.CrossBlock",Zhe);class qhe extends os{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(r=>{const n=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),o=e._getGLType(r.type);t=t.replace(n,o),i=i.replace(n,o)}),this._outputs.forEach(r=>{const n=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),o=e._getGLType(r.type);t=t.replace(n,o),i=i.replace(n,o)}),e._emitFunction(i,t,""),this._outputs.forEach(r=>{e.compilationString+=this._declareOutput(r,e)+`; +`}),e.compilationString+=i+"(";let s=!1;return this._inputs.forEach((r,n)=>{var o,l,c;n>0&&(e.compilationString+=", "),this._inputSamplers&&this._inputSamplers.indexOf(r.name)!==-1?e.compilationString+=(c=(l=(o=r.connectedPoint)===null||o===void 0?void 0:o.ownerBlock)===null||l===void 0?void 0:l.samplerName)!==null&&c!==void 0?c:r.associatedVariableName:e.compilationString+=r.associatedVariableName,s=!0}),this._outputs.forEach((r,n)=>{(n>0||s)&&(e.compilationString+=", "),e.compilationString+=r.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,s;this._options=e,this._code=e.code.join(` +`)+` +`,this.name=this.name||e.name,this.target=Pe[e.target],(t=e.inParameters)===null||t===void 0||t.forEach((r,n)=>{const o=he[r.type];r.type==="sampler2D"||r.type==="samplerCube"?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(r.name),this.registerInput(r.name,he.Object,!0,Pe.VertexAndFragment,new fl(r.name,this,xo.Input,aC,"ImageSourceBlock"))):this.registerInput(r.name,o),Object.defineProperty(this,r.name,{get:function(){return this._inputs[n]},enumerable:!0,configurable:!0})}),(i=e.outParameters)===null||i===void 0||i.forEach((r,n)=>{this.registerOutput(r.name,he[r.type]),Object.defineProperty(this,r.name,{get:function(){return this._outputs[n]},enumerable:!0,configurable:!0}),r.type==="BasedOnInput"&&(this._outputs[n]._typeConnectionSource=this._findInputByName(r.typeFromInput)[0])}),(s=e.inLinkedConnectionTypes)===null||s===void 0||s.forEach(r=>{this._linkConnectionTypes(this._findInputByName(r.input1)[1],this._findInputByName(r.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Rr.CameraPosition&&t(s));i||(i=new Er("cameraPosition"),i.setAsSystemValue(Rr.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}}$e("BABYLON.ViewDirectionBlock",Xee);class aue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("worldNormal",he.Vector4),this.registerInput("viewDirection",he.Vector3),this.registerInput("bias",he.Float),this.registerInput("power",he.Float),this.registerOutput("fresnel",he.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 Xee("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const t=new Er("bias");t.value=0,t.output.connectTo(this.bias)}if(!this.power.isConnected){const t=new Er("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}}$e("BABYLON.FresnelBlock",aue);class oue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("left",he.AutoDetect),this.registerInput("right",he.AutoDetect),this.registerOutput("output",he.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}}$e("BABYLON.MaxBlock",oue);class lue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("left",he.AutoDetect),this.registerInput("right",he.AutoDetect),this.registerOutput("output",he.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}}$e("BABYLON.MinBlock",lue);class cue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("left",he.AutoDetect),this.registerInput("right",he.AutoDetect),this.registerOutput("output",he.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(he.Float),this._inputs[0].excludedConnectionPointTypes.push(he.Matrix),this._inputs[1].excludedConnectionPointTypes.push(he.Float),this._inputs[1].excludedConnectionPointTypes.push(he.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}}$e("BABYLON.DistanceBlock",cue);class hue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("value",he.AutoDetect),this.registerOutput("output",he.Float),this._inputs[0].excludedConnectionPointTypes.push(he.Float),this._inputs[0].excludedConnectionPointTypes.push(he.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}}$e("BABYLON.LengthBlock",hue);class uue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("value",he.AutoDetect),this.registerOutput("output",he.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}}$e("BABYLON.NegateBlock",uue);class due extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("value",he.AutoDetect),this.registerInput("power",he.AutoDetect),this.registerOutput("output",he.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}}$e("BABYLON.PowBlock",due);class fue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("seed",he.AutoDetect),this.registerOutput("output",he.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(he.Vector2|he.Vector3|he.Vector4|he.Color3|he.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}}$e("BABYLON.RandomNumberBlock",fue);class pue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("x",he.Float),this.registerInput("y",he.Float),this.registerOutput("output",he.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}}$e("BABYLON.ArcTan2Block",pue);class mue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("value",he.AutoDetect),this.registerInput("edge0",he.Float),this.registerInput("edge1",he.Float),this.registerOutput("output",he.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}}$e("BABYLON.SmoothStepBlock",mue);class _ue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("input",he.AutoDetect),this.registerOutput("output",he.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===he.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); +`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName}; +`,this}}$e("BABYLON.ReciprocalBlock",_ue);class gue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("value",he.AutoDetect),this.registerInput("reference",he.AutoDetect),this.registerInput("distance",he.Float),this.registerInput("replacement",he.AutoDetect),this.registerOutput("output",he.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(he.Float),this._inputs[0].excludedConnectionPointTypes.push(he.Matrix),this._inputs[1].excludedConnectionPointTypes.push(he.Float),this._inputs[1].excludedConnectionPointTypes.push(he.Matrix),this._inputs[3].excludedConnectionPointTypes.push(he.Float),this._inputs[3].excludedConnectionPointTypes.push(he.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}}$e("BABYLON.ReplaceColorBlock",gue);class vue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("value",he.AutoDetect),this.registerInput("steps",he.AutoDetect),this.registerOutput("output",he.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(he.Matrix),this._inputs[1].excludedConnectionPointTypes.push(he.Matrix)}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}}$e("BABYLON.PosterizeBlock",vue);var CP;(function(a){a[a.SawTooth=0]="SawTooth",a[a.Square=1]="Square",a[a.Triangle=2]="Triangle"})(CP||(CP={}));class Cue extends os{constructor(e){super(e,Pe.Neutral),this.kind=CP.SawTooth,this.registerInput("input",he.AutoDetect),this.registerOutput("output",he.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(he.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 CP.SawTooth:{e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); +`;break}case CP.Square:{e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); +`;break}case CP.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}}$e("BABYLON.WaveBlock",Cue);class UY{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 Aue extends os{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,Pe.Neutral),this.colorSteps=[new UY(0,Ie.Black()),new UY(1,Ie.White())],this.onValueChangedObservable=new Se,this.registerInput("gradient",he.AutoDetect),this.registerOutput("output",he.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(he.Float|he.Vector2|he.Vector3|he.Vector4|he.Color3|he.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"),s=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)}; +`,e.compilationString+=`float ${s}; +`;let r=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==he.Float&&(r+=".x");for(let n=1;n!0){if(!this.intensity.isConnected){const i=new Er("Refraction intensity",Pe.Fragment,he.Float);i.value=1,i.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Rr.View&&t(s));i||(i=new Er("view"),i.setAsSystemValue(Rr.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this._getTexture(),r=s&&s.getTextureMatrix;i.setValue("SS_REFRACTION",r,!0),r&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLODRefractionAlpha,s.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,s.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&s.isCube?!s.invertZ:s.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",s.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",s.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!s.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 s,r,n,o;super.bind(e,t,i);const l=this._getTexture();if(!l)return;l.isCube?e.setTexture(this._cubeSamplerName,l):e.setTexture(this._2DSamplerName,l),e.setMatrix(this._refractionMatrixName,l.getRefractionTextureMatrix());let c=1;l.isCube||l.depth&&(c=l.depth);const h=(o=(r=(s=this.volumeIndexOfRefraction.connectInputBlock)===null||s===void 0?void 0:s.value)!==null&&r!==void 0?r:(n=this.indexOfRefractionConnectionPoint.connectInputBlock)===null||n===void 0?void 0:n.value)!==null&&o!==void 0?o:1.5;e.setFloat4(this._vRefractionInfosName,l.level,1/h,c,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset,1/h);const u=l.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,u,Bt.Log2(u)),l.boundingBoxSize){const p=l;e.setVector3("vRefractionPosition",p.boundingBoxPosition),e.setVector3("vRefractionSize",p.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=Ic.Parse(e.texture,t,i):this.texture=Te.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}z([ws("Link refraction to transparency",Ms.Boolean,"ADVANCED",{notifiers:{update:!0}})],JL.prototype,"linkRefractionWithTransparency",void 0);z([ws("Invert refraction Y",Ms.Boolean,"ADVANCED",{notifiers:{update:!0}})],JL.prototype,"invertRefractionY",void 0);z([ws("Use thickness as depth",Ms.Boolean,"ADVANCED",{notifiers:{update:!0}})],JL.prototype,"useThicknessAsDepth",void 0);$e("BABYLON.RefractionBlock",JL);class WB extends os{constructor(e){super(e,Pe.Fragment),this._isUnique=!0,this.registerInput("thickness",he.Float,!1,Pe.Fragment),this.registerInput("tintColor",he.Color3,!0,Pe.Fragment),this.registerInput("translucencyIntensity",he.Float,!0,Pe.Fragment),this.registerInput("translucencyDiffusionDist",he.Color3,!0,Pe.Fragment),this.registerInput("refraction",he.Object,!0,Pe.Fragment,new fl("refraction",this,xo.Input,JL,"RefractionBlock")),this.registerOutput("subsurface",he.Object,Pe.Fragment,new fl("subsurface",this,xo.Output,WB,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity")}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 subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new Er("SubSurface thickness",Pe.Fragment,he.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",s||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",s,!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)}static GetCode(e,t,i,s){var r,n,o,l,c,h,u,p,m,_,f,d,C,v,y,M;let b="";const E=t?.thickness.isConnected?t.thickness.associatedVariableName:"0.",S=t?.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",I=t?.translucencyIntensity.isConnected?t?.translucencyIntensity.associatedVariableName:"1.",D=t?.translucencyDiffusionDist.isConnected?t?.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",R=t?.refraction.isConnected?(r=t?.refraction.connectedPoint)===null||r===void 0?void 0:r.ownerBlock:null,L=R?.tintAtDistance.isConnected?R.tintAtDistance.associatedVariableName:"1.",w=R?.intensity.isConnected?R.intensity.associatedVariableName:"1.",N=R?.view.isConnected?R.view.associatedVariableName:"";return b+=(n=R?.getCode(e))!==null&&n!==void 0?n:"",b+=`subSurfaceOutParams subSurfaceOut; + + #ifdef SUBSURFACE + vec2 vThicknessParam = vec2(0., ${E}); + vec4 vTintColor = vec4(${S}, ${L}); + vec3 vSubSurfaceIntensity = vec3(${w}, ${I}, 0.); + + subSurfaceBlock( + vSubSurfaceIntensity, + vThicknessParam, + vTintColor, + normalW, + specularEnvironmentReflectance, + #ifdef SS_THICKNESSANDMASK_TEXTURE + vec4(0.), + #endif + #ifdef REFLECTION + #ifdef SS_TRANSLUCENCY + ${i?._reflectionMatrixName}, + #ifdef USESPHERICALFROMREFLECTIONMAP + #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) + reflectionOut.irradianceVector, + #endif + #if defined(REALTIME_FILTERING) + ${i?._cubeSamplerName}, + ${i?._vReflectionFilteringInfoName}, + #endif + #endif + #ifdef USEIRRADIANCEMAP + irradianceSampler, + #endif + #endif + #endif + #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) + surfaceAlbedo, + #endif + #ifdef SS_REFRACTION + ${s}.xyz, + viewDirectionW, + ${N}, + ${(o=R?._vRefractionInfosName)!==null&&o!==void 0?o:""}, + ${(l=R?._refractionMatrixName)!==null&&l!==void 0?l:""}, + ${(c=R?._vRefractionMicrosurfaceInfosName)!==null&&c!==void 0?c:""}, + vLightingIntensity, + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha, + #endif + #ifdef ${(h=R?._defineLODRefractionAlpha)!==null&&h!==void 0?h:"IGNORE"} + NdotVUnclamped, + #endif + #ifdef ${(u=R?._defineLinearSpecularRefraction)!==null&&u!==void 0?u:"IGNORE"} + roughness, + #endif + alphaG, + #ifdef ${(p=R?._define3DName)!==null&&p!==void 0?p:"IGNORE"} + ${(m=R?._cubeSamplerName)!==null&&m!==void 0?m:""}, + #else + ${(_=R?._2DSamplerName)!==null&&_!==void 0?_:""}, + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${(f=R?._define3DName)!==null&&f!==void 0?f:"IGNORE"} + ${(d=R?._cubeSamplerName)!==null&&d!==void 0?d:""}, + ${(C=R?._cubeSamplerName)!==null&&C!==void 0?C:""}, + #else + ${(v=R?._2DSamplerName)!==null&&v!==void 0?v:""}, + ${(y=R?._2DSamplerName)!==null&&y!==void 0?y:""}, + #endif + #endif + #ifdef ANISOTROPIC + anisotropicOut, + #endif + #ifdef REALTIME_FILTERING + ${(M=R?._vRefractionFilteringInfoName)!==null&&M!==void 0?M:""}, + #endif + #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC + vRefractionPosition, + vRefractionSize, + #endif + #endif + #ifdef SS_TRANSLUCENCY + ${D}, + #endif + subSurfaceOut + ); + + #ifdef SS_REFRACTION + surfaceAlbedo = subSurfaceOut.surfaceAlbedo; + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha = subSurfaceOut.alpha; + #endif + #endif + #else + subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; + #endif +`,b}_buildBlock(e){return e.target===Pe.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}$e("BABYLON.SubSurfaceBlock",WB);const cAe={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 Oh extends os{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Pe.Fragment:Pe.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Pe.Fragment:Pe.Vertex}constructor(e){super(e,Pe.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Ie.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",he.Vector4,!1,Pe.Vertex),this.registerInput("worldNormal",he.Vector4,!1,Pe.Fragment),this.registerInput("view",he.Matrix,!1),this.registerInput("cameraPosition",he.Vector3,!1,Pe.Fragment),this.registerInput("perturbedNormal",he.Vector4,!0,Pe.Fragment),this.registerInput("baseColor",he.Color3,!0,Pe.Fragment),this.registerInput("metallic",he.Float,!1,Pe.Fragment),this.registerInput("roughness",he.Float,!1,Pe.Fragment),this.registerInput("ambientOcc",he.Float,!0,Pe.Fragment),this.registerInput("opacity",he.Float,!0,Pe.Fragment),this.registerInput("indexOfRefraction",he.Float,!0,Pe.Fragment),this.registerInput("ambientColor",he.Color3,!0,Pe.Fragment),this.registerInput("reflection",he.Object,!0,Pe.Fragment,new fl("reflection",this,xo.Input,fD,"ReflectionBlock")),this.registerInput("clearcoat",he.Object,!0,Pe.Fragment,new fl("clearcoat",this,xo.Input,JP,"ClearCoatBlock")),this.registerInput("sheen",he.Object,!0,Pe.Fragment,new fl("sheen",this,xo.Input,dD,"SheenBlock")),this.registerInput("subsurface",he.Object,!0,Pe.Fragment,new fl("subsurface",this,xo.Input,WB,"SubSurfaceBlock")),this.registerInput("anisotropy",he.Object,!0,Pe.Fragment,new fl("anisotropy",this,xo.Input,RW,"AnisotropyBlock")),this.registerInput("iridescence",he.Object,!0,Pe.Fragment,new fl("iridescence",this,xo.Input,qj,"IridescenceBlock")),this.registerOutput("ambientClr",he.Color3,Pe.Fragment),this.registerOutput("diffuseDir",he.Color3,Pe.Fragment),this.registerOutput("specularDir",he.Color3,Pe.Fragment),this.registerOutput("clearcoatDir",he.Color3,Pe.Fragment),this.registerOutput("sheenDir",he.Color3,Pe.Fragment),this.registerOutput("diffuseInd",he.Color3,Pe.Fragment),this.registerOutput("specularInd",he.Color3,Pe.Fragment),this.registerOutput("clearcoatInd",he.Color3,Pe.Fragment),this.registerOutput("sheenInd",he.Color3,Pe.Fragment),this.registerOutput("refraction",he.Color3,Pe.Fragment),this.registerOutput("lighting",he.Color3,Pe.Fragment),this.registerOutput("shadow",he.Float,Pe.Fragment),this.registerOutput("alpha",he.Float,Pe.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(s=>s.systemValue===Rr.CameraPosition&&t(s));i||(i=new Er("cameraPosition"),i.setAsSystemValue(Rr.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Rr.View&&t(s));i||(i=new Er("view"),i.setAsSystemValue(Rr.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===Fr.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Fr.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const s=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",s.indexOf(".")<0?s+".":s,!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 r=e.getScene();if(r.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&&Xt.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)ze.PrepareDefinesForLights(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,ze.PrepareDefinesForMultiview(r,i);else{const o={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};ze.PrepareDefinesForLight(r,e,this.light,this._lightId,i,!0,o),o.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;ze.PrepareUniformsAndSamplersForLight(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,n)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var s,r;if(!i)return;const n=i.getScene();this.light?ze.BindLight(this.light,this._lightId,n,e,!0):ze.BindLights(n,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const o=this._scene.ambientColor;o&&e.setColor3("ambientFromScene",o);const l=n.useRightHandedSystem===(n._mirroredCameraPosition!=null);e.setFloat(this._invertNormalName,l?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const c=1,h=(r=(s=this.indexOfRefraction.connectInputBlock)===null||s===void 0?void 0:s.value)!==null&&r!==void 0?r:1.5,u=Math.pow((h-c)/(h+c),2);this._metallicReflectanceColor.scaleToRef(u*this._metallicF0Factor,hn.Color3[0]);const p=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,hn.Color3[0],p),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;const s=this.worldPosition,r=`//${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",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",r,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const n="v_"+s.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${s.associatedVariableName}; +`);const o=this.reflection.isConnected?(t=this.reflection.connectedPoint)===null||t===void 0?void 0:t.ownerBlock:null;o&&(o.viewConnectionPoint=this.view),e.compilationString+=(i=o?.handleVertexSide(e))!==null&&i!==void 0?i:"",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",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:s.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${s.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{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 t,i,s,r,n,o,l,c,h,u,p,m,_,f,d,C,v,y,M,b,E,S,I,D,R,L,w,N,V,W,G,ie,Z,q,K,j,H,Y,J,te,re;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=yW(this._scene));const ee=this.reflection.isConnected?(t=this.reflection.connectedPoint)===null||t===void 0?void 0:t.ownerBlock:null;if(ee&&(ee.worldPositionConnectionPoint=this.worldPosition,ee.cameraPositionConnectionPoint=this.cameraPosition,ee.worldNormalConnectionPoint=this.worldNormal,ee.viewConnectionPoint=this.view),e.target!==Pe.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 oe=`//${this.name}`,ae=this.perturbedNormal;let fe=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(fe=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${fe}; +`,oe),e.compilationString+=`${fe} = ${this.worldPosition.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",oe,{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 +`):fe="v_"+fe,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",oe,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",oe,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",oe),e._emitFunctionFromInclude("importanceSampling",oe),e._emitFunctionFromInclude("pbrHelperFunctions",oe),e._emitFunctionFromInclude("imageProcessingDeclaration",oe),e._emitFunctionFromInclude("imageProcessingFunctions",oe),e._emitFunctionFromInclude("shadowsFragmentFunctions",oe,{replaceStrings:[{search:/vPositionW/g,replace:fe+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",oe,{replaceStrings:[{search:/vPositionW/g,replace:fe+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",oe),e._emitFunctionFromInclude("pbrBRDFFunctions",oe,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(i=ee?._defineSkyboxName)!==null&&i!==void 0?i:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",oe),e._emitFunctionFromInclude("pbrDirectLightingFunctions",oe,{replaceStrings:[{search:/vPositionW/g,replace:fe+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",oe),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",oe),e._emitFunctionFromInclude("pbrBlockReflectivity",oe),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",oe),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",oe),e._emitFunctionFromInclude("pbrBlockAnisotropic",oe),e._emitUniformFromString("vLightingIntensity","vec4"),ee?.generateOnlyFragmentCode&&(e.compilationString+=ee.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} - ${fe}.xyz); +`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz; +`,e.compilationString+=`vec3 normalW = ${ae.isConnected?"normalize("+ae.associatedVariableName+".xyz)":"geometricNormalW"}; +`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",oe,{replaceStrings:[{search:/vPositionW/g,replace:fe+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",oe),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",oe),e.compilationString+=`#ifdef UNLIT + vec3 diffuseBase = vec3(1., 1., 1.); + #else +`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",oe,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(s=ee?._defineSkyboxName)!==null&&s!==void 0?s:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(r=ee?._define3DName)!==null&&r!==void 0?r:"REFLECTIONMAP_3D"}]});const de=this.anisotropy.isConnected?(n=this.anisotropy.connectedPoint)===null||n===void 0?void 0:n.ownerBlock:null;de&&(de.worldPositionConnectionPoint=this.worldPosition,de.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=de.getCode(e,!this.perturbedNormal.isConnected)),ee&&ee.hasTexture&&(e.compilationString+=ee.getCode(e,de?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",oe,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(o=ee?._define3DName)!==null&&o!==void 0?o:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(l=ee?._defineOppositeZ)!==null&&l!==void 0?l:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(c=ee?._defineProjectionName)!==null&&c!==void 0?c:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(h=ee?._defineSkyboxName)!==null&&h!==void 0?h:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(u=ee?._defineLODReflectionAlpha)!==null&&u!==void 0?u:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(p=ee?._defineLinearSpecularReflection)!==null&&p!==void 0?p:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:(m=ee?._vReflectionFilteringInfoName)!==null&&m!==void 0?m:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",oe,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const me=this.sheen.isConnected?(_=this.sheen.connectedPoint)===null||_===void 0?void 0:_.ownerBlock:null;me&&(e.compilationString+=me.getCode(ee)),e._emitFunctionFromInclude("pbrBlockSheen",oe,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(f=ee?._define3DName)!==null&&f!==void 0?f:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(d=ee?._defineSkyboxName)!==null&&d!==void 0?d:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(C=ee?._defineLODReflectionAlpha)!==null&&C!==void 0?C:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(v=ee?._defineLinearSpecularReflection)!==null&&v!==void 0?v:"LINEARSPECULARREFLECTION"}]});const Fe=this.iridescence.isConnected?(y=this.iridescence.connectedPoint)===null||y===void 0?void 0:y.ownerBlock:null;e.compilationString+=qj.GetCode(Fe),e._emitFunctionFromInclude("pbrBlockIridescence",oe,{replaceStrings:[]});const je=this.clearcoat.isConnected?(M=this.clearcoat.connectedPoint)===null||M===void 0?void 0:M.ownerBlock:null,nt=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,we=this.perturbedNormal.isConnected&&((E=((b=this.perturbedNormal.connectedPoint)===null||b===void 0?void 0:b.ownerBlock).worldTangent)===null||E===void 0?void 0:E.isConnected),Ke=this.anisotropy.isConnected&&((S=this.anisotropy.connectedPoint)===null||S===void 0?void 0:S.ownerBlock).worldTangent.isConnected;let ft=we||!this.perturbedNormal.isConnected&&Ke;e.compilationString+=JP.GetCode(e,je,ee,fe,nt,ft,this.worldNormal.associatedVariableName),nt&&(ft=(I=je?.worldTangent.isConnected)!==null&&I!==void 0?I:!1),e._emitFunctionFromInclude("pbrBlockClearcoat",oe,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(D=ee?._define3DName)!==null&&D!==void 0?D:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(R=ee?._defineOppositeZ)!==null&&R!==void 0?R:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(L=ee?._defineProjectionName)!==null&&L!==void 0?L:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(w=ee?._defineSkyboxName)!==null&&w!==void 0?w:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(N=ee?._defineLODReflectionAlpha)!==null&&N!==void 0?N:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(V=ee?._defineLinearSpecularReflection)!==null&&V!==void 0?V:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:ft?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",oe,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(W=ee?._defineSkyboxName)!==null&&W!==void 0?W:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(G=ee?._define3DName)!==null&&G!==void 0?G:"REFLECTIONMAP_3D"}]});const yt=this.subsurface.isConnected?(ie=this.subsurface.connectedPoint)===null||ie===void 0?void 0:ie.ownerBlock:null,Ze=this.subsurface.isConnected?(q=((Z=this.subsurface.connectedPoint)===null||Z===void 0?void 0:Z.ownerBlock).refraction.connectedPoint)===null||q===void 0?void 0:q.ownerBlock:null;Ze&&(Ze.viewConnectionPoint=this.view,Ze.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=WB.GetCode(e,yt,ee,fe),e._emitFunctionFromInclude("pbrBlockSubSurface",oe,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(K=ee?._define3DName)!==null&&K!==void 0?K:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(j=ee?._defineOppositeZ)!==null&&j!==void 0?j:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(H=ee?._defineProjectionName)!==null&&H!==void 0?H:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:(Y=Ze?._define3DName)!==null&&Y!==void 0?Y:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:(J=Ze?._defineLODRefractionAlpha)!==null&&J!==void 0?J:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:(te=Ze?._defineLinearSpecularRefraction)!==null&&te!==void 0?te:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:(re=Ze?._defineOppositeZ)!==null&&re!==void 0?re:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",oe),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",oe,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",oe,{repeatKey:"maxSimultaneousLights"}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",oe),e.compilationString+=`#endif +`;const mt=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let Je=Fr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();Je.indexOf(".")===-1&&(Je+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",oe,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:mt+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:Je}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",oe,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",oe,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",oe,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:fe},{search:/albedoTexture\.rgb;/g,replace:`vec3(1.); +gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); +`}]});for(const Yt of this._outputs)if(Yt.hasEndpoints){const Vt=cAe[Yt.name];if(Vt){const[Ot,et]=Vt;et&&(e.compilationString+=`#if ${et} +`),e.compilationString+=`${this._declareOutput(Yt,e)} = ${Ot}; +`,et&&(e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(Yt,e)} = vec3(0.); +`,e.compilationString+=`#endif +`)}else console.error(`There's no remapping for the ${Yt.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){var s,r;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=(s=e.lightFalloff)!==null&&s!==void 0?s: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=(r=e.realTimeFilteringQuality)!==null&&r!==void 0?r: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()}}z([ws("Direct lights",Ms.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Oh.prototype,"directIntensity",void 0);z([ws("Environment lights",Ms.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Oh.prototype,"environmentIntensity",void 0);z([ws("Specular highlights",Ms.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Oh.prototype,"specularIntensity",void 0);z([ws("Light falloff",Ms.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Fr.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Fr.LIGHTFALLOFF_GLTF},{label:"Standard",value:Fr.LIGHTFALLOFF_STANDARD}]})],Oh.prototype,"lightFalloff",void 0);z([ws("Alpha Testing",Ms.Boolean,"OPACITY")],Oh.prototype,"useAlphaTest",void 0);z([ws("Alpha CutOff",Ms.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],Oh.prototype,"alphaTestCutoff",void 0);z([ws("Alpha blending",Ms.Boolean,"OPACITY")],Oh.prototype,"useAlphaBlending",void 0);z([ws("Radiance over alpha",Ms.Boolean,"RENDERING",{notifiers:{update:!0}})],Oh.prototype,"useRadianceOverAlpha",void 0);z([ws("Specular over alpha",Ms.Boolean,"RENDERING",{notifiers:{update:!0}})],Oh.prototype,"useSpecularOverAlpha",void 0);z([ws("Specular anti-aliasing",Ms.Boolean,"RENDERING",{notifiers:{update:!0}})],Oh.prototype,"enableSpecularAntiAliasing",void 0);z([ws("Realtime filtering",Ms.Boolean,"RENDERING",{notifiers:{update:!0}})],Oh.prototype,"realTimeFiltering",void 0);z([ws("Realtime filtering quality",Ms.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],Oh.prototype,"realTimeFilteringQuality",void 0);z([ws("Energy Conservation",Ms.Boolean,"ADVANCED",{notifiers:{update:!0}})],Oh.prototype,"useEnergyConservation",void 0);z([ws("Radiance occlusion",Ms.Boolean,"ADVANCED",{notifiers:{update:!0}})],Oh.prototype,"useRadianceOcclusion",void 0);z([ws("Horizon occlusion",Ms.Boolean,"ADVANCED",{notifiers:{update:!0}})],Oh.prototype,"useHorizonOcclusion",void 0);z([ws("Unlit",Ms.Boolean,"ADVANCED",{notifiers:{update:!0}})],Oh.prototype,"unlit",void 0);z([ws("Force normal forward",Ms.Boolean,"ADVANCED",{notifiers:{update:!0}})],Oh.prototype,"forceNormalForward",void 0);z([ws("Generate only fragment code",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Oh._OnGenerateOnlyFragmentCodeChanged}})],Oh.prototype,"generateOnlyFragmentCode",void 0);z([ws("Debug mode",Ms.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}]})],Oh.prototype,"debugMode",void 0);z([ws("Split position",Ms.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],Oh.prototype,"debugLimit",void 0);z([ws("Output factor",Ms.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],Oh.prototype,"debugFactor",void 0);$e("BABYLON.PBRMetallicRoughnessBlock",Oh);class Iue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("left",he.AutoDetect),this.registerInput("right",he.AutoDetect),this.registerOutput("output",he.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}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}}$e("BABYLON.ModBlock",Iue);class Lue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("row0",he.Vector4),this.registerInput("row1",he.Vector4),this.registerInput("row2",he.Vector4),this.registerInput("row3",he.Vector4),this.registerOutput("output",he.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 Er("row0");e.value=new Ui(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Er("row1");e.value=new Ui(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Er("row2");e.value=new Ui(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Er("row3");e.value=new Ui(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,s=this.row1,r=this.row2,n=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName}, ${n.associatedVariableName}); +`,this}}$e("BABYLON.MatrixBuilder",Lue);var a_;(function(a){a[a.Equal=0]="Equal",a[a.NotEqual=1]="NotEqual",a[a.LessThan=2]="LessThan",a[a.GreaterThan=3]="GreaterThan",a[a.LessOrEqual=4]="LessOrEqual",a[a.GreaterOrEqual=5]="GreaterOrEqual",a[a.Xor=6]="Xor",a[a.Or=7]="Or",a[a.And=8]="And"})(a_||(a_={}));class Rue extends os{constructor(e){super(e,Pe.Neutral),this.condition=a_.LessThan,this.registerInput("a",he.Float),this.registerInput("b",he.Float),this.registerInput("true",he.AutoDetect,!0),this.registerInput("false",he.AutoDetect,!0),this.registerOutput("output",he.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=he.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",s=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case a_.Equal:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${s}; +`;break}case a_.NotEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${s}; +`;break}case a_.LessThan:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${s}; +`;break}case a_.LessOrEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${s}; +`;break}case a_.GreaterThan:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${s}; +`;break}case a_.GreaterOrEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${s}; +`;break}case a_.Xor:{e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${s}; +`;break}case a_.Or:{e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${s}; +`;break}case a_.And:{e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${s}; +`;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.${a_[this.condition]}; +`}}$e("BABYLON.ConditionalBlock",Rue);class Qee extends os{constructor(e){super(e,Pe.Neutral),this.octaves=6,this.registerInput("seed",he.AutoDetect),this.registerInput("chaos",he.AutoDetect,!0),this.registerInput("offsetX",he.Float,!0),this.registerInput("offsetY",he.Float,!0),this.registerInput("offsetZ",he.Float,!0),this.registerOutput("output",he.Float),this._inputs[0].acceptedConnectionPointTypes.push(he.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(he.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 t,i;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;const s=` + + 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); + }`,r=` + 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; + }`,n=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",s,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,r.replace(/fbm/gi,n).replace(/OCTAVES/gi,(this.octaves|0).toString()),"// CloudBlockCode FBM");const o=e._getFreeVariableName("st"),l=((t=this.seed.connectedPoint)===null||t===void 0?void 0:t.type)===he.Vector2?"vec2":"vec3";e.compilationString+=`${l} ${o} = ${this.seed.associatedVariableName}; +`,this.offsetX.isConnected&&(e.compilationString+=`${o}.x += 0.1 * ${this.offsetX.associatedVariableName}; +`),this.offsetY.isConnected&&(e.compilationString+=`${o}.y += 0.1 * ${this.offsetY.associatedVariableName}; +`),this.offsetZ.isConnected&&l==="vec3"&&(e.compilationString+=`${o}.z += 0.1 * ${this.offsetZ.associatedVariableName}; +`);let c="";return this.chaos.isConnected?c=this.chaos.associatedVariableName:c=((i=this.seed.connectedPoint)===null||i===void 0?void 0:i.type)===he.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${n}(${o}, ${c}); +`,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}}z([ws("Octaves",Ms.Int)],Qee.prototype,"octaves",void 0);$e("BABYLON.CloudBlock",Qee);class Pue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("seed",he.Vector2),this.registerInput("offset",he.Float),this.registerInput("density",he.Float),this.registerOutput("output",he.Float),this.registerOutput("cells",he.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"),s=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0; +`,e.compilationString+=`float ${s} = 0.0; +`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${s}); +`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; +`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${s}; +`),this}}$e("BABYLON.VoronoiNoiseBlock",Pue);class Due extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("input",he.AutoDetect),this.registerOutput("output",he.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!==Pe.VertexAndFragment)return t.target;if(e.connectedPoint.target!==Pe.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){(this._target&e)===0&&(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}}$e("BABYLON.ElbowBlock",Due);class fQ extends os{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)===null||e===void 0?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e?.getScene())!==null&&t!==void 0?t:Ii.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}get textureY(){var e;return this.sourceY.isConnected?((e=this.sourceY.connectedPoint)===null||e===void 0?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return!((e=this.sourceZ)===null||e===void 0)&&e.isConnected?((t=this.sourceY.connectedPoint)===null||t===void 0?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return e?.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){var e,t;return(t=(e=this._getImageSourceBlock(this.sourceY))===null||e===void 0?void 0:e.samplerName)!==null&&t!==void 0?t:null}get samplerZName(){var e,t;return(t=(e=this._getImageSourceBlock(this.sourceZ))===null||e===void 0?void 0:e.samplerName)!==null&&t!==void 0?t:null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:Ii.LastCreatedScene;i?.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:Ii.LastCreatedScene;i?.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,Pe.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",he.AutoDetect,!1),this.registerInput("normal",he.AutoDetect,!1),this.registerInput("sharpness",he.Float,!0),this.registerInput("source",he.Object,!0,Pe.VertexAndFragment,new fl("source",this,xo.Input,aC,"ImageSourceBlock")),this.registerInput("sourceY",he.Object,!0,Pe.VertexAndFragment,new fl("sourceY",this,xo.Input,aC,"ImageSourceBlock")),t||this.registerInput("sourceZ",he.Object,!0,Pe.VertexAndFragment,new fl("sourceZ",this,xo.Input,aC,"ImageSourceBlock")),this.registerOutput("rgba",he.Color4,Pe.Neutral),this.registerOutput("rgb",he.Color3,Pe.Neutral),this.registerOutput("r",he.Float,Pe.Neutral),this.registerOutput("g",he.Float,Pe.Neutral),this.registerOutput("b",he.Float,Pe.Neutral),this.registerOutput("a",he.Float,Pe.Neutral),this.registerOutput("level",he.Float,Pe.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(he.Color3|he.Vector3|he.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(he.Color3|he.Vector3|he.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 s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!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){var t,i;const s=this.samplerName,r=(t=this.samplerYName)!==null&&t!==void 0?t:s,n=(i=this.samplerZName)!==null&&i!==void 0?i:s,o=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",l=e._getFreeVariableName("x"),c=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),u=e._getFreeVariableName("w"),p=e._getFreeVariableName("n"),m=e._getFreeVariableName("uvx"),_=e._getFreeVariableName("uvy"),f=e._getFreeVariableName("uvz");e.compilationString+=` + vec3 ${p} = ${this.normal.associatedVariableName}.xyz; + + vec2 ${m} = ${this.position.associatedVariableName}.yz; + vec2 ${_} = ${this.position.associatedVariableName}.zx; + vec2 ${f} = ${this.position.associatedVariableName}.xy; + `,this.projectAsCube&&(e.compilationString+=` + ${m}.xy = ${m}.yx; + + if (${p}.x >= 0.0) { + ${m}.x = -${m}.x; + } + if (${p}.y < 0.0) { + ${_}.y = -${_}.y; + } + if (${p}.z < 0.0) { + ${f}.x = -${f}.x; + } + `),e.compilationString+=` + vec4 ${l} = texture2D(${s}, ${m}); + vec4 ${c} = texture2D(${r}, ${_}); + vec4 ${h} = texture2D(${n}, ${f}); + + // blend weights + vec3 ${u} = pow(abs(${p}), vec3(${o})); + + // blend and return + vec4 ${this._tempTextureRead} = (${l}*${u}.x + ${c}*${u}.y + ${h}*${u}.z) / (${u}.x + ${u}.y + ${u}.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 s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s}; +`,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&&!Pl.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=Te.Parse(e.texture,t,i))}}z([ws("Project as cube",Ms.Boolean,"ADVANCED",{notifiers:{update:!0}})],fQ.prototype,"projectAsCube",void 0);$e("BABYLON.TriPlanarBlock",fQ);class Oue extends fQ{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;const i=this.samplerName,s=(t=this.samplerYName)!==null&&t!==void 0?t:this.samplerName,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("dpdx"),o=e._getFreeVariableName("dpdy"),l=e._getFreeVariableName("n"),c=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),u=e._getFreeVariableName("me"),p=e._getFreeVariableName("x"),m=e._getFreeVariableName("y"),_=e._getFreeVariableName("y");e.compilationString+=` + // grab coord derivatives for texturing + vec3 ${n} = dFdx(${this.position.associatedVariableName}.xyz); + vec3 ${o} = dFdy(${this.position.associatedVariableName}.xyz); + vec3 ${l} = abs(${this.normal.associatedVariableName}.xyz); + + // determine major axis (in x; yz are following axis) + ivec3 ${c} = (${l}.x>${l}.y && ${l}.x>${l}.z) ? ivec3(0,1,2) : + (${l}.y>${l}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine minor axis (in x; yz are following axis) + ivec3 ${h} = (${l}.x<${l}.y && ${l}.x<${l}.z) ? ivec3(0,1,2) : + (${l}.y<${l}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine median axis (in x; yz are following axis) + ivec3 ${u} = ivec3(3) - ${h} - ${c}; + + // project+fetch + vec4 ${p} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${c}.y], ${this.position.associatedVariableName}[${c}.z]), + vec2(${n}[${c}.y],${n}[${c}.z]), + vec2(${o}[${c}.y],${o}[${c}.z]) ); + vec4 ${m} = textureGrad( ${s}, vec2( ${this.position.associatedVariableName}[${u}.y], ${this.position.associatedVariableName}[${u}.z]), + vec2(${n}[${u}.y],${n}[${u}.z]), + vec2(${o}[${u}.y],${o}[${u}.z]) ); + + // blend factors + vec2 ${_} = vec2(${l}[${c}.x],${l}[${u}.x]); + // make local support + ${_} = clamp( (${_}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); + // shape transition + ${_} = pow( ${_}, vec2(${r}/8.0) ); + // blend and return + vec4 ${this._tempTextureRead} = (${p}*${_}.x + ${m}*${_}.y) / (${_}.x + ${_}.y); + `}}$e("BABYLON.BiPlanarBlock",Oue);class wue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("input",he.Matrix),this.registerOutput("output",he.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}}$e("BABYLON.MatrixDeterminantBlock",wue);class Nue extends os{constructor(e){super(e,Pe.Neutral),this.registerInput("input",he.Matrix),this.registerOutput("output",he.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}}$e("BABYLON.MatrixTransposeBlock",Nue);var La;(function(a){a[a.None=0]="None",a[a.Normal=1]="Normal",a[a.Tangent=2]="Tangent",a[a.VertexColor=3]="VertexColor",a[a.UV1=4]="UV1",a[a.UV2=5]="UV2",a[a.UV3=6]="UV3",a[a.UV4=7]="UV4",a[a.UV5=8]="UV5",a[a.UV6=9]="UV6"})(La||(La={}));class Zee extends os{constructor(e){super(e,Pe.Neutral),this.attributeType=La.None,this.registerInput("input",he.AutoDetect),this.registerInput("fallback",he.AutoDetect),this.registerOutput("output",he.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(t=>{var i;if(this.attributeType)return;const s=t.ownerBlock;if(s instanceof Er&&s.isAttribute)switch(s.name){case"color":this.attributeType=La.VertexColor;break;case"normal":this.attributeType=La.Normal;break;case"tangent":this.attributeType=La.Tangent;break;case"uv":this.attributeType=La.UV1;break;case"uv2":this.attributeType=La.UV2;break;case"uv3":this.attributeType=La.UV3;break;case"uv4":this.attributeType=La.UV4;break;case"uv5":this.attributeType=La.UV5;break;case"uv6":this.attributeType=La.UV6;break}else if(s instanceof Gee)switch((i=this.input.connectedPoint)===null||i===void 0?void 0:i.name){case"normalOutput":this.attributeType=La.Normal;break;case"tangentOutput":this.attributeType=La.Tangent;break;case"uvOutput":this.attributeType=La.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 La.VertexColor:t="VERTEXCOLOR_NME";break;case La.Normal:t="NORMAL";break;case La.Tangent:t="TANGENT";break;case La.UV1:t="UV1";break;case La.UV2:t="UV2";break;case La.UV3:t="UV3";break;case La.UV4:t="UV4";break;case La.UV5:t="UV5";break;case La.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){var s;super._deserialize(e,t,i),this.attributeType=(s=e.attributeType)!==null&&s!==void 0?s:La.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType}; +`,e}}z([ws("Attribute lookup",Ms.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:La.None},{label:"Normal",value:La.Normal},{label:"Tangent",value:La.Tangent},{label:"Vertex Color",value:La.VertexColor},{label:"UV1",value:La.UV1},{label:"UV2",value:La.UV2},{label:"UV3",value:La.UV3},{label:"UV4",value:La.UV4},{label:"UV5",value:La.UV5},{label:"UV6",value:La.UV6}]})],Zee.prototype,"attributeType",void 0);$e("BABYLON.MeshAttributeExistsBlock",Zee);var _o;(function(a){a[a.EaseInSine=0]="EaseInSine",a[a.EaseOutSine=1]="EaseOutSine",a[a.EaseInOutSine=2]="EaseInOutSine",a[a.EaseInQuad=3]="EaseInQuad",a[a.EaseOutQuad=4]="EaseOutQuad",a[a.EaseInOutQuad=5]="EaseInOutQuad",a[a.EaseInCubic=6]="EaseInCubic",a[a.EaseOutCubic=7]="EaseOutCubic",a[a.EaseInOutCubic=8]="EaseInOutCubic",a[a.EaseInQuart=9]="EaseInQuart",a[a.EaseOutQuart=10]="EaseOutQuart",a[a.EaseInOutQuart=11]="EaseInOutQuart",a[a.EaseInQuint=12]="EaseInQuint",a[a.EaseOutQuint=13]="EaseOutQuint",a[a.EaseInOutQuint=14]="EaseInOutQuint",a[a.EaseInExpo=15]="EaseInExpo",a[a.EaseOutExpo=16]="EaseOutExpo",a[a.EaseInOutExpo=17]="EaseInOutExpo",a[a.EaseInCirc=18]="EaseInCirc",a[a.EaseOutCirc=19]="EaseOutCirc",a[a.EaseInOutCirc=20]="EaseInOutCirc",a[a.EaseInBack=21]="EaseInBack",a[a.EaseOutBack=22]="EaseOutBack",a[a.EaseInOutBack=23]="EaseInOutBack",a[a.EaseInElastic=24]="EaseInElastic",a[a.EaseOutElastic=25]="EaseOutElastic",a[a.EaseInOutElastic=26]="EaseInOutElastic"})(_o||(_o={}));class Bue extends os{constructor(e){super(e,Pe.Neutral),this.type=_o.EaseInOutSine,this.registerInput("input",he.AutoDetect),this.registerOutput("output",he.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(he.Matrix),this._inputs[0].excludedConnectionPointTypes.push(he.Object),this._inputs[0].excludedConnectionPointTypes.push(he.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 s=` + vec${i} ret = vec${i}(0.0); + `;for(let r=1;r<=i;r++)s+=this._duplicateEntry(e,r===1?"x":r===2?"y":r===3?"z":"w")+`; +`;return s+=`return ret; +`,s}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",s="",r="";switch(this.input.type){case he.Float:r="float";break;case he.Vector2:r="vec2";break;case he.Vector3:case he.Color3:r="vec3";break;case he.Vector4:case he.Color4:r="vec4";break}switch(s=_o[this.type]+"_"+r,this.type){case _o.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case _o.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case _o.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case _o.EaseInQuad:i="return v * v";break;case _o.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case _o.EaseInOutQuad:{const n="VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0";i=this._duplicateVector(n,r);break}case _o.EaseInCubic:i="return v * v * v";break;case _o.EaseOutCubic:{const n="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(n,r);break}case _o.EaseInOutCubic:{const n="VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0";i=this._duplicateVector(n,r);break}case _o.EaseInQuart:i="return v * v * v * v";break;case _o.EaseOutQuart:{const n="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(n,r);break}case _o.EaseInOutQuart:{const n="VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0";i=this._duplicateVector(n,r);break}case _o.EaseInQuint:i="return v * v * v * v * v";break;case _o.EaseOutQuint:{const n="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(n,r);break}case _o.EaseInOutQuint:{const n="VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0";i=this._duplicateVector(n,r);break}case _o.EaseInExpo:{const n="VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)";i=this._duplicateVector(n,r);break}case _o.EaseOutExpo:{const n="VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)";i=this._duplicateVector(n,r);break}case _o.EaseInOutExpo:{const n="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";i=this._duplicateVector(n,r);break}case _o.EaseInCirc:{const n="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(n,r);break}case _o.EaseOutCirc:{const n="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(n,r);break}case _o.EaseInOutCirc:{const n="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";i=this._duplicateVector(n,r);break}case _o.EaseInBack:{i="return 2.70158 * v * v * v - 1.70158 * v * v";break}case _o.EaseOutBack:{const n="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(n,r);break}case _o.EaseInOutBack:{const n="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";i=this._duplicateVector(n,r);break}case _o.EaseInElastic:{const n="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))";i=this._duplicateVector(n,r);break}case _o.EaseOutElastic:{const n="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";i=this._duplicateVector(n,r);break}case _o.EaseInOutElastic:{const n="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";i=this._duplicateVector(n,r);break}}return e._emitFunction(s,`${r} ${s}(${r} v) {${i};} +`,""),e.compilationString+=this._declareOutput(t,e)+` = ${s}(${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.${_o[this.type]}; +`}}$e("BABYLON.CurveBlock",Bue);class hAe{optimize(e,t){}}class uAe{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 s=this.mm.get(e);s===void 0&&this.mm.set(e,s=new Map),s.set(t,i)}}class dAe{get standalone(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.standalone)!==null&&t!==void 0?t:!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.doNotInjectCode)!==null&&t!==void 0?t:!1}constructor(e,t,i){this._baseMaterial=e,this._scene=t??Ii.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new uAe,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add(s=>{var r;const n=(r=s.subMesh)===null||r===void 0?void 0:r.getMesh();n&&!this._meshes.has(n)&&this._meshes.set(n,n.onDisposeObservable.add(o=>{const l=this._subMeshToEffect.keys();for(let c=l.next();c.done!==!0;c=l.next()){const h=c.value;h?.getMesh()===o&&(this._subMeshToEffect.delete(h),this._subMeshToDepthWrapper.mm.delete(h))}})),this._subMeshToEffect.set(s.subMesh,[s.effect,this._scene.getEngine().currentRenderPassId]),this._subMeshToDepthWrapper.mm.delete(s.subMesh)})}getEffect(e,t,i){var s;const r=(s=this._subMeshToDepthWrapper.mm.get(e))===null||s===void 0?void 0:s.get(t);if(!r)return null;let n=r.drawWrapper[i];return n||(n=r.drawWrapper[i]=new ml(this._scene.getEngine()),n.setEffect(r.mainDrawWrapper.effect,r.mainDrawWrapper.defines)),n}isReadyForSubMesh(e,t,i,s,r){var n,o;return this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,s)?!1:(o=(n=this._makeEffect(e,t,i,r))===null||n===void 0?void 0:n.isReady())!==null&&o!==void 0?o:!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,s]=t.value;i.onDisposeObservable.remove(s)}}_makeEffect(e,t,i,s){var r,n,o;const l=this._scene.getEngine(),c=this._subMeshToEffect.get(e);if(!c)return null;const[h,u]=c;let p=this._subMeshToDepthWrapper.get(e,i);if(!p){const C=new ml(l);C.defines=(n=(r=e._getDrawWrapper(u))===null||r===void 0?void 0:r.defines)!==null&&n!==void 0?n:null,p={drawWrapper:[],mainDrawWrapper:C,depthDefines:"",token:WL()},p.drawWrapper[s]=C,this._subMeshToDepthWrapper.set(e,i,p)}const m=t.join(` +`);if(p.mainDrawWrapper.effect&&m===p.depthDefines)return p.mainDrawWrapper.effect;p.depthDefines=m;const _=h.getUniformNames().slice();let f=h.vertexSourceCodeBeforeMigration,d=h.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){const C=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:Ws.IncludesShadersStore.shadowMapVertexNormalBias,v=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:Ws.IncludesShadersStore.shadowMapVertexMetric,y=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:Ws.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow,M=Ws.IncludesShadersStore.shadowMapFragment;f=f.replace(/void\s+?main/g,Ws.IncludesShadersStore.shadowMapVertexExtraDeclaration+` +void main`),f=f.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,C),f.indexOf("#define SHADOWDEPTH_METRIC")!==-1?f=f.replace(/#define SHADOWDEPTH_METRIC/g,v):f=f.replace(/}\s*$/g,v+` +}`),f=f.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const b=d.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||d.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,E=d.indexOf("#define SHADOWDEPTH_FRAGMENT")!==-1;let S="";b?d=d.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,y):S=y+` +`,d=d.replace(/void\s+?main/g,Ws.IncludesShadersStore.shadowMapFragmentExtraDeclaration+` +void main`),E?d=d.replace(/#define SHADOWDEPTH_FRAGMENT/g,M):S+=M+` +`,S&&(d=d.replace(/}\s*$/g,S+"}")),_.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}p.mainDrawWrapper.effect=l.createEffect({vertexSource:f,fragmentSource:d,vertexToken:p.token,fragmentToken:p.token},{attributes:h.getAttributesNames(),uniformsNames:_,uniformBuffersNames:h.getUniformBuffersNames(),samplers:h.getSamplers(),defines:m+` +`+h.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:h.getIndexParameters()},l);for(let C=0;C{var M;(M=cl._EmptyColorsTexture)===null||M===void 0||M.dispose(),cl._EmptyColorsTexture=null}),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_previousAndSide"),e.push("grl_nextAndCounters"),e.push("grl_widths"),e.push("grl_colorPointers")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this._colorsTexture&&e.push(this._colorsTexture)}getUniforms(){return{ubo:[{name:"grl_projection",size:16,type:"mat4"},{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}],vertex:` + 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){var t;const i=this._scene.activeCamera;if(i){const o=i.getProjectionMatrix();e.updateMatrix("grl_projection",o)}else throw Error("GreasedLinePluginMaterial requires an active camera.");const s=ue.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 r=ue.Vector4[0];r.x=cl._BooleanToNumber(this.useDash),r.y=this._dashArray,r.z=this.dashOffset,r.w=this.dashRatio,e.updateVector4("grl_dashOptions",r);const n=ue.Vector4[1];n.x=this.colorMode,n.y=this.visibility,n.z=this._colorsTexture?this._colorsTexture.getSize().width:0,n.w=cl._BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",n),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",(t=this._colorsTexture)!==null&&t!==void 0?t:cl._EmptyColorsTexture)}prepareDefines(e,t,i){var s;e.GREASED_LINE_HAS_COLOR=!!this._color,e.GREASED_LINE_SIZE_ATTENUATION=(s=this._sizeAttenuation)!==null&&s!==void 0?s:!1,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===wL.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem}getClassName(){return cl.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){return e==="vertex"?{CUSTOM_VERTEX_DEFINITIONS:` + attribute vec4 grl_previousAndSide; + attribute vec4 grl_nextAndCounters; + attribute float grl_widths; + attribute vec3 grl_offsets; + attribute float grl_colorPointers; + + varying float grlCounters; + varying float grlColorPointer; + + vec2 grlFix( vec4 i, float aspect ) { + vec2 res = i.xy / i.w; + res.x *= aspect; + return res; + } + `,CUSTOM_VERTEX_UPDATE_POSITION:` + vec3 grlPositionOffset = grl_offsets; + positionUpdated += grlPositionOffset; + `,CUSTOM_VERTEX_MAIN_END:` + + float grlAspect = grl_aspect_resolution_lineWidth.x; + float grlBaseWidth = grl_aspect_resolution_lineWidth.w; + + grlColorPointer = grl_colorPointers; + + vec3 grlPrevious = grl_previousAndSide.xyz; + float grlSide = grl_previousAndSide.w; + + vec3 grlNext = grl_nextAndCounters.xyz; + grlCounters = grl_nextAndCounters.w; + + + mat4 grlMatrix = viewProjection * world; + 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_LNE_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); + + `,"!gl_Position\\=viewProjection\\*worldPos;":"//"}: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 == ${wb.COLOR_MODE_SET}.) { + gl_FragColor.rgb = grl_singleColor; + } else if (grlColorMode == ${wb.COLOR_MODE_ADD}.) { + gl_FragColor.rgb += grl_singleColor; + } else if (grlColorMode == ${wb.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 == ${wb.COLOR_MODE_SET}.) { + gl_FragColor = grlColor; + } else if (grlColorMode == ${wb.COLOR_MODE_ADD}.) { + gl_FragColor += grlColor; + } else if (grlColorMode == ${wb.COLOR_MODE_MULTIPLY}.) { + gl_FragColor *= grlColor; + } + } + #endif + `}:null}static _BooleanToNumber(e){return e?1:0}static _Color3toRGBAUint8(e){const t=new Uint8Array(e.length*4);for(let i=0,s=0;i 0. ? 1. : 0.; + } +#endif +#endif`,yAe=`#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`,zue=[new Ie(.98,.26,.38),new Ie(.47,.75,.3),new Ie(0,.26,.77),new Ie(.97,.6,.76),new Ie(.19,.63,.78),new Ie(.98,.8,.6),new Ie(.65,.43,.15),new Ie(.15,.47,.22),new Ie(.67,.71,.86),new Ie(.09,.46,.56),new Ie(.8,.98,.02),new Ie(.39,.29,.13),new Ie(.53,.63,.06),new Ie(.95,.96,.41),new Ie(1,.72,.94),new Ie(.63,.08,.31),new Ie(.66,.96,.95),new Ie(.22,.14,.19),new Ie(.14,.65,.59),new Ie(.93,1,.68),new Ie(.93,.14,.44),new Ie(.47,.86,.67),new Ie(.85,.07,.78),new Ie(.53,.64,.98),new Ie(.43,.37,.56),new Ie(.71,.65,.25),new Ie(.66,.19,.01),new Ie(.94,.53,.12),new Ie(.41,.44,.44),new Ie(.24,.71,.96),new Ie(.57,.28,.56),new Ie(.44,.98,.42)];var RP;(function(a){a[a.NONE=0]="NONE",a[a.TRIANGLES=1]="TRIANGLES",a[a.VERTICES=2]="VERTICES",a[a.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",a[a.UV0=4]="UV0",a[a.UV1=5]="UV1",a[a.VERTEXCOLORS=6]="VERTEXCOLORS",a[a.MATERIALIDS=7]="MATERIALIDS"})(RP||(RP={}));class MAe extends ta{constructor(){super(...arguments),this.DBG_MODE=RP.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class du extends l4{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){var i,s,r,n,o,l,c,h,u,p,m,_,f;const d=new MAe;d.DBG_MODE=(i=t.mode)!==null&&i!==void 0?i:d.DBG_MODE,d.DBG_MULTIPLY=(s=t.multiply)!==null&&s!==void 0?s:d.DBG_MULTIPLY,super(e,"MeshDebug",200,d,!0,!0),this._mode=d.DBG_MODE,this._multiply=d.DBG_MULTIPLY,this.shadedDiffuseColor=(r=t.shadedDiffuseColor)!==null&&r!==void 0?r:new Ie(1,1,1),this.shadedSpecularColor=(n=t.shadedSpecularColor)!==null&&n!==void 0?n:new Ie(.8,.8,.8),this.shadedSpecularPower=(o=t.shadedSpecularPower)!==null&&o!==void 0?o:10,this.wireframeThickness=(l=t.wireframeThickness)!==null&&l!==void 0?l:.7,this.wireframeTrianglesColor=(c=t.wireframeTrianglesColor)!==null&&c!==void 0?c:new Ie(0,0,0),this.wireframeVerticesColor=(h=t.wireframeVerticesColor)!==null&&h!==void 0?h:new Ie(.8,.8,.8),this.vertexColor=(u=t.vertexColor)!==null&&u!==void 0?u:new Ie(0,0,0),this.vertexRadius=(p=t.vertexRadius)!==null&&p!==void 0?p:1.2,this.uvScale=(m=t.uvScale)!==null&&m!==void 0?m:20,this.uvPrimaryColor=(_=t.uvPrimaryColor)!==null&&_!==void 0?_:new Ie(1,1,1),this.uvSecondaryColor=(f=t.uvSecondaryColor)!==null&&f!==void 0?f:new Ie(.5,.5,.5),this._materialColor=du.MaterialColors[du._PluginCount++%du.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().webGLVersion==1){Me.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){(this._mode==RP.VERTICES||this._mode==RP.TRIANGLES||this._mode==RP.TRIANGLES_VERTICES)&&!i.isVerticesDataPresent("dbg_initialPass")&&Me.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:bAe}}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:AAe,CUSTOM_VERTEX_MAIN_END:xAe}:{CUSTOM_FRAGMENT_DEFINITIONS:EAe,CUSTOM_FRAGMENT_MAIN_END:yAe}}static Reset(){this._PluginCount=0,this.MaterialColors=zue}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(e.getTotalIndices()==0)return i;if(t){const h=e.getVerticesDataKinds(),u=e.getIndices(),p={};for(const m of h)p[m]=e.getVerticesData(m);i=function(){e.setIndices(u);for(const m of h){const _=e.getVertexBuffer(m).getStrideSize();e.setVerticesData(m,p[m],void 0,_)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let h=0;h{DracoDecoderModule({wasmBinary:a}).then(t=>{e({module:t})})})}function eJ(a,e,t,i,s){let r=null,n=null,o=null;try{r=new a.Decoder,n=new a.DecoderBuffer,n.Init(e,e.byteLength);let l;const c=r.GetEncodedGeometryType(n);switch(c){case a.TRIANGULAR_MESH:{const p=new a.Mesh;if(l=r.DecodeBufferToMesh(n,p),!l.ok()||p.ptr===0)throw new Error(l.error_msg());const _=p.num_faces()*3,f=_*4,d=a._malloc(f);try{r.GetTrianglesUInt32Array(p,f,d);const C=new Uint32Array(_);C.set(new Uint32Array(a.HEAPF32.buffer,d,_)),i(C)}finally{a._free(d)}o=p;break}case a.POINT_CLOUD:{const p=new a.PointCloud;if(l=r.DecodeBufferToPointCloud(n,p),!l.ok()||!p.ptr)throw new Error(l.error_msg());o=p;break}default:throw new Error(`Invalid geometry type ${c}`)}const h=o.num_points(),u=(p,m,_,f)=>{const d=f.data_type(),C=f.num_components(),v=f.normalized(),y=f.byte_stride(),M=f.byte_offset(),E={[a.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:a.HEAPF32},[a.DT_INT8]:{typedArrayConstructor:Int8Array,heap:a.HEAP8},[a.DT_INT16]:{typedArrayConstructor:Int16Array,heap:a.HEAP16},[a.DT_INT32]:{typedArrayConstructor:Int32Array,heap:a.HEAP32},[a.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:a.HEAPU8},[a.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:a.HEAPU16},[a.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:a.HEAPU32}}[d];if(!E)throw new Error(`Invalid data type ${d}`);const S=h*C,I=S*E.typedArrayConstructor.BYTES_PER_ELEMENT,D=a._malloc(I);try{p.GetAttributeDataArrayForAllPoints(m,f,d,I,D);const R=new E.typedArrayConstructor(E.heap.buffer,D,S);s(_,R.slice(),M,y,v)}finally{a._free(D)}};if(t)for(const p in t){const m=t[p],_=r.GetAttributeByUniqueId(o,m);u(r,o,p,_)}else{const p={position:a.POSITION,normal:a.NORMAL,color:a.COLOR,uv:a.TEX_COORD};for(const m in p){const _=r.GetAttributeId(o,p[m]);if(_!==-1){const f=r.GetAttribute(o,_);u(r,o,m,f)}}}return h}finally{o&&a.destroy(o),n&&a.destroy(n),r&&a.destroy(r)}}function SAe(){let a;onmessage=e=>{const t=e.data;switch(t.id){case"init":{const i=t.decoder;i.url&&(importScripts(i.url),a=DracoDecoderModule({wasmBinary:i.wasmBinary})),postMessage({id:"initDone"});break}case"decodeMesh":{if(!a)throw new Error("Draco decoder module is not available");a.then(i=>{const s=eJ(i,t.dataView,t.attributes,r=>{postMessage({id:"indices",data:r},[r.buffer])},(r,n,o,l,c)=>{postMessage({id:"attribute",kind:r,data:n,offset:o,stride:l,normalized:c},[n.buffer])});postMessage({id:"decodeMeshDone",totalVertices:s})});break}}}}class J3{static get DecoderAvailable(){const e=J3.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 J3._Default||(J3._Default=new J3),J3._Default}constructor(e=J3.DefaultNumWorkers){const t=J3.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&typeof WebAssembly=="object"?{url:Be.GetAbsoluteUrl(t.wasmUrl),wasmBinaryPromise:Be.LoadFileAsync(Be.GetAbsoluteUrl(t.wasmBinaryUrl))}:{url:Be.GetAbsoluteUrl(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&typeof Worker=="function"&&typeof URL=="function"?this._workerPoolPromise=i.wasmBinaryPromise.then(s=>{const r=`${eJ}(${SAe})()`,n=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));return new PF(e,()=>new Promise((o,l)=>{const c=new Worker(n),h=p=>{c.removeEventListener("error",h),c.removeEventListener("message",u),l(p)},u=p=>{p.data.id==="initDone"&&(c.removeEventListener("error",h),c.removeEventListener("message",u),o(c))};c.addEventListener("error",h),c.addEventListener("message",u),c.postMessage({id:"init",decoder:{url:i.url,wasmBinary:s}})}))}):this._decoderModulePromise=i.wasmBinaryPromise.then(s=>{if(!i.url)throw new Error("Draco decoder module is not available");return Be.LoadScriptAsync(i.url).then(()=>TAe(s))})}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then(e=>{e.dispose()}),delete this._workerPoolPromise,delete this._decoderModulePromise}whenReadyAsync(){return this._workerPoolPromise?this._workerPoolPromise.then(()=>{}):this._decoderModulePromise?this._decoderModulePromise.then(()=>{}):Promise.resolve()}_decodeMeshAsync(e,t,i){const s=t instanceof ArrayBuffer?new Int8Array(t):new Int8Array(t.buffer,t.byteOffset,t.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then(r=>new Promise((n,o)=>{r.push((l,c)=>{let h=null;const u=[],p=f=>{l.removeEventListener("error",p),l.removeEventListener("message",m),o(f),c()},m=f=>{const d=f.data;switch(d.id){case"decodeMeshDone":{l.removeEventListener("error",p),l.removeEventListener("message",m),n({indices:h,attributes:u,totalVertices:d.totalVertices}),c();break}case"indices":{h=d.data;break}case"attribute":{u.push(new se(e,d.data,d.kind,!1,void 0,d.stride,void 0,d.offset,void 0,void 0,d.normalized,!0));break}}};l.addEventListener("error",p),l.addEventListener("message",m);const _=s.slice();l.postMessage({id:"decodeMesh",dataView:_,attributes:i},[_.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(r=>{let n=null;const o=[],l=eJ(r.module,s,i,c=>{n=c},(c,h,u,p,m)=>{o.push(new se(null,h,c,!1,void 0,p,void 0,u,void 0,void 0,m,!0))});return{indices:n,attributes:o,totalVertices:l}});throw new Error("Draco decoder module is not available")}decodeMeshToGeometryAsync(e,t,i,s){return this._decodeMeshAsync(t.getEngine(),i,s).then(r=>{const n=new au(e,t);r.indices&&n.setIndices(r.indices);for(const o of r.attributes)n.setVerticesBuffer(o);return n})}decodeMeshAsync(e,t){return this._decodeMeshAsync(null,e,t).then(i=>{const s=new Jt;i.indices&&(s.indices=i.indices);for(const r of i.attributes)s.set(r.getFloatData(i.totalVertices),r.getKind());return s})}}J3.Configuration={decoder:{wasmUrl:"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://preview.babylonjs.com/draco_decoder_gltf.wasm",fallbackUrl:"https://preview.babylonjs.com/draco_decoder_gltf.js"}};J3.DefaultNumWorkers=J3.GetDefaultNumWorkers();J3._Default=null;class wM{static get Default(){return wM._Default||(wM._Default=new wM),wM._Default}constructor(){const e=wM.Configuration.decoder;this._decoderModulePromise=Be.LoadScriptAsync(Be.GetAbsoluteUrl(e.url)).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,s,r){return this._decoderModulePromise.then(()=>{const n=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(n,t,i,e,s,r),n})}}wM.Configuration={decoder:{url:"https://preview.babylonjs.com/meshopt_decoder.js"}};wM._Default=null;let pre=0;class TX{constructor(e,t,i,s){this.pos=e,this.normal=t,this.uv=i,this.vertColor=s}clone(){var e,t;return new TX(this.pos.clone(),this.normal.clone(),(e=this.uv)===null||e===void 0?void 0:e.clone(),(t=this.vertColor)===null||t===void 0?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new TX(O.Lerp(this.pos,e.pos,t),O.Lerp(this.normal,e.normal,t),this.uv&&e.uv?lt.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?Zt.Lerp(this.vertColor,e.vertColor,t):void 0)}}class AP{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const s=i.subtract(e),r=t.subtract(e);if(s.lengthSquared()===0||r.lengthSquared()===0)return null;const n=O.Normalize(O.Cross(s,r));return new AP(n,O.Dot(n,e))}clone(){return new AP(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,s,r){let h=0;const u=[];let p,m;for(p=0;pAP.EPSILON?1:0;h|=_,u.push(_)}switch(h){case 0:(O.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:s.push(e);break;case 2:r.push(e);break;case 3:{const _=[],f=[];for(p=0;p=3&&(d=new Jj(_,e.shared),d.plane&&s.push(d)),f.length>=3&&(d=new Jj(f,e.shared),d.plane&&r.push(d));break}}}}AP.EPSILON=1e-5;class Jj{constructor(e,t){this.vertices=e,this.shared=t,this.plane=AP.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map(t=>t.clone());return new Jj(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}class c0{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new c0;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 c0(this.clone()._polygons),i=new c0(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),hL._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new c0(this._polygons),i=new c0(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 c0(this.clone()._polygons),i=new c0(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(),hL._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new c0(this._polygons),i=new c0(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 c0(this.clone()._polygons),i=new c0(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),hL._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new c0(this._polygons),i=new c0(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}buildMeshGeometry(e,t,i){const s=this.matrix.clone();s.invert();const r=new Oe(e,t),n=[],o=[],l=[];let c=null,h=null;const u=O.Zero(),p=O.Zero(),m=lt.Zero(),_=new Zt(0,0,0,0),f=this._polygons,d=[0,0,0];let C;const v={};let y,M=0;const b={};let E;i&&f.sort((S,I)=>S.shared.meshId===I.shared.meshId?S.shared.subMeshId-I.shared.subMeshId:S.shared.meshId-I.shared.meshId);for(let S=0,I=f.length;S +#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);} +`;Ue.ShadersStore[IAe]=LAe;const RAe="meshUVSpaceRendererPixelShader",PAe=`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);} +`;Ue.ShadersStore[RAe]=PAe;class dP{static _GetShader(e){if(!e._meshUVSpaceRendererShader){const t=new oh("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===void 0||i.dispose(),e._meshUVSpaceRendererShader=null}),e._meshUVSpaceRendererShader=t}return e._meshUVSpaceRendererShader}static _IsRenderTargetTexture(e){return e.renderList!==void 0}constructor(e,t,i){this._textureCreatedInternally=!1,this.clearColor=new Zt(0,0,0,0),this._mesh=e,this._scene=t,this._options=Object.assign({width:1024,height:1024,textureType:0,generateMipMaps:!0,optimizeUVAllocation:!0},i)}isReady(){return this.texture||this._createDiffuseRTT(),dP._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady()}renderTexture(e,t,i,s,r=0){if(this.texture||this._createDiffuseRTT(),dP._IsRenderTargetTexture(this.texture)){const n=this._createProjectionMatrix(t,i,s,r),o=dP._GetShader(this._scene);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",n),this.texture.render()}}clear(){if(dP._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const e=this._scene.getEngine();e.bindFramebuffer(this.texture.renderTarget),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this.texture.renderTarget)}}dispose(){this._textureCreatedInternally&&(this.texture.dispose(),this._textureCreatedInternally=!1)}_createDiffuseRTT(){this._textureCreatedInternally=!0;const e=this._createRenderTargetTexture(this._options.width,this._options.height);e.setMaterialForRendering(this._mesh,dP._GetShader(this._scene)),this.texture=e}_createRenderTargetTexture(e,t){const i=new Oa(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,s=0){const r=-Math.atan2(t.z,t.x)-Math.PI/2,n=Math.sqrt(t.x*t.x+t.z*t.z),o=Math.atan2(t.y,n),l=e.add(t.scale(i.z*.5)),c=ge.RotationYawPitchRoll(r,o,s).multiply(ge.Translation(l.x,l.y,l.z)),h=ge.Invert(c),u=ge.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),p=ge.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return h.multiply(u).multiply(p)}}Oe._TrailMeshParser=(a,e)=>$j.Parse(a,e);class $j extends Oe{constructor(e,t,i,s=1,r=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=n,this._generator=t,this.diameter=s,this._length=r,this._sectionVectors=[],this._sectionNormalVectors=[];for(let o=0;o{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(se.PositionKind),t=this.getVerticesData(se.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let n=3*this._sectionPolygonPointsCount;n{this._getSimplifier(e).simplify(t,s=>{t.distance!==void 0&&e.mesh.addLODLevel(t.distance,s),s.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()})});else{const t=this._getSimplifier(e),i=(s,r)=>{t.simplify(s,n=>{s.distance!==void 0&&e.mesh.addLODLevel(s.distance,n),n.isVisible=!0,r()})};$6.Run(e.settings.length,s=>{i(e.settings[s.index],()=>{s.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){switch(e.simplificationType){case eG.QUADRATIC:default:return new kue(e.mesh)}}}var eG;(function(a){a[a.QUADRATIC=0]="QUADRATIC"})(eG||(eG={}));class OAe{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class wAe{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new iB,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class iB{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,s,r,n,o,l,c){return this.data[e]*this.data[r]*this.data[c]+this.data[i]*this.data[s]*this.data[l]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[r]*this.data[o]-this.data[e]*this.data[n]*this.data[l]-this.data[t]*this.data[s]*this.data[c]}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 iB;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,s){return new iB(iB.DataFromNumbers(e,t,i,s))}static DataFromNumbers(e,t,i,s){return[e*e,e*t,e*i,e*s,t*t,t*i,t*s,i*i,i*s,s*s]}}class NAe{constructor(e,t){this.vertexId=e,this.triangleId=t}}class kue{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=Ls}simplify(e,t){this._initDecimatedMesh(),$6.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 s=~~(this._triangles.length*e.quality);let r=0;const n=this._triangles.length,o=(l,c)=>{setTimeout(()=>{l%5===0&&this._updateMesh(l===0);for(let p=0;p{const m=~~((this._triangles.length/2+p)%this._triangles.length),_=this._triangles[m];if(!!_&&!(_.error[3]>h||_.deleted||_.isDirty)){for(let f=0;f<3;++f)if(_.error[f]{E.indexOf(D)===-1&&(D.deletePending=!0,E.push(D))}),E.length%2!==0)continue;v.q=y.q.add(v.q),v.updatePosition(M);const S=this._references.length;r=this._updateTriangles(v,v,d,r),r=this._updateTriangles(v,y,C,r);const I=this._references.length-S;if(I<=v.triangleCount){if(I)for(let D=0;Dn-r<=s)},0)};$6.Run(this.decimationIterations,l=>{n-r<=s?l.breakLoop():o(l.index,()=>{l.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(se.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=u=>{if(i){for(let p=0;p{if(!s)return;const p=u+n.verticesStart,m=O.FromArray(s,p*3),_=o(m)||new wAe(m,this._vertices.length);_.originalOffsets.push(p),_.id===this._vertices.length&&this._vertices.push(_),l.push(_.id)},h=n.verticesCount;$6.SyncAsyncForLoop(h,this.syncIterations/4>>0,c,()=>{const u=p=>{if(!r)return;const _=(n.indexStart/3+p)*3,f=r[_+0],d=r[_+1],C=r[_+2],v=this._vertices[l[f-n.verticesStart]],y=this._vertices[l[d-n.verticesStart]],M=this._vertices[l[C-n.verticesStart]],b=new OAe([v,y,M]);b.originalOffset=_,this._triangles.push(b)};$6.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,u,()=>{this._init(t)})})}_init(e){const t=i=>{const s=this._triangles[i];s.normal=O.Cross(s._vertices[1].position.subtract(s._vertices[0].position),s._vertices[2].position.subtract(s._vertices[0].position)).normalize();for(let r=0;r<3;r++)s._vertices[r].q.addArrayInPlace(iB.DataFromNumbers(s.normal.x,s.normal.y,s.normal.z,-O.Dot(s.normal,s._vertices[0].position)))};$6.SyncAsyncForLoop(this._triangles.length,this.syncIterations,t,()=>{const i=s=>{const r=this._triangles[s];for(let n=0;n<3;++n)r.error[n]=this._calculateError(r._vertices[n],r._vertices[(n+1)%3]);r.error[3]=Math.min(r.error[0],r.error[1],r.error[2])};$6.SyncAsyncForLoop(this._triangles.length,this.syncIterations,i,()=>{e()})})}_reconstructMesh(e){const t=[];let i;for(i=0;i{n.push(M.position.x),n.push(M.position.y),n.push(M.position.z),h&&h.length&&(o.push(h[b*3]),o.push(h[b*3+1]),o.push(h[b*3+2])),u&&u.length&&(l.push(u[b*2]),l.push(u[b*2+1])),p&&p.length&&(c.push(p[b*4]),c.push(p[b*4+1]),c.push(p[b*4+2]),c.push(p[b*4+3])),++m})}const _=this._reconstructedMesh.getTotalIndices(),f=this._reconstructedMesh.getTotalVertices(),d=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const C=this._reconstructedMesh.getIndices(),v=this._mesh.getIndices();for(i=0;i{const b=v[s.originalOffset+M];let E=s._vertices[M].originalOffsets.indexOf(b);E<0&&(E=0),C.push(s._vertices[M].id+E+f)});this._reconstructedMesh.setIndices(C),this._reconstructedMesh.setVerticesData(se.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(se.NormalKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(se.UVKind,l),c.length>0&&this._reconstructedMesh.setVerticesData(se.ColorKind,c);const y=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],d.forEach(M=>{_d.AddToMesh(M.materialIndex,M.verticesStart,M.verticesCount,M.indexStart,M.indexCount,M.getMesh())}),_d.AddToMesh(y.materialIndex,f,m,_,t.length*3,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new Oe(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,s,r){for(let n=0;n.999)return!0;const m=O.Cross(u,p).normalize();if(s[n]=!1,O.Dot(m,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let n=0;n{const n=s.getVerticesData(se.PositionKind),o=s.getIndices();if(n&&o)for(let l=0,c=0;l[t.x,t.y,t.z])}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let s=e.length;s--;)t[s]=e[s].length/3,i+=t[s];return{total:i,counts:t}}static GetLineLength(e){if(e.length===0)return 0;let t;typeof e[0]=="number"?t=LM.ToVector3Array(e):t=e;const i=ue.Vector3[0];let s=0;for(let r=0;r{r.length>t?LM.SegmentizeSegmentByCount(r.point1,r.point2,Math.ceil(r.length/t)).forEach(o=>{s.push(o)}):(s.push(r.point1),s.push(r.point2))}),s}static SegmentizeLineBySegmentCount(e,t){const i=LM.GetLineLength(e)/t;return LM.SegmentizeLineBySegmentLength(e,i)}static GetLineSegments(e){const t=[];for(let i=0;is.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,s=!1){const r=t*i;let n=0,o=0;const l=e.length;for(let h=0;h[r.x,r.y,r.z])}static GetArrowCap(e,t,i,s,r,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,o]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const o=[],l=Pee(e,t,i,s);for(const c of l){for(const h of c.paths){const u=[],p=h.getPoints();for(const m of p)u.push(m.x,m.y,r);o.push(u)}if(n)for(const h of c.holes){const u=[],p=h.getPoints();for(const m of p)u.push(m.x,m.y,r);o.push(u)}}return o}}const BAe="greasedLinePixelShader",FAe=`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==1.) { +textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} +if (grlColorMode==0.) { +gl_FragColor=textureColor;} else if (grlColorMode==1.) { +gl_FragColor+=textureColor;} else if (grlColorMode==2.) { +gl_FragColor*=textureColor;}}} +`;Ue.ShadersStore[BAe]=FAe;const VAe="greasedLineVertexShader",zAe=`precision highp float;attribute vec4 grl_previousAndSide;attribute vec4 grl_nextAndCounters;attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;uniform mat4 worldViewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} +void main() {grlColorPointer=grl_colorPointers;float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=worldViewProjection;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_LNE_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;} +`;Ue.ShadersStore[VAe]=zAe;class G1 extends oh{constructor(e,t,i){var s,r,n,o,l,c,h,u,p,m,_,f,d;super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:["position","normal","grl_previousAndSide","grl_nextAndCounters","grl_widths","grl_offsets","grl_colorPointers"],uniforms:["worldViewProjection","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:t.useRightHandedSystem?["GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM"]:[]}),this._color=Ie.White(),this._colorsDistributionType=wL.COLOR_DISTRIBUTION_TYPE_SEGMENT,i=i||{color:G1.DEFAULT_COLOR},this._engine=t.getEngine(),this.visibility=(s=i.visibility)!==null&&s!==void 0?s:1,this.useDash=(r=i.useDash)!==null&&r!==void 0?r:!1,this.dashRatio=(n=i.dashRatio)!==null&&n!==void 0?n:.5,this.dashOffset=(o=i.dashOffset)!==null&&o!==void 0?o:0,this.dashCount=(l=i.dashCount)!==null&&l!==void 0?l:1,this.width=i.width?i.width:i.sizeAttenuation?G1.DEFAULT_WIDTH_ATTENUATED:G1.DEFAULT_WIDTH,this.sizeAttenuation=(c=i.sizeAttenuation)!==null&&c!==void 0?c:!1,this.color=(h=i.color)!==null&&h!==void 0?h:Ie.White(),this.useColors=(u=i.useColors)!==null&&u!==void 0?u:!1,this.colorsDistributionType=(p=i.colorDistributionType)!==null&&p!==void 0?p:wL.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=(m=i.colorsSampling)!==null&&m!==void 0?m:Ya.NEAREST_NEAREST,this.colorMode=(_=i.colorMode)!==null&&_!==void 0?_:wb.COLOR_MODE_SET,this._colors=(f=i.colors)!==null&&f!==void 0?f:null,this.resolution=(d=i.resolution)!==null&&d!==void 0?d:new lt(this._engine.getRenderWidth(),this._engine.getRenderHeight()),this._colors&&this.setColors(this._colors),this._engine.onDisposeObservable.add(()=>{var C;(C=G1._EmptyColorsTexture)===null||C===void 0||C.dispose()})}static _BooleanToNumber(e){return e?1:0}static _Color3toRGBAUint8(e){const t=new Uint8Array(e.length*4);for(let i=0,s=0;ill.Parse(a,e);class ll extends Oe{constructor(e,t,i){var s,r,n,o;super(e,t,null,null,!1,!1),this.name=e,this._options=i,this._lazy=!1,this._updatable=!1,this.intersectionThreshold=.1,this._lazy=(s=i.lazy)!==null&&s!==void 0?s:!1,this._updatable=(r=i.updatable)!==null&&r!==void 0?r:!1,this._vertexPositions=[],this._indices=[],this._uvs=[],this._points=[],this._colorPointers=(n=i.colorPointers)!==null&&n!==void 0?n:[],this._widths=(o=i.widths)!==null&&o!==void 0?o:new Array(i.points.length).fill(1),this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(ll.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}static ConvertPoints(e){if(e.length&&Array.isArray(e)&&typeof e[0]=="number")return[e];if(e.length&&Array.isArray(e[0])&&typeof e[0][0]=="number")return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof O){const t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof O){const t=[];return e.forEach(s=>{t.push(s.flatMap(r=>[r.x,r.y,r.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[]}updateLazy(){var e;this._setPoints(this._points),this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(),this.refreshBoundingInfo(),(e=this.greasedLineMaterial)===null||e===void 0||e.updateLazy()}dispose(){super.dispose()}isLazy(){return this._lazy}get offsets(){return this._offsets}set offsets(e){this._offsets=e,this._offsetsBuffer?this._offsetsBuffer&&this._offsetsBuffer.update(e):this._createOffsetsBuffer(e)}get widths(){return this._widths}set widths(e){this._widths=e,this._lazy||this._widthsBuffer&&this._widthsBuffer.update(e)}get colorPointers(){return this._colorPointers}set colorPointers(e){this._colorPointers=e,this._lazy||this._colorPointersBuffer&&this._colorPointersBuffer.update(e)}get greasedLineMaterial(){var e,t;if(this.material&&this.material instanceof G1)return this.material;const i=(t=(e=this.material)===null||e===void 0?void 0:e.pluginManager)===null||t===void 0?void 0:t.getPlugin(cl.GREASED_LINE_MATERIAL_NAME);if(i)return i}get points(){const e=[];return e2.DeepCopy(this._points,e),e}addPoints(e){for(const t of e)this._points.push(t);this._lazy||this.setPoints(this._points)}_updateColorPointers(){let e=0;this._colorPointers=[],this._points.forEach(t=>{for(let i=0;i{var s;const r=[],n=[],o=[],l=LM.GetLineLength(i);for(let m=0,_=0;_0&&(o=ll._CopyV3(l,e),i.push(o[0],o[1],o[2]),i.push(o[0],o[1],o[2]));return ll._CompareV3(n-1,0,e)?o=ll._CopyV3(1,e):o=ll._CopyV3(n-1,e),i.push(o[0],o[1],o[2]),i.push(o[0],o[1],o[2]),{previous:t,next:i,uvs:r,side:s}}_createVertexBuffers(){const e=new Jt;e.positions=this._vertexPositions,e.indices=this._indices,e.uvs=this._uvs,e.applyToMesh(this,this._options.updatable);const t=this._scene.getEngine(),i=new Q1(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));const s=new Q1(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(s.createVertexBuffer("grl_nextAndCounters",0,4));const r=new Q1(t,this._widths,this._updatable,1);this.setVerticesBuffer(r.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=r;const n=new Q1(t,this._colorPointers,this._updatable,1);this.setVerticesBuffer(n.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=n}_createOffsetsBuffer(e){const t=this._scene.getEngine(),i=new Q1(t,e,this._updatable,3);this.setVerticesBuffer(i.createVertexBuffer("grl_offsets",0,3)),this._offsetsBuffer=i}}ll._V_START=new O;ll._V_END=new O;ll._V_OFFSET_START=new O;ll._V_OFFSET_END=new O;var RM;(function(a){a[a.COLOR_DISTRIBUTION_NONE=0]="COLOR_DISTRIBUTION_NONE",a[a.COLOR_DISTRIBUTION_REPEAT=1]="COLOR_DISTRIBUTION_REPEAT",a[a.COLOR_DISTRIBUTION_EVEN=2]="COLOR_DISTRIBUTION_EVEN",a[a.COLOR_DISTRIBUTION_START=3]="COLOR_DISTRIBUTION_START",a[a.COLOR_DISTRIBUTION_END=4]="COLOR_DISTRIBUTION_END",a[a.COLOR_DISTRIBUTION_START_END=5]="COLOR_DISTRIBUTION_START_END"})(RM||(RM={}));var q9;(function(a){a[a.WIDTH_DISTRIBUTION_NONE=0]="WIDTH_DISTRIBUTION_NONE",a[a.WIDTH_DISTRIBUTION_REPEAT=1]="WIDTH_DISTRIBUTION_REPEAT",a[a.WIDTH_DISTRIBUTION_EVEN=2]="WIDTH_DISTRIBUTION_EVEN",a[a.WIDTH_DISTRIBUTION_START=3]="WIDTH_DISTRIBUTION_START",a[a.WIDTH_DISTRIBUTION_END=4]="WIDTH_DISTRIBUTION_END",a[a.WIDTH_DISTRIBUTION_START_END=5]="WIDTH_DISTRIBUTION_START_END"})(q9||(q9={}));function jue(a,e,t){t=t??Ii.LastCreatedScene;let i;switch(e.materialType){case YB.MATERIAL_TYPE_PBR:i=new ji(a,t),new cl(i,t,e);break;case YB.MATERIAL_TYPE_SIMPLE:i=new G1(a,t,e);break;default:i=new jt(a,t),new cl(i,t,e);break}return i}function qee(a,e,t,i){var s,r,n,o,l,c;i=i??Ii.LastCreatedScene;let h;const u=ll.ConvertPoints(e.points);let p=0;Array.isArray(u[0])&&u.forEach(f=>{p+=f.length/3}),e.widthDistribution=(s=e.widthDistribution)!==null&&s!==void 0?s:q9.WIDTH_DISTRIBUTION_START,t=t??{color:cl.DEFAULT_COLOR},t.createAndAssignMaterial=(r=t.createAndAssignMaterial)!==null&&r!==void 0?r:!0,t.colorDistribution=(n=t?.colorDistribution)!==null&&n!==void 0?n:RM.COLOR_DISTRIBUTION_START,t.materialType=(o=t.materialType)!==null&&o!==void 0?o:YB.MATERIAL_TYPE_STANDARD;const m=Gue(p,(l=e.widths)!==null&&l!==void 0?l:[],e.widthDistribution),_=t?.colors?Wue(p,t.colors,t.colorDistribution,(c=t.color)!==null&&c!==void 0?c:cl.DEFAULT_COLOR):void 0;if(e.instance){h=e.instance;const f=h.widths;if(f){const d=f.slice();for(const C of m)d.push(C);h.widths=d}else h.widths=m;h.addPoints(u)}else{const f={points:u,updatable:e.updatable,widths:m,lazy:e.lazy};if(h=new ll(a,i,f),t){const d={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:_};if(t.createAndAssignMaterial){const C=jue(a,d,i);h.material=C}}}if(_&&e.instance&&e.instance.greasedLineMaterial){const f=e.instance.greasedLineMaterial.colors;if(f){const d=f.concat(_);e.instance.greasedLineMaterial.setColors(d,h.isLazy())}}return h}function Gue(a,e,t,i=1,s=1){const r=a-e.length/2,n=[];if(r<0)return e.slice(0,a*2);if(r>0){if(t===q9.WIDTH_DISTRIBUTION_START_END){const o=Math.floor(e.length/2);for(let h=0,u=0;h0){if(t===RM.COLOR_DISTRIBUTION_START_END){const n=Math.floor(e.length/2);for(let o=0;o=this._thinInstanceDataStorage.instancesCount)return!1;const i=this._thinInstanceDataStorage.matrixData;return e.copyToArray(i,a*16),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[a]=e),t&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0};Oe.prototype.thinInstanceSetAttributeAt=function(a,e,t,i=!0){return a===se.ColorKind&&(a=se.ColorInstanceKind),!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[a]||e>=this._thinInstanceDataStorage.instancesCount?!1:(this._thinInstanceUpdateBufferSize(a,0),this._userThinInstanceBuffersStorage.data[a].set(t,e*this._userThinInstanceBuffersStorage.strides[a]),i&&this.thinInstanceBufferUpdated(a),!0)};Object.defineProperty(Oe.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(a){var e,t;const i=(e=this._thinInstanceDataStorage.matrixData)!==null&&e!==void 0?e:(t=this.source)===null||t===void 0?void 0:t._thinInstanceDataStorage.matrixData,s=i?i.length/16:0;a<=s&&(this._thinInstanceDataStorage.instancesCount=a)},enumerable:!0,configurable:!0});Oe.prototype._thinInstanceCreateMatrixBuffer=function(a,e,t=!1){a===se.ColorKind&&(a=se.ColorInstanceKind);const i=new Q1(this.getEngine(),e,!t,16,!1,!0);for(let s=0;s<4;s++)this.setVerticesBuffer(i.createVertexBuffer(a+s,s*4,4));return i};Oe.prototype.thinInstanceSetBuffer=function(a,e,t=0,i=!1){var s,r,n;t=t||16,a==="matrix"?((s=this._thinInstanceDataStorage.matrixBuffer)===null||s===void 0||s.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())):a==="previousMatrix"?((r=this._thinInstanceDataStorage.previousMatrixBuffer)===null||r===void 0||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=e,e!==null&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",e,i))):(a===se.ColorKind&&(a=se.ColorInstanceKind),e===null?!((n=this._userThinInstanceBuffersStorage)===null||n===void 0)&&n.data[a]&&(this.removeVerticesData(a),delete this._userThinInstanceBuffersStorage.data[a],delete this._userThinInstanceBuffersStorage.strides[a],delete this._userThinInstanceBuffersStorage.sizes[a],delete this._userThinInstanceBuffersStorage.vertexBuffers[a]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[a]=e,this._userThinInstanceBuffersStorage.strides[a]=t,this._userThinInstanceBuffersStorage.sizes[a]=e.length,this._userThinInstanceBuffersStorage.vertexBuffers[a]=new se(this.getEngine(),e,a,!i,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[a])))};Oe.prototype.thinInstanceBufferUpdated=function(a){var e,t,i;a==="matrix"?(e=this._thinInstanceDataStorage.matrixBuffer)===null||e===void 0||e.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):a==="previousMatrix"?(t=this._thinInstanceDataStorage.previousMatrixBuffer)===null||t===void 0||t.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(a===se.ColorKind&&(a=se.ColorInstanceKind),!((i=this._userThinInstanceBuffersStorage)===null||i===void 0)&&i.vertexBuffers[a]&&this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(this._userThinInstanceBuffersStorage.data[a],0))};Oe.prototype.thinInstancePartialBufferUpdate=function(a,e,t){var i;a==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(e,t):(a===se.ColorKind&&(a=se.ColorInstanceKind),!((i=this._userThinInstanceBuffersStorage)===null||i===void 0)&&i.vertexBuffers[a]&&this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(e,t))};Oe.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const a=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=new Array;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}getConnectedValue(e){var t,i,s;return this.isConnected?!((t=this._connectedPoint)===null||t===void 0)&&t._storedFunction?(i=this._connectedPoint)===null||i===void 0?void 0:i._storedFunction(e):(s=this._connectedPoint)===null||s===void 0?void 0:s._storedValue:this.value}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=Ge.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=new Array,this.excludedConnectionPointTypes=new Array,this.onConnectionObservable=new Se,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===W9.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==Ge.AutoDetect)return e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1?W9.Compatible:W9.TypeIncompatible;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return W9.TypeIncompatible;let s=i,r=t;return this.direction===XB.Input&&(s=t,r=i),s.isAnAncestorOf(r)?W9.HierarchyIssue:W9.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&&!this._outputs.some(i=>i.hasEndpoints)&&!this.isDebug)return!1;this._buildId=e.buildId;for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.notConnectedNonOptionalInputs.push(i);continue}const s=i.connectedPoint.ownerBlock;s&&s!==this&&s.build(e)}this._customBuildStep(e),e.verbose&&console.log(`Building ${this.name} [${this.getClassName()}]`);const t=Zr.Now;this._buildBlock(e),this._buildExecutionTime=Zr.Now-t;for(const i of this._outputs)for(const s of i.endpoints){const r=s.ownerBlock;r&&r.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(e){const t={};t.customType="BABYLON."+this.getClassName(),t.id=this.uniqueId,t.name=this.name,t.inputs=[],t.outputs=[];for(const i of this.inputs)t.inputs.push(i.serialize());for(const i of this.outputs)t.outputs.push(i.serialize(!1));return t}_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(s=>{const r=this.inputs.find(n=>n.name===s.name);if(!!r&&(s.displayName&&(r.displayName=s.displayName),s.isExposedOnFrame&&(r.isExposedOnFrame=s.isExposedOnFrame,r.exposedPortPosition=s.exposedPortPosition),s.value!==void 0&&s.value!==null))if(s.valueType==="number")r.value=s.value;else{const n=Bo(s.valueType);n&&(r.value=n.FromArray(s.value))}}),i&&i.forEach((s,r)=>{s.displayName&&(this.outputs[r].displayName=s.displayName),s.isExposedOnFrame&&(this.outputs[r].isExposedOnFrame=s.isExposedOnFrame,this.outputs[r].exposedPortPosition=s.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 s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.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 r=0;do r++,this._codeVariableName=i+r;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let s=` +// ${this.getClassName()} +`;this.comments&&(s+=`// ${this.comments} +`),s+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); +`,s+=this._dumpPropertiesCode();for(const r of this.inputs){if(!r.isConnected)continue;const o=r.connectedPoint.ownerBlock;t.indexOf(o)===-1&&(s+=o._dumpCode(e,t))}for(const r of this.outputs)if(!!r.hasEndpoints)for(const n of r.endpoints){const o=n.ownerBlock;o&&t.indexOf(o)===-1&&(s+=o._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=Bo(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()}}z([X("comment")],Vr.prototype,"comments",void 0);class Jee extends Vr{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",Ge.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}$e("BABYLON.GeometryOutputBlock",Jee);var Pn;(function(a){a[a.None=0]="None",a[a.Positions=1]="Positions",a[a.Normals=2]="Normals",a[a.Tangents=3]="Tangents",a[a.UV=4]="UV",a[a.UV2=5]="UV2",a[a.UV3=6]="UV3",a[a.UV4=7]="UV4",a[a.UV5=8]="UV5",a[a.UV6=9]="UV6",a[a.Colors=10]="Colors",a[a.VertexID=11]="VertexID",a[a.FaceID=12]="FaceID",a[a.GeometryID=13]="GeometryID",a[a.CollectionID=14]="CollectionID",a[a.LoopID=15]="LoopID",a[a.InstanceID=16]="InstanceID"})(Pn||(Pn={}));class Yue{constructor(){this._rotationMatrix=new ge,this._scalingMatrix=new ge,this._positionMatrix=new ge,this._scalingRotationMatrix=new ge,this._transformMatrix=new ge,this._tempVector3=new O,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 Pn.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():!this.geometryContext||!this.geometryContext.positions?O.Zero():O.FromArray(this.geometryContext.positions,i*3);case Pn.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():!this.geometryContext||!this.geometryContext.normals?O.Zero():O.FromArray(this.geometryContext.normals,i*3);case Pn.Colors:return!this.geometryContext||!this.geometryContext.colors?Ui.Zero():Ui.FromArray(this.geometryContext.colors,i*4);case Pn.Tangents:return!this.geometryContext||!this.geometryContext.tangents?Ui.Zero():Ui.FromArray(this.geometryContext.tangents,i*4);case Pn.UV:return!this.geometryContext||!this.geometryContext.uvs?lt.Zero():lt.FromArray(this.geometryContext.uvs,i*2);case Pn.UV2:return!this.geometryContext||!this.geometryContext.uvs2?lt.Zero():lt.FromArray(this.geometryContext.uvs2,i*2);case Pn.UV3:return!this.geometryContext||!this.geometryContext.uvs3?lt.Zero():lt.FromArray(this.geometryContext.uvs3,i*2);case Pn.UV4:return!this.geometryContext||!this.geometryContext.uvs4?lt.Zero():lt.FromArray(this.geometryContext.uvs4,i*2);case Pn.UV5:return!this.geometryContext||!this.geometryContext.uvs5?lt.Zero():lt.FromArray(this.geometryContext.uvs5,i*2);case Pn.UV6:return!this.geometryContext||!this.geometryContext.uvs6?lt.Zero():lt.FromArray(this.geometryContext.uvs6,i*2);case Pn.VertexID:return i;case Pn.FaceID:return this.executionContext.getExecutionFaceIndex();case Pn.LoopID:return this.executionContext.getExecutionLoopIndex();case Pn.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case Pn.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case Pn.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 Ge.Vector2:return new lt(i,i);case Ge.Vector3:return new O(i,i,i);case Ge.Vector4:return new Ui(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||s===void 0?void 0:s.type)===t)return r;switch(t){case Ge.Vector2:return new lt(r,r);case Ge.Vector3:return new O(r,r,r);case Ge.Vector4:return new Ui(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 ${Pn[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,s,r){ge.ScalingToRef(s.x,s.y,s.z,this._scalingMatrix),ge.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),ge.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 n=0;nt.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.${Pn[this._contextualSource]}; +`;const t=[];let i="";switch(this.type){case Ge.Float:case Ge.Int:i=`${this.value}`;break;case Ge.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case Ge.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case Ge.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===Ge.Float||this.type===Ge.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=Bo(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}$e("BABYLON.GeometryInputBlock",Lc);class pQ extends Vr{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",Ge.Float,!0,1),this.registerInput("width",Ge.Float,!0,0),this.registerInput("height",Ge.Float,!0,0),this.registerInput("depth",Ge.Float,!0,0),this.registerInput("subdivisions",Ge.Int,!0,1),this.registerInput("subdivisionsX",Ge.Int,!0,0),this.registerInput("subdivisionsY",Ge.Int,!0,0),this.registerInput("subdivisionsZ",Ge.Int,!0,0),this.registerOutput("geometry",Ge.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 Lc("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new Lc("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Lc("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new Lc("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=s=>{t.size=this.size.getConnectedValue(s),t.width=this.width.getConnectedValue(s),t.height=this.height.getConnectedValue(s),t.depth=this.depth.getConnectedValue(s);const r=this.subdivisions.getConnectedValue(s),n=this.subdivisionsX.getConnectedValue(s),o=this.subdivisionsY.getConnectedValue(s),l=this.subdivisionsZ.getConnectedValue(s);return r&&(t.segments=r),n&&(t.widthSegments=n),o&&(t.heightSegments=o),l&&(t.depthSegments=l),Ece(t)};this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedFunction=()=>i(e).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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],pQ.prototype,"evaluateContext",void 0);$e("BABYLON.BoxBlock",pQ);class Q3{_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=Q3._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=new Array,this.onBuildObservable=new Se,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 Be.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:Q3.EditorURL;Be.LoadScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e?.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(e?.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){const t=Object.assign({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 s=Zr.Now;this._initializeBlock(this.outputBlock,i);const r=new Yue;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=Q3._BuildIdGenerator++),this._buildExecutionTime=Zr.Now-s,r.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=r.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new Oe(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 s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._initializeBlock(r,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 s of e.blocks){const r=Bo(s.customType);if(r){const n=new r;n._deserialize(s),i[s.id]=n,this.attachedBlocks.push(n)}}for(const s of this.attachedBlocks)if(s.isTeleportOut){const r=s,n=r._tempEntryPointUniqueId;n&&i[n].attachToEndpoint(r)}for(let s=0;so.targetConnectionName)&&!t||this._restoreConnections(n,e,i)}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const s=e.locations||e.editorData.locations;for(const n of s)i[n.blockId]&&(n.blockId=i[n.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&s.concat(this.editorData.locations),e.locations?this.editorData={locations:s}:(this.editorData=e.editorData,this.editorData.locations=s);const r=[];for(const n in i)r[n]=i[n].uniqueId;this.editorData.map=r}this.comment=e.comment}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(!!n){for(const o of r.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===s.name){const l=n.getInputByName(o.inputName);if(!l||l.isConnected)continue;s.connectTo(l,!0),this._restoreConnections(n,t,i);continue}}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let s=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); +`;for(const r of t)r.isInput&&e.indexOf(r)===-1&&(s+=r._dumpCode(i,e));return this.outputBlock&&(e=[],s+=`// Connections +`,s+=this.outputBlock._dumpCodeForOutputConnections(e),s+=`// Output nodes +`,s+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; +`,s+=`nodeGeometry.build(); +`),s}_gatherBlocks(e,t){if(t.indexOf(e)===-1){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._gatherBlocks(r,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new pQ("Box");e.autoConfigure();const t=new Jee("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=Kt.Clone(()=>new Q3(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e,t){const i=t?{}:Kt.Serialize(this);i.editorData=JSON.parse(JSON.stringify(this.editorData));let s=[];t?s=t:(i.customType="BABYLON.NodeGeometry",this.outputBlock&&(i.outputNodeId=this.outputBlock.uniqueId)),i.blocks=[];for(const r of s)i.blocks.push(r.serialize(e));if(!t)for(const r of this.attachedBlocks)s.indexOf(r)===-1&&i.blocks.push(r.serialize(e));return i}dispose(){for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){const t=new Q3(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=Kt.Parse(()=>new Q3(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return e==="_BLANK"?Promise.resolve(Q3.CreateDefault("blank")):new Promise((s,r)=>{const n=new wl;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(o.nodeGeometry);t||(t=Kt.Parse(()=>new Q3(e),l,null)),t.parseSerializedObject(l),t.snippetId=e;try{i||t.build(),s(t)}catch(c){r(c)}}else r("Unable to load the snippet "+e)}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}Q3._BuildIdGenerator=0;Q3.EditorURL=`https://unpkg.com/babylonjs-node-geometry-editor@${He.Version}/babylon.nodeGeometryEditor.js`;Q3.SnippetUrl="https://snippet.babylonjs.com";z([X()],Q3.prototype,"name",void 0);z([X("comment")],Q3.prototype,"comment",void 0);class mQ extends Vr{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=Ls,this.registerInput("geometry",Ge.Geometry),this.registerOutput("output",Ge.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 s=this.geometry.getConnectedValue(i),r=[],n={};for(let l=0;ln[l]),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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mQ.prototype,"evaluateContext",void 0);z([ws("Epsilon",Ms.Float,"ADVANCED",{notifiers:{rebuild:!0}})],mQ.prototype,"epsilon",void 0);$e("BABYLON.GeometryOptimizeBlock",mQ);class $ee extends Vr{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",Ge.Float,!0,1),this.registerInput("width",Ge.Float,!0,0),this.registerInput("height",Ge.Float,!0,0),this.registerOutput("geometry",Ge.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 Lc("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new Lc("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Lc("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=s=>(t.size=this.size.getConnectedValue(s),t.width=this.width.getConnectedValue(s),t.height=this.height.getConnectedValue(s),MK(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedFunction=()=>i(e).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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],$ee.prototype,"evaluateContext",void 0);$e("BABYLON.PlaneBlock",$ee);class Xue extends Vr{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.registerOutput("geometry",Ge.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}const e=Jt.ExtractFromMesh(this._mesh,!1,!0);this._cachedVertexData=null,this.geometry._storedFunction=()=>e.clone()}serialize(e){const t=super.serialize();return e&&(this._mesh?t.cachedVertexData=Jt.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(t.cachedVertexData=this._cachedVertexData.serialize())),t}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=Jt.Parse(e.cachedVertexData))}}$e("BABYLON.MeshBlock",Xue);class ete extends Vr{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",Ge.Float,!0,1),this.registerInput("radiusX",Ge.Float,!0,0),this.registerInput("radiusY",Ge.Float,!0,0),this.registerInput("radiusZ",Ge.Float,!0,0),this.registerInput("subdivisions",Ge.Int,!0,4),this.registerOutput("geometry",Ge.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 Lc("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=s=>(t.radius=this.radius.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),t.radiusX=this.radiusX.getConnectedValue(s),t.radiusY=this.radiusY.getConnectedValue(s),t.radiusZ=this.radiusZ.getConnectedValue(s),SK(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedFunction=()=>i(e).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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ete.prototype,"evaluateContext",void 0);$e("BABYLON.IcoSphereBlock",ete);class tte extends Vr{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",Ge.Int,!0,32),this.registerInput("diameter",Ge.Float,!0,1),this.registerInput("diameterX",Ge.Float,!0,0),this.registerInput("diameterY",Ge.Float,!0,0),this.registerInput("diameterZ",Ge.Float,!0,0),this.registerInput("arc",Ge.Float,!0,1),this.registerInput("slice",Ge.Float,!0,1),this.registerOutput("geometry",Ge.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 Lc("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=s=>(t.segments=this.segments.getConnectedValue(s),t.diameter=this.diameter.getConnectedValue(s),t.diameterX=this.diameterX.getConnectedValue(s),t.diameterY=this.diameterY.getConnectedValue(s),t.diameterZ=this.diameterZ.getConnectedValue(s),t.arc=this.arc.getConnectedValue(s),t.slice=this.slice.getConnectedValue(s),UK(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedFunction=()=>i(e).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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],tte.prototype,"evaluateContext",void 0);$e("BABYLON.SphereBlock",tte);class ite extends Vr{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",Ge.Float,!0,1),this.registerInput("height",Ge.Float,!0,1),this.registerInput("subdivisions",Ge.Int,!0,1),this.registerInput("subdivisionsX",Ge.Int,!0,0),this.registerInput("subdivisionsY",Ge.Int,!0,0),this.registerOutput("geometry",Ge.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 Lc("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Lc("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=s=>(t.width=this.width.getConnectedValue(s),t.height=this.height.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),t.subdivisionsX=this.subdivisionsX.getConnectedValue(s),t.subdivisionsY=this.subdivisionsY.getConnectedValue(s),SM(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedFunction=()=>i(e).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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ite.prototype,"evaluateContext",void 0);$e("BABYLON.GridBlock",ite);class ste extends Vr{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",Ge.Float,!0,1),this.registerInput("thickness",Ge.Float,!0,.5),this.registerInput("tessellation",Ge.Int,!0,16),this.registerOutput("geometry",Ge.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 Lc("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=s=>(t.thickness=this.thickness.getConnectedValue(s),t.diameter=this.diameter.getConnectedValue(s),t.tessellation=this.tessellation.getConnectedValue(s),BK(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedFunction=()=>i(e).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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ste.prototype,"evaluateContext",void 0);$e("BABYLON.TorusBlock",ste);class rte extends Vr{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",Ge.Float,!0,25),this.registerInput("diameter",Ge.Float,!0,1),this.registerInput("diameterTop",Ge.Float,!0,-1),this.registerInput("diameterBottom",Ge.Float,!0,-1),this.registerInput("subdivisions",Ge.Int,!0,1),this.registerInput("tessellation",Ge.Int,!0,24),this.registerInput("arc",Ge.Float,!0,1),this.registerOutput("geometry",Ge.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 Lc("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new Lc("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=s=>(t.height=this.height.getConnectedValue(s),t.diameter=this.diameter.getConnectedValue(s),t.diameterTop=this.diameterTop.getConnectedValue(s),t.diameterBottom=this.diameterBottom.getConnectedValue(s),t.diameterTop===-1&&(t.diameterTop=t.diameter),t.diameterBottom===-1&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),t.arc=this.arc.getConnectedValue(s),NK(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedFunction=()=>i(e).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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],rte.prototype,"evaluateContext",void 0);$e("BABYLON.CylinderBlock",rte);class nte extends Vr{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",Ge.Float,!0,1),this.registerInput("radius",Ge.Float,!0,.25),this.registerInput("tessellation",Ge.Int,!0,16),this.registerInput("subdivisions",Ge.Int,!0,2),this.registerOutput("geometry",Ge.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 Lc("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new Lc("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=s=>(t.height=this.height.getConnectedValue(s),t.radius=this.radius.getConnectedValue(s),t.tessellation=this.tessellation.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),kK(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedFunction=()=>i(e).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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],nte.prototype,"evaluateContext",void 0);$e("BABYLON.CapsuleBlock",nte);class ate extends Vr{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",Ge.Float,!0,.5),this.registerInput("tessellation",Ge.Int,!0,64),this.registerInput("arc",Ge.Float,!0,1),this.registerOutput("geometry",Ge.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 Lc("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=s=>(t.radius=this.radius.getConnectedValue(s),t.tessellation=this.tessellation.getConnectedValue(s),t.arc=this.arc.getConnectedValue(s),jK(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedFunction=()=>i(e).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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ate.prototype,"evaluateContext",void 0);$e("BABYLON.DiscBlock",ate);class Kue extends Vr{constructor(e){super(e),this.registerOutput("geometry",Ge.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}$e("BABYLON.NullBlock",Kue);class ote extends Vr{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",Ge.Geometry),this.registerInput("positions",Ge.Vector3),this.registerOutput("output",Ge.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),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}const s=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),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 s=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),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 s=[],r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),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 s=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),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 s=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndext.getConnectedValue(r)+i.getConnectedValue(r):e=r=>t.getConnectedValue(r).add(r.adapt(i,t.type));break}case Kf.Subtract:{s?e=r=>t.getConnectedValue(r)-i.getConnectedValue(r):e=r=>t.getConnectedValue(r).subtract(r.adapt(i,t.type));break}case Kf.Multiply:{s?e=r=>t.getConnectedValue(r)*i.getConnectedValue(r):e=r=>t.getConnectedValue(r).multiply(r.adapt(i,t.type));break}case Kf.Divide:{s?e=r=>t.getConnectedValue(r)/i.getConnectedValue(r):e=r=>t.getConnectedValue(r).divide(r.adapt(i,t.type));break}case Kf.Min:{if(s)e=r=>Math.min(t.getConnectedValue(r),i.getConnectedValue(r));else switch(t.type){case Ge.Vector2:{e=r=>lt.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}case Ge.Vector3:{e=r=>O.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}case Ge.Vector4:{e=r=>Ui.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}}break}case Kf.Max:if(s)e=r=>Math.max(t.getConnectedValue(r),i.getConnectedValue(r));else{switch(t.type){case Ge.Vector2:{e=r=>lt.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}case Ge.Vector3:{e=r=>O.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}case Ge.Vector4:{e=r=>Ui.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}}break}}this.output._storedFunction=r=>t.type===Ge.Int?e(r)|0:e(r)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${Kf[this.operation]}; +`}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}z([ws("Operation",Ms.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:Kf.Add},{label:"Subtract",value:Kf.Subtract},{label:"Multiply",value:Kf.Multiply},{label:"Divide",value:Kf.Divide},{label:"Max",value:Kf.Max},{label:"Min",value:Kf.Min}]})],ute.prototype,"operation",void 0);$e("BABYLON.MathBlock",ute);class Que extends Vr{constructor(e){super(e),this.registerInput("value",Ge.AutoDetect),this.registerInput("fromMin",Ge.Float,!0,0),this.registerInput("fromMax",Ge.Float,!0,1),this.registerInput("toMin",Ge.Float,!0,0),this.registerInput("toMax",Ge.Float,!0,1),this.registerOutput("output",Ge.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(Ge.Vector2),this._inputs[0].excludedConnectionPointTypes.push(Ge.Vector3),this._inputs[0].excludedConnectionPointTypes.push(Ge.Vector4),this._inputs[0].excludedConnectionPointTypes.push(Ge.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Ge.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Ge.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),s=this.fromMax.getConnectedValue(e),r=this.toMin.getConnectedValue(e),n=this.toMax.getConnectedValue(e),o=(t-i)/(s-i)*(n-r)+r;return this.output.type===Ge.Int?Math.floor(o):o}}}$e("BABYLON.MapRangeBlock",Que);var su;(function(a){a[a.Equal=0]="Equal",a[a.NotEqual=1]="NotEqual",a[a.LessThan=2]="LessThan",a[a.GreaterThan=3]="GreaterThan",a[a.LessOrEqual=4]="LessOrEqual",a[a.GreaterOrEqual=5]="GreaterOrEqual",a[a.Xor=6]="Xor",a[a.Or=7]="Or",a[a.And=8]="And"})(su||(su={}));class dte extends Vr{constructor(e){super(e),this.test=su.Equal,this.registerInput("left",Ge.Float),this.registerInput("right",Ge.Float,!0,0),this.registerInput("ifTrue",Ge.AutoDetect,!0,1),this.registerInput("ifFalse",Ge.AutoDetect,!0,0),this.registerOutput("output",Ge.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=Ge.Float,this._inputs[0].acceptedConnectionPointTypes.push(Ge.Int),this._inputs[1].acceptedConnectionPointTypes.push(Ge.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),s=this.right.getConnectedValue(t);let r=!1;switch(this.test){case su.Equal:r=Bt.WithinEpsilon(i,s,Ls);break;case su.NotEqual:r=i!==s;break;case su.LessThan:r=is;break;case su.LessOrEqual:r=i<=s;break;case su.GreaterOrEqual:r=i>=s;break;case su.Xor:r=!!i&&!s||!i&&!!s;break;case su.Or:r=!!i||!!s;break;case su.And:r=!!i&&!!s;break}return r};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${su[this.test]}; +`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}z([ws("Test",Ms.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:su.Equal},{label:"NotEqual",value:su.NotEqual},{label:"LessThan",value:su.LessThan},{label:"GreaterThan",value:su.GreaterThan},{label:"LessOrEqual",value:su.LessOrEqual},{label:"GreaterOrEqual",value:su.GreaterOrEqual},{label:"Xor",value:su.Xor},{label:"Or",value:su.Or},{label:"And",value:su.And}]})],dte.prototype,"test",void 0);$e("BABYLON.ConditionBlock",dte);var Hb;(function(a){a[a.None=0]="None",a[a.LoopID=1]="LoopID",a[a.InstanceID=2]="InstanceID"})(Hb||(Hb={}));class fte extends Vr{constructor(e){super(e),this._currentLockId=-1,this.lockMode=Hb.None,this.registerInput("min",Ge.AutoDetect),this.registerInput("max",Ge.AutoDetect),this.registerOutput("output",Ge.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(Ge.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Ge.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Ge.Texture),this._inputs[1].excludedConnectionPointTypes.push(Ge.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Ge.Geometry),this._inputs[1].excludedConnectionPointTypes.push(Ge.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 Lc("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new Lc("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case Ge.Int:case Ge.Float:{e=t=>{const i=this.min.getConnectedValue(t)||0,s=this.max.getConnectedValue(t)||0;return i+Math.random()*(s-i)};break}case Ge.Vector2:{e=t=>{const i=this.min.getConnectedValue(t)||lt.Zero(),s=this.max.getConnectedValue(t)||lt.Zero();return new lt(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y))};break}case Ge.Vector3:{e=t=>{const i=this.min.getConnectedValue(t)||O.Zero(),s=this.max.getConnectedValue(t)||O.Zero();return new O(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y),i.z+Math.random()*(s.z-i.z))};break}case Ge.Vector4:{e=t=>{const i=this.min.getConnectedValue(t)||Ui.Zero(),s=this.max.getConnectedValue(t)||Ui.Zero();return new Ui(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y),i.z+Math.random()*(s.z-i.z),i.w+Math.random()*(s.w-i.w))};break}}this.lockMode===Hb.None||!e?this.output._storedFunction=e:this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case Hb.InstanceID:i=t.getContextualValue(Pn.InstanceID,!0)||0;break;case Hb.LoopID:i=t.getContextualValue(Pn.LoopID,!0)||0;break}return this._currentLockId!==i&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${Hb[this.lockMode]}; +`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}z([ws("LockMode",Ms.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:Hb.None},{label:"LoopID",value:Hb.LoopID},{label:"InstanceID",value:Hb.InstanceID}]})],fte.prototype,"lockMode",void 0);$e("BABYLON.RandomBlock",fte);class Zue extends Vr{constructor(e){super(e),this.registerInput("offset",Ge.Vector3,!0,O.Zero()),this.registerInput("scale",Ge.Float,!0,1),this.registerInput("octaves",Ge.Float,!0,2,0,16),this.registerInput("roughness",Ge.Float,!0,.5,0,1),this.registerOutput("output",Ge.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,s){const r=e&15,n=r<8?t:i,o=r===12||r==14?t:s,l=r<4?i:o;return this._negateIf(n,r&n)+this._negateIf(l,r&2)}_fade(e){return e*e*e*(e*(e*6-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928559+(3<<2)+13,n+=i,r+=t,s+=e,n^=r,n-=this._hashBitRotate(r,14),s^=n,s-=this._hashBitRotate(n,11),r^=s,r-=this._hashBitRotate(s,25),n^=r,n-=this._hashBitRotate(r,16),s^=n,s-=this._hashBitRotate(n,4),r^=s,r-=this._hashBitRotate(s,14),n^=r,n-=this._hashBitRotate(r,24),n}_mix(e,t,i,s,r,n,o,l,c,h,u){const p=1-c,m=1-h;return(1-u)*(m*(e*p+t*c)+h*(i*p+s*c))+u*(m*(r*p+n*c)+h*(o*p+l*c))}_perlinNoise(e){const t=(e.x|0)-(e.x<0?1:0),i=(e.y|0)-(e.y<0?1:0),s=(e.z|0)-(e.z<0?1:0),r=e.x-t,n=e.y-i,o=e.z-s,l=this._fade(r),c=this._fade(n),h=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,o),this._noiseGrad(this._hash(t+1,i,s),r-1,n,o),this._noiseGrad(this._hash(t,i+1,s),r,n-1,o),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,o),this._noiseGrad(this._hash(t,i,s+1),r,n,o-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,o-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,o-1),l,c,h)}_perlinSigned(e){return this._perlinNoise(e)*.982}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,s,r){const n=new O(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let o=1,l=1,c=0,h=0;e=Bt.Clamp(e,0,15);const u=e|0;for(let f=0;f<=u;f++){const d=this._perlin(n.scale(o));h+=d*l,c+=l,l*=Bt.Clamp(t,0,1),o*=2}const p=e-Math.floor(e);if(p==0)return h/c;const m=this._perlin(n.scale(o));let _=h+m*l;return h/=c,_/=c+l,(1-p)*h+p*_}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(Pn.Positions),i=this.octaves.getConnectedValue(e),s=this.roughness.getConnectedValue(e),r=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,s,t,r,n)}}}$e("BABYLON.NoiseBlock",Zue);class pte extends Vr{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",Ge.Geometry),this.registerInput("geometry1",Ge.Geometry,!0),this.registerInput("geometry2",Ge.Geometry,!0),this.registerInput("geometry3",Ge.Geometry,!0),this.registerInput("geometry4",Ge.Geometry,!0),this.registerOutput("output",Ge.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}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 s=this.geometry0.getConnectedValue(i);const r=[];return this.geometry1.isConnected&&r.push(this.geometry1.getConnectedValue(i)),this.geometry2.isConnected&&r.push(this.geometry2.getConnectedValue(i)),this.geometry3.isConnected&&r.push(this.geometry3.getConnectedValue(i)),this.geometry4.isConnected&&r.push(this.geometry4.getConnectedValue(i)),r.length&&s&&(s=s.merge(r,!0,!1,!0,!0)),s};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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],pte.prototype,"evaluateContext",void 0);$e("BABYLON.MergeGeometryBlock",pte);class mte extends Vr{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",Ge.Geometry,!0),this.registerInput("geometry1",Ge.Geometry,!0),this.registerInput("geometry2",Ge.Geometry,!0),this.registerInput("geometry3",Ge.Geometry,!0),this.registerInput("geometry4",Ge.Geometry,!0),this.registerInput("geometry5",Ge.Geometry,!0),this.registerInput("geometry6",Ge.Geometry,!0),this.registerInput("geometry7",Ge.Geometry,!0),this.registerInput("geometry8",Ge.Geometry,!0),this.registerInput("geometry9",Ge.Geometry,!0),this.registerOutput("output",Ge.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,s){if(e.isConnected){const r=e.getConnectedValue(t);r.metadata=r.metadata||{},r.metadata.collectionId=i,s.push(r)}}_buildBlock(e){const t=i=>{const s=[];return this._storeGeometry(this.geometry0,i,0,s),this._storeGeometry(this.geometry1,i,1,s),this._storeGeometry(this.geometry2,i,2,s),this._storeGeometry(this.geometry3,i,3,s),this._storeGeometry(this.geometry4,i,4,s),this._storeGeometry(this.geometry5,i,5,s),this._storeGeometry(this.geometry6,i,6,s),this._storeGeometry(this.geometry7,i,7,s),this._storeGeometry(this.geometry8,i,8,s),this._storeGeometry(this.geometry9,i,9,s),s.length?s[Math.round(Math.random()*(s.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}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mte.prototype,"evaluateContext",void 0);$e("BABYLON.GeometryCollectionBlock",mte);class que extends Vr{constructor(e){super(e),this.registerInput("input",Ge.AutoDetect),this.registerOutput("output",Ge.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=s=>i.getConnectedValue(s)}}$e("BABYLON.GeometryElbowBlock",que);class Jue extends Vr{constructor(e){super(e),this.registerInput("geometry",Ge.Geometry),this.registerOutput("output",Ge.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=[]),Jt.ComputeNormals(t.positions,t.indices,t.normals),t}}}$e("BABYLON.ComputeNormalsBlock",Jue);class $ue extends Vr{constructor(e){super(e),this.registerInput("xyzw ",Ge.Vector4,!0),this.registerInput("xyz ",Ge.Vector3,!0),this.registerInput("xy ",Ge.Vector2,!0),this.registerInput("zw ",Ge.Vector2,!0),this.registerInput("x ",Ge.Float,!0),this.registerInput("y ",Ge.Float,!0),this.registerInput("z ",Ge.Float,!0),this.registerInput("w ",Ge.Float,!0),this.registerOutput("xyzw",Ge.Vector4),this.registerOutput("xyz",Ge.Vector3),this.registerOutput("xy",Ge.Vector2),this.registerOutput("zw",Ge.Vector2),this.registerOutput("x",Ge.Float),this.registerOutput("y",Ge.Float),this.registerOutput("z",Ge.Float),this.registerOutput("w",Ge.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,s=this.zIn,r=this.wIn,n=this.xyIn,o=this.zwIn,l=this.xyzIn,c=this.xyzwIn,h=this.xyzwOut,u=this.xyzOut,p=this.xyOut,m=this.zwOut,_=this.xOut,f=this.yOut,d=this.zOut,C=this.wOut,v=y=>{if(c.isConnected)return c.getConnectedValue(y);let M=0,b=0,E=0,S=0;if(t.isConnected&&(M=t.getConnectedValue(y)),i.isConnected&&(b=i.getConnectedValue(y)),s.isConnected&&(E=s.getConnectedValue(y)),r.isConnected&&(S=r.getConnectedValue(y)),n.isConnected){const I=n.getConnectedValue(y);I&&(M=I.x,b=I.y)}if(o.isConnected){const I=o.getConnectedValue(y);I&&(E=I.x,S=I.y)}if(l.isConnected){const I=l.getConnectedValue(y);I&&(M=I.x,b=I.y,E=I.z)}return new Ui(M,b,E,S)};h._storedFunction=y=>v(y),u._storedFunction=y=>{const M=v(y);return new O(M.x,M.y,M.z)},p._storedFunction=y=>{const M=v(y);return new lt(M.x,M.y)},m._storedFunction=y=>{const M=v(y);return new lt(M.z,M.w)},_._storedFunction=y=>v(y).x,f._storedFunction=y=>v(y).y,d._storedFunction=y=>v(y).z,C._storedFunction=y=>v(y).w}}$e("BABYLON.VectorConverterBlock",$ue);class ede extends Vr{constructor(e){super(e),this.registerInput("input",Ge.AutoDetect),this.registerOutput("output",Ge.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(Ge.Float),this._inputs[0].excludedConnectionPointTypes.push(Ge.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Ge.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Ge.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()}}$e("BABYLON.NormalizeVectorBlock",ede);class _te extends Vr{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",Ge.Geometry),this.registerInput("id",Ge.Int,!0,0),this.registerOutput("output",Ge.Geometry),this.id.acceptedConnectionPointTypes.push(Ge.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 s=this.geometry.getConnectedValue(i);if(!s||!s.indices||!s.positions)return s;const r=new gj;return r.materialIndex=this.id.getConnectedValue(i)|0,r.indexStart=0,r.indexCount=s.indices.length,r.verticesStart=0,r.verticesCount=s.positions.length/3,s.materialInfos=[r],s};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)}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],_te.prototype,"evaluateContext",void 0);$e("BABYLON.SetMaterialIDBlock",_te);var Rn;(function(a){a[a.Cos=0]="Cos",a[a.Sin=1]="Sin",a[a.Abs=2]="Abs",a[a.Exp=3]="Exp",a[a.Round=4]="Round",a[a.Floor=5]="Floor",a[a.Ceiling=6]="Ceiling",a[a.Sqrt=7]="Sqrt",a[a.Log=8]="Log",a[a.Tan=9]="Tan",a[a.ArcTan=10]="ArcTan",a[a.ArcCos=11]="ArcCos",a[a.ArcSin=12]="ArcSin",a[a.Sign=13]="Sign",a[a.Negate=14]="Negate",a[a.OneMinus=15]="OneMinus",a[a.Reciprocal=16]="Reciprocal",a[a.ToDegrees=17]="ToDegrees",a[a.ToRadians=18]="ToRadians"})(Rn||(Rn={}));class gte extends Vr{constructor(e){super(e),this.operation=Rn.Cos,this.registerInput("input",Ge.AutoDetect),this.registerOutput("output",Ge.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Ge.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Ge.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Ge.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 Rn.Cos:{t=i=>Math.cos(i);break}case Rn.Sin:{t=i=>Math.sin(i);break}case Rn.Abs:{t=i=>Math.abs(i);break}case Rn.Exp:{t=i=>Math.exp(i);break}case Rn.Round:{t=i=>Math.round(i);break}case Rn.Floor:{t=i=>Math.floor(i);break}case Rn.Ceiling:{t=i=>Math.ceil(i);break}case Rn.Sqrt:{t=i=>Math.sqrt(i);break}case Rn.Log:{t=i=>Math.log(i);break}case Rn.Tan:{t=i=>Math.tan(i);break}case Rn.ArcTan:{t=i=>Math.atan(i);break}case Rn.ArcCos:{t=i=>Math.acos(i);break}case Rn.ArcSin:{t=i=>Math.asin(i);break}case Rn.Sign:{t=i=>Math.sign(i);break}case Rn.Negate:{t=i=>-i;break}case Rn.OneMinus:{t=i=>1-i;break}case Rn.Reciprocal:{t=i=>1/i;break}case Rn.ToRadians:{t=i=>i*Math.PI/180;break}case Rn.ToDegrees:{t=i=>i*180/Math.PI;break}}if(!t){this.input._storedFunction=null,this.input._storedValue=null;return}switch(this.input.type){case Ge.Int:case Ge.Float:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return t(s)};break}case Ge.Vector2:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new lt(t(s.x),t(s.y))};break}case Ge.Vector3:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new O(t(s.x),t(s.y),t(s.z))};break}case Ge.Vector4:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new Ui(t(s.x),t(s.y),t(s.z),t(s.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.${Rn[this.operation]}; +`}}z([ws("Operation",Ms.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:Rn.Cos},{label:"Sin",value:Rn.Sin},{label:"Abs",value:Rn.Abs},{label:"Exp",value:Rn.Exp},{label:"Round",value:Rn.Round},{label:"Floor",value:Rn.Floor},{label:"Ceiling",value:Rn.Ceiling},{label:"Sqrt",value:Rn.Sqrt},{label:"Log",value:Rn.Log},{label:"Tan",value:Rn.Tan},{label:"ArcTan",value:Rn.ArcTan},{label:"ArcCos",value:Rn.ArcCos},{label:"ArcSin",value:Rn.ArcSin},{label:"Sign",value:Rn.Sign},{label:"Negate",value:Rn.Negate},{label:"OneMinus",value:Rn.OneMinus},{label:"Reciprocal",value:Rn.Reciprocal},{label:"ToDegrees",value:Rn.ToDegrees},{label:"ToRadians",value:Rn.ToRadians}]})],gte.prototype,"operation",void 0);$e("BABYLON.GeometryTrigonometryBlock",gte);class vte extends Vr{constructor(e){super(e),this._rotationMatrix=new ge,this._scalingMatrix=new ge,this._translationMatrix=new ge,this._scalingRotationMatrix=new ge,this._transformMatrix=new ge,this.evaluateContext=!0,this.registerInput("value",Ge.AutoDetect),this.registerInput("matrix",Ge.Matrix,!0),this.registerInput("translation",Ge.Vector3,!0,O.Zero()),this.registerInput("rotation",Ge.Vector3,!0,O.Zero()),this.registerInput("scaling",Ge.Vector3,!0,O.One()),this.registerOutput("output",Ge.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Ge.Float),this._inputs[0].excludedConnectionPointTypes.push(Ge.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Ge.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 s=this.value.getConnectedValue(i);if(!s)return null;let r;if(this.matrix.isConnected)r=this.matrix.getConnectedValue(i);else{const n=this.scaling.getConnectedValue(i),o=this.rotation.getConnectedValue(i),l=this.translation.getConnectedValue(i);ge.ScalingToRef(n.x,n.y,n.z,this._scalingMatrix),ge.RotationYawPitchRollToRef(o.y,o.x,o.z,this._rotationMatrix),ge.TranslationToRef(l.x,l.y,l.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),r=this._transformMatrix}switch(this.value.type){case Ge.Geometry:{const n=s.clone();return n.transform(r),n}case Ge.Vector2:return lt.Transform(s,r);case Ge.Vector3:return O.TransformCoordinates(s,r);case Ge.Vector4:return Ui.TransformCoordinates(s,r)}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)}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vte.prototype,"evaluateContext",void 0);$e("BABYLON.GeometryTransformBlock",vte);class tde extends Vr{constructor(e){super(e),this.registerInput("angle",Ge.Float,!1,0),this.registerOutput("matrix",Ge.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Lc("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>ge.RotationX(this.angle.getConnectedValue(t))}}$e("BABYLON.RotationXBlock",tde);class ide extends Vr{constructor(e){super(e),this.registerInput("angle",Ge.Float,!1,0),this.registerOutput("matrix",Ge.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Lc("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>ge.RotationY(this.angle.getConnectedValue(t))}}$e("BABYLON.RotationYBlock",ide);class sde extends Vr{constructor(e){super(e),this.registerInput("angle",Ge.Float,!1,0),this.registerOutput("matrix",Ge.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Lc("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>ge.RotationZ(this.angle.getConnectedValue(t))}}$e("BABYLON.RotationZBlock",sde);class rde extends Vr{constructor(e){super(e),this.registerInput("scale",Ge.Vector3,!1,O.One()),this.registerOutput("matrix",Ge.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new Lc("Scale");e.value=new O(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.scale.getConnectedValue(t);return ge.Scaling(i.x,i.y,i.z)}}}$e("BABYLON.ScalingBlock",rde);class nde extends Vr{constructor(e){super(e),this.registerInput("source",Ge.Vector3,!0,O.Up()),this.registerInput("target",Ge.Vector3,!0,O.Left()),this.registerOutput("matrix",Ge.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(),s=this.target.getConnectedValue(t).clone(),r=new ge;return i.normalize(),s.normalize(),ge.RotationAlignToRef(i,s,r,!0),r}}}$e("BABYLON.AlignBlock",nde);class ade extends Vr{constructor(e){super(e),this.registerInput("translation",Ge.Vector3,!1,O.Zero()),this.registerOutput("matrix",Ge.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new Lc("Translation");e.value=new O(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.translation.getConnectedValue(t);return ge.Translation(i.x,i.y,i.z)}}}$e("BABYLON.TranslationBlock",ade);class gQ extends Vr{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",Ge.Geometry),this.registerInput("instance",Ge.Geometry,!0),this.registerInput("density",Ge.Float,!0,1,0,1),this.registerInput("matrix",Ge.Matrix,!0),this.registerInput("rotation",Ge.Vector3,!0,O.Zero()),this.registerInput("scaling",Ge.Vector3,!0,O.One()),this.scaling.acceptedConnectionPointTypes.push(Ge.Float),this.registerOutput("output",Ge.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 s=this._vertexData.positions.length/3;const r=[],n=new O,o=new Array;let l=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexh)continue;n.fromArray(l,this._currentIndex*3);const u=c.clone();if(this.matrix.isConnected){const p=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(u,n,p,r)}else{const p=i.adaptInput(this.scaling,Ge.Vector3,O.OneReadOnly),m=this.rotation.getConnectedValue(i)||O.ZeroReadOnly;i._instantiate(u,n,m,p,r)}this._currentLoopIndex++}if(i.restoreGeometryContext(),i.restoreExecutionContext(),i.restoreInstancingContext(),r.length)if(r.length===1)this._vertexData=r[0];else{const c=r.splice(0,1)[0];this._vertexData=c.merge(r,!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)}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],gQ.prototype,"evaluateContext",void 0);z([ws("Remove duplicated positions",Ms.Boolean,"ADVANCED",{notifiers:{update:!0}})],gQ.prototype,"removeDuplicatedPositions",void 0);$e("BABYLON.InstantiateOnVerticesBlock",gQ);class Cte extends Vr{constructor(e){super(e),this._currentPosition=new O,this._vertex0=new O,this._vertex1=new O,this._vertex2=new O,this._tempVector0=new O,this._tempVector1=new O,this.evaluateContext=!0,this.registerInput("geometry",Ge.Geometry),this.registerInput("instance",Ge.Geometry,!0),this.registerInput("count",Ge.Int,!0,256),this.registerInput("matrix",Ge.Matrix,!0),this.registerInput("rotation",Ge.Vector3,!0,O.Zero()),this.registerInput("scaling",Ge.Vector3,!0,O.One()),this.scaling.acceptedConnectionPointTypes.push(Ge.Float),this.registerOutput("output",Ge.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(),O.Cross(this._tempVector1,this._tempVector0)}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 s=null;const r=this.count.getConnectedValue(i),n=this._vertexData.indices.length/3,o=r/n;let l=0;const c=[];let h=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=r);p++){let m=Math.random(),_=Math.random();if(m>_){const y=m;m=_,_=y}const f=m,d=_-m,C=1-f-d;if(this._currentPosition.set(f*this._vertex0.x+d*this._vertex1.x+C*this._vertex2.x,f*this._vertex0.y+d*this._vertex1.y+C*this._vertex2.y,f*this._vertex0.z+d*this._vertex1.z+C*this._vertex2.z),s=this.instance.getConnectedValue(i),!s||!s.positions||s.positions.length===0){l-=o;continue}const v=s.clone();if(this.matrix.isConnected){const y=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(v,this._currentPosition,y,c)}else{const y=i.adaptInput(this.scaling,Ge.Vector3,O.OneReadOnly),M=this.rotation.getConnectedValue(i)||O.ZeroReadOnly;i._instantiate(v,this._currentPosition,M,y,c)}h++,this._currentLoopIndex++}}if(c.length)if(c.length===1)this._vertexData=c[0];else{const u=c.splice(0,1)[0];this._vertexData=u.merge(c,!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)}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Cte.prototype,"evaluateContext",void 0);$e("BABYLON.InstantiateOnFacesBlock",Cte);class Ate extends Vr{constructor(e){super(e),this._currentPosition=new O,this._vertex0=new O,this._vertex1=new O,this._vertex2=new O,this.evaluateContext=!0,this.registerInput("geometry",Ge.Geometry),this.registerInput("instance",Ge.Geometry,!0),this.registerInput("count",Ge.Int,!0,256),this.registerInput("matrix",Ge.Matrix,!0),this.registerInput("rotation",Ge.Vector3,!0,O.Zero()),this.registerInput("scaling",Ge.Vector3,!0,O.One()),this.scaling.acceptedConnectionPointTypes.push(Ge.Float),this.registerOutput("output",Ge.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 matrix(){return this._inputs[2]}get count(){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 s=null;const r=this.count.getConnectedValue(i),n=[],o=zB(this._vertexData.positions,0,this._vertexData.positions.length/3),l=o.minimum,c=o.maximum,h=new O(1,0,0),u=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let p=0;p0&&_++}if(_%2===0){p--;continue}if(s=this.instance.getConnectedValue(i),!s||!s.positions||s.positions.length===0)continue;const f=s.clone();if(this.matrix.isConnected){const d=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(f,this._currentPosition,d,n)}else{const d=i.adaptInput(this.scaling,Ge.Vector3,O.OneReadOnly),C=this.rotation.getConnectedValue(i)||O.ZeroReadOnly;i._instantiate(f,this._currentPosition,C,d,n)}this._currentLoopIndex++}if(n.length)if(n.length===1)this._vertexData=n[0];else{const p=n.splice(0,1)[0];this._vertexData=p.merge(n,!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)}}z([ws("Evaluate context",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Ate.prototype,"evaluateContext",void 0);$e("BABYLON.InstantiateOnVolumeBlock",Ate);class xte extends Vr{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",Ge.Geometry,!0),this.registerInput("count",Ge.Int,!0,1),this.registerInput("matrix",Ge.Matrix,!0),this.registerInput("position",Ge.Vector3,!0,O.Zero()),this.registerInput("rotation",Ge.Vector3,!0,O.Zero()),this.registerInput("scaling",Ge.Vector3,!0,O.One()),this.scaling.acceptedConnectionPointTypes.push(Ge.Float),this.registerOutput("output",Ge.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get matrix(){return this._inputs[2]}get position(){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=>{i.pushExecutionContext(this),i.pushInstancingContext(this);const s=this.count.getConnectedValue(i),r=[];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}}$e("BABYLON.IntFloatConverterBlock",ode);class lde extends Vr{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",Ge.AutoDetect),this.registerOutput("output",Ge.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Ge.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Ge.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 s=this.input.getConnectedValue(i);return s==null?(this.log.push("null"),s):(this.log.push(s.toString()),s)};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}$e("BABYLON.DebugBlock",lde);class cde extends Vr{constructor(e){super(e),this.registerInput("geometry",Ge.Geometry),this.registerOutput("output",Ge.Geometry),this.registerOutput("id",Ge.Int),this.registerOutput("collectionId",Ge.Int),this.registerOutput("verticesCount",Ge.Int),this.registerOutput("facesCount",Ge.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)}}$e("BABYLON.GeometryInfoBlock",cde);var jb;(function(a){a[a.Spherical=0]="Spherical",a[a.Cylindrical=1]="Cylindrical",a[a.Cubic=2]="Cubic"})(jb||(jb={}));class bte extends Vr{constructor(e){super(e),this.mapping=jb.Spherical,this.registerInput("position",Ge.Vector3),this.registerInput("center",Ge.Vector3,!0,O.Zero()),this.registerOutput("uv",Ge.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get center(){return this._inputs[1]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected){this.uv._storedFunction=null,this.uv._storedValue=null;return}const e=O.Zero(),t=i=>{const s=this.position.getConnectedValue(i),r=this.center.getConnectedValue(i),n=lt.Zero();switch(this.mapping){case jb.Spherical:{s.subtractToRef(r,e);const o=e.length();o>0&&(n.x=Math.acos(e.y/o)/Math.PI,(e.x!==0||e.z!==0)&&(n.y=Math.atan2(e.x,e.z)/(Math.PI*2)));break}case jb.Cylindrical:{s.subtractToRef(r,e);const o=e.length();o>0&&(n.x=Math.atan2(e.x/o,e.z/o)/(Math.PI*2),n.y=(e.y+1)/2);break}case jb.Cubic:{const o=Math.abs(s.x),l=Math.abs(s.y),c=Math.abs(s.z);let h=0,u=0;o>=l&&o>=c?(h=s.y-r.y,u=s.z-r.z):l>=o&&l>=c?(h=s.x-r.x,u=s.z-r.z):(h=s.x-r.x,u=s.y-r.y),n.x=h*.5+.5,n.y=u*.5+.5;break}}return n};this.uv._storedFunction=i=>t(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${jb[this.mapping]}; +`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}z([ws("Mapping",Ms.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:jb.Spherical},{label:"Cylindrical",value:jb.Cylindrical},{label:"Cubic",value:jb.Cubic}]})],bte.prototype,"mapping",void 0);$e("BABYLON.MappingBlock",bte);class hde extends Vr{constructor(e){super(e),this.registerInput("matrix0",Ge.Matrix),this.registerInput("matrix1",Ge.Matrix),this.registerOutput("output",Ge.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)}}}$e("BABYLON.MatrixComposeBlock",hde);class ude extends Vr{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",Ge.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)t.indexOf(s)===-1&&(i+=s._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)}}$e("BABYLON.TeleportInBlock",ude);class dde extends Vr{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",Ge.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 e,t;const i=super.serialize();return i.entryPoint=(t=(e=this.entryPoint)===null||e===void 0?void 0:e.uniqueId)!==null&&t!==void 0?t:"",i}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}$e("BABYLON.TeleportOutBlock",dde);class fde extends Vr{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.registerOutput("texture",Ge.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{const s=new Image,r=document.createElement("canvas"),n=r.getContext("2d");s.onload=()=>{r.width=s.width,r.height=s.height,n.drawImage(s,0,0);const l=n.getImageData(0,0,s.width,s.height).data,c=new Float32Array(l.length);for(let h=0;h{this._data=null,i()},s.src=e})}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}_buildBlock(){if(!this._data){this.texture._storedValue=null;return}const e={data:this._data,width:this._width,height:this._height};this.texture._storedValue=e}serialize(){const e=super.serialize();return e.width=this._width,e.height=this._height,this._data&&(e.data=Array.from(this._data)),e}_deserialize(e){super._deserialize(e),this._width=e.width,this._height=e.height,e.data&&(this._data=new Float32Array(e.data))}}$e("BABYLON.GeometryTextureBlock",fde);class Ete extends Vr{constructor(e){super(e),this.clampCoordinates=!0,this.registerInput("texture",Ge.Texture),this.registerInput("coordinates",Ge.Vector2),this.registerOutput("rgba",Ge.Vector4),this.registerOutput("rgb",Ge.Vector3),this.registerOutput("r",Ge.Float),this.registerOutput("g",Ge.Float),this.registerOutput("b",Ge.Float),this.registerOutput("a",Ge.Float)}getClassName(){return"GeometryTextureFetchBlock"}get texture(){return this.inputs[0]}get coordinates(){return this.inputs[1]}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]}_repeatClamp(e){return e>=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 s=this.coordinates.getConnectedValue(t);if(!s)return null;const r=this.clampCoordinates?Math.max(0,Math.min(s.x,1)):this._repeatClamp(s.x),n=this.clampCoordinates?Math.max(0,Math.min(s.y,1)):this._repeatClamp(s.y),o=Math.floor(r*(i.width-1)),l=Math.floor(n*(i.height-1)),c=o+i.width*l;return Ui.FromArray(i.data,c*4)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>e(t).toVector3(),this.r._storedFunction=t=>e(t).x,this.g._storedFunction=t=>e(t).y,this.b._storedFunction=t=>e(t).z,this.a._storedFunction=t=>e(t).w}_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}}z([ws("Clamp Coordinates",Ms.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Ete.prototype,"clampCoordinates",void 0);$e("BABYLON.GeometryTextureFetchBlock",Ete);class pde extends Vr{constructor(e){super(e),this.registerInput("geometry",Ge.Geometry),this.registerOutput("min",Ge.Vector3),this.registerOutput("max",Ge.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?zB(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?zB(t.positions,0,t.positions.length/3).maximum:null}}}$e("BABYLON.BoundingBlock",pde);class UAe{constructor(e=Recast){if(this.bjsRECAST={},this.name="RecastJSPlugin",this._maximumSubStepCount=10,this._timeStep=1/60,this._timeFactor=1,this._worker=null,typeof e=="function"?Me.Error("RecastJS is not ready. Please make sure you await Recast() before using the plugin."):this.bjsRECAST=e,!this.isSupported()){Me.Error("RecastJS is not available. Please make sure you included the js file.");return}this.setTimeStep(),this._tempVec1=new this.bjsRECAST.Vec3,this._tempVec2=new this.bjsRECAST.Vec3}setWorkerURL(e){return window&&window.Worker?(this._worker=new Worker(e),!0):!1}setTimeStep(e=1/60){this._timeStep=e}getTimeStep(){return this._timeStep}setMaximumSubStepCount(e=10){this._maximumSubStepCount=e}getMaximumSubStepCount(){return this._maximumSubStepCount}set timeFactor(e){this._timeFactor=Math.max(e,0)}get timeFactor(){return this._timeFactor}createNavMesh(e,t,i){this._worker&&!i?console.warn("A worker is avaible but no completion callback. Defaulting to blocking navmesh creation"):!this._worker&&i&&console.warn("A completion callback is avaible but no worker. Defaulting to blocking navmesh creation"),this.navMesh=new this.bjsRECAST.NavMesh;let s,r,n;const o=[],l=[];let c=0;for(s=0;s{this.update(s.getEngine().getDeltaTime()*.001*e.timeFactor)})}addAgent(e,t,i){const s=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;s.radius=t.radius,s.height=t.height,s.maxAcceleration=t.maxAcceleration,s.maxSpeed=t.maxSpeed,s.collisionQueryRange=t.collisionQueryRange,s.pathOptimizationRange=t.pathOptimizationRange,s.separationWeight=t.separationWeight,s.updateFlags=7,s.obstacleAvoidanceType=0,s.queryFilterType=0,s.userData=0;const r=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),s);return this.transforms.push(i),this.agents.push(r),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new O(0,0,0)),r}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new O(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 O(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 O(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<=Ls)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=Ls)this.recastCrowd.update(e);else{let s=Math.floor(e/t);i&&s>i&&(s=i),s<1&&(s=1);const r=e/s;for(let n=0;nh&&n.ynew Yf(a,e,t);class Yf{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=Yf._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,Yf.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Be.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 s=!1,r=i();const n=new wl;navigator.onLine&&(s=!0,r=r+(r.match(/\?/)==null?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",()=>{if(n.status===200||Yf._ValidateXHRData(n,1))try{const o=JSON.parse(n.response);this._enableSceneOffline=o.enableSceneOffline,this._enableTexturesOffline=o.enableTexturesOffline&&Yf._IsUASupportingBlobStorage,o.version&&!isNaN(parseInt(o.version))&&(this._manifestVersionFound=o.version),e(!0)}catch{t()}else t()},!1),n.addEventListener("error",()=>{if(s){s=!1;const o=i();n.open("GET",o),n.send()}else t()},!1);try{n.send()}catch{Me.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 s=this._idbFactory.open("babylonjs",1);s.onerror=()=>{i()},s.onblocked=()=>{Me.Error("IDB request blocked. Please reload the page."),i()},s.onsuccess=()=>{this._db=s.result,e()},s.onupgradeneeded=r=>{if(this._db=r.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(n){Me.Error("Error while creating object stores. Exception: "+n.message),i()}}}}loadImage(e,t){const i=Yf._ReturnFullUrlLocation(e),s=()=>{!this._hasReachedQuota&&this._db!==null?this._saveImageIntoDBAsync(i,t):t.src=e};this._mustUpdateRessources?s():this._loadImageFromDBAsync(i,t,s)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&this._db!==null){let s;const r=this._db.transaction(["textures"]);r.onabort=()=>{t.src=e},r.oncomplete=()=>{let o;s&&typeof URL=="function"?(o=URL.createObjectURL(s.data),t.onerror=()=>{Me.Error("Error loading image from blob URL: "+o+" switching back to web url: "+e),t.src=e},t.src=o):i()};const n=r.objectStore("textures").get(e);n.onsuccess=o=>{s=o.target.result},n.onerror=()=>{Me.Error("Error loading texture "+e+" from DB."),t.src=e}}else Me.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 s=()=>{let r;if(i&&typeof URL=="function")try{r=URL.createObjectURL(i)}catch{r=URL.createObjectURL(i)}r&&(t.src=r)};if(Yf._IsUASupportingBlobStorage){const r=new wl;r.open("GET",e),r.responseType="blob",r.addEventListener("load",()=>{if(r.status===200&&this._db){i=r.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=l=>{try{const h=l.target.error;h&&h.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}s()},n.oncomplete=()=>{s()};const o={textureUrl:e,data:i};try{const l=n.objectStore("textures").put(o);l.onsuccess=()=>{},l.onerror=()=>{s()}}catch(l){l.code===25&&(Yf._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),r.addEventListener("error",()=>{Me.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),r.send()}else t.src=e}else Me.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 s;try{const r=this._db.transaction(["versions"]);r.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},r.onabort=()=>{t(-1)};const n=r.objectStore("versions").get(e);n.onsuccess=o=>{s=o.target.result},n.onerror=()=>{Me.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(r){Me.Error("Error while accessing 'versions' object store (READ OP). Exception: "+r.message),t(-1)}}else Me.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=n=>{try{const o=n.target.error;o&&o.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const s={sceneUrl:e,data:this._manifestVersionFound},r=i.objectStore("versions").put(s);r.onsuccess=()=>{},r.onerror=()=>{Me.Error("Error in DB add version request in BABYLON.Database.")}}catch(i){Me.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+i.message),t(-1)}else t(-1)}loadFile(e,t,i,s,r){const n=Yf._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,r,s)};this._checkVersionFromDB(n,l=>{l!==-1?this._mustUpdateRessources?this._saveFileAsync(n,t,i,r,s):this._loadFileAsync(n,t,o):s&&s()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let s;e.indexOf(".babylon")!==-1?s="scenes":s="textures";let r;const n=this._db.transaction([s]);n.oncomplete=()=>{r?t(r.data):i()},n.onabort=()=>{i()};const o=n.objectStore(s).get(e);o.onsuccess=l=>{r=l.target.result},o.onerror=()=>{Me.Error("Error loading file "+e+" from DB."),i()}}else Me.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,s,r){if(this._isSupported){let n;e.indexOf(".babylon")!==-1?n="scenes":n="textures";const o=new wl;let l;o.open("GET",e+(e.match(/\?/)==null?"?":"&")+Date.now()),s&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(o.status===200||o.status<400&&Yf._ValidateXHRData(o,s?6:1))if(l=s?o.response:o.responseText,!this._hasReachedQuota&&this._db){const c=this._db.transaction([n],"readwrite");c.onabort=u=>{try{const p=u.target.error;p&&p.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}t(l)},c.oncomplete=()=>{t(l)};let h;n==="scenes"?h={sceneUrl:e,data:l,version:this._manifestVersionFound}:h={textureUrl:e,data:l};try{const u=c.objectStore(n).put(h);u.onsuccess=()=>{},u.onerror=()=>{Me.Error("Error in DB add file request in BABYLON.Database.")}}catch{t(l)}}else t(l);else o.status>=400&&r?r(o):t()},!1),o.addEventListener("error",()=>{Me.Error("error on XHR request."),r&&r()},!1),o.send()}else Me.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),r&&r()}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=SW(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}}Yf._IsUASupportingBlobStorage=!0;Yf.IDBStorageEnabled=!1;Yf._ParseURL=a=>{const e=document.createElement("a");e.href=a;const t=a.substring(0,a.lastIndexOf("#")),i=a.substring(t.lastIndexOf("/")+1,a.length);return a.substring(0,a.indexOf(i,0))};Yf._ReturnFullUrlLocation=a=>a.indexOf("http:/")===-1&&a.indexOf("https:/")===-1&&typeof window<"u"?Yf._ParseURL(window.location.href)+a:a;class _de{_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 kAe="gpuUpdateParticlesPixelShader",HAe=`#version 300 es +void main() {discard;} +`;Ue.ShadersStore[kAe]=HAe;const jAe="gpuUpdateParticlesVertexShader",GAe=`#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 +}}`;Ue.ShadersStore[jAe]=GAe;class gde{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,t;return(t=(e=this._updateEffect)===null||e===void 0?void 0:e.isReady())!==null&&t!==void 0?t:!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 DL&&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 Ws("gpuUpdateParticles",this._updateEffectOptions,this._engine),new _de(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 s=this._engine;s.bindTransformFeedbackBuffer(t.getBuffer()),s.setRasterizerState(!1),s.beginTransformFeedback(!0),s.drawArraysType(3,0,i),s.endTransformFeedback(),s.setRasterizerState(!0),s.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 +}} +`;Ue.ShadersStoreWGSL[WAe]=YAe;class vde{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,t;return(t=(e=this._updateComputeShader)===null||e===void 0?void 0:e.isReady())!==null&&t!==void 0?t:!1}createUpdateBuffer(e){var t;const i={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&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new LF("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split(` +`)}),(t=this._simParamsComputeShader)===null||t===void 0||t.dispose(),this._simParamsComputeShader=new es(this._engine),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 _de(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){const t=new Xle(this._engine,e.length*4,11);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 r=0;r=n.gradient&&e<=o.gradient){const l=(e-n.gradient)/(o.gradient-n.gradient);i(n,o,l);return}}const s=t.length-1;i(t[s],t[s],1)}}class KB{constructor(e){this.particleSystem=e,this.position=O.Zero(),this.direction=O.Zero(),this.color=new Zt(0,0,0,0),this.colorStep=new Zt(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new lt(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Zt(0,0,0,0),this._currentColor2=new Zt(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=KB._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 s;this._initialSpriteCellLoop?s=Bt.Clamp(e*t%this.lifeTime/this.lifeTime):s=Bt.Clamp(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+s*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const i=ue.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,ue.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(ue.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=KB._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 Ui(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()))}}KB._Count=0;var QB;(function(a){a[a.ATTACHED=0]="ATTACHED",a[a.END=1]="END"})(QB||(QB={}));class pI{constructor(e){if(this.particleSystem=e,this.type=QB.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=Bo("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(!e)e=new O;else if(e instanceof O)e=e.clone();else if(e.getClassName().indexOf("Mesh")!==-1){const i=Bo("BABYLON.Mesh");e=new i("",e.getScene()),e.isVisible=!1}const t=new pI(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,s=!1){throw Ys("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new pI(pI._ParseParticleSystem(s,t,i,!0));return r.type=e.type,r.inheritDirection=e.inheritDirection,r.inheritedVelocityAmount=e.inheritedVelocityAmount,r.particleSystem._isSubEmitter=!0,r}dispose(){this.particleSystem.dispose()}}const XAe="particlesPixelShader",KAe=`#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 +#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 +#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 +}`;Ue.ShadersStore[XAe]=KAe;const QAe="particlesVertexShader",ZAe=`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 +#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) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include +#include +#define CUSTOM_VERTEX_MAIN_END +}`;Ue.ShadersStore[QAe]=ZAe;class xr extends lC{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,i;return(i=(t=this._customWrappers[e])===null||t===void 0?void 0:t.effect)!==null&&i!==void 0?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return(t=this._customWrappers[e])!==null&&t!==void 0?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new ml(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 Se),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,s=null,r=!1,n=.01){super(e),this._emitterInverseWorldMatrix=ge.Identity(),this._inheritedVelocityOffset=new O,this.onDisposeObservable=new Se,this.onStoppedObservable=new Se,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new Zt(0,0,0,0),this._colorDiff=new Zt(0,0,0,0),this._scaledDirection=O.Zero(),this._scaledGravity=O.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._disposeEmitterOnDispose=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this.recycleParticle=l=>{const c=this._particles.pop();c!==l&&c.copyTo(l),this._stockParticles.push(c)},this._createParticle=()=>{let l;if(this._stockParticles.length!==0?(l=this._stockParticles.pop(),l._reset()):l=new KB(this),this._subEmitters&&this._subEmitters.length>0){const c=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];l._attachedSubEmitters=[],c.forEach(h=>{if(h.type===QB.ATTACHED){const u=h.clone();l._attachedSubEmitters.push(u),u.particleSystem.start()}})}return l},this._emitFromParticle=l=>{if(!this._subEmitters||this._subEmitters.length===0)return;const c=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[c].forEach(h=>{if(h.type===QB.END){const u=h.clone();l._inheritParticleInfoToSubEmitter(u),u.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(u.particleSystem),u.particleSystem.start()}})},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,!i||i.getClassName()==="Scene"?(this._scene=i||Ii.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=ge.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new ml(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new PL;let o=null;this.updateFunction=l=>{var c;let h=null;this.noiseTexture&&(h=this.noiseTexture.getSize(),(c=this.noiseTexture.getContent())===null||c===void 0||c.then(p=>{o=p}));const u=l===this._particles;for(let p=0;pm.lifeTime){const v=m.age-f;_=(m.lifeTime-f)*_/v,m.age=m.lifeTime}const d=m.age/m.lifeTime;this._colorGradients&&this._colorGradients.length>0?W3.GetCurrentGradient(d,this._colorGradients,(v,y,M)=>{v!==m._currentColorGradient&&(m._currentColor1.copyFrom(m._currentColor2),y.getColorToRef(m._currentColor2),m._currentColorGradient=v),Zt.LerpToRef(m._currentColor1,m._currentColor2,M,m.color)}):(m.colorStep.scaleToRef(_,this._scaledColorStep),m.color.addInPlace(this._scaledColorStep),m.color.a<0&&(m.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&W3.GetCurrentGradient(d,this._angularSpeedGradients,(v,y,M)=>{v!==m._currentAngularSpeedGradient&&(m._currentAngularSpeed1=m._currentAngularSpeed2,m._currentAngularSpeed2=y.getFactor(),m._currentAngularSpeedGradient=v),m.angularSpeed=Bt.Lerp(m._currentAngularSpeed1,m._currentAngularSpeed2,M)}),m.angle+=m.angularSpeed*_;let C=_;if(this._velocityGradients&&this._velocityGradients.length>0&&W3.GetCurrentGradient(d,this._velocityGradients,(v,y,M)=>{v!==m._currentVelocityGradient&&(m._currentVelocity1=m._currentVelocity2,m._currentVelocity2=y.getFactor(),m._currentVelocityGradient=v),C*=Bt.Lerp(m._currentVelocity1,m._currentVelocity2,M)}),m.direction.scaleToRef(C,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&W3.GetCurrentGradient(d,this._limitVelocityGradients,(v,y,M)=>{v!==m._currentLimitVelocityGradient&&(m._currentLimitVelocity1=m._currentLimitVelocity2,m._currentLimitVelocity2=y.getFactor(),m._currentLimitVelocityGradient=v);const b=Bt.Lerp(m._currentLimitVelocity1,m._currentLimitVelocity2,M);m.direction.length()>b&&m.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&W3.GetCurrentGradient(d,this._dragGradients,(v,y,M)=>{v!==m._currentDragGradient&&(m._currentDrag1=m._currentDrag2,m._currentDrag2=y.getFactor(),m._currentDragGradient=v);const b=Bt.Lerp(m._currentDrag1,m._currentDrag2,M);this._scaledDirection.scaleInPlace(1-b)}),this.isLocal&&m._localPosition?(m._localPosition.addInPlace(this._scaledDirection),O.TransformCoordinatesToRef(m._localPosition,this._emitterWorldMatrix,m.position)):m.position.addInPlace(this._scaledDirection),o&&h&&m._randomNoiseCoordinates1){const v=this._fetchR(m._randomNoiseCoordinates1.x,m._randomNoiseCoordinates1.y,h.width,h.height,o),y=this._fetchR(m._randomNoiseCoordinates1.z,m._randomNoiseCoordinates2.x,h.width,h.height,o),M=this._fetchR(m._randomNoiseCoordinates2.y,m._randomNoiseCoordinates2.z,h.width,h.height,o),b=ue.Vector3[0],E=ue.Vector3[1];b.copyFromFloats((2*v-1)*this.noiseStrength.x,(2*y-1)*this.noiseStrength.y,(2*M-1)*this.noiseStrength.z),b.scaleToRef(_,E),m.direction.addInPlace(E)}if(this.gravity.scaleToRef(_,this._scaledGravity),m.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&W3.GetCurrentGradient(d,this._sizeGradients,(v,y,M)=>{v!==m._currentSizeGradient&&(m._currentSize1=m._currentSize2,m._currentSize2=y.getFactor(),m._currentSizeGradient=v),m.size=Bt.Lerp(m._currentSize1,m._currentSize2,M)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&W3.GetCurrentGradient(d,this._colorRemapGradients,(v,y,M)=>{const b=Bt.Lerp(v.factor1,y.factor1,M),E=Bt.Lerp(v.factor2,y.factor2,M);m.remapData.x=b,m.remapData.y=E-b}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&W3.GetCurrentGradient(d,this._alphaRemapGradients,(v,y,M)=>{const b=Bt.Lerp(v.factor1,y.factor1,M),E=Bt.Lerp(v.factor2,y.factor2,M);m.remapData.z=b,m.remapData.w=E-b})),this._isAnimationSheetEnabled&&m.updateCellIndex(),m._inheritParticleInfoToSubEmitters(),m.age>=m.lifeTime){this._emitFromParticle(m),m._attachedSubEmitters&&(m._attachedSubEmitters.forEach(v=>{v.particleSystem.disposeOnStop=!0,v.particleSystem.stop()}),m._attachedSubEmitters=null),this.recycleParticle(m),u&&p--;continue}}}}_addFactorGradient(e,t,i,s){const r=new Mte(t,i,s);e.push(r),e.sort((n,o)=>n.gradiento.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const s of e){if(s.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=hn.Color3[0];for(let i=0;i{Ie.LerpToRef(r.color,n.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=Ya.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 Cde(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 s=new yte(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort((r,n)=>r.gradientn.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?.dispose();this._drawWrappers=[]}_fetchR(e,t,i,s,r){e=Math.abs(e)*.5+.5,t=Math.abs(t)*.5+.5;const n=e*i%i|0,o=t*s%s|0,l=(n+o*i)*4;return r[l]/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===xr.BILLBOARDMODE_STRETCHED||this.billboardMode===xr.BILLBOARDMODE_STRETCHED_LOCAL)&&(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 Q1(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(se.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[se.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(se.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[se.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const c=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=c,i+=1}if(!this._isBillboardBased||this.billboardMode===xr.BILLBOARDMODE_STRETCHED||this.billboardMode===xr.BILLBOARDMODE_STRETCHED_LOCAL){const c=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=c,i+=3}if(this._useRampGradients){const c=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=c,i+=4}let l;if(this._useInstancing){const c=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Q1(e,c,!1,2),l=this._spriteBuffer.createVertexBuffer("offset",0,2)}else l=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=l,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 s=0;s{e instanceof xr?this._subEmitters.push([new pI(e)]):e instanceof pI?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)})}start(e=this.startDelay){var t;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}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&this._subEmitters.length!=0&&(this.activeSubSystems=new Array),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||t===void 0?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 s=0;s0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,s){let r=e*this._vertexBufferSize;if(this._vertexData[r++]=t.position.x+this.worldOffset.x,this._vertexData[r++]=t.position.y+this.worldOffset.y,this._vertexData[r++]=t.position.z+this.worldOffset.z,this._vertexData[r++]=t.color.r,this._vertexData[r++]=t.color.g,this._vertexData[r++]=t.color.b,this._vertexData[r++]=t.color.a,this._vertexData[r++]=t.angle,this._vertexData[r++]=t.scale.x*t.size,this._vertexData[r++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[r++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===xr.BILLBOARDMODE_STRETCHED||this.billboardMode===xr.BILLBOARDMODE_STRETCHED_LOCAL)&&(this._vertexData[r++]=t.direction.x,this._vertexData[r++]=t.direction.y,this._vertexData[r++]=t.direction.z);else if(t._initialDirection){let n=t._initialDirection;this.isLocal&&(O.TransformNormalToRef(n,this._emitterWorldMatrix,ue.Vector3[0]),n=ue.Vector3[0]),n.x===0&&n.z===0&&(n.x=.001),this._vertexData[r++]=n.x,this._vertexData[r++]=n.y,this._vertexData[r++]=n.z}else{let n=t.direction;this.isLocal&&(O.TransformNormalToRef(n,this._emitterWorldMatrix,ue.Vector3[0]),n=ue.Vector3[0]),n.x===0&&n.z===0&&(n.x=.001),this._vertexData[r++]=n.x,this._vertexData[r++]=n.y,this._vertexData[r++]=n.z}this._useRampGradients&&t.remapData&&(this._vertexData[r++]=t.remapData.x,this._vertexData[r++]=t.remapData.y,this._vertexData[r++]=t.remapData.z,this._vertexData[r++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(i===0?i=this._epsilon:i===1&&(i=1-this._epsilon),s===0?s=this._epsilon:s===1&&(s=1-this._epsilon)),this._vertexData[r++]=i,this._vertexData[r++]=s)}_stopSubEmitters(){!this.activeSubSystems||(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=new Array)}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);e!==-1&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_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=ge.Translation(i.x,i.y,i.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);let t;for(let i=0;i0){const r=Bt.Clamp(this._actualFrame/this.targetStopDuration);W3.GetCurrentGradient(r,this._lifeTimeGradients,(n,o)=>{const l=n,c=o,h=l.getFactor(),u=c.getFactor(),p=(r-l.gradient)/(c.gradient-l.gradient);t.lifeTime=Bt.Lerp(h,u,p)})}else t.lifeTime=Bt.RandomRange(this.minLifeTime,this.maxLifeTime);const s=Bt.RandomRange(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(),O.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),s===0?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(s),!this._sizeGradients||this._sizeGradients.length===0?t.size=Bt.RandomRange(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(Bt.RandomRange(this.minScaleX,this.maxScaleX),Bt.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const r=this._actualFrame/this.targetStopDuration;W3.GetCurrentGradient(r,this._startSizeGradients,(n,o,l)=>{n!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=o.getFactor(),this._currentStartSizeGradient=n);const c=Bt.Lerp(this._currentStartSize1,this._currentStartSize2,l);t.scale.scaleInPlace(c)})}if(!this._angularSpeedGradients||this._angularSpeedGradients.length===0?t.angularSpeed=Bt.RandomRange(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=Bt.RandomRange(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 r=Bt.RandomRange(0,1);Zt.LerpToRef(this.color1,this.color2,r,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 Ui(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 O(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new O(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[se.PositionKind,se.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1){const i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return lh(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&PI(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===xr.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case xr.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case xr.BILLBOARDMODE_STRETCHED:case xr.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===xr.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case xr.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL");break}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...xr._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==xr.BILLBOARDMODE_STRETCHED&&this.billboardMode!==xr.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...xr._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(Dr.PrepareUniforms(e,this._imageProcessingConfigurationDefines),Dr.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);const s=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let r=this._drawWrappers[s];r||(r=this._drawWrappers[s]=[]);let n=r[e];n||(n=new ml(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const o=i.join(` +`);if(n.defines!==o){const l=[],c=[],h=[];this.fillUniformsAttributesAndSamplerNames(c,l,h),n.setEffect(this._engine.createEffect("particles",l,c,h,o),o)}return n}animate(e=!1){var t;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:((t=this._scene)===null||t===void 0?void 0:t.getAnimationRatio())||1);let i;if(this.manualEmitCount>-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let s=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const r=this._actualFrame/this.targetStopDuration;W3.GetCurrentGradient(r,this._emitRateGradients,(n,o,l)=>{n!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=o.getFactor(),this._currentEmitRateGradient=n),s=Bt.Lerp(this._currentEmitRate1,this._currentEmitRate2,l)})}i=s*this._scaledUpdateSpeed>>0,this._newPartsExcess+=s*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let s=0;for(let r=0;r=0&&(m.invertToRef(ue.Matrix[0]),u.setMatrix("invView",ue.Matrix[0])),this._vertexArrayObject!==void 0?!((s=this._scene)===null||s===void 0)&&s.forceWireframe?p.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,u):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,u)),this._engine.bindVertexArrayObject(this._vertexArrayObject,!((r=this._scene)===null||r===void 0)&&r.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?p.bindBuffers(this._vertexBuffers,!((o=this._scene)===null||o===void 0)&&o.forceWireframe?this._linesIndexBuffer:this._indexBuffer,u):p.bindBuffers(this._vertexBuffers,!((n=this._scene)===null||n===void 0)&&n.forceWireframe?this._linesIndexBufferUseInstancing:null,u),this.useLogarithmicDepth&&this._scene&&ze.BindLogDepth(_,u,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(u),e){case xr.BLENDMODE_ADD:p.setAlphaMode(1);break;case xr.BLENDMODE_ONEONE:p.setAlphaMode(6);break;case xr.BLENDMODE_STANDARD:p.setAlphaMode(2);break;case xr.BLENDMODE_MULTIPLY:p.setAlphaMode(4);break}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(u),this._useInstancing?!((l=this._scene)===null||l===void 0)&&l.forceWireframe?p.drawElementsType(6,0,10,this._particles.length):p.drawArraysType(7,0,4,this._particles.length):!((c=this._scene)===null||c===void 0)&&c.forceWireframe?p.drawElementsType(1,0,this._particles.length*10):p.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===xr.BLENDMODE_MULTIPLYADD?t=this._render(xr.BLENDMODE_MULTIPLY)+this._render(xr.BLENDMODE_ADD):t=this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}dispose(e=!0){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._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let t=0;t-1&&this._scene.particleSystems.splice(t,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){const s=Object.assign({},this._customWrappers);let r=null;const n=this._engine;if(n.createEffectForParticles&&this.customShader!=null){r=this.customShader;const c=r.shaderOptions.defines.length>0?r.shaderOptions.defines.join(` +`):"",h=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,c);s[0]?s[0].effect=h:this.setCustomEffect(h,0)}const o=this.serialize(i),l=xr.Parse(o,this._scene||this._engine,this._rootUrl);return l.name=e,l.customShader=r,l._customWrappers=s,t===void 0&&(t=this.emitter),this.noiseTexture&&(l.noiseTexture=this.noiseTexture.clone()),l.emitter=t,this.preventAutoStart||l.start(),l}serialize(e=!1){const t={};if(xr._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const s=[];for(const r of i)s.push(r.serialize(e));t.subEmitters.push(s)}}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 d=t.emitter;e.emitterId=d.id}else{const d=t.emitter;e.emitter=d.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,Kt.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 s=t.getColorGradients();if(s){e.colorGradients=[];for(const d of s){const C={gradient:d.gradient,color1:d.color1.asArray()};d.color2?C.color2=d.color2.asArray():C.color2=d.color1.asArray(),e.colorGradients.push(C)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const d of r){const C={gradient:d.gradient,color:d.color.asArray()};e.rampGradients.push(C)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const d of n){const C={gradient:d.gradient,factor1:d.factor1};d.factor2!==void 0?C.factor2=d.factor2:C.factor2=d.factor1,e.colorRemapGradients.push(C)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const d of o){const C={gradient:d.gradient,factor1:d.factor1};d.factor2!==void 0?C.factor2=d.factor2:C.factor2=d.factor1,e.alphaRemapGradients.push(C)}}const l=t.getSizeGradients();if(l){e.sizeGradients=[];for(const d of l){const C={gradient:d.gradient,factor1:d.factor1};d.factor2!==void 0?C.factor2=d.factor2:C.factor2=d.factor1,e.sizeGradients.push(C)}}const c=t.getAngularSpeedGradients();if(c){e.angularSpeedGradients=[];for(const d of c){const C={gradient:d.gradient,factor1:d.factor1};d.factor2!==void 0?C.factor2=d.factor2:C.factor2=d.factor1,e.angularSpeedGradients.push(C)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const d of h){const C={gradient:d.gradient,factor1:d.factor1};d.factor2!==void 0?C.factor2=d.factor2:C.factor2=d.factor1,e.velocityGradients.push(C)}}const u=t.getDragGradients();if(u){e.dragGradients=[];for(const d of u){const C={gradient:d.gradient,factor1:d.factor1};d.factor2!==void 0?C.factor2=d.factor2:C.factor2=d.factor1,e.dragGradients.push(C)}}const p=t.getEmitRateGradients();if(p){e.emitRateGradients=[];for(const d of p){const C={gradient:d.gradient,factor1:d.factor1};d.factor2!==void 0?C.factor2=d.factor2:C.factor2=d.factor1,e.emitRateGradients.push(C)}}const m=t.getStartSizeGradients();if(m){e.startSizeGradients=[];for(const d of m){const C={gradient:d.gradient,factor1:d.factor1};d.factor2!==void 0?C.factor2=d.factor2:C.factor2=d.factor1,e.startSizeGradients.push(C)}}const _=t.getLifeTimeGradients();if(_){e.lifeTimeGradients=[];for(const d of _){const C={gradient:d.gradient,factor1:d.factor1};d.factor2!==void 0?C.factor2=d.factor2:C.factor2=d.factor1,e.lifeTimeGradients.push(C)}}const f=t.getLimitVelocityGradients();if(f){e.limitVelocityGradients=[];for(const d of f){const C={gradient:d.gradient,factor1:d.factor1};d.factor2!==void 0?C.factor2=d.factor2:C.factor2=d.factor1,e.limitVelocityGradients.push(C)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,s){var r,n,o;let l;i instanceof Oi?l=null:l=i;const c=Bo("BABYLON.Texture");if(c&&l&&(e.texture?t.particleTexture=c.Parse(e.texture,l,s):e.textureName&&(t.particleTexture=new c(s+e.textureName,l,!1,e.invertY!==void 0?e.invertY:!0),t.particleTexture.name=e.textureName)),!e.emitterId&&e.emitterId!==0&&e.emitter===void 0?t.emitter=O.Zero():e.emitterId&&l?t.emitter=l.getLastMeshById(e.emitterId):t.emitter=O.FromArray(e.emitter),t.isLocal=!!e.isLocal,e.renderingGroupId!==void 0&&(t.renderingGroupId=e.renderingGroupId),e.isBillboardBased!==void 0&&(t.isBillboardBased=e.isBillboardBased),e.billboardMode!==void 0&&(t.billboardMode=e.billboardMode),e.useLogarithmicDepth!==void 0&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(let u=0;u0?l.shaderOptions.defines.join(` +`):"";o=c.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,p)}const u=new xr(n,r||e.capacity,t,o,e.isAnimationSheetEnabled);if(u.customShader=l,u._rootUrl=i,e.id&&(u.id=e.id),e.subEmitters){u.subEmitters=[];for(const p of e.subEmitters){const m=[];for(const _ of p)m.push(pI.Parse(_,t,i));u.subEmitters.push(m)}}return xr._Parse(e,u,t,i),e.textureMask&&(u.textureMask=Zt.FromArray(e.textureMask)),e.preventAutoStart&&(u.preventAutoStart=e.preventAutoStart),!s&&!u.preventAutoStart&&u.start(),u}}xr.BILLBOARDMODE_Y=2;xr.BILLBOARDMODE_ALL=7;xr.BILLBOARDMODE_STRETCHED=8;xr.BILLBOARDMODE_STRETCHED_LOCAL=9;pI._ParseParticleSystem=xr.Parse;const qAe="clipPlaneFragmentDeclaration2",JAe=`#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 +`;Ue.IncludesShadersStore[qAe]=JAe;const $Ae="gpuRenderParticlesPixelShader",exe=`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 +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 +#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 +} +`;Ue.ShadersStore[$Ae]=exe;const txe="clipPlaneVertexDeclaration2",ixe=`#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 +`;Ue.IncludesShadersStore[txe]=ixe;const sxe="gpuRenderParticlesVertexShader",rxe=`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 +#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) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include +#include +}`;Ue.ShadersStore[sxe]=rxe;class iC extends lC{static get IsSupported(){if(!Ii.LastCreatedEngine)return!1;const e=Ii.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]))}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}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==xr.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(xr.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(xr.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,i;return(i=(t=this._customWrappers[e])===null||t===void 0?void 0:t.effect)!==null&&i!==void 0?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return(t=this._customWrappers[e])!==null&&t!==void 0?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new ml(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new Se),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 yte(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===void 0||e.reset()}_addFactorGradient(e,t,i){const s=new Mte(t,i);e.push(s),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((r,n)=>r.gradientn.gradient?1:0);const s=this;s[t]&&(s[t].dispose(),s[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,s=null,r=!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.onDisposeObservable=new Se,this.onStoppedObservable=new Se,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,!i||i.getClassName()==="Scene"?(this._scene=i||Ii.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=ge.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().supportComputeShaders){if(!Bo("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Bo("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!Bo("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Bo("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new ml(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new ml(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 n=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),o=t;isFinite(o)&&(n.capacity=o),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new PL;const l=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let c=[];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]),l=this._platform.createParticleBuffer(i),c=this._platform.createParticleBuffer(i);this._buffer0=new Q1(t,l,!1,this._attributesStrideSize),this._buffer1=new Q1(t,c,!1,this._attributesStrideSize),this._spriteBuffer=new Q1(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?!0:(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);let s=this._drawWrappers[e];s||(s=new ml(this._engine),s.drawContext&&(s.drawContext.useInstancing=!0),this._drawWrappers[e]=s);const r=i.join(` +`);if(s.defines!==r){const n=[],o=[],l=[];this.fillUniformsAttributesAndSamplerNames(o,n,l),s.setEffect(this._engine.createEffect("gpuRenderParticles",n,o,l,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[se.PositionKind,"age","life","size","angle"];return e||r.push(se.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",se.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1){const i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return lh(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&PI(this,this._scene,e),t===xr.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 xr.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case xr.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case xr.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(...iC._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===xr.BILLBOARDMODE_STRETCHED)),e.push(...iC._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(Dr.PrepareUniforms(e,this._imageProcessingConfigurationDefines),Dr.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:((t=this._scene)===null||t===void 0?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 s=new Float32Array(this._rawTextureWidth);for(let r=0;r{s[r]=Bt.Lerp(o.factor1,l.factor1,c)})}this[t]=Ya.CreateRTexture(s,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=hn.Color4[0];for(let i=0;i{Zt.LerpToRef(r.color1,n.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=Ya.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,s,r,n,o;const l=this._getWrapper(e),c=l.effect;this._engine.enableEffect(l);const h=((i=this._scene)===null||i===void 0?void 0:i.getViewMatrix())||ge.IdentityReadOnly;if(c.setMatrix("view",h),c.setMatrix("projection",(s=this.defaultProjectionMatrix)!==null&&s!==void 0?s:this._scene.getProjectionMatrix()),c.setTexture("diffuseSampler",this.particleTexture),c.setVector2("translationPivot",this.translationPivot),c.setVector3("worldOffset",this.worldOffset),this.isLocal&&c.setMatrix("emitterWM",t),this._colorGradientsTexture?c.setTexture("colorGradientSampler",this._colorGradientsTexture):c.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const p=this.particleTexture.getBaseSize();c.setFloat3("sheetInfos",this.spriteCellWidth/p.width,this.spriteCellHeight/p.height,p.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const p=this._scene.activeCamera;c.setVector3("eyePosition",p.globalPosition)}const u=c.defines;if(this._scene&&wc(c,this,this._scene),u.indexOf("#define BILLBOARDMODE_ALL")>=0){const p=h.clone();p.invert(),c.setMatrix("invView",p)}switch(this.useLogarithmicDepth&&this._scene&&ze.BindLogDepth(u,c,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(c),e){case xr.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case xr.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case xr.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case xr.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4);break}return this._platform.bindDrawBuffers(this._targetIndex,c,!((r=this._scene)===null||r===void 0)&&r.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(c),!((n=this._scene)===null||n===void 0)&&n.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),!((o=this._scene)===null||o===void 0)&&o.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect())return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const i=this.emitter;e=ue.Matrix[0],ge.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 n=0;n1){const n=this._accumulatedCount|0;this._accumulatedCount-=n,this._currentActiveCount+=n}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 n=this.emitter;i=ue.Matrix[0],ge.TranslationToRef(n.x,n.y,n.z,i)}const s=this._engine;this.updateInAnimate||this._update(i);let r=0;return!e&&!t&&(s.setState(!1),this.forceDepthWrite&&s.setDepthWrite(!0),this.blendMode===xr.BLENDMODE_MULTIPLYADD?r=this._render(xr.BLENDMODE_MULTIPLY,i)+this._render(xr.BLENDMODE_ADD,i):r=this._render(this.blendMode,i),this._engine.setAlphaMode(0)),r}rebuild(){const e=()=>{!this._recreateUpdateEffect()||!this._platform.isUpdateBufferReady()?setTimeout(e,10):this._initialize(!0)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),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?r.shaderOptions.defines.join(` +`):"";s[0]=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,c,void 0,void 0,void 0,this)}const o=this.serialize(i),l=iC.Parse(o,this._scene||this._engine,this._rootUrl);return l.name=e,l.customShader=r,l._customWrappers=s,t===void 0&&(t=this.emitter),this.noiseTexture&&(l.noiseTexture=this.noiseTexture.clone()),l.emitter=t,l}serialize(e=!1){const t={};return xr._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,s=!1,r){const n=e.name;let o,l;t instanceof Oi?o=t:(l=t,o=l.getEngine());const c=new iC(n,{capacity:r||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(c._rootUrl=i,e.customShader&&o.createEffectForParticles){const h=e.customShader,u=h.shaderOptions.defines.length>0?h.shaderOptions.defines.join(` +`):"",p=o.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,u,void 0,void 0,void 0,c);c.setCustomEffect(p,0),c.customShader=h}return e.id&&(c.id=e.id),e.activeParticleCount&&(c.activeParticleCount=e.activeParticleCount),xr._Parse(e,c,t,i),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),!s&&!c.preventAutoStart&&c.start(),c}}class $P{constructor(){this._emitterNodeIsOwned=!0,this.systems=new Array}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 s=$d("emitterSphere",{diameter:e.diameter,segments:e.segments},i);s.renderingGroupId=t;const r=new jt("emitterSphereMaterial",i);r.emissiveColor=e.color,s.material=r;for(const n of this.systems)n.emitter=s;this._emitterNode=s}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,s){const r=new $P,n=this.BaseAssetsUrl+"/textures/";t=t||Ii.LastCreatedScene;for(const o of e.systems)r.systems.push(i?iC.Parse(o,t,n,!0,s):xr.Parse(o,t,n,!0,s));if(e.emitter){const o=e.emitter.options;switch(e.emitter.kind){case"Sphere":r.setEmitterAsSphere({diameter:o.diameter,segments:o.segments,color:Ie.FromArray(o.color)},e.emitter.renderingGroupId,t);break}}return r}}$P.BaseAssetsUrl="https://assets.babylonjs.com/particles";class eD{static CreateDefault(e,t=500,i,s=!1){let r;return s?r=new iC("default system",{capacity:t},i):r=new xr("default system",t,i),r.emitter=e,r.particleTexture=new Te("https://assets.babylonjs.com/textures/flare.png",r.getScene()),r.createConeEmitter(.1,Math.PI/4),r.color1=new Zt(1,1,1,1),r.color2=new Zt(1,1,1,1),r.colorDead=new Zt(1,1,1,0),r.minSize=.1,r.maxSize=.1,r.minEmitPower=2,r.maxEmitPower=2,r.updateSpeed=1/60,r.emitRate=30,r}static CreateAsync(e,t,i=!1,s){t||(t=Ii.LastCreatedScene);const r={};return t.addPendingData(r),new Promise((n,o)=>{if(i&&!iC.IsSupported)return t.removePendingData(r),o("Particle system with GPU is not supported.");Be.LoadFile(`${eD.BaseAssetsUrl}/systems/${e}.json`,l=>{t.removePendingData(r);const c=JSON.parse(l.toString());return n($P.Parse(c,t,i,s))},void 0,void 0,void 0,()=>(t.removePendingData(r),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){const t=new $P;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,s=!1,r="",n){return new Promise((o,l)=>{const c=new wl;c.addEventListener("readystatechange",()=>{if(c.readyState==4)if(c.status==200){const h=JSON.parse(c.responseText);let u;s?u=iC.Parse(h,i,r,!1,n):u=xr.Parse(h,i,r,!1,n),e&&(u.name=e),o(u)}else l("Unable to load the particle system")}),c.open("GET",t),c.send()})}static ParseFromSnippetAsync(e,t,i=!1,s="",r){if(e==="_BLANK"){const n=this.CreateDefault(null);return n.start(),Promise.resolve(n)}return new Promise((n,o)=>{const l=new wl;l.addEventListener("readystatechange",()=>{if(l.readyState==4)if(l.status==200){const c=JSON.parse(JSON.parse(l.responseText).jsonPayload),h=JSON.parse(c.particleSystem);let u;i?u=iC.Parse(h,t,s,!1,r):u=xr.Parse(h,t,s,!1,r),u.snippetId=e,n(u)}else o("Unable to load the snippet "+e)}),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()})}}eD.BaseAssetsUrl=$P.BaseAssetsUrl;eD.SnippetUrl="https://snippet.babylonjs.com";eD.CreateFromSnippetAsync=eD.ParseFromSnippetAsync;pc.AddParser(ai.NAME_PARTICLESYSTEM,(a,e,t,i)=>{const s=pc.GetIndividualParser(ai.NAME_PARTICLESYSTEM);if(!!s&&a.particleSystems!==void 0&&a.particleSystems!==null)for(let r=0,n=a.particleSystems.length;ra.activeParticleCount?iC.Parse(a,e,t):xr.Parse(a,e,t));He.prototype.createEffectForParticles=function(a,e=[],t=[],i="",s,r,n,o){var l;let c=[],h=[];const u=[];return o?o.fillUniformsAttributesAndSamplerNames(h,c,u):(c=xr._GetAttributeNamesOrOptions(),h=xr._GetEffectCreationOptions()),i.indexOf(" BILLBOARD")===-1&&(i+=` +#define BILLBOARD +`),o?.isAnimationSheetEnabled&&i.indexOf(" ANIMATESHEET")===-1&&(i+=` +#define ANIMATESHEET +`),t.indexOf("diffuseSampler")===-1&&t.push("diffuseSampler"),this.createEffect({vertex:(l=o?.vertexShaderName)!==null&&l!==void 0?l:"particles",fragmentElement:a},c,h.concat(e),u.concat(t),i,s,r,n)};Oe.prototype.getEmittedParticleSystems=function(){const a=new Array;for(let e=0;er.sqDistance-s.sqDistance,this._materialSortFunction=(s,r)=>s.materialIndex-r.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||Ii.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?.computeBoundingBox?i.computeBoundingBox:!1,this._autoFixFaceOrientation=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 g0(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new xde}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(this.nbParticles===0&&!this.mesh){const t=RF("",{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 Oe(this.name,this._scene);this.mesh=t}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&Jt.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 Jt;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,se.PositionKind),e.set(this._normals32,se.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,se.UVKind),this._colors32.length>0&&e.set(this._colors32,se.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let t=0;for(let i=0;i_?_:r,s=Math.round(_/r),n=0):s=s>_?_:s;const f=[],d=[],C=[],v=[],y=[],M=O.Zero(),b=s;for(;m<_;){s=b+Math.floor((1+n)*Math.random()),m>_-s&&(s=_-m),f.length=0,d.length=0,C.length=0,v.length=0,y.length=0;let E=0;for(let j=m*3;j<(m+s)*3;j++){C.push(E);const H=l[j],Y=H*3;if(f.push(o[Y],o[Y+1],o[Y+2]),d.push(u[Y],u[Y+1],u[Y+2]),c){const J=H*2;v.push(c[J],c[J+1])}if(h){const J=H*4;y.push(h[J],h[J+1],h[J+2],h[J+3])}E++}let S=this.nbParticles;const I=this._posToShape(f),D=this._uvsToShapeUV(v),R=C.slice(),L=y.slice(),w=d.slice();M.copyFromFloats(0,0,0);let N;for(N=0;N65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const G=b.materialIndex!==null?b.materialIndex:0;this.depthSortedParticles.push(new Ade(m,t,r.length,G))}return b}_posToShape(e){const t=[];for(let i=0;i=this.nbParticles||!this._updatable)return[];const s=this.particles,r=this.nbParticles;if(t=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(e!=0||t!=this.nbParticles-1)){const Z=this.mesh.getBoundingInfo();Z&&(y.copyFrom(Z.minimum),M.copyFrom(Z.maximum))}L=this.particles[e]._pos;const ie=L/3|0;N=ie*4,W=ie*2;for(let Z=e;Z<=t;Z++){const q=this.particles[Z];this.updateParticle(q);const K=q._model._shape,j=q._model._shapeUV,H=q._rotationMatrix,Y=q.position,J=q.rotation,te=q.scaling,re=q._globalPosition;if(_){const ee=this.depthSortedParticles[Z];ee.idx=q.idx,ee.ind=q._ind,ee.indicesLength=q._model._indicesLength,ee.sqDistance=O.DistanceSquared(q.position,b)}if(!q.alive||q._stillInvisible&&!q.isVisible&&!this._recomputeInvisibles){G=K.length,L+=G*3,N+=G*4,W+=G*2;continue}if(q.isVisible){q._stillInvisible=!1;const ee=f[12];if(q.pivot.multiplyToRef(te,ee),this.billboard&&(J.x=0,J.y=0),(this._computeParticleRotation||this.billboard)&&q.getRotationMatrix(s),q.parentId!==null){const fe=this.getParticleById(q.parentId);if(fe){const de=fe._rotationMatrix,me=fe._globalPosition,Fe=Y.x*de[1]+Y.y*de[4]+Y.z*de[7],je=Y.x*de[0]+Y.y*de[3]+Y.z*de[6],nt=Y.x*de[2]+Y.y*de[5]+Y.z*de[8];if(re.x=me.x+je,re.y=me.y+Fe,re.z=me.z+nt,this._computeParticleRotation||this.billboard){const we=s.m;H[0]=we[0]*de[0]+we[1]*de[3]+we[2]*de[6],H[1]=we[0]*de[1]+we[1]*de[4]+we[2]*de[7],H[2]=we[0]*de[2]+we[1]*de[5]+we[2]*de[8],H[3]=we[4]*de[0]+we[5]*de[3]+we[6]*de[6],H[4]=we[4]*de[1]+we[5]*de[4]+we[6]*de[7],H[5]=we[4]*de[2]+we[5]*de[5]+we[6]*de[8],H[6]=we[8]*de[0]+we[9]*de[3]+we[10]*de[6],H[7]=we[8]*de[1]+we[9]*de[4]+we[10]*de[7],H[8]=we[8]*de[2]+we[9]*de[5]+we[10]*de[8]}}else q.parentId=null}else if(re.x=Y.x,re.y=Y.y,re.z=Y.z,this._computeParticleRotation||this.billboard){const fe=s.m;H[0]=fe[0],H[1]=fe[1],H[2]=fe[2],H[3]=fe[4],H[4]=fe[5],H[5]=fe[6],H[6]=fe[8],H[7]=fe[9],H[8]=fe[10]}const ae=f[11];for(q.translateFromPivot?ae.setAll(0):ae.copyFrom(ee),G=0;G0)for(let n=0;n(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 Jt;t.set(this._positions32,se.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,se.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,se.ColorKind));const s=new Oe(this.name,this._scene);t.applyToMesh(s,this._updatable),this.mesh=s,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let r=e;return r||(r=new jt("point cloud material",this._scene),r.emissiveColor=new Ie(i,i,i),r.disableLighting=!0,r.pointsCloud=!0,r.pointSize=this._size),s.material=r,new Promise(n=>n(s))}_addParticle(e,t,i,s){const r=new bde(e,t,i,s,this);return this.particles.push(r),r}_randomUnitVector(e){e.position=new O(Math.random(),Math.random(),Math.random()),e.color=new Zt(1,1,1,1)}_getColorIndicesForCoord(e,t,i,s){const r=e._groupImageData,n=i*(s*4)+t*4,o=[n,n+1,n+2,n+3],l=o[0],c=o[1],h=o[2],u=o[3],p=r[l],m=r[c],_=r[h],f=r[u];return new Zt(p/255,m/255,_/255,f)}_setPointsColorOrUV(e,t,i,s,r,n,o,l){l=l??0,i&&e.updateFacetData();const h=2*e.getBoundingInfo().boundingSphere.radius;let u=e.getVerticesData(se.PositionKind);const p=e.getIndices(),m=e.getVerticesData(se.UVKind+(l?l+1:"")),_=e.getVerticesData(se.ColorKind),f=O.Zero();e.computeWorldMatrix();const d=e.getWorldMatrix();if(!d.isIdentity()){u=u.slice(0);for(let Ci=0;Ci1&&(Tt=1),$i<0&&($i=0),$i>1&&($i=1),Ie.HSVtoRGBToRef(Wt,Tt,$i,Qi),hi.set(Qi.r,Qi.g,Qi.b,1)):hi=Je.set(Math.random(),Math.random(),Math.random(),1),Gi.color=new Zt(hi.x,hi.y,hi.z,hi.w),this._colors.push(hi.x,hi.y,hi.z,hi.w))}}_colorFromTexture(e,t,i){if(e.material===null){Me.Warn(e.name+"has no material."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const r=e.material.getActiveTextures();if(r.length===0){Me.Warn(e.name+"has no usable texture."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const n=e.clone();n.setEnabled(!1),this._promises.push(new Promise(o=>{Sn.WhenAllReady(r,()=>{let l=t._textureNb;l<0&&(l=0),l>r.length-1&&(l=r.length-1);const c=()=>{t._groupImgWidth=r[l].getSize().width,t._groupImgHeight=r[l].getSize().height,this._setPointsColorOrUV(n,t,i,!0,!0,void 0,void 0,r[l].coordinatesIndex),n.dispose(),o()};t._groupImageData=null;const h=r[l].readPixels();h?h.then(u=>{t._groupImageData=u,c()}):c()})}))}_calculateDensity(e,t,i){let s=new Array,r,n,o,l,c,h,u,p,m,_,f,d;const C=O.Zero(),v=O.Zero(),y=O.Zero(),M=O.Zero(),b=O.Zero(),E=O.Zero();let S,I,D,R,L;const w=new Array;let N=0;const V=i.length/3;for(let q=0;q0&&(s=s.map(q=>q+ie));for(let q=0;q3)&&(n=jf.Random);const o=e.getVerticesData(se.PositionKind),l=e.getIndices();this._groups.push(this._groupCounter);const c=new kY(this._groupCounter,null);switch(c._groupDensity=this._calculateDensity(t,o,l),n===jf.Color?c._textureNb=s||0:s=s||new Zt(1,1,1,1),n){case jf.Color:this._colorFromTexture(e,c,!1);break;case jf.UV:this._setPointsColorOrUV(e,c,!1,!1,!1);break;case jf.Random:this._setPointsColorOrUV(e,c,!1);break;case jf.Stated:this._setPointsColorOrUV(e,c,!1,void 0,void 0,s,r);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,s,r){let n=i||jf.Random;(isNaN(n)||n<0||n>3)&&(n=jf.Random);const o=e.getVerticesData(se.PositionKind),l=e.getIndices();this._groups.push(this._groupCounter);const c=new kY(this._groupCounter,null);switch(c._groupDensity=this._calculateDensity(t,o,l),n===jf.Color?c._textureNb=s||0:s=s||new Zt(1,1,1,1),n){case jf.Color:this._colorFromTexture(e,c,!0);break;case jf.UV:this._setPointsColorOrUV(e,c,!0,!1,!1);break;case jf.Random:this._setPointsColorOrUV(e,c,!0);break;case jf.Stated:this._setPointsColorOrUV(e,c,!0,void 0,void 0,s,r);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){var s,r;if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const n=ue.Matrix[0],o=this.mesh,l=this._colors32,c=this._positions32,h=this._uvs32,u=ue.Vector3,p=u[5].copyFromFloats(1,0,0),m=u[6].copyFromFloats(0,1,0),_=u[7].copyFromFloats(0,0,1),f=u[8].setAll(Number.MAX_VALUE),d=u[9].setAll(-Number.MAX_VALUE);ge.IdentityToRef(n);let C=0;if(!((s=this.mesh)===null||s===void 0)&&s.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(e!=0||t!=this.nbParticles-1)){const b=(r=this.mesh)===null||r===void 0?void 0:r.getBoundingInfo();b&&(f.copyFrom(b.minimum),d.copyFrom(b.maximum))}C=0;let v=0,y=0,M=0;for(let b=e;b<=t;b++){const E=this.particles[b];C=E.idx,v=3*C,y=4*C,M=2*C,this.updateParticle(E);const S=E._rotationMatrix,I=E.position,D=E._globalPosition;if(this._computeParticleRotation&&E.getRotationMatrix(n),E.parentId!==null){const H=this.particles[E.parentId],Y=H._rotationMatrix,J=H._globalPosition,te=I.x*Y[1]+I.y*Y[4]+I.z*Y[7],re=I.x*Y[0]+I.y*Y[3]+I.z*Y[6],ee=I.x*Y[2]+I.y*Y[5]+I.z*Y[8];if(D.x=J.x+re,D.y=J.y+te,D.z=J.z+ee,this._computeParticleRotation){const oe=n.m;S[0]=oe[0]*Y[0]+oe[1]*Y[3]+oe[2]*Y[6],S[1]=oe[0]*Y[1]+oe[1]*Y[4]+oe[2]*Y[7],S[2]=oe[0]*Y[2]+oe[1]*Y[5]+oe[2]*Y[8],S[3]=oe[4]*Y[0]+oe[5]*Y[3]+oe[6]*Y[6],S[4]=oe[4]*Y[1]+oe[5]*Y[4]+oe[6]*Y[7],S[5]=oe[4]*Y[2]+oe[5]*Y[5]+oe[6]*Y[8],S[6]=oe[8]*Y[0]+oe[9]*Y[3]+oe[10]*Y[6],S[7]=oe[8]*Y[1]+oe[9]*Y[4]+oe[10]*Y[7],S[8]=oe[8]*Y[2]+oe[9]*Y[5]+oe[10]*Y[8]}}else if(D.x=0,D.y=0,D.z=0,this._computeParticleRotation){const H=n.m;S[0]=H[0],S[1]=H[1],S[2]=H[2],S[3]=H[4],S[4]=H[5],S[5]=H[6],S[6]=H[8],S[7]=H[9],S[8]=H[10]}const L=u[11];E.translateFromPivot?L.setAll(0):L.copyFrom(E.pivot);const w=u[0];w.copyFrom(E.position);const N=w.x-E.pivot.x,V=w.y-E.pivot.y,W=w.z-E.pivot.z;let G=N*S[0]+V*S[3]+W*S[6],ie=N*S[1]+V*S[4]+W*S[7],Z=N*S[2]+V*S[5]+W*S[8];G+=L.x,ie+=L.y,Z+=L.z;const q=c[v]=D.x+p.x*G+m.x*ie+_.x*Z,K=c[v+1]=D.y+p.y*G+m.y*ie+_.y*Z,j=c[v+2]=D.z+p.z*G+m.z*ie+_.z*Z;if(this._computeBoundingBox&&(f.minimizeInPlaceFromFloats(q,K,j),d.maximizeInPlaceFromFloats(q,K,j)),this._computeParticleColor&&E.color){const H=E.color,Y=this._colors32;Y[y]=H.r,Y[y+1]=H.g,Y[y+2]=H.b,Y[y+3]=H.a}if(this._computeParticleTexture&&E.uv){const H=E.uv,Y=this._uvs32;Y[M]=H.x,Y[M+1]=H.y}}return o&&(i&&(this._computeParticleColor&&o.updateVerticesData(se.ColorKind,l,!1,!1),this._computeParticleTexture&&o.updateVerticesData(se.UVKind,h,!1,!1),o.updateVerticesData(se.PositionKind,c,!1,!1)),this._computeBoundingBox&&(o.hasBoundingInfo?o.getBoundingInfo().reConstruct(f,d,o._worldMatrix):o.buildBoundingInfo(f,d,o._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){var e;(e=this.mesh)===null||e===void 0||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===void 0||e.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new O(-t,-t,-t),new O(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(Ir.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(a){this._physicsImpostor!==a&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=a,a&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0});Ir.prototype.getPhysicsImpostor=function(){return this.physicsImpostor};Ir.prototype.applyImpulse=function(a,e){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(a,e),this):this};Ir.prototype.setPhysicsLinkWith=function(a,e,t,i){return!this.physicsImpostor||!a.physicsImpostor?this:(this.physicsImpostor.createJoint(a.physicsImpostor,$n.HingeJoint,{mainPivot:e,connectedPivot:t,nativeParams:i}),this)};class vQ{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw Ys("")}constructor(e,t=vQ.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new O(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,s){this._physicsPlugin.raycast(e,t,i,s)}raycast(e,t,i){const s=new MW;return this._physicsPlugin.raycast(e,t,s,i),s}}class CQ{constructor(e,t,i,s){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disablePreStep=!0,this._isDisposed=!1,!s)return;const r=s.getPhysicsEngine();if(!r)throw new Error("No Physics Engine available.");if(this._physicsEngine=r,r.getPluginVersion()!=2)throw new Error("Plugin version is incorrect. Expected version 2.");const n=r.getPhysicsPlugin();if(!n)throw new Error("No Physics Plugin available.");this._physicsPlugin=n,e.rotationQuaternion||(e.rotationQuaternion=ke.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i;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,r.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}getClassName(){return"PhysicsBody"}clone(e){const t=new CQ(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}set shape(e){this._physicsPlugin.setShape(this,e)}get shape(){return this._physicsPlugin.getShape(this)}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){return this._physicsPlugin.getLinearVelocityToRef(this,e,t)}getLinearVelocity(e){const t=new O;return this.getLinearVelocityToRef(t,e),t}setAngularVelocity(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)}getAngularVelocityToRef(e,t){return this._physicsPlugin.getAngularVelocityToRef(this,e,t)}getAngularVelocity(e){const t=new O;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 O;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){var i;if(((i=this._pluginDataInstances)===null||i===void 0?void 0:i.length)>0){const s=t||0,r=this.transformNode._thinInstanceDataStorage.matrixData;r&&e.set(r[s*16+12],r[s*16+13],r[s*16+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,s){this._physicsPlugin.addConstraint(this,e,t,i,s)}syncWithBone(e,t,i,s,r,n){const o=this.transformNode;if(o.rotationQuaternion)if(r){const h=ue.Quaternion[0];e.getRotationQuaternionToRef(sr.WORLD,t,h),h.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(sr.WORLD,t,o.rotationQuaternion);const l=ue.Vector3[0],c=ue.Vector3[1];n||(n=ue.Vector3[2],n.x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,c),e.getAbsolutePositionToRef(t,l),s==null&&i&&(s=i.length()),s!=null&&(l.x+=c.x*s,l.y+=c.y*s,l.z+=c.z*s),o.setAbsolutePosition(l)}iterateOverAllInstances(e){var t;if(((t=this._pluginDataInstances)===null||t===void 0?void 0:t.length)>0)for(let i=0;i{this.dispose()})}_getObjectBoundingBox(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new sv(new O(-.5,-.5,-.5),new O(.5,.5,.5))}_hasVertices(e){return e?.getTotalVertices()>0}_addSizeOptions(){var e,t,i,s,r,n,o,l;this.transformNode.computeWorldMatrix(!0);const c=this._getObjectBoundingBox(),h=ue.Vector3[0];h.copyFrom(c.extendSize),h.scaleInPlace(2),h.multiplyInPlace(this.transformNode.scaling),h.x=Math.abs(h.x),h.y=Math.abs(h.y),h.z=Math.abs(h.z);const u=ue.Vector3[1];if(u.copyFrom(c.minimum),u.multiplyInPlace(this.transformNode.scaling),!this._options.center){const p=new O;p.copyFrom(c.center),p.multiplyInPlace(this.transformNode.scaling),this._options.center=p}switch(this.type){case rh.SPHERE:!this._options.radius&&Bt.WithinEpsilon(h.x,h.y,1e-4)&&Bt.WithinEpsilon(h.x,h.z,1e-4)?this._options.radius=h.x/2:this._options.radius||(Me.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(h.x,h.y,h.z)/2);break;case rh.CAPSULE:{const p=h.x/2;this._options.radius=(e=this._options.radius)!==null&&e!==void 0?e:p,this._options.pointA=(t=this._options.pointA)!==null&&t!==void 0?t:new O(0,u.y+p,0),this._options.pointB=(i=this._options.pointB)!==null&&i!==void 0?i:new O(0,u.y+h.y-p,0)}break;case rh.CYLINDER:{const p=h.x/2;this._options.radius=(s=this._options.radius)!==null&&s!==void 0?s:p,this._options.pointA=(r=this._options.pointA)!==null&&r!==void 0?r:new O(0,u.y,0),this._options.pointB=(n=this._options.pointB)!==null&&n!==void 0?n:new O(0,u.y+h.y,0)}break;case rh.MESH:case rh.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 rh.BOX:this._options.extents=(o=this._options.extents)!==null&&o!==void 0?o:new O(h.x,h.y,h.z),this._options.rotation=(l=this._options.rotation)!==null&&l!==void 0?l:ke.Identity();break}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class Cxe{constructor(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addNodeMeshes(e,t){e.computeWorldMatrix(!0);const i=ue.Matrix[0];if(ge.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,i),e instanceof Oe?this._addMesh(e,i):e instanceof ov&&this._addMesh(e.sourceMesh,i),t){const s=ue.Matrix[1];e.computeWorldMatrix().invertToRef(s);const r=ue.Matrix[2];s.multiplyToRef(i,r),e.getChildMeshes(!1).filter(o=>!o.physicsBody).forEach(o=>{const l=o.computeWorldMatrix(),c=ue.Matrix[3];l.multiplyToRef(r,c),o instanceof Oe?this._addMesh(o,c):o instanceof ov&&this._addMesh(o.sourceMesh,c)})}}_addMesh(e,t){const i=e.getVerticesData(se.PositionKind)||[],s=i.length/3,r=this._vertices.length;for(let n=0;n0)for(const t of e._pluginDataInstances)this._bodyCollisionObservable.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId);e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId))}initBodyInstances(e,t,i){var s,r;const n=(r=(s=i._thinInstanceDataStorage)===null||s===void 0?void 0:s.instancesCount)!==null&&r!==void 0?r:0,o=i._thinInstanceDataStorage.matrixData;!o||(this._createOrUpdateBodyInstances(e,t,o,0,n,!1),e._pluginDataInstances.forEach((l,c)=>{this._bodies.set(l.hpBodyId[0],{body:e,index:c})}))}_createOrUpdateBodyInstances(e,t,i,s,r,n){const o=ue.Quaternion[0],l=ge.Identity();for(let c=s;co){this._createOrUpdateBodyInstances(e,l,n,o,r,!1);const c=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];for(let h=o;h{this._hknp.HP_Body_SetEventMask(s.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:O.FromArray(e[0]),mass:e[1],inertia:O.FromArray(e[2]),inertiaOrientation:ke.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 K5.STATIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case K5.ANIMATED:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case K5.DYNAMIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC);break}}setMotionType(e,t,i){this._applyToBodyOrInstances(e,s=>{this._internalSetMotionType(s,t)},i)}getMotionType(e,t){const i=this._getPluginReference(e,t),s=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(s){case this._hknp.MotionType.STATIC:return K5.STATIC;case this._hknp.MotionType.KINEMATIC:return K5.ANIMATED;case this._hknp.MotionType.DYNAMIC:return K5.DYNAMIC}throw new Error("Unknown motion type: "+s)}_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),s=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(s)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,s=>{s.userMassProps=t,this._internalUpdateMassProperties(s)},i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),s=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(s)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,s=>{this._hknp.HP_Body_SetLinearDamping(s.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,s=>{this._hknp.HP_Body_SetAngularDamping(s.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,s=>{this._hknp.HP_Body_SetLinearVelocity(s.hpBodyId,this._bVecToV3(t))},i)}getLinearVelocityToRef(e,t,i){const s=this._getPluginReference(e,i),r=this._hknp.HP_Body_GetLinearVelocity(s.hpBodyId)[1];this._v3ToBvecRef(r,t)}_applyToBodyOrInstances(e,t,i){var s;if(((s=e._pluginDataInstances)===null||s===void 0?void 0:s.length)>0&&i===void 0)for(let r=0;r{this._hknp.HP_Body_ApplyImpulse(r.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))},s)}applyForce(e,t,i,s){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,s)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,s=>{this._hknp.HP_Body_SetAngularVelocity(s.hpBodyId,this._bVecToV3(t))},i)}getAngularVelocityToRef(e,t,i){const s=this._getPluginReference(e,i),r=this._hknp.HP_Body_GetAngularVelocity(s.hpBodyId)[1];this._v3ToBvecRef(r,t)}setPhysicsBodyTransformation(e,t){const i=e.transformNode;if(e.numInstances>0){const r=i._thinInstanceDataStorage.matrixData;if(!r)return;const n=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),r,0,n,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}setTargetTransform(e,t,i,s){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetTargetQTransform(r.hpBodyId,[this._bVecToV3(t),this._bQuatToV4(i)])},s)}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,s=>{this._hknp.HP_Body_SetGravityFactor(s.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 rh.SPHERE:{const s=i.radius||1,r=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateSphere(r,s)[1]}break;case rh.BOX:{const s=i.rotation?this._bQuatToV4(i.rotation):[0,0,0,1],r=i.extents?this._bVecToV3(i.extents):[1,1,1],n=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateBox(n,s,r)[1]}break;case rh.CAPSULE:{const s=i.pointA?this._bVecToV3(i.pointA):[0,0,0],r=i.pointB?this._bVecToV3(i.pointB):[0,1,0],n=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCapsule(s,r,n)[1]}break;case rh.CONTAINER:e._pluginData=this._hknp.HP_Shape_CreateContainer()[1];break;case rh.CYLINDER:{const s=i.pointA?this._bVecToV3(i.pointA):[0,0,0],r=i.pointB?this._bVecToV3(i.pointB):[0,1,0],n=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCylinder(s,r,n)[1]}break;case rh.CONVEX_HULL:case rh.MESH:{const s=i.mesh;if(s){const r=!!i.includeChildMeshes,n=t!=rh.CONVEX_HULL,o=new Cxe(s,n,s?.getScene());o.addNodeMeshes(s,r);const l=o.getVertices(this._hknp),c=l.numObjects/3;if(t==rh.CONVEX_HULL)e._pluginData=this._hknp.HP_Shape_CreateConvexHull(l.offset,c)[1];else{const h=o.getTriangles(this._hknp),u=h.numObjects/3;e._pluginData=this._hknp.HP_Shape_CreateMesh(l.offset,c,h.offset,u)[1],o.freeBuffer(this._hknp,h)}o.freeBuffer(this._hknp,l)}else throw new Error("No mesh provided to create physics shape.")}break;default:throw new Error("Unsupported Shape Type.")}}setShapeFilterMembershipMask(e,t){const i=this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][1];this._hknp.HP_Shape_SetFilterInfo(e._pluginData,[t,i])}getShapeFilterMembershipMask(e){return this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][0]}setShapeFilterCollideMask(e,t){const i=this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][0];this._hknp.HP_Shape_SetFilterInfo(e._pluginData,[i,t])}getShapeFilterCollideMask(e){return this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][1]}setMaterial(e,t){var i,s,r,n,o;const l=(i=t.friction)!==null&&i!==void 0?i:.5,c=(s=t.staticFriction)!==null&&s!==void 0?s:l,h=(r=t.restitution)!==null&&r!==void 0?r:0,u=(n=t.frictionCombine)!==null&&n!==void 0?n:EM.MINIMUM,p=(o=t.restitutionCombine)!==null&&o!==void 0?o:EM.MAXIMUM,m=[c,l,h,this._materialCombineToNative(u),this._materialCombineToNative(p)];this._hknp.HP_Shape_SetMaterial(e._pluginData,m)}setDensity(e,t){this._hknp.HP_Shape_SetDensity(e._pluginData,t)}getDensity(e){return this._hknp.HP_Shape_GetDensity(e._pluginData)[1]}_getTransformInfos(e){if(e.parent)return e.computeWorldMatrix(!0),[this._bVecToV3(e.absolutePosition),this._bQuatToV4(e.absoluteRotationQuaternion)];let t=ue.Quaternion[0];if(e.rotationQuaternion)t=e.rotationQuaternion;else{const s=e.rotation;ke.FromEulerAnglesToRef(s.x,s.y,s.z,t)}return[this._bVecToV3(e.position),this._bQuatToV4(t)]}addChild(e,t,i,s,r){const n=[i?this._bVecToV3(i):[0,0,0],s?this._bQuatToV4(s):[0,0,0,1],r?this._bVecToV3(r):[1,1,1]];this._hknp.HP_Shape_AddChild(e._pluginData,t._pluginData,n)}removeChild(e,t){this._hknp.HP_Shape_RemoveChild(e._pluginData,t)}getNumChildren(e){return this._hknp.HP_Shape_GetNumChildren(e._pluginData)[1]}setTrigger(e,t){this._hknp.HP_Shape_SetTrigger(e._pluginData,t)}getBoundingBox(e){return{}}getBodyGeometry(e){var t;const i=((t=e._pluginDataInstances)===null||t===void 0?void 0:t.length)>0?e._pluginDataInstances[0]:e._pluginData,s=this._hknp.HP_Body_GetShape(i.hpBodyId)[1],r=this._hknp.HP_Shape_CreateDebugDisplayGeometry(s);if(r[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const n=this._hknp.HP_DebugGeometry_GetInfo(r[1])[1],o=new Float32Array(this._hknp.HEAPU8.buffer,n[0],n[1]*3),l=new Uint32Array(this._hknp.HEAPU8.buffer,n[2],n[3]*3),c=o.slice(0),h=l.slice(0);return this._hknp.HP_DebugGeometry_Release(r[1]),{positions:c,indices:h}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,s,r){var n,o,l,c,h;const u=e.type,p=e.options;if(!u||!p){Me.Warn("No constraint type or options. Constraint is invalid.");return}if(t._pluginDataInstances.length>0&&s===void 0||i._pluginDataInstances.length>0&&r===void 0){Me.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");return}e._pluginData=(n=e._pluginData)!==null&&n!==void 0?n:[];const m=this._hknp.HP_Constraint_Create()[1];e._pluginData.push(m);const _=this._getPluginReference(t,s).hpBodyId,f=this._getPluginReference(i,r).hpBodyId;this._hknp.HP_Constraint_SetParentBody(m,_),this._hknp.HP_Constraint_SetChildBody(m,f),this._constraintToBodyIdPair.set(m[0],[_[0],f[0]]);const d=p.pivotA?this._bVecToV3(p.pivotA):this._bVecToV3(O.Zero()),C=(o=p.axisA)!==null&&o!==void 0?o:new O(1,0,0),v=this._tmpVec3[0];p.perpAxisA?v.copyFrom(p.perpAxisA):C.getNormalToRef(v),this._hknp.HP_Constraint_SetAnchorInParent(m,d,this._bVecToV3(C),this._bVecToV3(v));const y=p.pivotB?this._bVecToV3(p.pivotB):this._bVecToV3(O.Zero()),M=(l=p.axisB)!==null&&l!==void 0?l:new O(1,0,0),b=this._tmpVec3[0];if(p.perpAxisB?b.copyFrom(p.perpAxisB):M.getNormalToRef(b),this._hknp.HP_Constraint_SetAnchorInChild(m,y,this._bVecToV3(M),this._bVecToV3(b)),e._initOptions||(e._initOptions={axisA:C.clone(),axisB:M.clone(),perpAxisA:v.clone(),perpAxisB:b.clone(),pivotA:new O(d[0],d[1],d[2]),pivotB:new O(y[0],y[1],y[2])}),u==qf.LOCK)this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(u==qf.DISTANCE){const S=p.maxDistance||0,I=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(m,I,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(m,I,S),this._hknp.HP_Constraint_SetAxisMaxLimit(m,I,S)}else if(u==qf.HINGE)this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(u==qf.PRISMATIC)this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(u==qf.SLIDER)this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(u==qf.BALL_AND_SOCKET)this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(m,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(u==qf.SIX_DOF){const S=e;for(const I of S.limits){const D=this._constraintAxisToNative(I.axis);((c=I.minLimit)!==null&&c!==void 0?c:-1)==0&&((h=I.maxLimit)!==null&&h!==void 0?h:-1)==0?this._hknp.HP_Constraint_SetAxisMode(m,D,this._hknp.ConstraintAxisLimitMode.LOCKED):(I.minLimit!=null&&(this._hknp.HP_Constraint_SetAxisMode(m,D,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(m,D,I.minLimit)),I.maxLimit!=null&&(this._hknp.HP_Constraint_SetAxisMode(m,D,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(m,D,I.maxLimit))),I.stiffness&&this._hknp.HP_Constraint_SetAxisStiffness(m,D,I.stiffness),I.damping&&this._hknp.HP_Constraint_SetAxisDamping(m,D,I.damping)}}else throw new Error("Unsupported Constraint Type.");const E=!!p.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(m,E),this._hknp.HP_Constraint_SetEnabled(m,!0)}getBodiesUsingConstraint(e){const t=[];for(const i of e._pluginData){const s=this._constraintToBodyIdPair.get(i[0]);if(s){const r=this._bodies.get(s[0]),n=this._bodies.get(s[1]);r&&n&&t.push({parentBody:r.body,parentBodyIndex:r.index,childBody:n.body,childBodyIndex:n.index})}}return t}addConstraint(e,t,i,s,r){this.initConstraint(i,e,t,s,r)}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 s of e._pluginData)this._hknp.HP_Constraint_SetAxisFriction(s,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 s of e._pluginData)this._hknp.HP_Constraint_SetAxisMode(s,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=e._pluginData&&e._pluginData[0];if(i){const s=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(s)}return null}setAxisMinLimit(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMinLimit(s,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 s of e._pluginData)this._hknp.HP_Constraint_SetAxisMaxLimit(s,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 s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorType(s,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 s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorTarget(s,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 s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorMaxForce(s,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}raycast(e,t,i,s){var r,n;const o=(r=s?.membership)!==null&&r!==void 0?r:-1,l=(n=s?.collideWith)!==null&&n!==void 0?n:-1;i.reset(e,t);const c=[this._bVecToV3(e),this._bVecToV3(t),[o,l]];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,c),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const h=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1],u=h[1][3],p=h[1][4],m=h[1][5];i.setHitData({x:p[0],y:p[1],z:p[2]},{x:u[0],y:u[1],z:u[2]},m),i.calculateHitDistance();const _=this._bodies.get(h[1][0][0]);i.body=_?.body,i.bodyIndex=_?.index}}getCollisionObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionObservable.get(t);return i||(i=new Se,this._bodyCollisionObservable.set(t,i)),i}getCollisionEndedObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionEndedObservable.get(t);return i||(i=new Se,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(s=>{this._hknp.HP_Body_SetEventMask(s.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 s=this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1];s=t?s|this._hknp.EventType.COLLISION_FINISHED.value:s&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach(r=>{this._hknp.HP_Body_SetEventMask(r.hpBodyId,s)}):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,s)}_notifyTriggers(){let e=this._hknp.HP_World_GetTriggerEvents(this.world)[1];const t=new vre;for(;e;){vre.readToRef(this._hknp.HEAPU8.buffer,e,t);const i=this._bodies.get(t.bodyIdA),s=this._bodies.get(t.bodyIdB),r={collider:i.body,colliderIndex:i.index,collidedAgainst:s.body,collidedAgainstIndex:s.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(r),e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new gre,i=Number(this.world);for(;e;){gre.readToRef(this._hknp.HEAPU8.buffer,e,t);const s=this._bodies.get(t.contactOnA.bodyId),r=this._bodies.get(t.contactOnB.bodyId),n={collider:s.body,colliderIndex:s.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,type:this._nativeCollisionValueToCollisionType(t.type)};if(n.type===U5.COLLISION_FINISHED)this.onCollisionEndedObservable.notifyObservers(n);else{t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);const o=O.Dot(this._tmpVec3[0],t.contactOnA.normal);n.point=t.contactOnA.position,n.distance=o,n.impulse=t.impulseApplied,n.normal=t.contactOnA.normal,this.onCollisionObservable.notifyObservers(n)}if(this._bodyCollisionObservable.size&&n.type!==U5.COLLISION_FINISHED){const o=this._bodyCollisionObservable.get(t.contactOnA.bodyId),l=this._bodyCollisionObservable.get(t.contactOnB.bodyId);o?o.notifyObservers(n):l&&(n.collider=r.body,n.colliderIndex=r.index,n.collidedAgainst=s.body,n.collidedAgainstIndex=s.index,n.normal=t.contactOnB.normal,l.notifyObservers(n))}else if(this._bodyCollisionEndedObservable.size){const o=this._bodyCollisionEndedObservable.get(t.contactOnA.bodyId),l=this._bodyCollisionEndedObservable.get(t.contactOnB.bodyId);o?o.notifyObservers(n):l&&(n.collider=r.body,n.colliderIndex=r.index,n.collidedAgainst=s.body,n.collidedAgainstIndex=s.index,n.normal=t.contactOnB.normal,l.notifyObservers(n))}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 AL.POSITION:return this._hknp.ConstraintMotorType.POSITION;case AL.VELOCITY:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE}_nativeToMotorType(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return AL.POSITION;case this._hknp.ConstraintMotorType.VELOCITY:return AL.VELOCITY}return AL.NONE}_materialCombineToNative(e){switch(e){case EM.GEOMETRIC_MEAN:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case EM.MINIMUM:return this._hknp.MaterialCombine.MINIMUM;case EM.MAXIMUM:return this._hknp.MaterialCombine.MAXIMUM;case EM.ARITHMETIC_MEAN:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case EM.MULTIPLY:return this._hknp.MaterialCombine.MULTIPLY}}_constraintAxisToNative(e){switch(e){case Nb.LINEAR_X:return this._hknp.ConstraintAxis.LINEAR_X;case Nb.LINEAR_Y:return this._hknp.ConstraintAxis.LINEAR_Y;case Nb.LINEAR_Z:return this._hknp.ConstraintAxis.LINEAR_Z;case Nb.ANGULAR_X:return this._hknp.ConstraintAxis.ANGULAR_X;case Nb.ANGULAR_Y:return this._hknp.ConstraintAxis.ANGULAR_Y;case Nb.ANGULAR_Z:return this._hknp.ConstraintAxis.ANGULAR_Z;case Nb.LINEAR_DISTANCE:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}}_nativeToLimitMode(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return bM.FREE;case this._hknp.ConstraintAxisLimitMode.LIMITED:return bM.LIMITED;case this._hknp.ConstraintAxisLimitMode.LOCKED:return bM.LOCKED}return bM.FREE}_limitModeToNative(e){switch(e){case bM.FREE:return this._hknp.ConstraintAxisLimitMode.FREE;case bM.LIMITED:return this._hknp.ConstraintAxisLimitMode.LIMITED;case bM.LOCKED:return this._hknp.ConstraintAxisLimitMode.LOCKED}}_nativeCollisionValueToCollisionType(e){switch(e){case this._hknp.EventType.COLLISION_STARTED.value:return U5.COLLISION_STARTED;case this._hknp.EventType.COLLISION_FINISHED.value:return U5.COLLISION_FINISHED;case this._hknp.EventType.COLLISION_CONTINUED.value:return U5.COLLISION_CONTINUED}return U5.COLLISION_STARTED}_nativeTriggerCollisionValueToCollisionType(e){switch(e){case 8:return U5.TRIGGER_ENTERED;case 16:return U5.TRIGGER_EXITED}return U5.TRIGGER_ENTERED}}oi.prototype.getPhysicsEngine=function(){return this._physicsEngine};oi.prototype.enablePhysics=function(a=null,e){if(this._physicsEngine)return!0;let t=this._getComponent(ai.NAME_PHYSICSENGINE);t||(t=new xxe(this),this._addComponent(t));try{if(!e||e?.getPluginVersion()===1)this._physicsEngine=new TW(a,e);else if(e?.getPluginVersion()===2)this._physicsEngine=new vQ(a,e);else throw new Error("Unsupported Physics plugin version.");return this._physicsTimeAccumulator=0,!0}catch(i){return Me.Error(i.message),!1}};oi.prototype.disablePhysicsEngine=function(){!this._physicsEngine||(this._physicsEngine.dispose(),this._physicsEngine=null)};oi.prototype.isPhysicsEnabled=function(){return this._physicsEngine!==void 0};oi.prototype.deleteCompoundImpostor=function(a){const e=a.parts[0].mesh;e.physicsImpostor&&(e.physicsImpostor.dispose(),e.physicsImpostor=null)};oi.prototype._advancePhysicsEngineStep=function(a){if(this._physicsEngine){const e=this._physicsEngine.getSubTimeStep();if(e>0)for(this._physicsTimeAccumulator+=a;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(a/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class xxe{constructor(e){this.name=ai.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new Se,this.scene.onAfterPhysicsObservable=new Se,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(Ki.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(a){this._physicsBody!==a&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=a,a&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0});Ki.prototype.getPhysicsBody=function(){return this.physicsBody};Ki.prototype.applyImpulse=function(a,e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(a,e),this};class PP{static GetContactPointToRef(e,t,i,s,r){const n=e.getScene().getPhysicsEngine(),o=n?.getPluginVersion();if(o===1){const c=new gr(t,i).intersectsMesh(e);if(c.hit&&c.pickedPoint)return s.copyFrom(c.pickedPoint),!0}else if(o===2)return e.physicsBody.getObjectCenterWorldToRef(s,r),!0;return!1}static HasAppliedForces(e,t){var i,s,r;return e.getMotionType(t)===K5.STATIC||((s=(i=e.getMassProperties(t))===null||i===void 0?void 0:i.mass)!==null&&s!==void 0?s:0)===0||((r=e.transformNode)===null||r===void 0?void 0:r.getTotalVertices())===0}static IsInsideCylinder(e,t,i,s){const r=ue.Vector3[0];return e.subtractToRef(t,r),Math.abs(r.x)<=i&&Math.abs(r.z)<=i&&r.y>=0&&r.y<=s}}class bxe{constructor(e){if(this._hitData={force:new O,contactPoint:new O,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),!this._physicsEngine){Me.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.");return}}applyRadialExplosionImpulse(e,t,i,s){if(!this._physicsEngine)return Me.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 r=!1;if(typeof t=="number"){const l=t;t=new sB,t.radius=l,t.strength=i??t.strength,t.falloff=s??t.falloff}else r=!!(t.affectedImpostorsCallback||t.affectedBodiesCallback);const n=new Cre(this._scene,t),o=this._hitData;if(this._physicsEngine.getPluginVersion()===1){const l=Array();this._physicsEngine.getImpostors().forEach(h=>{!n.getImpostorHitData(h,e,o)||(h.applyImpulse(o.force,o.contactPoint),r&&l.push({impostor:h,hitData:this._copyPhysicsHitData(o)}))}),n.triggerAffectedImpostorsCallback(l)}else this._applicationForBodies(n,e,o,r,(l,c)=>{l.applyImpulse(c.force,c.contactPoint,c.instanceIndex)});return n.dispose(!1),n}applyRadialExplosionForce(e,t,i,s){if(!this._physicsEngine)return Me.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 r=!1;if(typeof t=="number"){const l=t;t=new sB,t.radius=l,t.strength=i??t.strength,t.falloff=s??t.falloff}else r=!!(t.affectedImpostorsCallback||t.affectedBodiesCallback);const n=new Cre(this._scene,t),o=this._hitData;if(this._physicsEngine.getPluginVersion()===1){const l=Array();this._physicsEngine.getImpostors().forEach(h=>{!n.getImpostorHitData(h,e,o)||(h.applyForce(o.force,o.contactPoint),r&&l.push({impostor:h,hitData:this._copyPhysicsHitData(o)}))}),n.triggerAffectedImpostorsCallback(l)}else this._applicationForBodies(n,e,o,r,(l,c)=>{l.applyForce(c.force,c.contactPoint,c.instanceIndex)});return n.dispose(!1),n}_applicationForBodies(e,t,i,s,r){const n=Array(),o=this._physicsEngine.getBodies();for(const l of o)l.iterateOverAllInstances((c,h)=>{!e.getBodyHitData(c,t,i,h)||(r(c,i),s&&n.push({body:c,hitData:this._copyPhysicsHitData(i)}))});e.triggerAffectedBodiesCallback(n)}gravitationalField(e,t,i,s){if(!this._physicsEngine)return Me.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 n=t;t=new sB,t.radius=n,t.strength=i??t.strength,t.falloff=s??t.falloff}const r=new Exe(this,this._scene,e,t);return r.dispose(!1),r}updraft(e,t,i,s,r){if(!this._physicsEngine)return Me.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 Rte,t.radius=o,t.strength=i??t.strength,t.height=s??t.height,t.updraftMode=r??t.updraftMode}const n=new AQ(this._scene,e,t);return n.dispose(!1),n}vortex(e,t,i,s){if(!this._physicsEngine)return Me.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 n=t;t=new Pte,t.radius=n,t.strength=i??t.strength,t.height=s??t.height}const r=new ZB(this._scene,e,t);return r.dispose(!1),r}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class Cre{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options=Object.assign(Object.assign({},new sB),this._options)}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,s){const r=ue.Vector3[0];r.copyFrom(t).subtractInPlace(i);const n=ue.Vector3[1];if(!PP.GetContactPointToRef(e,i,r,n,s.instanceIndex))return!1;const l=O.Distance(i,n);if(l>this._options.radius)return!1;const c=this._options.falloff===tG.Constant?this._options.strength:this._options.strength*(1-l/this._options.radius);return r.scaleInPlace(c),s.force.copyFrom(r),s.contactPoint.copyFrom(n),s.distanceFromOrigin=l,!0}getBodyHitData(e,t,i,s){if(PP.HasAppliedForces(e,s))return!1;const r=e.transformNode,n=e.getObjectCenterWorld(s);return i.instanceIndex=s,this._getHitData(r,n,t,i)}getImpostorHitData(e,t,i){if(e.mass===0||e.object.getClassName()!=="Mesh"&&e.object.getClassName()!=="InstancedMesh")return!1;const s=e.object;if(!this._intersectsWithSphere(s,t,this._options.radius))return!1;const r=e.getObjectCenter();return this._getHitData(s,r,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=$d("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 Exe{constructor(e,t,i,s){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=s,this._dataFetched=!1,this._options=Object.assign(Object.assign({},new sB),this._options),this._tickCallback=this._tick.bind(this),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||e===void 0?void 0:e.clone("radialExplosionEventSphereClone"))}}}class AQ{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=O.Zero(),this._originDirection=O.Zero(),this._cylinderPosition=O.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new Rte),this._options),this._origin.addToRef(new O(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new O(0,this._options.height,0),this._originTop),this._options.updraftMode===qB.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this),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===qB.Perpendicular?i=this._originDirection:i=e.subtract(this._originTop);const s=O.Distance(this._origin,e),r=this._options.strength*-1,n=i.multiplyByFloats(r,r,r);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=s}_getBodyHitData(e,t,i){if(PP.HasAppliedForces(e))return!1;const s=e.getObjectCenterWorld(i);return PP.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)?(t.instanceIndex=i,this._getHitData(s,t),!0):!1}_getImpostorHitData(e,t){if(e.mass===0)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(s,t),!0}_tick(){const e=AQ._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,s)=>{!this._getBodyHitData(i,e,s)||i.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=J1("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}}AQ._HitData={force:new O,contactPoint:new O,distanceFromOrigin:0};class ZB{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=O.Zero(),this._cylinderPosition=O.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new Pte),this._options),this._origin.addToRef(new O(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new O(0,this._options.height,0),this._originTop),this._tickCallback=this._tick.bind(this),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 s=ZB.originOnPlane;s.set(this._origin.x,t.y,this._origin.z);const r=ue.Vector3[0];t.subtractToRef(s,r);const n=ue.Vector3[1];if(!PP.GetContactPointToRef(e,s,r,n,i.instanceIndex))return!1;const c=O.Distance(n,s)/this._options.radius,h=ue.Vector3[2];n.normalizeToRef(h),c>this._options.centripetalForceThreshold&&h.negateInPlace();let u,p,m;if(c>this._options.centripetalForceThreshold)u=h.x*this._options.centripetalForceMultiplier,p=h.y*this._options.updraftForceMultiplier,m=h.z*this._options.centripetalForceMultiplier;else{const f=O.Cross(s,t).normalize();u=(f.x+h.x)*this._options.centrifugalForceMultiplier,p=this._originTop.y*this._options.updraftForceMultiplier,m=(f.z+h.z)*this._options.centrifugalForceMultiplier}const _=ue.Vector3[3];return _.set(u,p,m),_.scaleInPlace(this._options.strength),i.force.copyFrom(_),i.contactPoint.copyFrom(t),i.distanceFromOrigin=c,!0}_getBodyHitData(e,t,i){if(PP.HasAppliedForces(e,i))return!1;const s=e.transformNode,r=e.getObjectCenterWorld(i);return PP.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)?(t.instanceIndex=i,this._getHitData(s,r,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 s=e.getObjectCenter();return this._getHitData(i,s,t),!0}_tick(){const e=ZB.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,s)=>{!this._getBodyHitData(i,e,s)||i.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=J1("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)}}ZB.originOnPlane=O.Zero();ZB.hitData={force:new O,contactPoint:new O,distanceFromOrigin:0};class sB{constructor(){this.radius=5,this.strength=10,this.falloff=tG.Constant,this.sphere={segments:32,diameter:1}}}class Rte{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=qB.Center}}class Pte{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}var tG;(function(a){a[a.Constant=0]="Constant",a[a.Linear=1]="Linear"})(tG||(tG={}));var qB;(function(a){a[a.Center=0]="Center",a[a.Perpendicular=1]="Perpendicular"})(qB||(qB={}));const yxe="blackAndWhitePixelShader",Mxe=`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);}`;Ue.ShadersStore[yxe]=Mxe;class PW extends rs{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,s,r,n){super(e,"blackAndWhite",["degree"],null,t,i,s,r,n),this.degree=1,this.onApplyObservable.add(o=>{o.setFloat("degree",this.degree)})}static _Parse(e,t,i,s){return Kt.Parse(()=>new PW(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}z([X()],PW.prototype,"degree",void 0);$e("BABYLON.BlackAndWhitePostProcess",PW);class An{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!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 l=r.attachPostProcess(o);this._indicesForCamera[n].push(l)}),this._cameras[n]||(this._cameras[n]=r)}}_detachCameras(e){const t=Be.MakeArray(e||this._cameras);if(!!t)for(let i=0;i{s.detachPostProcess(o)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){const t=Be.MakeArray(e||this._cameras);if(!!t)for(let i=0;i{s.detachPostProcess(n)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}const Txe="extractHighlightsPixelShader",Sxe=`#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;}`;Ue.ShadersStore[Txe]=Sxe;class xQ extends rs{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0,l=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,o,void 0,null,l),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add(c=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&c.setTextureFromPostProcess("textureSampler",this._inputPostProcess),c.setFloat("threshold",Math.pow(this.threshold,GN)),c.setFloat("exposure",this._exposure)})}}z([X()],xQ.prototype,"threshold",void 0);$e("BABYLON.ExtractHighlightsPostProcess",xQ);const Ixe="bloomMergePixelShader",Lxe=`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); } +`;Ue.ShadersStore[Ixe]=Lxe;class bQ extends rs{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,o,l,c,h=0,u=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,o,l,c,null,h,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(p=>{p.setTextureFromPostProcess("textureSampler",t),p.setTextureFromPostProcessOutput("bloomBlur",i),p.setFloat("bloomWeight",this.weight)}),u||this.updateEffect()}}z([X()],bQ.prototype,"weight",void 0);$e("BABYLON.BloomMergePostProcess",bQ);class rJ extends An{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,s,r=0,n=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new xQ("highlights",1,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new Rh("horizontal blur",new lt(1,0),10,t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new Rh("vertical blur",new lt(0,1),10,t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new bQ("bloomMerge",this._downscale,this._blurY,i,t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),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,s){return Kt.Parse(()=>new c7(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}z([X()],c7.prototype,"aberrationAmount",void 0);z([X()],c7.prototype,"radialIntensity",void 0);z([X()],c7.prototype,"direction",void 0);z([X()],c7.prototype,"centerPosition",void 0);z([X()],c7.prototype,"screenWidth",void 0);z([X()],c7.prototype,"screenHeight",void 0);$e("BABYLON.ChromaticAberrationPostProcess",c7);const Dxe="circleOfConfusionPixelShader",Oxe=`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);} +`;Ue.ShadersStore[Dxe]=Oxe;class pD extends rs{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,o,l=0,c=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,o,null,l,void 0,null,c),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){Me.Warn("No depth texture set on CircleOfConfusionPostProcess");return}h.setTexture("depthSampler",this._depthTexture);const p=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);h.setFloat("focusDistance",this.focusDistance),h.setFloat("cocPrecalculation",p);const m=this._depthTexture.activeCamera;h.setFloat2("cameraMinMaxZ",m.minZ,m.maxZ-m.minZ)})}set depthTexture(e){this._depthTexture=e}}z([X()],pD.prototype,"lensSize",void 0);z([X()],pD.prototype,"fStop",void 0);z([X()],pD.prototype,"focusDistance",void 0);z([X()],pD.prototype,"focalLength",void 0);$e("BABYLON.CircleOfConfusionPostProcess",pD);const wxe="colorCorrectionPixelShader",Nxe=`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);}`;Ue.ShadersStore[wxe]=Nxe;class DW extends rs{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,o);const l=s?.getScene()||null;this._colorTableTexture=new Te(t,l,!0,!1,Te.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=Te.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=Te.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=c=>{c.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return Kt.Parse(()=>new DW(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}z([X()],DW.prototype,"colorTableUrl",void 0);$e("BABYLON.ColorCorrectionPostProcess",DW);const Bxe="convolutionPixelShader",Fxe=`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);}`;Ue.ShadersStore[Bxe]=Fxe;class h7 extends rs{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,o,l=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,o,null,l),this.kernel=t,this.onApply=c=>{c.setFloat2("screenSize",this.width,this.height),c.setArray("kernel",this.kernel)}}static _Parse(e,t,i,s){return Kt.Parse(()=>new h7(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,s)}}h7.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1];h7.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0];h7.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1];h7.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0];h7.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2];h7.GaussianKernel=[0,1,0,1,1,1,0,1,0];z([X()],h7.prototype,"kernel",void 0);$e("BABYLON.ConvolutionPostProcess",h7);class iG extends Rh{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,o,l=null,c=Te.BILINEAR_SAMPLINGMODE,h,u,p=0,m=!1,_=5){super(e,i,s,r,n,c=2,h,u,p,`#define DOF 1 +`,m,_),this.direction=i,this.externalTextureSamplerBinding=!!l,this.onApplyObservable.add(f=>{l!=null&&f.setTextureFromPostProcess("textureSampler",l),f.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)})}}z([X()],iG.prototype,"direction",void 0);$e("BABYLON.DepthOfFieldBlurPostProcess",iG);const Vxe="depthOfFieldMergePixelShader",zxe=`#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 +} +`;Ue.ShadersStore[Vxe]=zxe;class yde extends rs{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,o,l,c,h=0,u=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,o,l,c,null,h,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(p=>{p.setTextureFromPostProcess("textureSampler",t),p.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach((m,_)=>{p.setTextureFromPostProcessOutput("blurStep"+(s.length-_-1),m)})}),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+` +`),super.updateEffect(e,t,i,s,r,n)}}var DP;(function(a){a[a.Low=0]="Low",a[a.Medium=1]="Medium",a[a.High=2]="High"})(DP||(DP={}));class nJ extends An{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=DP.Low,s=0,r=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];const n=e.getEngine(),o=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new pD("circleOfConfusion",t,1,null,Te.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let l=1,c=15;switch(i){case DP.High:{l=3,c=51;break}case DP.Medium:{l=2,c=31;break}default:{c=15,l=1;break}}const h=c/Math.pow(2,l-1);let u=1;for(let p=0;pnew EQ(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}$e("BABYLON.DisplayPassPostProcess",EQ);const Hxe="filterPixelShader",jxe=`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);}`;Ue.ShadersStore[Hxe]=jxe;class OW extends rs{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"filter",["kernelMatrix"],null,i,s,r,n,o),this.kernelMatrix=t,this.onApply=l=>{l.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return Kt.Parse(()=>new OW(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}z([vK()],OW.prototype,"kernelMatrix",void 0);$e("BABYLON.FilterPostProcess",OW);const Gxe="fxaaPixelShader",Wxe=`#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;c.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,s){return Kt.Parse(()=>new mD(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}$e("BABYLON.FxaaPostProcess",mD);const Kxe="grainPixelShader",Qxe=`#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);}`;Ue.ShadersStore[Kxe]=Qxe;class _D extends rs{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,o=0,l=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,o,void 0,null,l),this.intensity=30,this.animated=!1,this.onApplyObservable.add(c=>{c.setFloat("intensity",this.intensity),c.setFloat("animatedSeed",this.animated?Math.random()+1:1)})}static _Parse(e,t,i,s){return Kt.Parse(()=>new _D(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}z([X()],_D.prototype,"intensity",void 0);z([X()],_D.prototype,"animated",void 0);$e("BABYLON.GrainPostProcess",_D);const Zxe="highlightsPixelShader",qxe=`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); }`;Ue.ShadersStore[Zxe]=qxe;class Jxe extends rs{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0){super(e,"highlights",null,null,t,i,s,r,n,null,o)}}const $xe="mrtFragmentDeclaration",ebe=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +layout(location=0) out vec4 glFragData[{X}]; +#endif +`;Ue.IncludesShadersStore[$xe]=ebe;const tbe="geometryPixelShader",ibe=`#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 +normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); +#else +normalOutput=normalize(vNormalV); +#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 +} +`;Ue.ShadersStore[tbe]=ibe;const sbe="geometryVertexDeclaration",rbe="uniform mat4 viewProjection;uniform mat4 view;";Ue.IncludesShadersStore[sbe]=rbe;const nbe="geometryUboDeclaration",abe=`#include +`;Ue.IncludesShadersStore[nbe]=abe;const obe="geometryVertexShader",lbe=`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 +vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); +#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 +} +`;Ue.ShadersStore[obe]=lbe;const Mde=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];lh(Mde);class dl{_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===dl.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===dl.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===dl.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===dl.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===dl.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 dl.POSITION_TEXTURE_TYPE:return this._positionIndex;case dl.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case dl.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;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 this._ratio}constructor(e,t=1,i=15){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new Zt(0,0,0,0),this._clearDepthColor=new Zt(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._ratio=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,dl._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[se.PositionKind,se.NormalKind],n=e.getMesh();if(i){let m=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(s.push("#define ALPHATEST"),s.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),m=!0),i.bumpTexture&&Xt.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),m=!0),this._enableReflectivity){let _=!1;i.getClassName()==="PBRMetallicRoughnessMaterial"?(i.metallicRoughnessTexture!==null&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),m=!0,_=!0),i.metallic!==null&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),_=!0),i.roughness!==null&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),_=!0),_&&(i.baseTexture!==null&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),m=!0),i.baseColor!==null&&s.push("#define ALBEDOCOLOR"))):i.getClassName()==="PBRSpecularGlossinessMaterial"?(i.specularGlossinessTexture!==null?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),m=!0,i.specularGlossinessTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor!==null&&s.push("#define REFLECTIVITYCOLOR"),i.glossiness!==null&&s.push("#define GLOSSINESS")):i.getClassName()==="PBRMaterial"?(i.metallicTexture!==null&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),m=!0,_=!0),i.metallic!==null&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),_=!0),i.roughness!==null&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),_=!0),_?(i.albedoTexture!==null&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),m=!0),i.albedoColor!==null&&s.push("#define ALBEDOCOLOR")):(i.reflectivityTexture!==null?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),m=!0):i.reflectivityColor!==null&&s.push("#define REFLECTIVITYCOLOR"),i.microSurface!==null&&s.push("#define GLOSSINESS"))):i.getClassName()==="StandardMaterial"&&(i.specularTexture!==null&&(s.push("#define REFLECTIVITYTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),m=!0),i.specularColor!==null&&s.push("#define REFLECTIVITYCOLOR"))}m&&(s.push("#define NEED_UV"),n.isVerticesDataPresent(se.UVKind)&&(r.push(se.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(se.UV2Kind)&&(r.push(se.UV2Kind),s.push("#define UV2")))}this._linkedWithPrePass&&(s.push("#define PREPASS"),this._depthIndex!==-1&&(s.push("#define DEPTH_INDEX "+this._depthIndex),s.push("#define PREPASS_DEPTH")),this._normalIndex!==-1&&(s.push("#define NORMAL_INDEX "+this._normalIndex),s.push("#define PREPASS_NORMAL"))),this._enablePosition&&(s.push("#define POSITION"),s.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(s.push("#define VELOCITY"),s.push("#define VELOCITY_INDEX "+this._velocityIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(n)===-1&&s.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(s.push("#define REFLECTIVITY"),s.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),n.useBones&&n.computeBonesUsingShaders?(r.push(se.MatricesIndicesKind),r.push(se.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(se.MatricesIndicesExtraKind),r.push(se.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0");const o=n.morphTargetManager;let l=0;o&&o.numInfluencers>0&&(l=o.numInfluencers,s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+l),o.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),ze.PrepareAttributesForMorphTargetsInfluencers(r,n,l)),t&&(s.push("#define INSTANCES"),ze.PushAttributesForInstances(r,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES")),this._linkedWithPrePass?s.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):s.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),PI(i,this._scene,s);const c=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),u=h.defines,p=s.join(` +`);return u!==p&&h.setEffect(c.createEffect("geometry",{attributes:r,uniformsNames:Mde,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets"],defines:p,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:l}},c),p),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=[];let t=2;return e.push("gBuffer_Depth","gBuffer_Normal"),this._enablePosition&&(this._positionIndex=t,t++,e.push("gBuffer_Position")),this._enableVelocity&&(this._velocityIndex=t,t++,e.push("gBuffer_Velocity")),this._enableReflectivity&&(this._reflectivityIndex=t,t++,e.push("gBuffer_Reflectivity")),[t,e]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i]=this._assignRenderTargetIndices();let s=0;if(e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2),this._multiRenderTarget=new CL("gBuffer",{width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio},t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:s,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=Te.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Te.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const r=[!0],n=[!1],o=[!0];for(let p=1;p{p.bindAttachments(this.useSpecificClearForDepthTexture?c:l),p.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(p.bindAttachments(h),p.clear(this._clearDepthColor,!0,!0,!0)),p.bindAttachments(l)}),this._resizeObserver=e.onResizeObservable.add(()=>{this._multiRenderTarget&&this._multiRenderTarget.resize({width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio})});const u=p=>{const m=p.getRenderingMesh(),_=p.getEffectiveMesh(),f=this._scene,d=f.getEngine(),C=p.getMaterial();if(!C)return;if(_._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[_.uniqueId]&&(this._previousTransformationMatrices[_.uniqueId]={world:ge.Identity(),viewProjection:f.getTransformMatrix()},m.skeleton)){const b=m.skeleton.getTransformMatrices(m);this._previousBonesTransformationMatrices[m.uniqueId]=this._copyBonesTransformationMatrices(b,new Float32Array(b.length))}const v=m._getInstancesRenderList(p._id,!!p.getReplacementMesh());if(v.mustReturn)return;const y=d.getCaps().instancedArrays&&(v.visibleInstances[p._id]!==null||m.hasThinInstances),M=_.getWorldMatrix();if(this.isReady(p,y)){const b=p._getDrawWrapper();if(!b)return;const E=b.effect;d.enableEffect(b),y||m._bind(p,E,C.fillMode),this._useUbo?(ze.BindSceneUniformBuffer(E,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(E.setMatrix("viewProjection",f.getTransformMatrix()),E.setMatrix("view",f.getViewMatrix()));let S;const I=m._instanceDataStorage;if(!I.isFrozen&&(C.backFaceCulling||m.overrideMaterialSideOrientation!==null)){const D=_._getWorldMatrixDeterminant();S=m.overrideMaterialSideOrientation,S===null&&(S=C.sideOrientation),D<0&&(S=S===Lt.ClockWiseSideOrientation?Lt.CounterClockWiseSideOrientation:Lt.ClockWiseSideOrientation)}else S=I.sideOrientation;if(C._preBind(b,S),C.needAlphaTesting()){const D=C.getAlphaTestTexture();D&&(E.setTexture("diffuseSampler",D),E.setMatrix("diffuseMatrix",D.getTextureMatrix()))}C.bumpTexture&&f.getEngine().getCaps().standardDerivatives&&Xt.BumpTextureEnabled&&(E.setFloat3("vBumpInfos",C.bumpTexture.coordinatesIndex,1/C.bumpTexture.level,C.parallaxScaleBias),E.setMatrix("bumpMatrix",C.bumpTexture.getTextureMatrix()),E.setTexture("bumpSampler",C.bumpTexture),E.setFloat2("vTangentSpaceParams",C.invertNormalMapX?-1:1,C.invertNormalMapY?-1:1)),this._enableReflectivity&&(C.getClassName()==="PBRMetallicRoughnessMaterial"?(C.metallicRoughnessTexture!==null&&(E.setTexture("reflectivitySampler",C.metallicRoughnessTexture),E.setMatrix("reflectivityMatrix",C.metallicRoughnessTexture.getTextureMatrix())),C.metallic!==null&&E.setFloat("metallic",C.metallic),C.roughness!==null&&E.setFloat("glossiness",1-C.roughness),C.baseTexture!==null&&(E.setTexture("albedoSampler",C.baseTexture),E.setMatrix("albedoMatrix",C.baseTexture.getTextureMatrix())),C.baseColor!==null&&E.setColor3("albedoColor",C.baseColor)):C.getClassName()==="PBRSpecularGlossinessMaterial"?(C.specularGlossinessTexture!==null?(E.setTexture("reflectivitySampler",C.specularGlossinessTexture),E.setMatrix("reflectivityMatrix",C.specularGlossinessTexture.getTextureMatrix())):C.specularColor!==null&&E.setColor3("reflectivityColor",C.specularColor),C.glossiness!==null&&E.setFloat("glossiness",C.glossiness)):C.getClassName()==="PBRMaterial"?(C.metallicTexture!==null&&(E.setTexture("reflectivitySampler",C.metallicTexture),E.setMatrix("reflectivityMatrix",C.metallicTexture.getTextureMatrix())),C.metallic!==null&&E.setFloat("metallic",C.metallic),C.roughness!==null&&E.setFloat("glossiness",1-C.roughness),C.roughness!==null||C.metallic!==null||C.metallicTexture!==null?(C.albedoTexture!==null&&(E.setTexture("albedoSampler",C.albedoTexture),E.setMatrix("albedoMatrix",C.albedoTexture.getTextureMatrix())),C.albedoColor!==null&&E.setColor3("albedoColor",C.albedoColor)):(C.reflectivityTexture!==null?(E.setTexture("reflectivitySampler",C.reflectivityTexture),E.setMatrix("reflectivityMatrix",C.reflectivityTexture.getTextureMatrix())):C.reflectivityColor!==null&&E.setColor3("reflectivityColor",C.reflectivityColor),C.microSurface!==null&&E.setFloat("glossiness",C.microSurface))):C.getClassName()==="StandardMaterial"&&(C.specularTexture!==null&&(E.setTexture("reflectivitySampler",C.specularTexture),E.setMatrix("reflectivityMatrix",C.specularTexture.getTextureMatrix())),C.specularColor!==null&&E.setColor3("reflectivityColor",C.specularColor))),wc(E,C,this._scene),m.useBones&&m.computeBonesUsingShaders&&m.skeleton&&(E.setMatrices("mBones",m.skeleton.getTransformMatrices(m)),this._enableVelocity&&E.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[m.uniqueId])),ze.BindMorphTargetParameters(m,E),m.morphTargetManager&&m.morphTargetManager.isUsingTextureForTargets&&m.morphTargetManager._bind(E),this._enableVelocity&&(E.setMatrix("previousWorld",this._previousTransformationMatrices[_.uniqueId].world),E.setMatrix("previousViewProjection",this._previousTransformationMatrices[_.uniqueId].viewProjection)),y&&m.hasThinInstances&&E.setMatrix("world",M),m._processRendering(_,p,E,C.fillMode,v,y,(D,R)=>{D||E.setMatrix("world",R)})}this._enableVelocity&&(this._previousTransformationMatrices[_.uniqueId].world=M.clone(),this._previousTransformationMatrices[_.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),m.skeleton&&this._copyBonesTransformationMatrices(m.skeleton.getTransformMatrices(m),this._previousBonesTransformationMatrices[_.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(p,m,_)=>{if((_||m===0)&&p.subMeshes)for(let f=0;f{let d;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(f.length){for(e.setColorWrite(!1),d=0;d{throw Ys("GeometryBufferRendererSceneComponent")};class cbe{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(oi.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(a){a&&a.isSupported&&(this._geometryBufferRenderer=a)},enumerable:!0,configurable:!0});oi.prototype.enableGeometryBufferRenderer=function(a=1,e=15){return this._geometryBufferRenderer?this._geometryBufferRenderer:(this._geometryBufferRenderer=new dl(this,a,e),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null),this._geometryBufferRenderer)};oi.prototype.disableGeometryBufferRenderer=function(){!this._geometryBufferRenderer||(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class Tde{constructor(e){this.name=ai.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ai.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}dl._SceneComponentInitialization=a=>{let e=a._getComponent(ai.NAME_GEOMETRYBUFFERRENDERER);e||(e=new Tde(a),a._addComponent(e))};const hbe="motionBlurPixelShader",ube=`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 +} +`;Ue.ShadersStore[hbe]=ube;class eR extends rs{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,s,r,n,o,l=0,c=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,o,`#define GEOMETRY_SUPPORTED +#define SAMPLES 64.0 +#define OBJECT_BASED`,l,void 0,null,c),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=!0)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new cbe)),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 Me.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();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=ge.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 lt(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(dl.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=ue.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 lt(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const i=this._geometryBufferRenderer.getTextureIndex(dl.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,s){return Kt.Parse(()=>new eR(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}z([X()],eR.prototype,"motionStrength",void 0);z([X()],eR.prototype,"motionBlurSamples",null);z([X()],eR.prototype,"isObjectBased",null);$e("BABYLON.MotionBlurPostProcess",eR);const dbe="refractionPixelShader",fbe="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);}";Ue.ShadersStore[dbe]=fbe;class tR extends rs{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,s,r,n,o,l,c,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,l,c,h),this._ownRefractionTexture=!0,this.color=i,this.depth=s,this.colorLevel=r,this.refractionTextureUrl=t,this.onActivateObservable.add(u=>{this._refTexture=this._refTexture||new Te(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,s){return Kt.Parse(()=>new tR(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}z([X()],tR.prototype,"color",void 0);z([X()],tR.prototype,"depth",void 0);z([X()],tR.prototype,"colorLevel",void 0);z([X()],tR.prototype,"refractionTextureUrl",void 0);$e("BABYLON.RefractionPostProcess",tR);const pbe="sharpenPixelShader",mbe=`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.);}`;Ue.ShadersStore[pbe]=mbe;class gD extends rs{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,o=0,l=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,o,void 0,null,l),this.colorAmount=1,this.edgeAmount=.3,this.onApply=c=>{c.setFloat2("screenSize",this.width,this.height),c.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return Kt.Parse(()=>new gD(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}z([X()],gD.prototype,"colorAmount",void 0);z([X()],gD.prototype,"edgeAmount",void 0);$e("BABYLON.SharpenPostProcess",gD);class iR{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(Be.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];!i||i._disable(Be.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Be.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}setPrePassRenderer(e){return!1}dispose(){}}z([X()],iR.prototype,"_name",void 0);class Sde{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 s=this._renderPipelines[e];!s||s._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];!i||i._detachCameras(t)}enableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];!s||s._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];!s||s._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(oi.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let a=this._getComponent(ai.NAME_POSTPROCESSRENDERPIPELINEMANAGER);a||(a=new Ide(this),this._addComponent(a)),this._postProcessRenderPipelineManager=new Sde}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class Ide{constructor(e){this.name=ai.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ai.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 xd extends iR{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 rJ(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 nJ(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 rJ(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new c7("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,Te.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new An(o,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new _D("Grain",1,null,Te.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new An(o,this.GrainPostProcessId,()=>this.grain,!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,Be.SetImmediate(()=>{this._buildPipeline()}))}),this._buildPipeline()}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 lW("imageProcessing",1,null,Te.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new An(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 mD("fxaa",1,null,Te.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new An(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._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&Me.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 xd(e._name,e._name._hdr,t),e,t,i)}}z([X()],xd.prototype,"sharpenEnabled",null);z([X()],xd.prototype,"bloomKernel",null);z([X()],xd.prototype,"_bloomWeight",void 0);z([X()],xd.prototype,"_bloomThreshold",void 0);z([X()],xd.prototype,"_hdr",void 0);z([X()],xd.prototype,"bloomWeight",null);z([X()],xd.prototype,"bloomThreshold",null);z([X()],xd.prototype,"bloomScale",null);z([X()],xd.prototype,"bloomEnabled",null);z([X()],xd.prototype,"depthOfFieldEnabled",null);z([X()],xd.prototype,"depthOfFieldBlurLevel",null);z([X()],xd.prototype,"fxaaEnabled",null);z([X()],xd.prototype,"samples",null);z([X()],xd.prototype,"imageProcessingEnabled",null);z([X()],xd.prototype,"glowLayerEnabled",null);z([X()],xd.prototype,"chromaticAberrationEnabled",null);z([X()],xd.prototype,"grainEnabled",null);$e("BABYLON.DefaultRenderingPipeline",xd);const _be="lensHighlightsPixelShader",gbe=`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;}`;Ue.ShadersStore[_be]=gbe;const vbe="depthOfFieldPixelShader",Cbe=`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;}} +`;Ue.ShadersStore[vbe]=Cbe;class Abe extends iR{constructor(e,t,i,s=1,r){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(s),this._createHighlightsPostProcess(s),this._createDepthOfFieldPostProcess(s/4),this.addEffect(new An(i.getEngine(),this.LensChromaticAberrationEffect,()=>this._chromaticAberrationPostProcess,!0)),this.addEffect(new An(i.getEngine(),this.HighlightsEnhancingEffect,()=>this._highlightsPostProcess,!0)),this.addEffect(new An(i.getEngine(),this.LensDepthOfFieldEffect,()=>this._depthOfFieldPostProcess,!0)),this._highlightsGain===-1&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),r&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}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 rs("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,Te.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 rs("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,Te.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 rs("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,Te.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 s=0;s1e-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 An(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new An(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new An(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new An(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let t=0;t{if(!this._scene.activeCamera)return;const c=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,h=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;l.setFloat("outSize",c>0?c:h),l.setInt("samples",this.bilateralSamples),l.setFloat("soften",this.bilateralSoften),l.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?l.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&l.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,s=1-e*.85,r=Math.sqrt(1-s*s);return new O(Math.cos(i)*r,Math.sin(i)*r,s)}_generateHemisphere(){const e=this.samples,t=[];let i,s=0;for(;s{var n,o,l,c;if(!!this._scene.activeCamera){if(r.setArray3("sampleSphere",this._sampleSphere),r.setFloat("randTextureTiles",32),r.setFloat("samplesFactor",1/this.samples),r.setFloat("totalStrength",this.totalStrength),r.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),r.setFloat("radius",this.radius),r.setFloat("maxZ",this.maxZ),r.setFloat("minZAspect",this.minZAspect),r.setFloat("base",this.base),r.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===Pi.PERSPECTIVE_CAMERA)r.setMatrix3x3("depthProjection",Dh.PERSPECTIVE_DEPTH_PROJECTION),r.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),r.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const h=this._scene.getEngine().getRenderWidth()/2,u=this._scene.getEngine().getRenderHeight()/2,p=(n=this._scene.activeCamera.orthoLeft)!==null&&n!==void 0?n:-h,m=(o=this._scene.activeCamera.orthoRight)!==null&&o!==void 0?o:h,_=(l=this._scene.activeCamera.orthoBottom)!==null&&l!==void 0?l:-u,f=(c=this._scene.activeCamera.orthoTop)!==null&&c!==void 0?c:u;r.setMatrix3x3("depthProjection",Dh.ORTHO_DEPTH_PROJECTION),r.setFloat("xViewport",(m-p)*.5),r.setFloat("yViewport",(f-_)*.5)}r.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(r.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),r.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(r.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),r.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),r.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new xbe)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new rs("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Te.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=i=>{const s=this._scene.activeCamera.viewport;i.setVector4("viewport",ue.Vector4[0].copyFromFloats(s.x,s.y,s.width,s.height)),i.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const t=new Uint8Array(65536),i=lt.Zero();for(let r=0;rnew Dh(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}Dh.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1];Dh.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1];z([X()],Dh.prototype,"totalStrength",void 0);z([X()],Dh.prototype,"maxZ",void 0);z([X()],Dh.prototype,"minZAspect",void 0);z([X("epsilon")],Dh.prototype,"_epsilon",void 0);z([X("samples")],Dh.prototype,"_samples",void 0);z([X("textureSamples")],Dh.prototype,"_textureSamples",void 0);z([X()],Dh.prototype,"_forceGeometryBuffer",void 0);z([X()],Dh.prototype,"_ratio",void 0);z([X()],Dh.prototype,"_textureType",void 0);z([X()],Dh.prototype,"radius",void 0);z([X()],Dh.prototype,"base",void 0);z([X("bypassBlur")],Dh.prototype,"_bypassBlur",void 0);z([X("expensiveBlur")],Dh.prototype,"_expensiveBlur",void 0);z([X()],Dh.prototype,"bilateralSamples",void 0);z([X()],Dh.prototype,"bilateralSoften",void 0);z([X()],Dh.prototype,"bilateralTolerance",void 0);$e("BABYLON.SSAO2RenderingPipeline",Dh);const Tbe="ssaoPixelShader",Sbe=`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 An(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new An(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new An(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new An(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}_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],s=1/16;this._ssaoPostProcess=new rs("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Te.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES "+16+` +#define SSAO`),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=r=>{this._firstUpdate&&(r.setArray3("sampleSphere",i),r.setFloat("samplesFactor",s),r.setFloat("randTextureTiles",4)),r.setFloat("totalStrength",this.totalStrength),r.setFloat("radius",this.radius),r.setFloat("area",this.area),r.setFloat("fallOff",this.fallOff),r.setFloat("base",this.base),r.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),r.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new rs("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Te.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=t=>{t.setVector4("viewport",ue.Vector4[0].copyFromFloats(0,0,1,1)),t.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const t=new Uint8Array(1048576);for(let s=0;s0.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 p=this._geometryBufferRenderer,m=this._prePassRenderer;if(!m&&!p)return;if(p){const C=p.getTextureIndex(dl.POSITION_TEXTURE_TYPE),v=p.getTextureIndex(dl.REFLECTIVITY_TEXTURE_TYPE);u.setTexture("normalSampler",p.getGBuffer().textures[1]),u.setTexture("positionSampler",p.getGBuffer().textures[C]),u.setTexture("reflectivitySampler",p.getGBuffer().textures[v])}else if(m){const C=m.getIndex(1),v=m.getIndex(3),y=m.getIndex(6);u.setTexture("normalSampler",m.getRenderTarget().textures[y]),u.setTexture("positionSampler",m.getRenderTarget().textures[C]),u.setTexture("reflectivitySampler",m.getRenderTarget().textures[v])}const _=t.activeCamera;if(!_)return;const f=_.getViewMatrix(!0),d=_.getProjectionMatrix(!0);u.setMatrix("projection",d),u.setMatrix("view",f),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,s){return Kt.Parse(()=>new pv(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}z([X()],pv.prototype,"threshold",void 0);z([X()],pv.prototype,"strength",void 0);z([X()],pv.prototype,"reflectionSpecularFalloffExponent",void 0);z([X()],pv.prototype,"step",void 0);z([X()],pv.prototype,"roughnessFactor",void 0);z([X()],pv.prototype,"enableSmoothReflections",null);z([X()],pv.prototype,"reflectionSamples",null);z([X()],pv.prototype,"smoothSteps",null);$e("BABYLON.ScreenSpaceReflectionPostProcess",pv);const Pbe="standardPixelShader",Dbe=`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 +`;Ue.ShadersStore[Pbe]=Dbe;class On extends iR{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()){Me.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,s=null,r){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=r||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=s,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 pv("HDRPass",t,e,null,Te.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new An(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new rs("HDRPass","standard",[],[],e,null,Te.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 An(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 rs("HDRDepthOfFieldSource","standard",[],[],e,null,Te.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new An(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new rs("HDRVLSFinal","standard",[],[],e,null,Te.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new An(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new rs("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,Te.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new An(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new rs("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,Te.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new An(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 mD("fxaa",1,null,Te.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new An(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&Me.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 rs("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=s=>{let r=0;const n=this.downSampleX4PostProcess.width,o=this.downSampleX4PostProcess.height;for(let l=-2;l<2;l++)for(let c=-2;c<2;c++)i[r]=(l+.5)*(1/n),i[r+1]=(c+.5)*(1/o),r+=2;s.setArray2("dsOffsets",i)},this.addEffect(new An(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new rs("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=s=>{const r=1/this.brightPassPostProcess.width,n=1/this.brightPassPostProcess.height;i[0]=-.5*r,i[1]=.5*n,i[2]=.5*r,i[3]=.5*n,i[4]=-.5*r,i[5]=-.5*n,i[6]=.5*r,i[7]=-.5*n,s.setArray2("dsOffsets",i),s.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new An(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,s="blurWidth"){const r=e.getEngine(),n=new Rh("HDRBlurH_"+i,new lt(1,0),this[s],t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new Rh("HDRBlurV_"+i,new lt(0,1),this[s],t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add(()=>{const l=n.width/r.getRenderWidth();n.kernel=this[s]*l}),o.onActivateObservable.add(()=>{const l=o.height/r.getRenderHeight();o.kernel=this.horizontalBlur?64*l:this[s]*l}),this.addEffect(new An(e.getEngine(),"HDRBlurH"+i,()=>n,!0)),this.addEffect(new An(e.getEngine(),"HDRBlurV"+i,()=>o,!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new rs("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Te.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 An(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const s=i.getGBuffer();this.volumetricLightPostProcess=new rs("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define VLS +#define NB_STEPS `+this._volumetricLightStepsCount.toFixed(1));const r=lt.Zero();this.volumetricLightPostProcess.onApply=n=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const o=this.sourceLight.getShadowGenerator();n.setTexture("shadowMapSampler",o.getShadowMap()),n.setTexture("positionSampler",s.textures[2]),n.setColor3("sunColor",this.sourceLight.diffuse),n.setVector3("sunDirection",this.sourceLight.getShadowDirection()),n.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),n.setMatrix("shadowViewProjection",o.getTransformMatrix()),n.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),n.setFloat("scatteringPower",this.volumetricLightPower),r.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),r.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),n.setVector2("depthValues",r)}},this.addEffect(new An(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new rs("HDRVLSMerge","standard",[],["originalSampler"],t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=n=>{n.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new An(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,On.LuminanceSteps);this.luminancePostProcess=new rs("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const s=[];this.luminancePostProcess.onApply=n=>{const o=1/this.luminancePostProcess.width,l=1/this.luminancePostProcess.height;s[0]=-.5*o,s[1]=.5*l,s[2]=.5*o,s[3]=.5*l,s[4]=-.5*o,s[5]=-.5*l,s[6]=.5*o,s[7]=-.5*l,n.setArray2("lumOffsets",s)},this.addEffect(new An(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let n=On.LuminanceSteps-1;n>=0;n--){i=Math.pow(3,n);let o=`#define LUMINANCE_DOWN_SAMPLE +`;n===0&&(o+="#define FINAL_DOWN_SAMPLER");const l=new rs("HDRLuminanceDownSample"+n,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,o,t);this.luminanceDownSamplePostProcesses.push(l)}let r=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((n,o)=>{const l=new Array(18);n.onApply=c=>{if(!r)return;let h=0;for(let u=-1;u<2;u++)for(let p=-1;p<2;p++)l[h]=u/r.width,l[h+1]=p/r.height,h+=2;c.setArray2("dsOffsets",l),c.setFloat("halfDestPixelSize",.5/r.width),o===this.luminanceDownSamplePostProcesses.length-1?r=this.luminancePostProcess:r=n},o===this.luminanceDownSamplePostProcesses.length-1&&(n.onAfterRender=()=>{const c=e.getEngine().readPixels(0,0,1,1),h=new Ui(1/(255*255*255),1/(255*255),1/255,1);c.then(u=>{const p=new Uint8Array(u.buffer);this._hdrCurrentLuminance=(p[0]*h.x+p[1]*h.y+p[2]*h.z+p[3]*h.w)/100})}),this.addEffect(new An(e.getEngine(),"HDRLuminanceDownSample"+o,()=>n,!0))})}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new rs("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join(` +`),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=o=>{if(o.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const l=(n-r)/1e3;this._hdrCurrentLuminances-this.hdrIncreaseRate*l?s-=this.hdrIncreaseRate*l:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=Bt.Clamp(s,this.hdrMinimumLuminance,1e20),o.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new An(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new rs("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new An(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new rs("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new An(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));const i=new lt(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=n=>{n.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),n.setTexture("lensColorSampler",this.lensColorTexture),n.setFloat("strength",this.lensFlareStrength),n.setFloat("ghostDispersal",this.lensFlareGhostDispersal),n.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,n.setVector2("resolution",i),n.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const s=ge.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=ge.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=n=>{if(!this._scene.activeCamera)return;n.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),n.setTexture("lensDirtSampler",this.lensFlareDirtTexture),n.setTexture("lensStarSampler",this.lensStarTexture);const o=this._scene.activeCamera.getViewMatrix().getRow(0),l=this._scene.activeCamera.getViewMatrix().getRow(2);let c=O.Dot(o.toVector3(),new O(1,0,0))+O.Dot(l.toVector3(),new O(0,0,1));c*=4;const h=ge.FromValues(Math.cos(c)*.5,-Math.sin(c),0,0,Math.sin(c),Math.cos(c)*.5,0,0,0,0,1,0,0,0,0,1),u=r.multiply(h).multiply(s);n.setMatrix("lensStarMatrix",u),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new rs("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Te.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 An(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new eR("HDRMotionBlur",e,t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new rs("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Te.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define MOTION_BLUR +#define MAX_MOTION_SAMPLES `+this.motionBlurSamples.toFixed(1),0);let i=0,s=ge.Identity();const r=ge.Identity();let n=ge.Identity();const o=lt.Zero();this.motionBlurPostProcess.onApply=l=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),l.setMatrix("inverseViewProjection",r),l.setMatrix("prevViewProjection",s),s=n,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,l.setVector2("screenSize",o),i=e.getEngine().getFps()/60,l.setFloat("motionScale",i),l.setFloat("motionStrength",this.motionStrength),l.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new An(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 On(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&Kt.Parse(()=>s.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),s}}On.LuminanceSteps=6;z([X()],On.prototype,"brightThreshold",void 0);z([X()],On.prototype,"blurWidth",void 0);z([X()],On.prototype,"horizontalBlur",void 0);z([X()],On.prototype,"exposure",null);z([xs("lensTexture")],On.prototype,"lensTexture",void 0);z([X()],On.prototype,"volumetricLightCoefficient",void 0);z([X()],On.prototype,"volumetricLightPower",void 0);z([X()],On.prototype,"volumetricLightBlurScale",void 0);z([X()],On.prototype,"hdrMinimumLuminance",void 0);z([X()],On.prototype,"hdrDecreaseRate",void 0);z([X()],On.prototype,"hdrIncreaseRate",void 0);z([X()],On.prototype,"hdrAutoExposure",null);z([xs("lensColorTexture")],On.prototype,"lensColorTexture",void 0);z([X()],On.prototype,"lensFlareStrength",void 0);z([X()],On.prototype,"lensFlareGhostDispersal",void 0);z([X()],On.prototype,"lensFlareHaloWidth",void 0);z([X()],On.prototype,"lensFlareDistortionStrength",void 0);z([X()],On.prototype,"lensFlareBlurWidth",void 0);z([xs("lensStarTexture")],On.prototype,"lensStarTexture",void 0);z([xs("lensFlareDirtTexture")],On.prototype,"lensFlareDirtTexture",void 0);z([X()],On.prototype,"depthOfFieldDistance",void 0);z([X()],On.prototype,"depthOfFieldBlurWidth",void 0);z([X()],On.prototype,"motionStrength",null);z([X()],On.prototype,"objectBasedMotionBlur",null);z([X()],On.prototype,"_ratio",void 0);z([X()],On.prototype,"BloomEnabled",null);z([X()],On.prototype,"DepthOfFieldEnabled",null);z([X()],On.prototype,"LensFlareEnabled",null);z([X()],On.prototype,"HDREnabled",null);z([X()],On.prototype,"VLSEnabled",null);z([X()],On.prototype,"MotionBlurEnabled",null);z([X()],On.prototype,"fxaaEnabled",null);z([X()],On.prototype,"screenSpaceReflectionsEnabled",null);z([X()],On.prototype,"volumetricLightStepsCount",null);z([X()],On.prototype,"motionBlurSamples",null);z([X()],On.prototype,"samples",null);$e("BABYLON.StandardRenderingPipeline",On);class Obe{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}const wbe="screenSpaceRayTrace",Nbe=`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;} +`;Ue.IncludesShadersStore[wbe]=Nbe;const Bbe="screenSpaceReflection2PixelShader",Fbe=`#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; +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 +} +`;Ue.ShadersStore[Bbe]=Fbe;const Vbe="screenSpaceReflection2BlurPixelShader",zbe=`#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);} +`;Ue.ShadersStore[Vbe]=zbe;const Ube="screenSpaceReflection2BlurCombinerPixelShader",kbe=`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 +} +`;Ue.ShadersStore[Ube]=kbe;const Hbe=ge.Compose(new O(.5,.5,.5),ke.Identity(),new O(.5,.5,.5)),jbe=ge.Compose(new O(.5,.5,1),ke.Identity(),new O(.5,.5,0));class $a extends iR{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,s=!1,r=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=r,this._forceGeometryBuffer=s,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const n=t.enableGeometryBufferRenderer();n&&(n.enableReflectivity=!0,n.useSpecificClearForDepthTexture=!0)}else{const n=t.enablePrePassRenderer();n&&(n.useSpecificClearForDepthTexture=!0,n.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 e,t;const i=this._scene.getEngine(),s=this._prePassRenderer;let r={width:i.getRenderWidth(),height:i.getRenderHeight()};if(s&&((e=this._scene.activeCamera)===null||e===void 0?void 0:e._getFirstPostProcess())===this._ssrPostProcess){const n=s.getRenderTarget();n&&n.textures&&(r=n.textures[s.getIndex(4)].getSize())}else!((t=this._ssrPostProcess)===null||t===void 0)&&t.inputTexture&&(r.width=this._ssrPostProcess.inputTexture.width,r.height=this._ssrPostProcess.inputTexture.height);return r}_updateEffectDefines(){var e;const t=[];(this._geometryBufferRenderer||this._prePassRenderer)&&t.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&t.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&t.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(t.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&t.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&t.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&t.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&t.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&t.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&t.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&t.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&t.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&t.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&t.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&t.push("#define SSR_USE_BLUR"),this._debug&&t.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&t.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&t.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&t.push("#define SSR_BLEND_WITH_FRESNEL"),this._reflectivityThreshold===0&&t.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(e=this._ssrPostProcess)===null||e===void 0||e.updateEffect(t.join(` +`))}_buildPipeline(){var e;if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;const t=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=(e=this._cameras)===null||e===void 0?void 0:e[0];i&&(this._depthRendererCamera=i,this._depthRenderer=new qL(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 An(t,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new An(t,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new An(t,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)),s=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==s)&&this._depthRenderer.getDepthMap().resize({width:i,height:s})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){const t=(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))!==null&&e!==void 0?e:-1;t!==-1&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,s;for(let r=0;r{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const l=t.getTextureIndex(dl.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[l]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const l=i.getIndex(5),c=i.getIndex(3),h=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[h]),e.setTexture("depthSampler",i.getRenderTarget().textures[l]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[c])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const s=this._scene.activeCamera;if(!s)return;const r=s.getViewMatrix(!0),n=s.getProjectionMatrix(!0);n.invertToRef(ue.Matrix[0]),r.invertToRef(ue.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",ue.Matrix[1]),e.setMatrix("invProjectionMatrix",ue.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",s.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();ge.ScalingToRef(o.width,o.height,1,ue.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?jbe:Hbe,ue.Matrix[3]),ue.Matrix[3].multiplyToRef(ue.Matrix[2],ue.Matrix[4]),e.setMatrix("projectionPixel",ue.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 Obe)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new rs("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(r=>{var n,o;const l=(o=(n=this._blurPostProcessX)===null||n===void 0?void 0:n.inputTexture.width)!==null&&o!==void 0?o:this._scene.getEngine().getRenderWidth();r.setFloat2("texelOffsetScale",this._blurDispersionStrength/l,0)}),this._blurPostProcessY=new rs("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(r=>{var n,o;const l=(o=(n=this._blurPostProcessY)===null||n===void 0?void 0:n.inputTexture.height)!==null&&o!==void 0?o:this._scene.getEngine().getRenderHeight();r.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/l)});const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+=`#define SSRAYTRACE_DEBUG +`),this._inputTextureColorIsInGammaSpace&&(s+=`#define SSR_INPUT_IS_GAMMA_SPACE +`),this._generateOutputInGammaSpace&&(s+=`#define SSR_OUTPUT_IS_GAMMA_SPACE +`),this.useFresnel&&(s+=`#define SSR_BLEND_WITH_FRESNEL +`,t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),this._reflectivityThreshold===0&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new rs("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(r=>{var n;const o=this._geometryBufferRenderer,l=this._prePassRenderer;if(!(!l&&!o)){if(l&&((n=this._scene.activeCamera)===null||n===void 0?void 0:n._getFirstPostProcess())===this._ssrPostProcess){const c=l.getRenderTarget();c&&c.textures&&r.setTexture("mainSampler",c.textures[l.getIndex(4)])}else r.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(o){const c=o.getTextureIndex(dl.REFLECTIVITY_TEXTURE_TYPE);r.setTexture("reflectivitySampler",o.getGBuffer().textures[c]),this.useFresnel&&(r.setTexture("normalSampler",o.getGBuffer().textures[1]),r.setTexture("depthSampler",o.getGBuffer().textures[0]))}else if(l){const c=l.getIndex(3);if(r.setTexture("reflectivitySampler",l.getRenderTarget().textures[c]),this.useFresnel){const h=l.getIndex(5),u=l.getIndex(6);r.setTexture("normalSampler",l.getRenderTarget().textures[u]),r.setTexture("depthSampler",l.getRenderTarget().textures[h])}}if(r.setFloat("strength",this.strength),r.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),r.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const c=this._scene.activeCamera;if(c){const h=c.getProjectionMatrix();h.invertToRef(ue.Matrix[0]),r.setMatrix("projection",h),r.setMatrix("invProjectionMatrix",ue.Matrix[0])}}}})}serialize(){const e=Kt.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return Kt.Parse(()=>new $a(e._name,t,e._ratio),e,t,i)}}z([X()],$a.prototype,"samples",null);z([X()],$a.prototype,"maxDistance",void 0);z([X()],$a.prototype,"step",void 0);z([X()],$a.prototype,"thickness",void 0);z([X()],$a.prototype,"strength",void 0);z([X()],$a.prototype,"reflectionSpecularFalloffExponent",void 0);z([X()],$a.prototype,"maxSteps",void 0);z([X()],$a.prototype,"roughnessFactor",void 0);z([X()],$a.prototype,"selfCollisionNumSkip",void 0);z([X()],$a.prototype,"_reflectivityThreshold",void 0);z([X("_ssrDownsample")],$a.prototype,"_ssrDownsample",void 0);z([X()],$a.prototype,"ssrDownsample",null);z([X("blurDispersionStrength")],$a.prototype,"_blurDispersionStrength",void 0);z([X("blurDownsample")],$a.prototype,"_blurDownsample",void 0);z([X("enableSmoothReflections")],$a.prototype,"_enableSmoothReflections",void 0);z([X("environmentTexture")],$a.prototype,"_environmentTexture",void 0);z([X("environmentTextureIsProbe")],$a.prototype,"_environmentTextureIsProbe",void 0);z([X("attenuateScreenBorders")],$a.prototype,"_attenuateScreenBorders",void 0);z([X("attenuateIntersectionDistance")],$a.prototype,"_attenuateIntersectionDistance",void 0);z([X("attenuateIntersectionIterations")],$a.prototype,"_attenuateIntersectionIterations",void 0);z([X("attenuateFacingCamera")],$a.prototype,"_attenuateFacingCamera",void 0);z([X("attenuateBackfaceReflection")],$a.prototype,"_attenuateBackfaceReflection",void 0);z([X("clipToFrustum")],$a.prototype,"_clipToFrustum",void 0);z([X("useFresnel")],$a.prototype,"_useFresnel",void 0);z([X("enableAutomaticThicknessComputation")],$a.prototype,"_enableAutomaticThicknessComputation",void 0);z([X("backfaceDepthTextureDownsample")],$a.prototype,"_backfaceDepthTextureDownsample",void 0);z([X("backfaceForceDepthWriteTransparentMeshes")],$a.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0);z([X("isEnabled")],$a.prototype,"_isEnabled",void 0);z([X("inputTextureColorIsInGammaSpace")],$a.prototype,"_inputTextureColorIsInGammaSpace",void 0);z([X("generateOutputInGammaSpace")],$a.prototype,"_generateOutputInGammaSpace",void 0);z([X("debug")],$a.prototype,"_debug",void 0);$e("BABYLON.SSRRenderingPipeline",$a);const Gbe="tonemapPixelShader",Wbe=`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);}`;Ue.ShadersStore[Gbe]=Wbe;var xP;(function(a){a[a.Hable=0]="Hable",a[a.Reinhard=1]="Reinhard",a[a.HejiDawson=2]="HejiDawson",a[a.Photographic=3]="Photographic"})(xP||(xP={}));class Ybe extends rs{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,s,r=2,n,o=0,l){super(e,"tonemap",["_ExposureAdjustment"],null,1,s,r,n,l,null,o),this._operator=t,this.exposureAdjustment=i;let c="#define ";this._operator===xP.Hable?c+="HABLE_TONEMAPPING":this._operator===xP.Reinhard?c+="REINHARD_TONEMAPPING":this._operator===xP.HejiDawson?c+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":this._operator===xP.Photographic&&(c+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(c),this.onApply=h=>{h.setFloat("_ExposureAdjustment",this.exposureAdjustment)}}}const Xbe="volumetricLightScatteringPixelShader",Kbe=`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 +} +`;Ue.ShadersStore[Qbe]=Zbe;const qbe="volumetricLightScatteringPassPixelShader",Jbe=`#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);} +`;Ue.ShadersStore[qbe]=Jbe;class S_ extends rs{get useDiffuseColor(){return Me.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){Me.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,s,r=100,n=Te.BILINEAR_SAMPLINGMODE,o,l,c){var h,u;super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,n,o,l,"#define NUM_SAMPLES "+r),this._screenCoordinates=lt.Zero(),this.customMeshPosition=O.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=new Array,this.includedMeshes=new Array,this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,c=(u=(h=i?.getScene())!==null&&h!==void 0?h:c)!==null&&u!==void 0?u:this._scene,o=c.getEngine(),this._viewPort=new hu(0,0,1,1).toGlobal(o.getRenderWidth(),o.getRenderHeight()),this.mesh=s??S_.CreateDefaultMesh("VolumetricLightScatteringMesh",c),this._createPass(c,t.passRatio||t),this.onActivate=p=>{this.isSupported||this.dispose(p),this.onActivate=null},this.onApplyObservable.add(p=>{this._updateMeshScreenCoordinates(c),p.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),p.setFloat("exposure",this.exposure),p.setFloat("decay",this.decay),p.setFloat("weight",this.weight),p.setFloat("density",this.density),p.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;const s=e.getMesh();if(s===this.mesh&&s.material)return s.material.isReady(s);const r=(i=s._internalAbstractMeshDataInfo._materialForRenderPass)===null||i===void 0?void 0:i[this._scene.getEngine().currentRenderPassId];if(r)return r.isReadyForSubMesh(s,e,t);const n=[],o=[se.PositionKind],l=e.getMaterial();l&&(l.needAlphaTesting()&&n.push("#define ALPHATEST"),s.isVerticesDataPresent(se.UVKind)&&(o.push(se.UVKind),n.push("#define UV1")),s.isVerticesDataPresent(se.UV2Kind)&&(o.push(se.UV2Kind),n.push("#define UV2"))),s.useBones&&s.computeBonesUsingShaders?(o.push(se.MatricesIndicesKind),o.push(se.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),t&&(n.push("#define INSTANCES"),ze.PushAttributesForInstances(o),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(void 0,!0),h=c.defines,u=n.join(` +`);return h!==u&&c.setEffect(s.getScene().getEngine().createEffect("volumetricLightScatteringPass",o,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:s.numBoneInfluencers}),u),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 Oa("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=Te.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Te.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const r=l=>{var c;const h=l.getRenderingMesh(),u=l.getEffectiveMesh();if(this._meshExcluded(h))return;u._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const p=l.getMaterial();if(!p)return;const m=h.getScene(),_=m.getEngine();_.setState(p.backFaceCulling,void 0,void 0,void 0,p.cullBackFaces);const f=h._getInstancesRenderList(l._id,!!l.getReplacementMesh());if(f.mustReturn)return;const d=_.getCaps().instancedArrays&&(f.visibleInstances[l._id]!==null||h.hasThinInstances);if(this._isReady(l,d)){const C=(c=u._internalAbstractMeshDataInfo._materialForRenderPass)===null||c===void 0?void 0:c[_.currentRenderPassId];let v=l._getDrawWrapper();if(h===this.mesh&&!v&&(v=p._getDrawWrapper()),!v)return;const y=v.effect;if(_.enableEffect(v),d||h._bind(l,y,p.fillMode),h===this.mesh)p.bind(u.getWorldMatrix(),h);else if(C)C.bindForSubMesh(u.getWorldMatrix(),u,l);else{if(y.setMatrix("viewProjection",m.getTransformMatrix()),p&&p.needAlphaTesting()){const M=p.getAlphaTestTexture();y.setTexture("diffuseSampler",M),M&&y.setMatrix("diffuseMatrix",M.getTextureMatrix())}h.useBones&&h.computeBonesUsingShaders&&h.skeleton&&y.setMatrices("mBones",h.skeleton.getTransformMatrices(h))}d&&h.hasThinInstances&&y.setMatrix("world",u.getWorldMatrix()),h._processRendering(u,l,y,Lt.TriangleFillMode,f,d,(M,b)=>{M||y.setMatrix("world",b)})}};let n;const o=new Zt(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{n=e.clearColor,e.clearColor=o}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=n}),this._volumetricLightScatteringRTT.customIsReadyFunction=(l,c,h)=>{if((h||c===0)&&l.subMeshes)for(let u=0;u{const p=e.getEngine();let m;if(u.length){for(p.setColorWrite(!1),m=0;mf._alphaIndex>d._alphaIndex?1:f._alphaIndexd._distanceToCamera?-1:0),p.setAlphaMode(2),m=0;m<_.length;m++)r(_[m]);p.setAlphaMode(0)}}}_updateMeshScreenCoordinates(e){const t=e.getTransformMatrix();let i;this.useCustomMeshPosition?i=this.customMeshPosition:this.attachedNode?i=this.attachedNode.position:i=this.mesh.parent?this.mesh.getAbsolutePosition():this.mesh.position;const s=O.Project(i,ge.Identity(),t,this._viewPort);this._screenCoordinates.x=s.x/this._viewPort.width,this._screenCoordinates.y=s.y/this._viewPort.height,this.invert&&(this._screenCoordinates.y=1-this._screenCoordinates.y)}static CreateDefaultMesh(e,t){const i=Jd(e,{size:1},t);i.billboardMode=Ir.BILLBOARDMODE_ALL;const s=new jt(e+"Material",t);return s.emissiveColor=new Ie(1,1,1),i.material=s,i}}z([bo()],S_.prototype,"customMeshPosition",void 0);z([X()],S_.prototype,"useCustomMeshPosition",void 0);z([X()],S_.prototype,"invert",void 0);z([xF()],S_.prototype,"mesh",void 0);z([X()],S_.prototype,"excludedMeshes",void 0);z([X()],S_.prototype,"includedMeshes",void 0);z([X()],S_.prototype,"exposure",void 0);z([X()],S_.prototype,"decay",void 0);z([X()],S_.prototype,"weight",void 0);z([X()],S_.prototype,"density",void 0);$e("BABYLON.VolumetricLightScatteringPostProcess",S_);const $be="screenSpaceCurvaturePixelShader",e7e=`precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform float curvature_ridge;uniform float curvature_valley; +#ifndef CURVATURE_OFFSET +#define CURVATURE_OFFSET 1 +#endif +float curvature_soft_clamp(float curvature,float control) +{if (curvature<0.5/control) +return curvature*(1.0-curvature*control);return 0.25/control;} +float calculate_curvature(ivec2 texel,float ridge,float valley) +{vec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;vec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;vec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;vec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;float normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));if (normal_diff<0.0) +return -2.0*curvature_soft_clamp(-normal_diff,valley);return 2.0*curvature_soft_clamp(normal_diff,ridge);} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ivec2 texel=ivec2(gl_FragCoord.xy);vec4 baseColor=texture2D(textureSampler,vUV);float curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);baseColor.rgb*=curvature+1.0;gl_FragColor=baseColor;}`;Ue.ShadersStore[$be]=e7e;class NF extends rs{getClassName(){return"ScreenSpaceCurvaturePostProcess"}constructor(e,t,i,s,r,n,o,l=0,c=!1){super(e,"screenSpaceCurvature",["curvature_ridge","curvature_valley"],["textureSampler","normalSampler"],i,s,r,n,o,void 0,l,void 0,null,c),this.ridge=1,this.valley=1,this._geometryBufferRenderer=t.enableGeometryBufferRenderer(),this._geometryBufferRenderer?this.onApply=h=>{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)}:Me.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=Ii.LastCreatedEngine;return e?e.getCaps().drawBuffersExtension:!1}static _Parse(e,t,i,s){return Kt.Parse(()=>new NF(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}z([X()],NF.prototype,"ridge",void 0);z([X()],NF.prototype,"valley",void 0);$e("BABYLON.ScreenSpaceCurvaturePostProcess",NF);const t7e="boundingBoxRendererFragmentDeclaration",i7e=`uniform vec4 color; +`;Ue.IncludesShadersStore[t7e]=i7e;const s7e="boundingBoxRendererUboDeclaration",r7e=`#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 +`;Ue.IncludesShadersStore[s7e]=r7e;const n7e="boundingBoxRendererPixelShader",a7e=`#include<__decl__boundingBoxRendererFragment> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;Ue.ShadersStore[n7e]=a7e;const o7e="boundingBoxRendererVertexDeclaration",l7e=`uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +`;Ue.IncludesShadersStore[o7e]=l7e;const c7e="boundingBoxRendererVertexShader",h7e=`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 +} +`;Ue.ShadersStore[c7e]=h7e;Object.defineProperty(oi.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(a){this._forceShowBoundingBoxes=a,a&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});oi.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new Lde(this)),this._boundingBoxRenderer};Object.defineProperty(Ir.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(a){this._showBoundingBox=a,a&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class Lde{constructor(e){this.name=ai.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Ie(1,1,1),this.backColor=new Ie(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new Se,this.onAfterBoxRenderingObservable=new Se,this.onResourcesReadyObservable=new Se,this.enabled=!0,this.renderList=new Sc(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new es(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new es(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(ai.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(ai.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(ai.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(ai.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 oh("colorShader",this.scene,"boundingBoxRenderer",{attributes:[se.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new oh("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[se.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=zK({size:1});this._vertexBuffers[se.PositionKind]=new se(e,t.positions,se.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[se.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(this.renderList.length===0||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;const s=this.scene.getEngine();s.setDepthWrite(!1);const r=this.scene.getTransformMatrix();for(let n=0;n{let e=a._getComponent(ai.NAME_DEPTHRENDERER);e||(e=new Rde(a),a._addComponent(e))};const u7e="oitFinalPixelShader",d7e=`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 +);}`;Ue.ShadersStore[u7e]=d7e;const f7e="oitBackBlendPixelShader",p7e=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { +discard;}}`;Ue.ShadersStore[f7e]=p7e;class m7e{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class HM{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 Sc(10),this._excludedSubMeshes=new Sc(10),this._excludedMeshes=[],this._colorCache=[new Zt(HM._DEPTH_CLEAR_VALUE,HM._DEPTH_CLEAR_VALUE,0,0),new Zt(-HM._MIN_DEPTH,HM._MAX_DEPTH,0,0),new Zt(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){Me.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let i=0;i +uniform vec4 color; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;Ue.ShadersStore[_7e]=g7e;const v7e="lineVertexShader",C7e=`#include +#include +attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; +#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 +#define CUSTOM_VERTEX_MAIN_END +}`;Ue.ShadersStore[v7e]=C7e;Ir.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this};Ir.prototype.enableEdgesRendering=function(a=.95,e=!1,t){return this.disableEdgesRendering(),this._edgesRenderer=new wW(this,a,e,!0,t),this};Object.defineProperty(Ir.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0});n7.prototype.enableEdgesRendering=function(a=.95,e=!1){return this.disableEdgesRendering(),this._edgesRenderer=new Dde(this,a,e),this};Mee.prototype.enableEdgesRendering=function(a=.95,e=!1){return n7.prototype.enableEdgesRendering.apply(this,arguments),this};class A7e{constructor(){this.edges=new Array,this.edgesConnectedCount=0}}class wW{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 oh("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,s=!0,r){var n;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 Sc(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new ml(e.getEngine())),this._prepareRessources(),s&&(!((n=r?.useAlternateEdgeFinder)!==null&&n!==void 0)||n?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=wW._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[se.PositionKind];e&&e._rebuild(),e=this._buffers[se.NormalKind],e&&e._rebuild();const i=this._source.getScene().getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[se.PositionKind];t&&(t.dispose(),this._buffers[se.PositionKind]=null),t=this._buffers[se.NormalKind],t&&(t.dispose(),this._buffers[se.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),(e=this._drawWrapper)===null||e===void 0||e.dispose()}_processEdgeForAdjacencies(e,t,i,s,r){return e===i&&t===s||e===s&&t===i?0:e===s&&t===r||e===r&&t===s?1:e===r&&t===i||e===i&&t===r?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,r){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)?1:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)?2:-1}_checkEdge(e,t,i,s,r){let n;t===void 0?n=!0:n=O.Dot(i[e],i[t]){R>=0&&D.push(R);for(let L=0;L=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let I=0;I<3;++I)I===n?e[I].sort((D,R)=>D[1]R[1]?1:0):e[I].sort((D,R)=>D[1]>R[1]?-1:D[1]=n+1;--I)r(e[I%3],l,I!==n+2?s[i[t+(I+1)%3]]:-1);const h=l.length,u=0,p=0;i.push(s[i[t+n]],o[0],l[0]),i.push(s[i[t+(n+1)%3]],l[h-1],o[c-1]);const m=c<=h,_=m?c:h,f=m?h:c,d=m?c-1:h-1,C=m?0:1;let v=c+h-2,y=m?u:p,M=m?p:u;const b=m?o:l,E=m?l:o;let S=0;for(;v-- >0;){C?i.push(b[y],E[M]):i.push(E[M],b[y]),S+=_;let I;S>=f&&yS){const L=E;E=S,S=L}const D=E+"_"+S,R=C[D];R?R.done||(O.Dot(M,R.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,s=i||this._source.hasThinInstances;let r=0;if(s)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(r=this.customInstances.length,!o.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!o.isFrozen){let l=0;for(let c=0;c0&&(this._useSpecificClearForDepthTexture&&this._mrtLayout[r]===5?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),s.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(s)}_resetLayout(){for(let e=0;el!=null),this._scene.autoClear=!0;const s=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!s&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const r=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:r&&(o=r),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;es!=null),t)){for(let s=0;s=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw Ys("PrePassRendererSceneComponent")};F2.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(oi.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(a){a&&a.isSupported&&(this._prePassRenderer=a)},enumerable:!0,configurable:!0});oi.prototype.enablePrePassRenderer=function(){return this._prePassRenderer?this._prePassRenderer:(this._prePassRenderer=new F2(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,Me.Error(`PrePassRenderer needs WebGL 2 support. +Maybe you tried to use the following features that need the PrePassRenderer : + + Subsurface Scattering`)),this._prePassRenderer)};oi.prototype.disablePrePassRenderer=function(){!this._prePassRenderer||(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class Ode{constructor(e){this.name=ai.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(ai.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(ai.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(ai.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(ai.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(ai.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(ai.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(ai.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(ai.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,s){if(!s)return;const r=e.getScene();r.prePassRenderer&&r.prePassRenderer.bindAttachmentsForEffect(s,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}}F2._SceneComponentInitialization=a=>{let e=a._getComponent(ai.NAME_PREPASSRENDERER);e||(e=new Ode(a),a._addComponent(e))};const b7e="fibonacci",E7e=`#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);}`;Ue.IncludesShadersStore[b7e]=E7e;const y7e="diffusionProfile",M7e="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";Ue.IncludesShadersStore[y7e]=M7e;const T7e="subSurfaceScatteringPixelShader",S7e=`#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){Me.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}const h=this.texelSize;c.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),c.setFloat2("texelSize",h.x,h.y),c.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),c.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),c.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),c.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),c.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),c.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),c.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)})}}class NW{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=ai.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Ie(1,1,1)),this._scene=e,NW._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return Me.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw Ys("SubSurfaceSceneComponent")};pc.AddParser(ai.NAME_SUBSURFACE,(a,e)=>{if(a.ssDiffusionProfileColors!==void 0&&a.ssDiffusionProfileColors!==null&&(e.enableSubSurfaceForPrePass(),e.subSurfaceConfiguration))for(let t=0,i=a.ssDiffusionProfileColors.length;t{let e=a._getComponent(ai.NAME_SUBSURFACE);e||(e=new wde(a),a._addComponent(e))};const L7e="outlinePixelShader",R7e=`#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 +}`;Ue.ShadersStore[L7e]=R7e;const P7e="outlineVertexShader",D7e=`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 +} +`;Ue.ShadersStore[P7e]=D7e;oi.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new JB(this)),this._outlineRenderer};Object.defineProperty(Oe.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(a){a&&this.getScene().getOutlineRenderer(),this._renderOutline=a},enumerable:!0,configurable:!0});Object.defineProperty(Oe.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(a){a&&this.getScene().getOutlineRenderer(),this._renderOverlay=a},enumerable:!0,configurable:!0});class JB{constructor(e){this.name=ai.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(ai.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(ai.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{_.setMatrix("world",d)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[se.PositionKind,se.NormalKind],n=e.getMesh(),o=e.getMaterial();if(!o)return!1;const l=n.getScene();o.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(se.UVKind)&&(r.push(se.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(se.UV2Kind)&&(r.push(se.UV2Kind),s.push("#define UV2"))),o.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),PI(o,l,s),n.useBones&&n.computeBonesUsingShaders?(r.push(se.MatricesIndicesKind),r.push(se.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(se.MatricesIndicesExtraKind),r.push(se.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0");const c=n.morphTargetManager;let h=0;c&&c.numInfluencers>0&&(h=c.numInfluencers,s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+h),c.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),ze.PrepareAttributesForMorphTargetsInfluencers(r,n,h)),t&&(s.push("#define INSTANCES"),ze.PushAttributesForInstances(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const u=e._getDrawWrapper(i,!0),p=u.defines,m=s.join(` +`);if(p!==m){const _=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];lh(_),u.setEffect(this.scene.getEngine().createEffect("outline",r,_,["diffuseSampler","morphTargets"],m,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),m)}return u.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const s=t.getMaterial();s&&s.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(JB._StencilReference),this._engine.setStencilFunctionReference(JB._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),s&&s.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const s=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(s),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}JB._StencilReference=4;class Dte{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===void 0)&&e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new Se,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 KM({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new KM({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===void 0||e.dispose(),(t=this._thicknessEffectWrapper)===null||t===void 0||t.dispose()}}class Nde extends Dte{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 OZ{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 s=0;s{this._postProcessRunningIndex===0?d.setTexture("textureSampler",e):d._bindTexture("textureSampler",m.inputTexture.texture),d.setInt("filterSize",this.blurFilterSize),d.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),m.onSizeChangedObservable.add(()=>{m._textures.forEach(d=>{d.texture.wrapU=Te.CLAMP_ADDRESSMODE,d.texture.wrapV=Te.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(m);const _=new rs("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);_.samples=this._samples,_.onApplyObservable.add(d=>{d.setInt("filterSize",this.blurFilterSize),d.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),_.onSizeChangedObservable.add(()=>{_._textures.forEach(d=>{d.texture.wrapU=Te.CLAMP_ADDRESSMODE,d.texture.wrapV=Te.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(_),m.autoClear=!1,_.autoClear=!1;const f=[];for(let d=0;d{this._postProcessRunningIndex===0?C.setTexture("textureSampler",e):C._bindTexture("textureSampler",_.inputTexture.texture),C.setInt("maxFilterSize",this.blurMaxFilterSize),C.setFloat2("blurDir",1/this._blurTextureSizeX,0),C.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),C.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),_.onSizeChangedObservable.add(()=>{_._textures.forEach(C=>{C.texture.wrapU=Te.CLAMP_ADDRESSMODE,C.texture.wrapV=Te.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(_);const f=new rs("BilateralBlurY","fluidRenderingBilateralBlur",m,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);f.samples=this._samples,f.onApplyObservable.add(C=>{C.setInt("maxFilterSize",this.blurMaxFilterSize),C.setFloat2("blurDir",0,1/this._blurTextureSizeY),C.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),C.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),f.onSizeChangedObservable.add(()=>{f._textures.forEach(C=>{C.texture.wrapU=Te.CLAMP_ADDRESSMODE,C.texture.wrapV=Te.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(f),_.autoClear=!1,f.autoClear=!1;const d=[];for(let C=0;C{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}),e.onApplyObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}))}_getProjectedParticleConstant(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan(((t=(e=this._camera)===null||e===void 0?void 0:e.fov)!==null&&t!==void 0?t:45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,s;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),(e=this._rt)===null||e===void 0||e.dispose(),this._rt=null,(t=this._texture)===null||t===void 0||t.dispose(),this._texture=null,(i=this._rtBlur)===null||i===void 0||i.dispose(),this._rtBlur=null,(s=this._textureBlurred)===null||s===void 0||s.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var o_;(function(a){a[a.DepthTexture=0]="DepthTexture",a[a.DepthBlurredTexture=1]="DepthBlurredTexture",a[a.ThicknessTexture=2]="ThicknessTexture",a[a.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",a[a.DiffuseTexture=4]="DiffuseTexture",a[a.Normals=5]="Normals",a[a.DiffuseRendering=6]="DiffuseRendering"})(o_||(o_={}));class aJ{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 Ie(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new O(-2,-1,1).normalize(),this._debugFeature=o_.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 Se,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 ge,this._depthClearColor=new Zt(1e6,1e6,1e6,1),this._thicknessClearColor=new Zt(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){var e,t,i;this.dispose(),this._needInitialization=!1;const s=(e=this._depthMapSize)!==null&&e!==void 0?e:this._engine.getRenderWidth(),r=this._depthMapSize!==null?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new OZ("Depth",this._scene,s,r,s,r,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const l=(t=this._diffuseMapSize)!==null&&t!==void 0?t:this._engine.getRenderWidth(),c=this._diffuseMapSize!==null?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new OZ("Diffuse",this._scene,l,c,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const n=(i=this._thicknessMapSize)!==null&&i!==void 0?i:this._engine.getRenderWidth(),o=this._thicknessMapSize!==null?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new OZ("Thickness",this._scene,n,o,n,o,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(){var e;const t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],s=["depthSampler"],r=[];if(this.dispose(!0),!this._camera)return;const n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,o=new lt(1/n.getSize().width,1/n.getSize().height);this._scene.useRightHandedSystem&&r.push("#define FLUIDRENDERING_RHS"),this._environmentMap!==null&&((e=this._environmentMap)!==null&&e!==void 0?e:this._scene.environmentTexture)&&(s.push("reflectionSampler"),r.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(s.push("diffuseSampler"),r.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(s.push("velocitySampler"),r.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),s.push("bgDepthSampler"),r.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),s.push("thicknessSampler")),this._debug&&(r.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===o_.Normals?r.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===o_.DiffuseRendering?r.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(r.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),s.push("debugSampler"),(this._debugFeature===o_.DepthTexture||this._debugFeature===o_.DepthBlurredTexture)&&r.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new rs("FluidRendering","fluidRenderingRender",i,s,1,null,2,t,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(r.join(` +`)),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add(l=>{var c,h,u,p,m,_,f,d,C,v,y,M,b,E,S,I,D,R,L,w,N,V,W;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),t.isWebGPU&&l.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(l.setTexture("depthSampler",this._depthRenderTarget.textureBlur),t.isWebGPU&&l.setTextureSampler("depthSamplerSampler",(p=(u=this._depthRenderTarget.textureBlur)===null||u===void 0?void 0:u.getInternalTexture())!==null&&p!==void 0?p:null)):(l.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&l.setTextureSampler("depthSamplerSampler",(h=(c=this._depthRenderTarget.texture)===null||c===void 0?void 0:c.getInternalTexture())!==null&&h!==void 0?h:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(l.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&l.setTextureSampler("diffuseSamplerSampler",(d=(f=this._diffuseRenderTarget.textureBlur)===null||f===void 0?void 0:f.getInternalTexture())!==null&&d!==void 0?d:null)):(l.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),t.isWebGPU&&l.setTextureSampler("diffuseSamplerSampler",(_=(m=this._diffuseRenderTarget.texture)===null||m===void 0?void 0:m.getInternalTexture())!==null&&_!==void 0?_:null)):l.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(l.setFloat("thickness",this.minimumThickness),l._bindTexture("bgDepthSampler",this._bgDepthTexture),t.isWebGPU&&l.setTextureSampler("bgDepthSamplerSampler",(C=this._bgDepthTexture)!==null&&C!==void 0?C:null)):(this._thicknessRenderTarget.enableBlur?(l.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&l.setTextureSampler("thicknessSamplerSampler",(b=(M=this._thicknessRenderTarget.textureBlur)===null||M===void 0?void 0:M.getInternalTexture())!==null&&b!==void 0?b:null)):(l.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&l.setTextureSampler("thicknessSamplerSampler",(y=(v=this._thicknessRenderTarget.texture)===null||v===void 0?void 0:v.getInternalTexture())!==null&&y!==void 0?y:null)),l.setFloat("minimumThickness",this.minimumThickness)),this._environmentMap!==null){const G=(E=this._environmentMap)!==null&&E!==void 0?E:this._scene.environmentTexture;G&&(l.setTexture("reflectionSampler",G),t.isWebGPU&&l.setTextureSampler("reflectionSamplerSampler",(S=G?.getInternalTexture())!==null&&S!==void 0?S:null))}if(l.setMatrix("viewMatrix",this._scene.getViewMatrix()),l.setMatrix("invProjectionMatrix",this._invProjectionMatrix),l.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),l.setVector2("texelSize",o),l.setFloat("density",this.density),l.setFloat("refractionStrength",this.refractionStrength),l.setFloat("fresnelClamp",this.fresnelClamp),l.setFloat("specularPower",this.specularPower),l.setVector3("dirLight",this.dirLight),l.setFloat("cameraFar",this._camera.maxZ),this._debug){let G=null;switch(this._debugFeature){case o_.DepthTexture:G=this._depthRenderTarget.texture;break;case o_.DepthBlurredTexture:G=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case o_.ThicknessTexture:G=(D=(I=this._thicknessRenderTarget)===null||I===void 0?void 0:I.texture)!==null&&D!==void 0?D:null;break;case o_.ThicknessBlurredTexture:G=!((R=this._thicknessRenderTarget)===null||R===void 0)&&R.enableBlur?(w=(L=this._thicknessRenderTarget)===null||L===void 0?void 0:L.textureBlur)!==null&&w!==void 0?w:null:(V=(N=this._thicknessRenderTarget)===null||N===void 0?void 0:N.texture)!==null&&V!==void 0?V:null;break;case o_.DiffuseTexture:this._diffuseRenderTarget&&(G=this._diffuseRenderTarget.texture);break}this._debugFeature!==o_.Normals&&(l.setTexture("debugSampler",G),t.isWebGPU&&l.setTextureSampler("debugSamplerSampler",(W=G?.getInternalTexture())!==null&&W!==void 0?W:null))}})}_clearTargets(){var e,t,i;!((e=this._depthRenderTarget)===null||e===void 0)&&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===void 0)&&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===void 0)&&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 t,i,s,r,n,o;if(this._needInitialization||!e.isReady())return;const l=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),!((t=this._depthRenderTarget)===null||t===void 0)&&t.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),!((i=this._diffuseRenderTarget)===null||i===void 0)&&i.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),!((s=this._thicknessRenderTarget)===null||s===void 0)&&s.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),(r=this._depthRenderTarget)===null||r===void 0||r.applyBlurPostProcesses(),(n=this._diffuseRenderTarget)===null||n===void 0||n.applyBlurPostProcesses(),(o=this._thicknessRenderTarget)===null||o===void 0||o.applyBlurPostProcesses(),l&&this._engine.bindFramebuffer(l)}dispose(e=!1){var t,i,s,r;e||((t=this._depthRenderTarget)===null||t===void 0||t.dispose(),this._depthRenderTarget=null,(i=this._diffuseRenderTarget)===null||i===void 0||i.dispose(),this._diffuseRenderTarget=null,(s=this._thicknessRenderTarget)===null||s===void 0||s.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),(r=this._renderPostProcess)===null||r===void 0||r.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class Bde extends Dte{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,s=!0;switch(t){case"velocity":i=3;break;case"offset":s=!1;break}this._vertexBuffers[t]=new se(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects();const e=["view","projection","size"],t=["position","offset","color"];this._diffuseEffectWrapper=new KM({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:t,uniformNames:e,samplerNames:[]})}isReady(){var e,t;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new se(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&((t=(e=this._diffuseEffectWrapper)===null||e===void 0?void 0:e.effect.isReady())!==null&&t!==void 0?t:!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===void 0||e.dispose();for(const t in this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}const O7e="copyTextureToTexturePixelShader",w7e=`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 +} +`;Ue.ShadersStore[O7e]=w7e;var SX;(function(a){a[a.None=0]="None",a[a.ToLinearSpace=1]="ToLinearSpace",a[a.ToGammaSpace=2]="ToGammaSpace"})(SX||(SX={}));class Fde{_textureIsInternal(e){return e.getInternalTexture===void 0}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new QG(e),this._effectWrapper=new KM({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=SX.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const s=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&s&&(this._engine.depthCullingState.depthFunc=s),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class N7e{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new Fde(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:s,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil")}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}const B7e="fluidRenderingParticleDepthVertexShader",F7e=`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 +} +`;Ue.ShadersStore[B7e]=F7e;const V7e="fluidRenderingParticleDepthPixelShader",z7e=`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 +} +`;Ue.ShadersStore[V7e]=z7e;const U7e="fluidRenderingParticleThicknessVertexShader",k7e=`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;} +`;Ue.ShadersStore[U7e]=k7e;const H7e="fluidRenderingParticleThicknessPixelShader",j7e=`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);} +`;Ue.ShadersStore[H7e]=j7e;const G7e="fluidRenderingParticleDiffuseVertexShader",W7e=`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;} +`;Ue.ShadersStore[G7e]=W7e;const Y7e="fluidRenderingParticleDiffusePixelShader",X7e=`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);} +`;Ue.ShadersStore[Y7e]=X7e;const K7e="fluidRenderingBilateralBlurPixelShader",Q7e=`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.);} +`;Ue.ShadersStore[K7e]=Q7e;const Z7e="fluidRenderingStandardBlurPixelShader",q7e=`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.);} +`;Ue.ShadersStore[Z7e]=q7e;const J7e="fluidRenderingRenderPixelShader",$7e=`/* 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);} +`;Ue.ShadersStore[J7e]=$7e;Object.defineProperty(oi.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(a){this._fluidRenderer=a},enumerable:!0,configurable:!0});oi.prototype.enableFluidRenderer=function(){return this._fluidRenderer?this._fluidRenderer:(this._fluidRenderer=new yQ(this),this._fluidRenderer)};oi.prototype.disableFluidRenderer=function(){var a;(a=this._fluidRenderer)===null||a===void 0||a.dispose(),this._fluidRenderer=null};function eEe(a){return!!a.particleSystem}class Vde{constructor(e){this.name=ai.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(ai.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(ai.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;(t=this.scene.fluidRenderer)===null||t===void 0||t._prepareRendering()}_afterCameraDraw(e){var t;(t=this.scene.fluidRenderer)===null||t===void 0||t._render(e)}rebuild(){this.scene._fluidRenderer&&(this.scene.disableFluidRenderer(),this.scene.enableFluidRenderer())}dispose(){this.scene.disableFluidRenderer()}}class yQ{static _SceneComponentInitialization(e){let t=e._getComponent(ai.NAME_FLUIDRENDERER);t||(t=new Vde(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,yQ._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,s){const r=new Nde(this._scene,e);r.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)),i||(i=new aJ(this._scene,s),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)),t!==void 0&&(i.generateDiffuseTexture=t);const n={object:r,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,s,r){const n=new Bde(this._scene,e,t);n.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)),s||(s=new aJ(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)),i!==void 0&&(s.generateDiffuseTexture=i);const o={object:n,targetRenderer:s};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 s=0;s{var c;n.inputTexture.depthStencilTexture||n.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,o[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${n.name}`);for(const h of o){const u=(c=h._thicknessRenderTarget)===null||c===void 0?void 0:c.renderTarget,p=u?.texture;if(u&&p){const m=p.width+"_"+p.height;let _=l[m];_||(_=l[m]=new N7e(this._engine,p.width,p.height)),_.depthRTWrapper._shareDepth(u)}}})}t=this._cameras.keys();for(let i=t.next();i.done!==!0;i=t.next()){const s=i.value,n=this._cameras.get(s)[1],o=e.get(s);if(o)for(const l in n)o[1][l]||n[l].dispose();else for(const l in n)n[l].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 t;for(let s=0;s{const t=e[1];for(const i in t)t[i].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class tEe{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,s,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=s||1,this._animationStarted=!0,this._onBaseAnimationEnd=r,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 MQ extends tEe{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 Se,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new Zt(1,1,1,1),this.position=O.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,s,r=null){this._onAnimationEnd=r,super.playAnimation(e,t,i,s,this._endAnimation)}dispose(){for(let e=0;e0)for(let r=0;r=s.distance)&&(s=o,t))break}return s||new cu};oi.prototype._internalMultiPickSprites=function(a,e,t){if(!cu)return null;let i=new Array;if(!t){if(!this.activeCamera)return null;t=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;st.actionManager?t.isPickable&&t.actionManager.hasPointerTriggers:!1}register(){this.scene._pointerMoveStage.registerStep(ai.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(ai.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(ai.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,s,r){const n=this.scene.pickSprite(t,i,this._spritePredicate,s,r);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,s,r){const n=this.scene;return s?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&r&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null)),i}_pointerDown(e,t,i,s){const r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers&&r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager)){switch(r._pickedDownSprite=i.pickedSprite,s.button){case 0:i.pickedSprite.actionManager.processTrigger(2,$o.CreateNewFromSprite(i.pickedSprite,r,s));break;case 1:i.pickedSprite.actionManager.processTrigger(4,$o.CreateNewFromSprite(i.pickedSprite,r,s));break;case 2:i.pickedSprite.actionManager.processTrigger(3,$o.CreateNewFromSprite(i.pickedSprite,r,s));break}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,$o.CreateNewFromSprite(i.pickedSprite,r,s))}return i}_pointerUp(e,t,i,s,r){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const o=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(7,$o.CreateNewFromSprite(o.pickedSprite,n,s)),o.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||o.pickedSprite.actionManager.processTrigger(1,$o.CreateNewFromSprite(o.pickedSprite,n,s)),r&&o.pickedSprite.actionManager.processTrigger(6,$o.CreateNewFromSprite(o.pickedSprite,n,s)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==o.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,$o.CreateNewFromSprite(n._pickedDownSprite,n,s)))}return i}}const iEe="imageProcessingCompatibility",sEe=`#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); +#endif +`;Ue.IncludesShadersStore[iEe]=sEe;const rEe="spritesPixelShader",nEe=`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 +}`;Ue.ShadersStore[rEe]=nEe;const aEe="spritesVertexShader",oEe=`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 +}`;Ue.ShadersStore[aEe]=oEe;class lEe{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,s=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=s,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Q1(e,this._vertexData,!0,this._vertexBufferSize);const r=this._buffer.createVertexBuffer(se.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o=6,l;if(this._useInstancing){const p=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Q1(e,p,!1,2),l=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else l=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;const c=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(se.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[se.PositionKind]=r,this._vertexBuffers.options=n,this._vertexBuffers.offsets=l,this._vertexBuffers.inverts=c,this._vertexBuffers.cellInfo=h,this._vertexBuffers[se.ColorKind]=u,this._createEffects()}_createEffects(){var e,t,i,s;(e=this._drawWrapperBase)===null||e===void 0||e.dispose(),(t=this._drawWrapperFog)===null||t===void 0||t.dispose(),(i=this._drawWrapperDepth)===null||i===void 0||i.dispose(),(s=this._drawWrapperFogDepth)===null||s===void 0||s.dispose(),this._drawWrapperBase=new ml(this._engine),this._drawWrapperFog=new ml(this._engine),this._drawWrapperDepth=new ml(this._engine,!1),this._drawWrapperFogDepth=new ml(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 r=this._pixelPerfect?`#define PIXEL_PERFECT +`:"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[se.PositionKind,"options","offsets","inverts","cellInfo",se.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],r),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[se.PositionKind,"options","offsets","inverts","cellInfo",se.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],r+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,s,r=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let n=this._drawWrapperBase,o=this._drawWrapperDepth,l=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&this._scene.fogMode!==0&&(n=this._drawWrapperFog,o=this._drawWrapperFogDepth,l=!0);const c=n.effect;if(!c.isReady())return;const h=this._engine,u=!!(this._scene&&this._scene.useRightHandedSystem),p=this.texture.getBaseSize(),m=Math.min(this._capacity,e.length);let _=0,f=!0;for(let y=0;y>0;t._xOffset=(t.cellIndex-h*c)*this.cellWidth/r.width,t._yOffset=h*this.cellHeight/r.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[l]=t.position.x,this._vertexData[l+1]=t.position.y,this._vertexData[l+2]=t.position.z,this._vertexData[l+3]=t.angle,this._vertexData[l+4]=t.width,this._vertexData[l+5]=t.height,this._useInstancing?l-=2:(this._vertexData[l+6]=i,this._vertexData[l+7]=s),n?this._vertexData[l+8]=t.invertU?0:1:this._vertexData[l+8]=t.invertU?1:0,this._vertexData[l+9]=t.invertV?1:0,this._vertexData[l+10]=t._xOffset,this._vertexData[l+11]=t._yOffset,this._vertexData[l+12]=t._xSize/r.width,this._vertexData[l+13]=t._ySize/r.height,this._vertexData[l+14]=t.color.r,this._vertexData[l+15]=t.color.g,this._vertexData[l+16]=t.color.b,this._vertexData[l+17]=t.color.a}_buildIndexBuffer(){const e=[];let t=0;for(let i=0;i{u.cellRef||(u.cellIndex=0);const m=u.cellIndex;typeof m=="number"&&isFinite(m)&&Math.floor(m)===m&&(u.cellRef=this._spriteMap[u.cellIndex]),u._xOffset=this._cellData[u.cellRef].frame.x/p.width,u._yOffset=this._cellData[u.cellRef].frame.y/p.height,u._xSize=this._cellData[u.cellRef].frame.w,u._ySize=this._cellData[u.cellRef].frame.h},r||(r=Ii.LastCreatedScene),r._getComponent(ai.NAME_SPRITE)||r._addComponent(new zde(r)),this._fromPacked=l,this._scene=r;const h=this._scene.getEngine();if(this._spriteRenderer=new lEe(h,i,n,r),s.width&&s.height)this.cellWidth=s.width,this.cellHeight=s.height;else if(s!==void 0)this.cellWidth=s,this.cellHeight=s;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Te(t,r,!0,!1,o)),this._fromPacked&&this._makePacked(t,c)}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 r={};for(let n=0;n0);const r=e.substring(0,s-1)+".json",n=()=>{Me.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},o=l=>{try{const c=JSON.parse(l),h=Reflect.ownKeys(c.frames);this._spriteMap=h,this._packedAndReady=!0,this._cellData=c.frames}catch{throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};Be.LoadFile(r,o,void 0,void 0,!1,n)}}_checkTextureAlpha(e,t,i,s,r){if(!e.useAlphaForPicking||!this.texture)return!0;const n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));const o=ue.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const l=(o.x-s.x)/(r.x-s.x),c=1-(o.y-s.y)/(r.y-s.y),h=e._xOffset*n.width+l*e._xSize|0,u=e._yOffset*n.height+c*e._ySize|0;return this._textureContent[(h+u*n.width)*4+3]>.5}intersects(e,t,i,s){const r=Math.min(this.capacity,this.sprites.length),n=O.Zero(),o=O.Zero();let l=Number.MAX_VALUE,c=null;const h=ue.Vector3[0],u=ue.Vector3[1],p=t.getViewMatrix();let m=e,_=e;for(let f=0;fC){if(!this._checkTextureAlpha(d,m,C,n,o))continue;if(_=m,l=C,c=d,s)break}}}}if(c){const f=new cu;p.invertToRef(ue.Matrix[0]),f.hit=!0,f.pickedSprite=c,f.distance=l;const d=ue.Vector3[2];return d.copyFrom(_.direction),d.normalize(),d.scaleInPlace(l),_.origin.addToRef(d,h),f.pickedPoint=O.TransformCoordinates(h,ue.Matrix[0]),f}return null}multiIntersects(e,t,i){const s=Math.min(this.capacity,this.sprites.length),r=O.Zero(),n=O.Zero();let o;const l=[],c=ue.Vector3[0].copyFromFloats(0,0,0),h=ue.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix();for(let p=0;p{const o=new wl;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),c=jM.Parse(l,i||Ii.LastCreatedScene,s);e&&(c.name=e),r(c)}else n("Unable to load the sprite manager")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return e==="_BLANK"?Promise.resolve(new jM("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((s,r)=>{const n=new wl;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(o.spriteManager),c=jM.Parse(l,t||Ii.LastCreatedScene,i);c.snippetId=e,s(c)}else r("Unable to load the snippet "+e)}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}jM.SnippetUrl="https://snippet.babylonjs.com";jM.CreateFromSnippetAsync=jM.ParseFromSnippetAsync;const cEe="spriteMapPixelShader",hEe=`#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;}`;Ue.ShadersStore[cEe]=hEe;const uEe="spriteMapVertexShader",dEe=`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;}`;Ue.ShadersStore[uEe]=dEe;class fEe{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,s,r){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=s,s.stageSize=s.stageSize||new lt(1,1),s.outputSize=s.outputSize||s.stageSize,s.outputPosition=s.outputPosition||O.Zero(),s.outputRotation=s.outputRotation||O.Zero(),s.layerCount=s.layerCount||1,s.maxAnimationFrames=s.maxAnimationFrames||0,s.baseTile=s.baseTile||0,s.flipU=s.flipU||!1,s.colorMultiply=s.colorMultiply||new O(1,1,1),this._scene=r,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(let p=0;p{if(this.spriteSheet&&this.spriteSheet.isReady()&&this.spriteSheet._texture){this._material.setVector2("spriteMapSize",new lt(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1));return}c<100&&setTimeout(()=>{c++,h()},100)};h(),this._material.setVector3("colorMul",s.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=Jd(e+":output",{size:1,updatable:!0},r),this._output.scaling.x=s.outputSize.x,this._output.scaling.y=s.outputSize.y,this.position=s.outputPosition,this.rotation=s.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||lt.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,s=>s===e);if(!t||!t.hit||!t.getTextureCoordinates)return new lt(-1,-1);const i=t.getTextureCoordinates();return i||new lt(-1,-1)}_createFrameBuffer(){const e=new Array;for(let s=0;s0&&(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 s=t.response.split(` +\r`);for(let r=0;r{e.dispose()}),this._frameMap.dispose()}}class pEe extends jM{constructor(e,t,i,s,r=null,n=.01,o=Te.TRILINEAR_SAMPLINGMODE){super(e,t,i,64,s,n,o,!0,r),this.name=e}}var NM;(function(a){a[a.INIT=0]="INIT",a[a.RUNNING=1]="RUNNING",a[a.DONE=2]="DONE",a[a.ERROR=3]="ERROR"})(NM||(NM={}));class u7{constructor(e){this.name=e,this._isCompleted=!1,this._taskState=NM.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=NM.RUNNING,this.runTask(e,()=>{this._onDoneCallback(t,i)},(s,r)=>{this._onErrorCallback(i,s,r)})}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=NM.INIT}_onErrorCallback(e,t,i){this._taskState=NM.ERROR,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=NM.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 Ude{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class kde extends u7{constructor(e,t,i,s,r){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=s,this.extension=r}runTask(e,t,i){As.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,s=>{this.loadedContainer=s,this.loadedMeshes=s.meshes,this.loadedTransformNodes=s.transformNodes,this.loadedParticleSystems=s.particleSystems,this.loadedSkeletons=s.skeletons,this.loadedAnimationGroups=s.animationGroups,t()},null,(s,r,n)=>{i(r,n)},this.extension)}}class Hde extends u7{constructor(e,t,i,s,r){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=s,this.extension=r}runTask(e,t,i){As.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,(s,r,n,o,l)=>{this.loadedMeshes=s,this.loadedTransformNodes=l,this.loadedParticleSystems=r,this.loadedSkeletons=n,this.loadedAnimationGroups=o,t()},null,(s,r,n)=>{i(r,n)},this.extension)}}class mEe extends u7{constructor(e,t,i,s,r){super(e),this.name=e,this.rootUrl=t,this.filename=i,this.targetConverter=s,this.extension=r}runTask(e,t,i){const s=e.animatables.length,r=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],As.ImportAnimations(this.rootUrl,this.filename,e,!1,TM.NoSync,this.targetConverter,()=>{this.loadedAnimatables=e.animatables.slice(s),this.loadedAnimationGroups=e.animationGroups.slice(r),t()},null,(n,o,l)=>{i(o,l)},this.extension)}}class jde extends u7{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,s=>{this.text=s,t()},void 0,!1,!1,(s,r)=>{s&&i(s.status+" "+s.statusText,r)})}}class Gde extends u7{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,s=>{this.data=s,t()},void 0,!0,!0,(s,r)=>{s&&i(s.status+" "+s.statusText,r)})}}class Wde extends u7{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const s=new Image;Be.SetCorsBehavior(this.url,s),s.onload=()=>{this.image=s,t()},s.onerror=r=>{i("Error loading image",r)},s.src=this.url}}class Yde extends u7{constructor(e,t,i,s=!0,r=Te.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=s,this.samplingMode=r}runTask(e,t,i){const s=()=>{t()},r=(n,o)=>{i(n,o)};this.texture=new Te(this.url,e,this.noMipmap,this.invertY,this.samplingMode,s,r)}}class Xde extends u7{constructor(e,t,i,s,r,n){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=s,this.files=r,this.prefiltered=n}runTask(e,t,i){const s=()=>{t()},r=(n,o)=>{i(n,o)};this.texture=new Ic(this.url,e,this.extensions,this.noMipmap,this.files,s,r,void 0,this.prefiltered)}}class Kde extends u7{constructor(e,t,i,s=!1,r=!0,n=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=s,this.generateHarmonics=r,this.gammaSpace=n,this.reserved=o}runTask(e,t,i){const s=()=>{t()},r=(n,o)=>{i(n,o)};this.texture=new fI(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,s,r)}}class Qde extends u7{constructor(e,t,i,s=!1,r=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=s,this.gammaSpace=r}runTask(e,t,i){const s=()=>{t()},r=(n,o)=>{i(n,o)};this.texture=new GB(this.url,e,this.size,this.noMipmap,this.gammaSpace,s,r)}}class _Ee{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new Se,this.onTaskErrorObservable=new Se,this.onTasksDoneObservable=new Se,this.onProgressObservable=new Se,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||Ii.LastCreatedScene}addContainerTask(e,t,i,s,r){const n=new kde(e,t,i,s,r);return this._tasks.push(n),n}addMeshTask(e,t,i,s,r){const n=new Hde(e,t,i,s,r);return this._tasks.push(n),n}addTextFileTask(e,t){const i=new jde(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new Gde(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new Wde(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,s,r=Te.TRILINEAR_SAMPLINGMODE){const n=new Yde(e,t,i,s,r);return this._tasks.push(n),n}addCubeTextureTask(e,t,i,s,r,n){const o=new Xde(e,t,i,s,r,n);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,s=!1,r=!0,n=!1,o=!1){const l=new Kde(e,t,i,s,r,n,o);return this._tasks.push(l),l}addEquiRectangularCubeTextureAssetTask(e,t,i,s=!1,r=!0){const n=new Qde(e,t,i,s,r);return this._tasks.push(n),n}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 Ude(this._waitingTasksCount,this._totalTasksCount,e))}catch(t){Me.Error("Error running progress callbacks."),console.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===NM.DONE){const s=this._tasks.indexOf(i);s>-1&&this._tasks.splice(s,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(t){Me.Error("Error running tasks-done callbacks."),console.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(s){i("Error executing task success callbacks",s)}},i=(s,r)=>{e._setErrorObject(s,r),this.onTaskError?this.onTaskError(e):e.onError||Me.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 BN{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}class gEe{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new O(1,1,1),this._newPosition=O.Zero(),this._centerPosition=O.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 s=0;s!0,this.displayLoadingUI=!0,this.loadAsync=(u,p)=>this.useAppend?As.AppendAsync("file:",u,this._currentScene,p):As.LoadAsync("file:",u,this._engine,p),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=s,this._additionalRenderLoopLogicCallback=r,this._textureLoadingCallback=n,this._startingProcessingFilesCallback=o,this._onReloadCallback=l,this._errorCallback=c}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,s){const r=e.createReader(),n=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");r.readEntries(o=>{i.count+=o.length;for(const l of o)l.isFile?l.file(c=>{c.correctName=n+c.name,t.push(c),--i.count===0&&s()}):l.isDirectory&&this._traverseFolder(l,t,i,s);--i.count===0&&s()})}_processFiles(e){for(let t=0;tthis._sceneFileToLoad=r)||(As.IsPluginForExtensionAvailable("."+s)&&(this._sceneFileToLoad=e[t]),Ote.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=new Array,i=[],s=e.dataTransfer?e.dataTransfer.items:null;for(let r=0;r{this._processFiles(t),r.count===0&&this._processReload()})}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){this._sceneFileToLoad?(this.useAppend||this._currentScene&&(Me.errorsCount>0&&Me.ClearLogCache(),this._engine.stopRenderLoop()),As.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)})):Me.Error("Please provide a valid .babylon file.")}}class wte{dispose(){if(this._observers&&this._observables)for(let e=0;e{n.skipNextObservers||o._willBeUnregistered||o.mask&e&&(o.scope?r=r.then(l=>(n.lastReturnValue=l,o.callback.apply(o.scope,[a,n]))):r=r.then(l=>(n.lastReturnValue=l,o.callback(a,n))),o.unregisterOnNextCall&&this._deferUnregister(o))}),await r,a};class hT{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class HY extends hT{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 s=0;sthis.maximumSize&&(r.scale(this.step),i=!1)}return i}}class oJ extends hT{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 jY extends hT{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class GY extends hT{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class WY extends hT{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class Zde extends hT{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return this.onApply?this.onApply(e,t):!0}}class YY extends hT{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class lJ extends hT{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class mI extends hT{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Oe))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 mI._UpdateSelectionTree}static set UpdateSelectionTree(e){mI._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const s=e.meshes.slice(0);let r=s.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,s=!0;for(let r=0;r{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,s){const r=new Nte(e,t||OP.ModerateDegradationAllowed(),!1);return i&&r.onSuccessObservable.add(()=>{i()}),s&&r.onFailureObservable.add(()=>{s()}),r.start(),r}}let cJ=[];const Bte=(a,e)=>{a.doNotSerialize||(e.vertexData.push(a.serializeVerticeData()),cJ[a.id]=!0)},qde=(a,e)=>{const t={},i=a._geometry;return i&&(a.getScene().getGeometryById(i.id)||Bte(i,e.geometries)),a.serialize&&a.serialize(t),t},vEe=(a,e)=>{if(a._isMesh){const t=a;if(t.delayLoadState===1||t.delayLoadState===0){const i=r=>{e.materials=e.materials||[],t.material&&!e.materials.some(n=>n.id===t.material.id)&&e.materials.push(r.serialize())};if(t.material&&!t.material.doNotSerialize)if(t.material instanceof g0){if(e.multiMaterials=e.multiMaterials||[],!e.multiMaterials.some(r=>r.id===t.material.id)){e.multiMaterials.push(t.material.serialize());for(const r of t.material.subMaterials)r&&i(r)}}else i(t.material);else t.material||i(t.getScene().defaultMaterial);const s=t._geometry;s&&(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=[]),Bte(s,e.geometries)),t.skeleton&&!t.skeleton.doNotSerialize&&(e.skeletons=e.skeletons||[],e.skeletons.push(t.skeleton.serialize())),e.meshes=e.meshes||[],e.meshes.push(qde(t,e))}}else if(a.getClassName()==="TransformNode"){const t=a;e.transformNodes.push(t.serialize())}else if(a.getClassName().indexOf("Camera")!==-1){const t=a;e.cameras.push(t.serialize())}else if(a.getClassName().indexOf("Light")!==-1){const t=a;e.lights.push(t.serialize())}};class nI{static ClearCache(){cJ=[]}static Serialize(e){return nI._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Te.ForceSerializeBuffers&&console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),nI.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 l=e.getPhysicsEngine();l&&(i.physicsEnabled=!0,i.physicsGravity=l.gravity.asArray(),i.physicsEngine=l.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const l of e.meshes){const c=l.morphTargetManager;c&&i.morphTargetManagers.push(c.serialize())}i.lights=[];let s,r;for(s=0;s0){i.animationGroups=[];for(let l=0;l0)for(i.reflectionProbes=[],s=0;st)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=r)):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}else if(e instanceof Object){for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const s=e[i];s instanceof Promise?t.push(s.then(r=>e[i]=r)):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}}}static SerializeMesh(e,t=!1,i=!1){const s={};if(s.meshes=[],s.transformNodes=[],s.cameras=[],s.lights=[],nI.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let r=0;r{e.indexOf(n)<0&&!n.doNotSerialize&&e.push(n)}),t&&e[r].parent&&e.indexOf(e[r].parent)<0&&!e[r].parent.doNotSerialize&&e.push(e[r].parent);return e.forEach(r=>{vEe(r,s)}),s}}class sG{static IsSupported(e){const t=e.getRenderingCanvas();return!!t&&typeof t.captureStream=="function"}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!sG.IsSupported(e))throw"Your browser does not support recording so far.";const i=e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options=Object.assign(Object.assign({},sG._DefaultOptions),t);const s=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const r of this._options.audioTracks)s.addTrack(r);this._mediaRecorder=new MediaRecorder(s,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=this._handleDataAvailable.bind(this),this._mediaRecorder.onerror=this._handleError.bind(this),this._mediaRecorder.onstop=this._handleStop.bind(this)}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,s)=>{this._resolve=i,this._reject=s})}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&&Be.Download(e,this._fileName)}}sG._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let $I=null;function BW(a,e,t,i,s="image/png",r=!1,n){const{height:o,width:l}=$de(a,e,t);if(!(o&&l)){Me.Error("Invalid 'size' parameter !");return}$I||($I=document.createElement("canvas")),$I.width=l,$I.height=o;const c=$I.getContext("2d"),h=a.getRenderWidth()/a.getRenderHeight();let u=l,p=u/h;p>o&&(p=o,u=p*h);const m=Math.max(0,l-u)/2,_=Math.max(0,o-p)/2;e.getScene().activeCamera!==e?FW(a,e,t,d=>{if(r){const C=new Blob([d]);Be.DownloadBlob(C),i&&i("")}else i&&i(d)},s,1,a.getCreationOptions().antialias,void 0,void 0,void 0,void 0,n):a.onEndFrameObservable.addOnce(()=>{const d=a.getRenderingCanvas();c&&d&&c.drawImage(d,m,_,u,p),$I&&(r?(Be.EncodeScreenshotCanvasData($I,void 0,s,void 0,n),i&&i("")):Be.EncodeScreenshotCanvasData($I,i,s,void 0,n))})}function Fte(a,e,t,i="image/png",s){return new Promise((r,n)=>{BW(a,e,t,o=>{typeof o<"u"?r(o):n(new Error("Data is undefined"))},i,void 0,s)})}function Jde(a,e,t,i,s="image/png",r){return new Promise(n=>{BW(a,e,{width:t,height:i},()=>{n()},s,!0,r)})}function FW(a,e,t,i,s="image/png",r=1,n=!1,o,l=!1,c=!1,h=!0,u){const{height:p,width:m,finalWidth:_,finalHeight:f}=$de(a,e,t),d={width:m,height:p};if(!(p&&m)){Me.Error("Invalid 'size' parameter !");return}const C={width:a.getRenderWidth(),height:a.getRenderHeight()};a.setSize(m,p);const v=e.getScene(),y=new Oa("screenShot",d,v,!1,!1,0,!1,Te.BILINEAR_SAMPLINGMODE,void 0,c,void 0,void 0,void 0,r);y.renderList=v.meshes.slice(),y.samples=r,y.renderSprites=l,y.activeCamera=e,y.forceLayerMaskCheck=h;const M=()=>{a.onEndFrameObservable.addOnce(()=>{_===m&&f===p?y.readPixels(void 0,void 0,void 0,!1).then(b=>{Nu.DumpData(m,p,b,i,s,o,!0,void 0,u),y.dispose()}):QK("pass",y.getInternalTexture(),v,void 0,void 0,void 0,_,f).then(b=>{a._readTexturePixels(b,_,f,-1,0,null,!0,!1,0,0).then(E=>{Nu.DumpData(_,f,E,i,s,o,!0,void 0,u),b.dispose()})})}),v.incrementRenderId(),v.resetCachedMaterial(),y.render(!0),v.incrementRenderId(),v.resetCachedMaterial(),a.setSize(C.width,C.height),e.getProjectionMatrix(!0),v.render()};if(n){const b=new mD("antialiasing",1,v.activeCamera);y.addPostProcess(b),b.getEffect().isReady()?M():b.getEffect().onCompiled=()=>{M()}}else M()}function Vte(a,e,t,i="image/png",s=1,r=!1,n,o=!1,l=!1,c=!0,h){return new Promise((u,p)=>{FW(a,e,t,m=>{typeof m<"u"?u(m):p(new Error("Data is undefined"))},i,s,r,n,o,l,c,h)})}function $de(a,e,t){let i=0,s=0,r=0,n=0;if(typeof t=="object"){const o=t.precision?Math.abs(t.precision):1;t.width&&t.height?(i=t.height*o,s=t.width*o):t.width&&!t.height?(s=t.width*o,i=Math.round(s/a.getAspectRatio(e))):t.height&&!t.width?(i=t.height*o,s=Math.round(i*a.getAspectRatio(e))):(s=Math.round(a.getRenderWidth()*o),i=Math.round(s/a.getAspectRatio(e))),t.finalWidth&&t.finalHeight?(n=t.finalHeight,r=t.finalWidth):t.finalWidth&&!t.finalHeight?(r=t.finalWidth,n=Math.round(r/a.getAspectRatio(e))):t.finalHeight&&!t.finalWidth?(n=t.finalHeight,r=Math.round(n*a.getAspectRatio(e))):(r=s,n=i)}else isNaN(t)||(i=t,s=t,r=t,n=t);return s&&(s=Math.floor(s)),i&&(i=Math.floor(i)),r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),{height:i|0,width:s|0,finalWidth:r|0,finalHeight:n|0}}const CEe={CreateScreenshot:BW,CreateScreenshotAsync:Fte,CreateScreenshotWithResizeAsync:Jde,CreateScreenshotUsingRenderTarget:FW,CreateScreenshotUsingRenderTargetAsync:Vte},AEe=()=>{Be.CreateScreenshot=BW,Be.CreateScreenshotAsync=Fte,Be.CreateScreenshotUsingRenderTarget=FW,Be.CreateScreenshotUsingRenderTargetAsync=Vte};AEe();var hJ;(function(a){a[a.Checkbox=0]="Checkbox",a[a.Slider=1]="Slider",a[a.Vector3=2]="Vector3",a[a.Quaternion=3]="Quaternion",a[a.Color3=4]="Color3",a[a.String=5]="String",a[a.Button=6]="Button",a[a.Options=7]="Options",a[a.Tab=8]="Tab",a[a.FileButton=9]="FileButton",a[a.Vector2=10]="Vector2"})(hJ||(hJ={}));class hj{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 O$(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class uJ{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const t={};return{getItem:i=>{const s=t[i];return s===void 0?null:s},setItem:(i,s)=>{t[i]=s}}}}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())}}uJ._Storage=uJ._GetStorage();class xEe{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,Kt.AllowLoadingUniqueId=!0,this._savedJSON=nI.Serialize(e),Kt.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=Te.ForceSerializeBuffers;Te.ForceSerializeBuffers=!1,Kt.AllowLoadingUniqueId=!0;const t=nI.Serialize(this._trackedScene);Kt.AllowLoadingUniqueId=!1;const i={};for(const s in t)this._compareCollections(s,this._savedJSON[s],t[s],i);return Te.ForceSerializeBuffers=e,i}_compareArray(e,t,i,s){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 n=0;nh.uniqueId===l);if(c.length){const h=c[0],u={};this._compareObjects(o,h,u)||(s[e]||(s[e]=[]),u.__state={id:h.id||h.name},s[e].push(u))}else{const h={__state:{deleteId:o.id||o.name}};s[e]||(s[e]=[]),s[e].push(h)}}for(let n=0;ns.getShadowGenerators());for(const s of i)if(s){const r=s.values();for(let n=r.next();n.done!==!0;n=r.next()){const o=n.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 s in e){const r=e[s],n=i[s];if(Array.isArray(n)||s==="shadowGenerators")switch(s){case"cameras":this._ApplyDeltaForEntity(r,t,t.getCameraById.bind(t),o=>Pi.Parse(o,t));break;case"lights":this._ApplyDeltaForEntity(r,t,t.getLightById.bind(t),o=>pr.Parse(o,t));break;case"shadowGenerators":this._ApplyDeltaForEntity(r,t,o=>this.GetShadowGeneratorById(t,o),o=>Us.Parse(o,t));break;case"meshes":this._ApplyDeltaForEntity(r,t,t.getMeshById.bind(t),o=>Oe.Parse(o,t,""));break;case"skeletons":this._ApplyDeltaForEntity(r,t,t.getSkeletonById.bind(t),o=>qM.Parse(o,t));break;case"materials":this._ApplyDeltaForEntity(r,t,t.getMaterialById.bind(t),o=>Lt.Parse(o,t,""));break;case"multiMaterials":this._ApplyDeltaForEntity(r,t,t.getMaterialById.bind(t),o=>g0.Parse(o,t,""));break;case"transformNodes":this._ApplyDeltaForEntity(r,t,t.getTransformNodeById.bind(t),o=>Ki.Parse(o,t,""));break;case"particleSystems":this._ApplyDeltaForEntity(r,t,t.getParticleSystemById.bind(t),o=>xr.Parse(o,t,""));break;case"morphTargetManagers":this._ApplyDeltaForEntity(r,t,t.getMorphTargetById.bind(t),o=>eC.Parse(o,t));break;case"postProcesses":this._ApplyDeltaForEntity(r,t,t.getPostProcessByName.bind(t),o=>rs.Parse(o,t,""));break}else isNaN(n)?n.fromArray&&n.fromArray(r):i[s]=r}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const s=e[i],r=t[i];r!==void 0&&(!isNaN(r)||Array.isArray(r)?t[i]=s:r.fromArray?r.fromArray(s):typeof r=="object"&&r!==null&&this._ApplyPropertiesToEntity(s,r))}}static _ApplyDeltaForEntity(e,t,i,s){for(const r of e)if(r.__state&&r.__state.id!==void 0){const n=i(r.__state.id);n&&(this._ApplyPropertiesToEntity(r,n),Kt.ParseProperties(r,n,t,null))}else if(r.__state&&r.__state.deleteId!==void 0){const n=i(r.__state.deleteId);n?.dispose()}else s(r)}}var $B;(function(a){class e{serialize(){const s={},r=new Array(this._characterToIdx.size);return this._characterToIdx.forEach((n,o)=>{r[n]=o}),s.characters=r,s.insertionCosts=this._insertionCosts,s.deletionCosts=this._deletionCosts,s.substitutionCosts=this._substitutionCosts,JSON.stringify(s)}static Deserialize(s){const r=JSON.parse(s),n=new e(r.characters);return n._insertionCosts=r.insertionCosts,n._deletionCosts=r.deletionCosts,n._substitutionCosts=r.substitutionCosts,n}constructor(s,r=null,n=null,o=null){r=r??(()=>1),n=n??(()=>1),o=o??((c,h)=>c===h?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(s.length),this._deletionCosts=new Array(s.length),this._substitutionCosts=new Array(s.length);let l;for(let c=0;ct._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+t._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=r,this._characters=s.map(n=>this._alphabet.getCharacterIdx(n))}distance(s){return t._Distance(this,s)}static _Distance(s,r){const n=s._alphabet;if(n!==r._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const o=s._characters,l=r._characters,c=o.length,h=l.length,u=t._CostMatrix;u[0][0]=0;for(let p=0;pnew Array(t._MAX_SEQUENCE_LENGTH+1)),a.Sequence=t})($B||($B={}));class oa{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new oa(t._segmentLength);return i._points=t._points.map(s=>new O(s._x,s._y,s._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/O.Distance(this._points[t-1],e);for(let s=i();s<=1;s=i()){const r=this._points[t-1].scale(1-s);e.scaleAndAddToRef(s,r),this._points.push(r),++t}}}resampleAtTargetResolution(e){const t=new oa(this.getLength()/e);return this._points.forEach(i=>{t.add(i)}),t}tokenize(e){const t=[],i=new O;for(let s=2;s.98?!1:(O.CrossToRef(oa._ForwardDir,oa._InverseFromVec,oa._UpDir),oa._UpDir.normalize(),ge.LookAtLHToRef(e,t,oa._UpDir,oa._LookMatrix),i.subtractToRef(t,oa._FromToVec),oa._FromToVec.normalize(),O.TransformNormalToRef(oa._FromToVec,oa._LookMatrix,s),!0)}static _TokenizeSegment(e,t){oa._BestMatch=0,oa._Score=O.Dot(e,t[0]),oa._BestScore=oa._Score;for(let i=1;ioa._BestScore&&(oa._BestMatch=i,oa._BestScore=oa._Score);return oa._BestMatch}}oa._ForwardDir=new O;oa._InverseFromVec=new O;oa._UpDir=new O;oa._FromToVec=new O;oa._LookMatrix=new ge;class rG{static Generate(e=64,t=256,i=.1,s=.001,r=[]){const l=new rG(e);for(let _=0;_(1-d)*_+d*f;for(let _=0;_{l.chars[f].subtractToRef(d,p),h=p.lengthSquared(),h>1e-6&&p.scaleAndAddToRef(1/(p.lengthSquared()*h),u)}),u.scaleInPlace(c),l.chars[f].addInPlace(u),l.chars[f].normalize()}return l}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new rG(t.length);for(let s=0;se.serialize()))}static Deserialize(e,t){const i=new BM;return i._sequences=JSON.parse(e).map(s=>$B.Sequence.Deserialize(s,t)),i}static CreateFromTrajectory(e,t,i){return BM.CreateFromTokenizationPyramid(BM._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new BM;return i._sequences=e.map(s=>new $B.Sequence(s,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=BM._FINEST_DESCRIPTOR_RESOLUTION){const s=[];for(let r=i;r>4;r=Math.floor(r/2))s.push(e.resampleAtTargetResolution(r).tokenize(t.chars));return s}distance(e){let t=0,i;for(let s=0;st.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),s=new eF;return s._descriptors=i.descriptors.map(r=>BM.Deserialize(r,t)),s._centroidIdx=i.centroidIdx,s._averageDistance=i.averageDistance,s}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(s=>{e+=i.distance(s)}),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,eF._MIN_AVERAGE_DISTANCE))}}eF._MIN_AVERAGE_DISTANCE=1;class IX{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 IX;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=rG.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=$B.Alphabet.Deserialize(t.levenshteinAlphabet);for(let s=0;sr===0?0:1,r=>r===0?0:1,(r,n)=>Math.min(1-O.Dot(e.chars[r],e.chars[n]),1)),s=new IX;return s._vector3Alphabet=e,s._levenshteinAlphabet=i,s}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new eF),this._nameToDescribedTrajectory.get(t).add(BM.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=BM.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach((o,l)=>{o.getMatchCost(t){const r=s.data;if(r.startsWith(nG._SERVER_PREFIX)){const n=r.substr(nG._SERVER_PREFIX.length);Me.Log(`[Reflector] Received server message: ${n.substr(0,64)}`),this._handleServerMessage(n);return}else Me.Log(`[Reflector] Received client message: ${r.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=s=>{Me.Log(`[Reflector] Disconnected ${s.code} ${s.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){switch(e){case"connected":{nI.SerializeAsync(this._scene).then(t=>{this._webSocket.send(`load|${JSON.stringify(t)}`)});break}}}_handleClientMessage(){}}nG._SERVER_PREFIX="$$";class TQ{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new Se,TQ.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===void 0||t.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch{}}unobserve(e){var t;try{(t=this._observer)===null||t===void 0||t.unobserve(e)}catch{}}dispose(){var e;(e=this._observer)===null||e===void 0||e.disconnect(),this._observer=null,this.onPressureChanged.clear()}}const bEe=1.5;class B9{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*bEe),t=new Float32Array(e);t.set(this._view),this._view=t}}const eL=1800,EEe=24,yEe="0",Are="timestamp",xre="numPoints",MEe=/\r/g,wZ="@";class k5{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const i=Zr.Now-this._startingTimestamp,s=this.datasets.ids.length,r=this.datasets.startingIndices.itemLength;let n=0;if(r>0){const o=this.datasets.startingIndices.at(r-1);n=o+this.datasets.data.at(o+k5.NumberOfPointsOffset)+k5.SliceDataOffset}if(this.datasets.startingIndices.push(n),this.datasets.data.push(i),this.datasets.data.push(s),this.datasets.ids.forEach(o=>{const l=this._strategies.get(o);!l||this.datasets.data.push(l.getData())}),this.datasetObservable.hasObservers()){const o=[i,s];for(let l=0;li.callback(this._datasetMeta,new D$(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var s;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&((s=this._strategies.get(e))===null||s===void 0||s.dispose(),this._strategies.delete(e));const r=o=>{let l=0,c=0;const h=o.onAfterRenderObservable.add(()=>{c=l,l=0}),u=this._customEventObservable.add(p=>{e===p.name&&(p.value!==void 0?l=p.value:l++)});return{id:e,getData:()=>c,dispose:()=>{o.onAfterRenderObservable.remove(h),this._customEventObservable.remove(u)}}},n={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:r,category:i}),n}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:s}of e){const r=t(this._scene);if(this._strategies.has(r.id)){r.dispose();continue}this.datasets.ids.push(r.id),i&&(i=i.replace(new RegExp(wZ,"g"),"")),this._datasetMeta.set(r.id,{color:this._getHexColorFromId(r.id),category:i,hidden:s}),this._strategies.set(r.id,r)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let s=0;s>s&255;i+=(yEe+r.toString(16)).substr(-2)}return i}getCurrentSlice(){const e=Zr.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(s=>{const r=this._strategies.get(s);!r||this.datasetObservable.hasObservers()&&i.push(r.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){const s=this._datasetMeta.get(e);!s||(s[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new B9(eL),this.datasets.ids.length=0,this.datasets.startingIndices=new B9(eL),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(MEe,"").split(` +`).map(u=>u.split(",").filter(p=>p.length>0)).filter(u=>u.length>0),s=0,r=k5.NumberOfPointsOffset;if(i.length<2)return!1;const n={ids:[],data:new B9(eL),startingIndices:new B9(eL)},[o,...l]=i;if(o.length<2||o[s]!==Are||o[r]!==xre)return!1;const c=new Map;for(let u=k5.SliceDataOffset;uu.dispose()),this._strategies.clear(),!t)for(const u of this.datasets.ids){const p=c.get(u);this._datasetMeta.set(u,{category:p,color:this._getHexColorFromId(u)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${Are},${xre}`;for(let i=0;i{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}const N5=()=>{};class TEe{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:N5}}}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 s=new TQ;return s.observe("cpu"),s.onPressureChanged.add(r=>{var n,o;for(const l of r)if(t&&l.factors.includes(t)||!t&&((o=(n=l.factors)===null||n===void 0?void 0:n.length)!==null&&o!==void 0?o:0)===0)switch(l.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:()=>s.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:N5})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:N5})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:N5})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:N5})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:N5})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:N5})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add(()=>{e.getEngine()._drawCalls.fetchNewFrame()}),s=e.onAfterRenderObservable.add(()=>{t=e.getEngine()._drawCalls.current});return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(s)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:N5})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:N5})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:N5})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:N5})}static AbsoluteFpsStrategy(){return e=>{const t=new fhe(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:N5}}}static MeshesSelectionStrategy(){return e=>{let t=Zr.Now,i=0;const s=e.onBeforeActiveMeshesEvaluationObservable.add(()=>{t=Zr.Now}),r=e.onAfterActiveMeshesEvaluationObservable.add(()=>{i=Zr.Now-t});return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(s),e.onAfterActiveMeshesEvaluationObservable.remove(r)}}}}static RenderTargetsStrategy(){return e=>{let t=Zr.Now,i=0;const s=e.onBeforeRenderTargetsRenderObservable.add(()=>{t=Zr.Now}),r=e.onAfterRenderTargetsRenderObservable.add(()=>{i=Zr.Now-t});return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(s),e.onAfterRenderTargetsRenderObservable.remove(r)}}}}static ParticlesStrategy(){return e=>{let t=Zr.Now,i=0;const s=e.onBeforeParticlesRenderingObservable.add(()=>{t=Zr.Now}),r=e.onAfterParticlesRenderingObservable.add(()=>{i=Zr.Now-t});return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(s),e.onAfterParticlesRenderingObservable.remove(r)}}}}static SpritesStrategy(){return e=>{var t,i;let s=Zr.Now,r=0;const n=(t=e.onBeforeSpritesRenderingObservable)===null||t===void 0?void 0:t.add(()=>{s=Zr.Now}),o=(i=e.onAfterSpritesRenderingObservable)===null||i===void 0?void 0:i.add(()=>{r=Zr.Now-s});return{id:"Sprites",getData:()=>r,dispose:()=>{var l,c;(l=e.onBeforeSpritesRenderingObservable)===null||l===void 0||l.remove(n),(c=e.onAfterSpritesRenderingObservable)===null||c===void 0||c.remove(o)}}}}static AnimationsStrategy(){return e=>{let t=Zr.Now,i=0;const s=e.onBeforeAnimationsObservable.add(()=>{t=Zr.Now}),r=e.onAfterAnimationsObservable.add(()=>{i=Zr.Now-t});return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterAnimationsObservable.remove(r)}}}}static PhysicsStrategy(){return e=>{var t,i;let s=Zr.Now,r=0;const n=(t=e.onBeforePhysicsObservable)===null||t===void 0?void 0:t.add(()=>{s=Zr.Now}),o=(i=e.onAfterPhysicsObservable)===null||i===void 0?void 0:i.add(()=>{r=Zr.Now-s});return{id:"Physics",getData:()=>r,dispose:()=>{var l,c;(l=e.onBeforePhysicsObservable)===null||l===void 0||l.remove(n),(c=e.onAfterPhysicsObservable)===null||c===void 0||c.remove(o)}}}}static RenderStrategy(){return e=>{let t=Zr.Now,i=0;const s=e.onBeforeDrawPhaseObservable.add(()=>{t=Zr.Now}),r=e.onAfterDrawPhaseObservable.add(()=>{i=Zr.Now-t});return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(s),e.onAfterDrawPhaseObservable.remove(r)}}}}static FrameTotalStrategy(){return e=>{let t=Zr.Now,i=0;const s=e.onBeforeAnimationsObservable.add(()=>{t=Zr.Now}),r=e.onAfterRenderObservable.add(()=>{i=Zr.Now-t});return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterRenderObservable.remove(r)}}}}static InterFrameStrategy(){return e=>{let t=Zr.Now,i=0;const s=e.onBeforeAnimationsObservable.add(()=>{i=Zr.Now-t}),r=e.onAfterRenderObservable.add(()=>{t=Zr.Now});return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterRenderObservable.remove(r)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new dhe(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(t.gpuFrameTimeCounter.current*1e-6,0),dispose:()=>{t.dispose()}}}}}oi.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new k5(this)),this._perfCollector};function SEe(a){const e=new Array,t=new Array,i=new Array,s=a.add(()=>{const n=e.length;for(let o=0;o{e.push(n),t.push(o),i.push(l)},dispose:()=>{a.remove(s)}}}Se.prototype.runCoroutineAsync=function(a){if(!this._coroutineScheduler){const e=SEe(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return xK(a,this._coroutineScheduler)};Se.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};const IEe="equirectangularPanoramaPixelShader",LEe=`#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 );}`;Ue.ShadersStore[IEe]=LEe;async function REe(a,e){var t,i;const s=(t=e.probe)!==null&&t!==void 0?t:new hD("tempProbe",e.size,a),r=!!e.probe;r||(e.position?s.position=e.position.clone():a.activeCamera&&(s.position=a.activeCamera.position.clone()));const n=e.meshesFilter?a.meshes.filter(e.meshesFilter):a.meshes;(i=s.renderList)===null||i===void 0||i.push(...n),s.refreshRate=Oa.REFRESHRATE_RENDER_ONCE,s.cubeTexture.render();const o=new Ihe("tempProceduralTexture","equirectangularPanorama",{width:e.size*2,height:e.size},a);return o.setTexture("cubeMap",s.cubeTexture),new Promise((l,c)=>{o.onGeneratedObservable.addOnce(()=>{const h=o.readPixels();if(!h){c(new Error("No Pixel Data found on procedural texture")),o.dispose(),r||s.dispose();return}h.then(u=>{o.dispose(),r||s.dispose(),e.filename?(Nu.DumpData(e.size*2,e.size,u,void 0,"image/png",e.filename),l(null)):l(u)})})})}class _I extends ku{constructor(e,t={}){super(e),this.options=t,this._direction=new O(0,0,-1),this._mat=new ge,this._onSelectEnabled=!1,this._origin=new O(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new Se,this._onHitTestResults=i=>{const s=i.map(r=>{const n=ge.FromArray(r.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||n.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&n.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),n),{xrHitResult:r,transformationMatrix:n}});this.lastNativeXRHitResults=i,this.onHitTestResultObservable.notifyObservers(s)},this._onSelect=i=>{!this._onSelectEnabled||_I.XRHitTestWithSelectEvent(i,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Be.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,s){return e.requestHitTest(t,i).then(r=>{const n=s||(o=>!!o.hitMatrix);return r.filter(n)})}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const s=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,s,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;ge.FromArrayToRef(t.transform.matrix,0,this._mat),O.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),O.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});_I.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}_I.Name=$r.HIT_TEST;_I.Version=1;_l.AddWebXRFeature(_I.Name,(a,e)=>()=>new _I(a,e),_I.Version,!1);let PEe=0;class rB extends ku{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 Se,this.onAnchorRemovedObservable=new Se,this.onAnchorUpdatedObservable=new Se,this._tmpVector=new O,this._tmpQuaternion=new ke,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 O,i=new ke){this._populateTmpTransformation(t,i);const s=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 r=await e.xrHitResult.createAnchor(s);return new Promise((n,o)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!0,xrTransformation:s,resolve:n,reject:o})})}catch(r){throw new Error(r)}else throw this.detach(),new Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new ke,i=!1){this._populateTmpTransformation(e,t);const s=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}),r=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(s,this._xrSessionManager.currentFrame):void 0;return new Promise((n,o)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:n,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(r=>!t.has(r.xrAnchor)).map(r=>this._trackedAnchors.indexOf(r));let s=0;i.forEach(r=>{const n=this._trackedAnchors.splice(r-s,1)[0];this.onAnchorRemovedObservable.notifyObservers(n),s++}),t.forEach(r=>{if(this._lastFrameDetected.has(r)){const n=this._findIndexInAnchorArray(r),o=this._trackedAnchors[n];try{this._updateAnchorWithXRFrame(r,o,e),o.attachedNode&&(o.attachedNode.rotationQuaternion=o.attachedNode.rotationQuaternion||new ke,o.transformationMatrix.decompose(o.attachedNode.scaling,o.attachedNode.rotationQuaternion,o.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(o)}catch{Be.Warn("Anchor could not be updated")}}else{const n={id:PEe++,xrAnchor:r,remove:()=>r.delete()},o=this._updateAnchorWithXRFrame(r,n,e);this._trackedAnchors.push(o),this.onAnchorAddedObservable.notifyObservers(o);const c=this._futureAnchors.filter(h=>h.nativeAnchor===r)[0];c&&(c.resolve(o),c.resolved=!0)}}),this._lastFrameDetected=t}this._futureAnchors.forEach(i=>{!i.resolved&&!i.submitted&&(this._createAnchorAtTransformation(i.xrTransformation,e).then(s=>{i.nativeAnchor=s},s=>{i.resolved=!0,i.reject(s)}),i.submitted=!0)})}_findIndexInAnchorArray(e){for(let t=0;t()=>new rB(a,e),rB.Version);let DEe=0;class nB extends ku{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new Se,this.onPlaneRemovedObservable=new Se,this.onPlaneUpdatedObservable=new Se,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"}_onXRFrame(e){var t;if(!this.attached||!this._enabled||!e)return;const i=e.detectedPlanes||((t=e.worldInformation)===null||t===void 0?void 0:t.detectedPlanes);if(i){for(let s=0;s{if(this._lastFrameDetected.has(s)){if(s.lastChangedTime===this._xrSessionManager.currentTimestamp){const r=this._findIndexInPlaneArray(s),n=this._detectedPlanes[r];this._updatePlaneWithXRPlane(s,n,e),this.onPlaneUpdatedObservable.notifyObservers(n)}}else{const r={id:DEe++,xrPlane:s,polygonDefinition:[]},n=this._updatePlaneWithXRPlane(s,r,e);this._detectedPlanes.push(n),this.onPlaneAddedObservable.notifyObservers(n)}}),this._lastFrameDetected=i}}_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(r=>{const n=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new O(r.x,r.y,r.z*n)});const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const r=t.transformationMatrix||new ge;ge.FromArrayToRef(s.transform.matrix,0,r),this._xrSessionManager.scene.useRightHandedSystem||r.toggleModelMatrixHandInPlace(),t.transformationMatrix=r,this._options.worldParentNode&&r.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),r)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new nB(a,e),nB.Version);class aB extends ku{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new Se}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)}}aB.Name=$r.BACKGROUND_REMOVER;aB.Version=1;_l.AddWebXRFeature(aB.Name,(a,e)=>()=>new aB(a,e),aB.Version,!0);class OEe{}class oB extends ku{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||ys.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=$d("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});s.isVisible=this._debugMode,s.isPickable=!1,s.rotationQuaternion=new ke;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new ys(s,t,Object.assign({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:s}}constructor(e,t){super(e),this._options=t,this._attachController=i=>{this._controllers[i.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||Me.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&i.inputSource.gamepad?i.onMotionControllerInitObservable.addOnce(s=>{s._doNotLoadControllerMesh?this._createPhysicsImpostor(i):s.onModelLoadedObservable.addOnce(()=>{const r=new ys(s.rootMesh,ys.MeshImpostor,Object.assign({mass:0},this._options.physicsProperties)),n=i.grip||i.pointer;this._controllers[i.uniqueId]={xrController:i,impostor:r,oldPos:n.position.clone(),oldRotation:n.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(i))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new ke,this._tmpVector=new O,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:ys.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=$d("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 ke,this._headsetMesh.isVisible=!1,this._headsetImpostor=new ys(this._headsetMesh,e.impostorType,Object.assign({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=Object.assign(Object.assign({},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===void 0)&&t.linearVelocity){const s=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(s.x,s.y,s.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(!((i=this._options.xrInput.xrCamera._lastXRViewerPose)===null||i===void 0)&&i.angularVelocity){const s=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(s.x,s.y,s.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach(s=>{var r,n;const o=this._controllers[s],l=o.xrController.grip||o.xrController.pointer,c=o.oldPos||o.impostorMesh.position;if(!((r=o.xrController._lastXRPose)===null||r===void 0)&&r.linearVelocity){const u=o.xrController._lastXRPose.linearVelocity;this._tmpVector.set(u.x,u.y,u.z),o.impostor.setLinearVelocity(this._tmpVector)}else l.position.subtractToRef(c,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),o.impostor.setLinearVelocity(this._tmpVector);c.copyFrom(l.position),this._debugMode&&console.log(this._tmpVector,"linear");const h=o.oldRotation||o.impostorMesh.rotationQuaternion;if(!((n=o.xrController._lastXRPose)===null||n===void 0)&&n.angularVelocity){const u=o.xrController._lastXRPose.angularVelocity;this._tmpVector.set(u.x,u.y,u.z),o.impostor.setAngularVelocity(this._tmpVector)}else if(!h.equalsWithEpsilon(l.rotationQuaternion)){h.conjugateInPlace().multiplyToRef(l.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 p=2*Math.atan2(u,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(p/(u*(this._delta/1e3)))}o.impostor.setAngularVelocity(this._tmpVector)}h.copyFrom(l.rotationQuaternion),this._debugMode&&console.log(this._tmpVector,this._tmpQuaternion,"angular")})}_detachController(e){const t=this._controllers[e];!t||(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}oB.Name=$r.PHYSICS_CONTROLLERS;oB.Version=1;_l.AddWebXRFeature(oB.Name,(a,e)=>()=>new oB(a,e),oB.Version,!0);class lB extends ku{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new ge,this._tmpPos=new O,this._tmpQuat=new ke,this._initHitTestSource=i=>{if(!i)return;const s=new XRRay(this.options.offsetRay||{}),r={space:this.options.useReferenceSpace?i:this._xrSessionManager.viewerReferenceSpace,offsetRay:s};if(this.options.entityTypes&&(r.entityTypes=this.options.entityTypes),!r.space){Be.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(r).then(n=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=n})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new Se,this.paused=!1,this.xrNativeFeatureName="hit-test",Be.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(s=>{const r=s.getPose(this._xrSessionManager.referenceSpace);if(!r)return;const n=r.transform.position,o=r.transform.orientation;this._tmpPos.set(n.x,n.y,n.z),this._tmpQuat.set(o.x,o.y,o.z,o.w),ge.FromFloat32ArrayToRefScaled(r.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 l={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:s};i.push(l)}),this.onHitTestResultObservable.notifyObservers(i)}}lB.Name=$r.HIT_TEST;lB.Version=2;_l.AddWebXRFeature(lB.Name,(a,e)=>()=>new lB(a,e),lB.Version,!1);class cB extends ku{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new Se,this.onFeaturePointsUpdatedObservable=new Se,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,s=new Array,r=new Array;for(let n=0;n0&&this.onFeaturePointsAddedObservable.notifyObservers(r),s.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(s)}}_init(){!this._xrSessionManager.session.trySetFeaturePointCloudEnabled||!this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)||(this._enabled=!0)}}cB.Name=$r.FEATURE_POINTS;cB.Version=1;_l.AddWebXRFeature(cB.Name,a=>()=>new cB(a),cB.Version);let wEe=0;class hB extends ku{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new Se,this.onMeshRemovedObservable=new Se,this.onMeshUpdatedObservable=new Se,this.xrNativeFeatureName="mesh-detection",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=(t=e.worldInformation)===null||t===void 0?void 0:t.detectedMeshes;if(i){const s=new Set;this._detectedMeshes.forEach((r,n)=>{i.has(n)||s.add(n)}),s.forEach(r=>{const n=this._detectedMeshes.get(r);n&&(this.onMeshRemovedObservable.notifyObservers(n),this._detectedMeshes.delete(r))}),i.forEach(r=>{if(this._detectedMeshes.has(r)){if(r.lastChangedTime===this._xrSessionManager.currentTimestamp){const n=this._detectedMeshes.get(r);n&&(this._updateVertexDataWithXRMesh(r,n,e),this.onMeshUpdatedObservable.notifyObservers(n))}}else{const n={id:wEe++,xrMesh:r},o=this._updateVertexDataWithXRMesh(r,n,e);this._detectedMeshes.set(r,o),this.onMeshAddedObservable.notifyObservers(o)}})}}catch(i){console.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){if(t.xrMesh=e,t.worldParentNode=this._options.worldParentNode,this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=e.positions,t.normals=e.normals;else{t.positions=new Float32Array(e.positions.length);for(let r=0;r()=>new hB(a,e),hB.Version,!1);var AM;(function(a){a[a.NotReceived=0]="NotReceived",a[a.Waiting=1]="Waiting",a[a.Received=2]="Received"})(AM||(AM={}));class uB extends ku{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new Se,this.onTrackableImageFoundObservable=new Se,this.onTrackedImageUpdatedObservable=new Se,this._trackableScoreStatus=AM.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,s)=>({image:i,widthInMeters:this.options.images[s].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch{return Be.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===AM.Waiting)return;if(this._trackableScoreStatus===AM.NotReceived){this._checkScoresAsync();return}const t=e.getImageTrackingResults();for(const i of t){let s=!1;const r=i.index,n=this._trackedImages[r];if(!n)continue;n.xrTrackingResult=i,n.realWorldWidth!==i.measuredWidthInMeters&&(n.realWorldWidth=i.measuredWidthInMeters,s=!0);const o=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(o){const h=n.transformationMatrix;ge.FromArrayToRef(o.transform.matrix,0,h),this._xrSessionManager.scene.useRightHandedSystem||h.toggleModelMatrixHandInPlace(),s=!0}const c=i.trackingState==="emulated";n.emulated!==c&&(n.emulated=c,s=!0),s&&this.onTrackedImageUpdatedObservable.notifyObservers(n)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==AM.NotReceived)return;this._trackableScoreStatus=AM.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||e.length===0){this._trackableScoreStatus=AM.NotReceived;return}for(let t=0;t0?AM.Received:AM.NotReceived}}uB.Name=$r.IMAGE_TRACKING;uB.Version=1;_l.AddWebXRFeature(uB.Name,(a,e)=>()=>new uB(a,e),uB.Version,!1);class dB extends ku{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Be.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 Be.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 Be.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}}}}dB.Name=$r.DOM_OVERLAY;dB.Version=1;_l.AddWebXRFeature(dB.Name,(a,e)=>()=>new dB(a,e),dB.Version,!1);class gI extends ku{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){var i,s,r,n,o,l;if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new ke,this._tmpRotationMatrix=ge.Identity(),this._tmpTranslationDirection=new O,this._tmpMovementTranslation=new O,this._tempCacheQuaternion=new ke,this._attachController=c=>{if(this._controllers[c.uniqueId])return;this._controllers[c.uniqueId]={xrController:c,registeredComponents:[]};const h=this._controllers[c.uniqueId];if(h.xrController.inputSource.targetRayMode==="tracked-pointer"&&h.xrController.inputSource.gamepad){const u=()=>{if(c.motionController)for(const p of this._currentRegistrationConfigurations){let m=null;if(p.allowedComponentTypes)for(const f of p.allowedComponentTypes){const d=c.motionController.getComponentOfType(f);if(d!==null){m=d;break}}if(p.mainComponentOnly){const f=c.motionController.getMainComponent();if(f===null)continue;m=f}if(typeof p.componentSelectionPredicate=="function"&&(m=p.componentSelectionPredicate(c)),m&&p.forceHandedness&&c.inputSource.handedness!==p.forceHandedness||m===null)continue;const _={registrationConfiguration:p,component:m};h.registeredComponents.push(_),"axisChangedHandler"in p&&(_.onAxisChangedObserver=m.onAxisValueChangedObservable.add(f=>{p.axisChangedHandler(f,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in p&&(_.onButtonChangedObserver=m.onButtonStateChangedObservable.add(()=>{m.changes.pressed&&p.buttonChangedhandler(m.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};c.motionController?u():c.onMotionControllerInitObservable.addOnce(()=>{u()})}},!t||t.xrInput===void 0){Be.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=gI.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:(i=t.movementOrientationFollowsViewerPose)!==null&&i!==void 0?i:!0,movementSpeed:(s=t.movementSpeed)!==null&&s!==void 0?s:1,movementThreshold:(r=t.movementThreshold)!==null&&r!==void 0?r:.25,rotationEnabled:(n=t.rotationEnabled)!==null&&n!==void 0?n:!0,rotationSpeed:(o=t.rotationSpeed)!==null&&o!==void 0?o:1,rotationThreshold:(l=t.rotationThreshold)!==null&&l!==void 0?l:.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,ke.RotationYawPitchRollToRef(i,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(ke.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&&(ge.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),O.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]}}}gI.Name=$r.MOVEMENT;gI.REGISTRATIONS={default:[{allowedComponentTypes:[i4.THUMBSTICK_TYPE,i4.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(a,e,t)=>{e.rotateX=Math.abs(a.x)>t.rotationThreshold?a.x:0,e.rotateY=Math.abs(a.y)>t.rotationThreshold?a.y:0}},{allowedComponentTypes:[i4.THUMBSTICK_TYPE,i4.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(a,e,t)=>{e.moveX=Math.abs(a.x)>t.movementThreshold?a.x:0,e.moveY=Math.abs(a.y)>t.movementThreshold?a.y:0}}]};gI.Version=1;_l.AddWebXRFeature(gI.Name,(a,e)=>()=>new gI(a,e),gI.Version,!0);class fB extends ku{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=O.Up().negateInPlace(),this._lightColor=Ie.White(),this._intensity=1,this._sphericalHarmonics=new zL,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new Se,this._updateReflectionCubeMap=()=>{var i;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const r=Date.now();if(r-this._cubeMapPollTime{this._xrLightProbe=i,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new Sn(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 fB(a,e),fB.Version,!1);class pB extends ku{constructor(e){super(e),this.onEyeTrackingStartedObservable=new Se,this.onEyeTrackingEndedObservable=new Se,this.onEyeTrackingFrameUpdateObservable=new Se,this._eyeTrackingStartListener=t=>{this._latestEyeSpace=t.gazeSpace,this._gazeRay=new gr(O.Zero(),O.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);const i=t.transform.orientation;ue.Quaternion[0].set(i.x,i.y,i.z,i.w),this._xrSessionManager.scene.useRightHandedSystem?O.RightHandedForwardReadOnly.rotateByQuaternionToRef(ue.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,ue.Quaternion[0].z*=-1,ue.Quaternion[0].w*=-1,O.LeftHandedForwardReadOnly.rotateByQuaternionToRef(ue.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))}}pB.Name=$r.EYE_TRACKING;pB.Version=1;_l.AddWebXRFeature(pB.Name,a=>()=>new pB(a),pB.Version,!1);class NEe{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 BEe{constructor(){this._samples=new NEe(20),this._entropy=0,this.onFirstStepDetected=new Se}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=lt.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;no&&(l=b,o=M);if(on*this._squaredProjectionDistanceThreshold)return;const f=ue.Vector3[0];f.set(i,s,0);const d=ue.Vector3[1];d.set(h.x,h.y,0);const C=O.Cross(f,d).z>0,v=r.clone(),y=r.clone();c.subtractToRef(r,h),C?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,v),h.scaleAndAddToRef(this._axisToApexExtendFactor,y)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,v),h.scaleAndAddToRef(this._axisToApexShrinkFactor,y)),this.onFirstStepDetected.notifyObservers({leftApex:v,rightApex:y,currentPosition:r,currentStepDirection:C?"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 yj{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new BEe,this._walker=null,this._movement=new lt,this._millisecondsSinceLastUpdate=yj._MillisecondsPerUpdate,this.movementThisFrame=O.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(t=>{this._walker||(this._walker=new FEe(t.leftApex,t.rightApex,t.currentPosition,t.currentStepDirection),this._walker.onFootfall.add(()=>{console.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>=yj._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=yj._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 XY extends ku{static get Name(){return $r.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 O,this._forward=new O,this._position=new O,this._movement=new O,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&Me.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 yj(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,s=t.transform.matrix;this._up.copyFromFloats(s[4],s[5],i*s[6]),this._forward.copyFromFloats(s[8],s[9],i*s[10]),this._position.copyFromFloats(s[12],s[13],i*s[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||O.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}_l.AddWebXRFeature(XY.Name,(a,e)=>()=>new XY(a,e),XY.Version,!1);class e1e extends pee{constructor(e,t,i,s,r,n){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n}}class VEe extends mee{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t){var i,s,r,n;const o=this._lastSubImages.get(t),l=t=="left"?0:1,c=(i=e.colorTextureWidth)!==null&&i!==void 0?i:e.textureWidth,h=(s=e.colorTextureHeight)!==null&&s!==void 0?s:e.textureHeight;if(!this._renderTargetTextures[l]||o?.textureWidth!==c||o?.textureHeight!==h){let u;const p=(r=e.depthStencilTextureWidth)!==null&&r!==void 0?r:c,m=(n=e.depthStencilTextureHeight)!==null&&n!==void 0?n:h;(c===p||h===m)&&(u=e.depthStencilTexture),this._renderTargetTextures[l]=this._createRenderTargetTexture(c,h,null,e.colorTexture,u,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:c,framebufferHeight:h}}return this._lastSubImages.set(t,e),this._renderTargetTextures[l]}_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.eye)}_setViewportForSubImage(e,t){var i,s;const r=(i=t.colorTextureWidth)!==null&&i!==void 0?i:t.textureWidth,n=(s=t.colorTextureWidth)!==null&&s!==void 0?s:t.textureHeight,o=t.viewport;e.x=o.x/r,e.y=o.y/n,e.width=o.width/r,e.height=o.height/n}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return i?(this._setViewportForSubImage(e,i),!0):!1}}class t1e extends e1e{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,s=>new zEe(s,i,this)),this.layer=e}}class zEe extends VEe{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 UEe={},bre={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};class mB extends ku{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],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=Object.assign({},bre),i=this._options.preferMultiviewOnInit&&e.getCaps().multiview;return i&&(t.textureType="texture-array"),this.addXRSessionLayer(this.createProjectionLayer(t,i)),!0}detach(){return super.detach()?(this._existingLayers.length=0,!0):!1}createXRWebGLLayer(e=UEe){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new _ee(t)}createProjectionLayer(e=bre,t=!1){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'.");const i=this._xrWebGLBinding.createProjectionLayer(e);return new t1e(i,t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;const t=Object.assign({},this._xrSessionManager.session.renderState);t.baseLayer=void 0,t.layers=e.map(i=>i.layer),this._xrSessionManager.updateRenderState(t),this._xrSessionManager._setBaseLayerWrapper(e.length>0?e[0]:null)}isCompatible(){return!this._xrSessionManager.isNative&&typeof XRWebGLBinding<"u"&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){}}mB.Name=$r.LAYERS;mB.Version=1;_l.AddWebXRFeature(mB.Name,(a,e)=>()=>new mB(a,e),mB.Version,!1);class _B extends ku{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(){var e,t;if(!this._cachedWebGLTexture)return null;const i=this._xrSessionManager.scene.getEngine(),s=new dn(i,hr.Unknown);return s.isCube=!1,s.invertY=!1,s._useSRGBBuffer=!1,s.format=this.depthDataFormat==="ushort"?2:5,s.generateMipMaps=!1,s.type=this.depthDataFormat==="ushort"?5:1,s.samplingMode=7,s.width=(e=this.width)!==null&&e!==void 0?e:0,s.height=(t=this.height)!==null&&t!==void 0?t:0,s._cachedWrapU=1,s._cachedWrapV=1,s._hardwareTexture=new gF(this._cachedWebGLTexture,i._gl),s}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 Se,this.xrNativeFeatureName="depth-sensing",Be.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===void 0||e.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(i!=null)for(const s of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,s,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,s,this.depthDataFormat);break;default:Be.Error("Unknown depth usage"),this.detach();break}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(s===null)return;const{data:r,width:n,height:o,rawValueToMeters:l,getDepthInMeters:c}=s;switch(this._width=n,this._height=o,this._rawValueToMeters=l,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(c.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Ya.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,Te.NEAREST_SAMPLINGMODE,He.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(r)).map(h=>h*l));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(r).map(h=>h*l));break}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(s===null)return;const{texture:r,width:n,height:o}=s;this._width=n,this._height=o,this._cachedWebGLTexture=r;const l=this._xrSessionManager.scene,h=l.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Ya.CreateRTexture(null,n,o,l,!1,!0,Te.NEAREST_SAMPLINGMODE,i==="ushort"?He.TEXTURETYPE_UNSIGNED_BYTE:He.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 s=this.options.usagePreference.map(n=>{switch(n){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),r=this.options.dataFormatPreference.map(n=>{switch(n){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:s,dataFormatPreference:r}})}else i({})})}}_B.Name=$r.DEPTH_SENSING;_B.Version=1;_l.AddWebXRFeature(_B.Name,(a,e)=>()=>new _B(a,e),_B.Version,!1);const kEe="velocityPixelShader",HEe=`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 +}`;Ue.ShadersStore[kEe]=HEe;const jEe="velocityVertexShader",GEe=`#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 +}`;Ue.ShadersStore[jEe]=GEe;class i1e extends Oa{constructor(e,t,i,s=512){super("spacewarp rtt",s,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[ge.Identity(),ge.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 oh("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(r=>{this._previousWorldMatrices[r.uniqueId]=this._previousWorldMatrices[r.uniqueId]||r.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[r.uniqueId]),this._previousWorldMatrices[r.uniqueId]=r.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(s=>{this._originalPairing.push([s,s.material]),s.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(s=>{s[0].material=s[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 s1e{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,s,r){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new i1e(s,r,this._scene,n),l=o.renderTarget;return i&&(l._framebuffer=i),l._colorTextureArray=s,l._depthStencilTextureArray=r,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let s=this._renderTargetTextures.get(t.eye);const r=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return(!s||i?.textureWidth!==r||i?.textureHeight!=n)&&(s=this._createRenderTargetTexture(r,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,s),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n}),this._lastSubImages.set(t,e),s}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 gB extends ku{constructor(e){super(e),this.dependsOn=[$r.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 s1e(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._xrSessionManager.scene.onAfterRenderObservable.add(this._onAfterRender.bind(this)),!0}_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)}}gB.Name=$r.SPACE_WARP;gB.Version=1;_l.AddWebXRFeature(gB.Name,a=>()=>new gB(a),gB.Version,!1);class r1e extends lD{constructor(e,t,i){super(e,WEe[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(){}}ou.RegisterController("generic-hand-select-grasp",(a,e)=>new r1e(e,a.gamepad,a.handedness));const WEe={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 vI extends lD{constructor(e,t,i){super(e,YEe["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=vI.MODEL_LEFT_FILENAME:e=vI.MODEL_RIGHT_FILENAME;const t="default",i=vI.MODEL_BASE_URL+t+"/";return{filename:e,path:i}}_getModelLoadingConstraints(){const e=As.IsPluginForExtensionAvailable(".glb");return e||Me.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 s=this._mapping.buttons[t],r=s.rootNodeName;if(!r){Me.Log("Skipping unknown button at index: "+i+" with mapped name: "+t);return}const n=this._getChildByName(this.rootMesh,r);if(!n){Me.Warn("Missing button mesh with name: "+r);return}if(s.valueMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.valueNodeName),s.pressedMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.pressedNodeName),s.unpressedMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.unpressedNodeName),s.valueMesh&&s.pressedMesh&&s.unpressedMesh){const o=this.getComponent(t);o&&o.onButtonStateChangedObservable.add(l=>{this._lerpTransform(s,l.value)},void 0,!0)}else Me.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(t=>{const i=this.getComponent(t);!i.isAxes()||["x-axis","y-axis"].forEach(s=>{if(!this.rootMesh)return;const r=this._mapping.axes[t][s],n=this._getChildByName(this.rootMesh,r.rootNodeName);if(!n){Me.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?i&&i.onAxisValueChangedObservable.add(o=>{const l=s==="x-axis"?o.x:o.y;this._lerpTransform(r,l,!0)},void 0,!0):Me.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){this.rootMesh=new Oe(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;inew vI(e,a.gamepad,a.handedness));const YEe={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 sC extends lD{constructor(e,t,i,s=!1,r=!1){super(e,XEe[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=sC.MODEL_LEFT_FILENAME:e=sC.MODEL_RIGHT_FILENAME;const t=this._isQuest()?sC.QUEST_MODEL_BASE_URL:sC.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(s=>{const r=s&&this.getComponent(s);r&&r.onButtonStateChangedObservable.add(n=>{if(!(!this.rootMesh||this.disableAnimation))switch(s){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-n.value*.2,this._modelRootNode.getChildren()[3].position.y=-n.value*.005,this._modelRootNode.getChildren()[3].position.z=-n.value*.005);return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*n.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(n.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(n.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new Oe(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=ke.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}}sC.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/";sC.MODEL_LEFT_FILENAME="left.babylon";sC.MODEL_RIGHT_FILENAME="right.babylon";sC.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/";ou.RegisterController("oculus-touch",(a,e)=>new sC(e,a.gamepad,a.handedness));ou.RegisterController("oculus-touch-legacy",(a,e)=>new sC(e,a.gamepad,a.handedness,!0));const XEe={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 tD extends lD{constructor(e,t,i){super(e,KEe[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){const e=tD.MODEL_FILENAME,t=tD.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(s=>{if(!(!this.rootMesh||this.disableAnimation))switch(t){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-s.value*.15;return;case"xr-standard-touchpad":return;case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new Oe(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=ke.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}tD.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/";tD.MODEL_FILENAME="wand.babylon";ou.RegisterController("htc-vive",(a,e)=>new tD(e,a.gamepad,a.handedness));const KEe={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 n1e{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(4+4),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=()=>{var t;return(t=this._nativeImpl._imageTrackingResults)!==null&&t!==void 0?t:[]}}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 s=this._xrTransform.orientation;return s.x=this._xrPoseVectorData[4],s.y=this._xrPoseVectorData[5],s.z=this._xrPoseVectorData[6],s.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")}}kce("NativeXRFrame",n1e);class a1e{constructor(e){this._userVariables=new Map,this._executionVariables=new Map,this._pendingBlocks=[],this._graphVariables=e}hasVariable(e){return this._userVariables.has(e)}setVariable(e,t){this._userVariables.set(e,t)}getVariable(e){return this._userVariables.get(e)}_getBlockPrefixedName(e,t){return`${e.uniqueId}_${t}`}_setExecutionVariable(e,t,i){this._executionVariables.set(this._getBlockPrefixedName(e,t),i)}_getExecutionVariable(e,t){return this._executionVariables.get(this._getBlockPrefixedName(e,t))}_deleteExecutionVariable(e,t){this._executionVariables.delete(this._getBlockPrefixedName(e,t))}get graphVariables(){return this._graphVariables}_addPendingBlock(e){this._pendingBlocks.push(e)}_removePendingBlock(e){const t=this._pendingBlocks.indexOf(e);t!==-1&&this._pendingBlocks.splice(t,1)}_clearPendingBlocks(){for(const e of this._pendingBlocks)e._cancelPendingTasks(this);this._pendingBlocks.length=0}}class QEe{constructor(){this._definitions=new Map}defineVariable(e,t){this._definitions.set(e,t)}generateContext(e){const t=new a1e(e);return this._definitions.forEach((i,s)=>{t.setVariable(s,i)}),t}}class ZEe{constructor(e){this.variableDefinitions=new QEe,this._eventBlocks=[],this._executionContexts=[],this._scene=e.scene,this._eventCoordinator=e.eventCoordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(this.dispose.bind(this))}createContext(){const e=this.variableDefinitions.generateContext({scene:this._scene,eventCoordinator:this._eventCoordinator});return this._executionContexts.push(e),e}addEventBlock(e){this._eventBlocks.push(e)}start(){this._executionContexts.length===0&&this.createContext();for(const e of this._executionContexts)for(const t of this._eventBlocks)t._startPendingTasks(e)}dispose(){for(const e of this._executionContexts)e._clearPendingBlocks();this._executionContexts.length=0,this._eventBlocks.length=0,this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null}}var tT;(function(a){a[a.Input=0]="Input",a[a.Output=1]="Output"})(tT||(tT={}));class o1e{constructor(e,t,i){this.name=e,this._connectionType=t,this._ownerBlock=i,this._connectedPoint=[]}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)}}class Ere extends o1e{constructor(e,t,i,s){super(e,t,i),this.richType=s,this._value=s.defaultValueBuilder()}_isSingularConnection(){return this.connectionType===tT.Input}set value(e){this._value=e}getValue(e){return this.connectionType===tT.Output?(this._ownerBlock._updateOutputs(e),this._value):this.isConnected()?this._connectedPoint[0].getValue(e):this._value}}class sR{constructor(){this.uniqueId=WL(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}_registerDataInput(e,t){const i=new Ere(e,tT.Input,this,t);return this.dataInputs.push(i),i}_registerDataOutput(e,t){const i=new Ere(e,tT.Output,this,t);return this.dataOutputs.push(i),i}}class dJ extends o1e{_isSingularConnection(){return this.connectionType===tT.Output}_activateSignal(e){var t;this.connectionType===tT.Input?this._ownerBlock._execute(e):(t=this._connectedPoint[0])===null||t===void 0||t._activateSignal(e)}}class SQ extends sR{constructor(){super(),this._signalInputs=[],this._signalOutputs=[],this.onStart=this._registerSignalInput("onStart")}_registerSignalInput(e){const t=new dJ(e,tT.Input,this);return this._signalInputs.push(t),t}_registerSignalOutput(e){const t=new dJ(e,tT.Output,this);return this._signalOutputs.push(t),t}}class zte extends SQ{constructor(){super(),this.onDone=this._registerSignalOutput("onDone")}_startPendingTasks(e){this._preparePendingTasks(e),e._addPendingBlock(this)}}class VW extends zte{_execute(e){this.onDone._activateSignal(e)}}class qEe{constructor(){this._customEventsMap=new Map}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new Se,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}const n4={typeName:"any",defaultValueBuilder:()=>{}},zW={typeName:"string",defaultValueBuilder:()=>""},as={typeName:"number",defaultValueBuilder:()=>0},d7={typeName:"boolean",defaultValueBuilder:()=>!1},Y2={typeName:"Vector2",defaultValueBuilder:()=>lt.Zero()},fu={typeName:"Vector3",defaultValueBuilder:()=>O.Zero()},X2={typeName:"Vector4",defaultValueBuilder:()=>Ui.Zero()},JEe={typeName:"Matrix",defaultValueBuilder:()=>ge.Identity()},$Ee={typeName:"Color3",defaultValueBuilder:()=>Ie.Black()},eye={typeName:"Color4",defaultValueBuilder:()=>new Zt(0,0,0,0)};class BF extends SQ{constructor(){super(),this.onDone=this._registerSignalOutput("onDone")}}class tye extends BF{constructor(){super(),this.startIndex=this._registerDataInput("startIndex",as),this.endIndex=this._registerDataInput("endIndex",as),this.step=this._registerDataInput("step",as),this.step.value=1,this.index=this._registerDataOutput("index",as),this.onLoop=this._registerSignalOutput("onLoop"),this.onDone=this._registerSignalOutput("onDone")}_executeLoop(e){let t=e._getExecutionVariable(this,"index");const i=e._getExecutionVariable(this,"endIndex");if(tthis._onAnimationEnd(o,e));this.runningAnimatable.value=o,r.push(o),e._setExecutionVariable(this,"runningAnimatables",r)}_execute(e){this._startPendingTasks(e),this.onDone._activateSignal(e)}_onAnimationEnd(e,t){var i;const s=(i=t._getExecutionVariable(this,"runningAnimatables"))!==null&&i!==void 0?i:[],r=s.indexOf(e);r!==-1&&s.splice(r,1),t._removePendingBlock(this),this.onAnimationEnd._activateSignal(t)}_cancelPendingTasks(e){var t;const i=(t=e._getExecutionVariable(this,"runningAnimatables"))!==null&&t!==void 0?t:[];for(const s of i)s.stop();e._deleteExecutionVariable(this,"runningAnimatables")}}class nye extends BF{constructor(e){super(),this.variableName=this._registerDataInput("variableName",zW),e?.variableName!==void 0&&(this.variableName.value=e.variableName),this.input=this._registerDataInput("input",n4),e?.input!==void 0&&(this.input.value=e.input)}_execute(e){const t=this.variableName.getValue(e);e.setVariable(t,this.input.getValue(e)),this.onDone._activateSignal(e)}}class aye extends BF{constructor(){super(),this.target=this._registerDataInput("target",n4),this.property=this._registerDataInput("property",zW),this.value=this._registerDataInput("value",n4)}_setProperty(e,t,i){const s=t.split(".");let r=e;for(let n=0;n=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.graphVariables.scene,r=new uhe({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.onDone._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);s!==-1?i.splice(s,1):Be.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.onTimerDone._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const i of t)i.dispose();e._deleteExecutionVariable(this,"runningTimers")}}class lye extends BF{constructor(){super(),this.eventId=this._registerDataInput("eventId",zW),this.eventData=this._registerDataInput("eventData",n4)}_execute(e){const t=this.eventId.getValue(e),i=this.eventData.getValue(e);e.graphVariables.eventCoordinator.notifyCustomEvent(t,i),this.onDone._activateSignal(e)}}class cye extends BF{constructor(){super(),this.animationToStop=this._registerDataInput("animationToStop",n4)}_execute(e){this.animationToStop.getValue(e).stop(),this.onDone._activateSignal(e)}}class hye extends sR{constructor(){super(),this.condition=this._registerDataInput("condition",d7),this.trueValue=this._registerDataInput("trueValue",n4),this.falseValue=this._registerDataInput("falseValue",n4),this.output=this._registerDataOutput("output",n4)}_updateOutputs(e){this.output.value=this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e)}}class uye extends sR{constructor(e){super(),this.variableName=this._registerDataInput("variableName",zW),e?.variableName&&(this.variableName.value=e.variableName),this.output=this._registerDataOutput("output",n4)}_updateOutputs(e){const t=this.variableName.getValue(e);e.hasVariable(t)&&(this.output.value=e.getVariable(t))}}class Eo extends sR{constructor(e,t,i,s){super(),this._operation=s,this.leftInput=this._registerDataInput("leftInput",e),this.rightInput=this._registerDataInput("rightInput",t),this.output=this._registerDataOutput("Output",i)}_updateOutputs(e){this.output.value=this._operation(this.leftInput.getValue(e),this.rightInput.getValue(e))}}class l1e extends sR{constructor(e,t){super(),this._operation=t,this.output=this._registerDataOutput("output",e)}_updateOutputs(){this.output.value=this._operation()}}class wh extends sR{constructor(e,t,i){super(),this._operation=i,this.input=this._registerDataInput("input",e),this.output=this._registerDataOutput("resultOutput",t)}_updateOutputs(e){this.output.value=this._operation(this.input.getValue(e))}}class dye extends Eo{constructor(){super(as,as,as,(e,t)=>e+t)}}class fye extends Eo{constructor(){super(as,as,as,(e,t)=>e-t)}}class pye extends Eo{constructor(){super(as,as,as,(e,t)=>e*t)}}class mye extends Eo{constructor(){super(as,as,as,(e,t)=>e/t)}}class _ye extends Eo{constructor(){super(as,as,as,(e,t)=>e%t)}}class gye extends Eo{constructor(){super(as,as,as,(e,t)=>Math.pow(e,t))}}class vye extends wh{constructor(){super(as,d7,e=>isNaN(e))}}class Cye extends wh{constructor(){super(as,d7,e=>!isFinite(e))}}class Aye extends wh{constructor(){super(as,as,e=>Math.sqrt(e))}}class xye extends wh{constructor(){super(as,as,e=>Math.abs(e))}}class bye extends wh{constructor(){super(as,as,e=>-e)}}class Eye extends wh{constructor(){super(as,as,e=>Math.floor(e))}}class yye extends wh{constructor(){super(as,as,e=>Math.ceil(e))}}class Mye extends Eo{constructor(){super(as,as,as,(e,t)=>Math.round(e/Math.pow(10,t))/Math.pow(10,t))}}class Tye extends wh{constructor(){super(as,as,e=>Math.trunc(e))}}class Sye extends wh{constructor(){super(as,as,e=>Math.exp(e))}}class Iye extends wh{constructor(){super(as,as,e=>Math.log10(e))}}class Lye extends wh{constructor(){super(as,as,e=>Math.log(e))}}class Rye extends wh{constructor(){super(as,as,e=>Math.log(e)/Math.LN2)}}class Pye extends wh{constructor(){super(as,as,e=>Math.sin(e))}}class Dye extends wh{constructor(){super(as,as,e=>Math.cos(e))}}class Oye extends wh{constructor(){super(as,as,e=>Math.tan(e))}}class wye extends wh{constructor(){super(as,as,e=>Math.asin(e))}}class Nye extends wh{constructor(){super(as,as,e=>Math.acos(e))}}class Bye extends wh{constructor(){super(as,as,e=>Math.atan(e))}}class Fye extends l1e{constructor(){super(as,()=>Math.E)}}class Vye extends l1e{constructor(){super(as,()=>Math.PI)}}class zye extends Eo{constructor(){super(as,as,as,(e,t)=>Math.atan2(e,t))}}class Uye extends Eo{constructor(){super(as,as,as,(e,t)=>e+Math.random()*(t-e))}}class kye extends Eo{constructor(){super(as,as,as,(e,t)=>Math.min(e,t))}}class Hye extends Eo{constructor(){super(as,as,as,(e,t)=>Math.max(e,t))}}class jye extends Eo{constructor(){super(as,as,d7,(e,t)=>e===t)}}class Gye extends Eo{constructor(){super(as,as,d7,(e,t)=>e>t)}}class Wye extends Eo{constructor(){super(as,as,d7,(e,t)=>e>=t)}}class Yye extends Eo{constructor(){super(as,as,d7,(e,t)=>ee<=t)}}class Kye extends sR{constructor(){super(),this.leftInput=this._registerDataInput("leftInput",as),this.rightInput=this._registerDataInput("rightInput",as),this.alphaInput=this._registerDataInput("alphaInput",as),this.resultOutput=this._registerDataOutput("resultOutput",as)}_updateOutputs(){this.resultOutput.value=this.leftInput.value+(this.rightInput.value-this.leftInput.value)*this.alphaInput.value}}class Qye extends Eo{constructor(){super(fu,fu,fu,(e,t)=>e.add(t))}}class Zye extends Eo{constructor(){super(fu,fu,fu,(e,t)=>e.subtract(t))}}class qye extends Eo{constructor(){super(fu,fu,fu,(e,t)=>e.multiply(t))}}class Jye extends Eo{constructor(){super(fu,fu,fu,(e,t)=>e.divide(t))}}class $ye extends Eo{constructor(){super(fu,as,fu,(e,t)=>e.scale(t))}}class eMe extends wh{constructor(){super(fu,as,e=>e.length())}}class tMe extends wh{constructor(){super(fu,fu,e=>e.normalizeToNew())}}class iMe extends Eo{constructor(){super(fu,fu,as,(e,t)=>O.Dot(e,t))}}class sMe extends Eo{constructor(){super(fu,fu,fu,(e,t)=>O.Cross(e,t))}}class rMe extends Eo{constructor(){super(Y2,Y2,Y2,(e,t)=>e.add(t))}}class nMe extends Eo{constructor(){super(Y2,Y2,Y2,(e,t)=>e.subtract(t))}}class aMe extends Eo{constructor(){super(Y2,Y2,Y2,(e,t)=>e.multiply(t))}}class oMe extends Eo{constructor(){super(Y2,Y2,Y2,(e,t)=>e.divide(t))}}class lMe extends Eo{constructor(){super(Y2,as,Y2,(e,t)=>e.scale(t))}}class cMe extends wh{constructor(){super(Y2,as,e=>e.length())}}class hMe extends wh{constructor(){super(Y2,Y2,e=>{const t=e.clone();return t.normalize(),t})}}class uMe extends Eo{constructor(){super(X2,X2,X2,(e,t)=>e.add(t))}}class dMe extends Eo{constructor(){super(X2,X2,X2,(e,t)=>e.subtract(t))}}class fMe extends Eo{constructor(){super(X2,X2,X2,(e,t)=>e.multiply(t))}}class pMe extends Eo{constructor(){super(X2,X2,X2,(e,t)=>e.divide(t))}}class mMe extends Eo{constructor(){super(X2,as,X2,(e,t)=>e.scale(t))}}class _Me extends wh{constructor(){super(X2,as,e=>e.length())}}class gMe extends wh{constructor(){super(X2,X2,e=>{const t=e.clone();return t.normalize(),t})}}class vMe extends VW{constructor(e){super(),this._meshVariableName=e.meshVariableName}_preparePendingTasks(e){let t=e._getExecutionVariable(this,"meshPickObserver");if(!t){const i=e.getVariable(this._meshVariableName);t=i.getScene().onPointerObservable.add(r=>{var n;r.type===mi.POINTERPICK&&((n=r.pickInfo)===null||n===void 0?void 0:n.pickedMesh)===i&&this._execute(e)});const s=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e.getVariable(this._meshVariableName),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}}class CMe extends VW{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const i=e.graphVariables.scene.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.graphVariables.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}}class AMe extends VW{constructor(e){super(),this._params=e,this.eventData=this._registerDataOutput("eventData",n4)}_preparePendingTasks(e){const t=e.graphVariables.eventCoordinator.getCustomEventObservable(this._params.eventId);this._eventObserver=t.add(i=>{this.eventData.value=i,this._execute(e)})}_cancelPendingTasks(e){const t=e.graphVariables.eventCoordinator.getCustomEventObservable(this._params.eventId);t?t.remove(this._eventObserver):Be.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this._params.eventId}`)}}class xMe extends VW{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneBeforeRender")){const i=e.graphVariables.scene.onBeforeRenderObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.graphVariables.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}}const bMe=Object.freeze(Object.defineProperty({__proto__:null,AbstractScene:pc,AbstractActionManager:$3,Action:Da,ActionEvent:$o,ActionManager:mn,Condition:FB,ValueCondition:tu,PredicateCondition:nle,StateCondition:ale,SwitchBooleanAction:ole,SetStateAction:lle,SetValueAction:cle,IncrementValueAction:hle,PlayAnimationAction:ule,StopAnimationAction:dle,DoNothingAction:H$,CombineAction:fle,ExecuteCodeAction:ple,SetParentAction:j$,PlaySoundAction:mle,StopSoundAction:_le,InterpolateValueAction:cX,Animatable:G$,_IAnimationState:u3e,Animation:at,AnimationPropertiesOverride:g3e,EasingFunction:Pc,CircleEase:Ale,BackEase:xle,BounceEase:v3e,CubicEase:C3e,ElasticEase:A3e,ExponentialEase:ble,PowerEase:x3e,QuadraticEase:Ele,QuarticEase:b3e,QuinticEase:E3e,SineEase:W$,BezierCurveEase:ZN,RuntimeAnimation:gle,AnimationEvent:CK,TargetedAnimation:yle,AnimationGroup:ev,get AnimationKeyInterpolation(){return kP},AnimationRange:HP,PathCursor:y3e,get AnimationGroupMaskMode(){return Bj},AnimationGroupMask:M3e,KeepAssets:Ple,InstantiatedEntries:Dle,AssetContainer:kG,Analyser:O3e,AudioEngine:Ole,AudioSceneComponent:v0,Sound:J5,SoundTrack:wle,WeightedSound:Nle,BakedVertexAnimationManager:nD,VertexAnimationBaker:N3e,AutoRotationBehavior:zle,BouncingBehavior:RL,FramingBehavior:u0,AttachToBoxBehavior:B3e,FadeInOutBehavior:yK,MultiPointerScaleBehavior:V3e,PointerDragBehavior:uc,SixDofDragBehavior:Z$,SurfaceMagnetismBehavior:Ule,BaseSixDofDragBehavior:Fb,FollowBehavior:kle,get HandConstraintZone(){return mL},get HandConstraintOrientation(){return k9},get HandConstraintVisibility(){return _L},HandConstraintBehavior:Yle,Bone:ca,BoneIKController:h_,BoneLookController:Wd,Skeleton:qM,Buffer:Q1,VertexBuffer:se,DataBuffer:qb,StorageBuffer:Xle,BaseCameraMouseWheelInput:qG,BaseCameraPointersInput:IK,ArcRotateCameraGamepadInput:$G,ArcRotateCameraKeyboardMoveInput:pC,ArcRotateCameraMouseWheelInput:SF,ArcRotateCameraPointersInput:x0,ArcRotateCameraVRDeviceOrientationInput:aee,FlyCameraKeyboardInput:OI,FlyCameraMouseInput:eW,FollowCameraKeyboardMoveInput:Ad,FollowCameraMouseWheelInput:YL,FollowCameraPointersInput:b0,FreeCameraDeviceOrientationInput:oee,FreeCameraGamepadInput:rW,FreeCameraKeyboardMoveInput:y_,FreeCameraMouseInput:tW,FreeCameraMouseWheelInput:mC,FreeCameraTouchInput:iW,FreeCameraVirtualJoystickInput:lee,CameraInputTypes:i1,CameraInputsManager:JG,Camera:Pi,TargetCamera:Zl,FreeCamera:q1,FreeCameraInputsManager:sW,TouchCamera:cee,ArcRotateCamera:dr,ArcRotateCameraInputsManager:LK,DeviceOrientationCamera:RK,FlyCamera:nW,FlyCameraInputsManager:Qle,FollowCamera:M_,ArcFollowCamera:qle,FollowCameraInputsManager:Zle,GamepadCamera:PK,AnaglyphArcRotateCamera:ice,AnaglyphFreeCamera:sce,AnaglyphGamepadCamera:rce,AnaglyphUniversalCamera:nce,StereoscopicArcRotateCamera:oce,StereoscopicFreeCamera:lce,StereoscopicGamepadCamera:cce,StereoscopicUniversalCamera:hce,StereoscopicScreenUniversalCamera:o4e,UniversalCamera:XL,VirtualJoysticksCamera:uce,VRCameraMetrics:KL,VRDeviceOrientationArcRotateCamera:fce,VRDeviceOrientationFreeCamera:OK,VRDeviceOrientationGamepadCamera:pce,OnAfterEnteringVRObservableEvent:k_e,VRExperienceHelper:WP,WebVRFreeCamera:wK,setStereoscopicAnaglyphRigMode:aW,setStereoscopicRigMode:oW,setVRRigMode:DK,setWebVRRigMode:mce,Collider:dW,DefaultCollisionCoordinator:bce,PickingInfo:cu,IntersectionInfo:hX,_MeshCollisionData:Ile,ComputeEffect:YP,ComputeShader:LF,BoundingBox:sv,BoundingInfo:dc,BoundingSphere:Jb,Octree:XP,OctreeBlock:Vj,OctreeSceneComponent:Cee,Ray:gr,AxesViewer:sI,BoneAxesViewer:j_e,get DebugLayerTab(){return Rq},DebugLayer:zG,PhysicsViewer:Cge,RayHelper:Dee,SkeletonViewer:h0,DirectionalLightFrustumViewer:Age,get DeviceType(){return Rs},get PointerInput(){return er},get NativePointerInput(){return Nj},get DualShockInput(){return yq},get DualSenseInput(){return Mq},get XboxInput(){return Tq},get SwitchInput(){return Sq},DeviceSource:Lq,DeviceSourceManager:ile,Constants:it,ThinEngine:Oi,Engine:He,EngineStore:Ii,NullEngineOptions:Rce,NullEngine:Pce,_OcclusionDataStorage:Oce,_forceTransformFeedbackToBundle:xge,EngineView:bge,allocateAndCopyTypedBuffer:lX,get ComputeBindingType(){return go},NativeDataStream:VL,ValidatedNativeDataStream:Hce,WebGLPipelineContext:joe,WebGLHardwareTexture:gF,get PowerPreference(){return Vq},get FeatureName(){return IM},get BufferMapState(){return zq},get BufferUsage(){return Pa},get MapMode(){return OL},get TextureDimension(){return nv},get TextureUsage(){return Oo},get TextureViewDimension(){return Ra},get TextureAspect(){return kb},get TextureFormat(){return Ae},get AddressMode(){return vP},get FilterMode(){return Qr},get MipmapFilterMode(){return Uq},get CompareFunction(){return Fu},get ShaderStage(){return H9},get BufferBindingType(){return dI},get SamplerBindingType(){return bI},get TextureSampleType(){return e4},get StorageTextureAccess(){return gX},get CompilationMessageType(){return kq},get PipelineErrorReason(){return Hq},get AutoLayoutMode(){return kB},get PrimitiveTopology(){return K3},get FrontFace(){return kj},get CullMode(){return JN},get ColorWriteFlags(){return jq},get BlendFactor(){return j1},get BlendOperation(){return j9},get StencilOperation(){return z5},get IndexFormat(){return EI},get VertexFormat(){return Zo},get InputStepMode(){return Hj},get ComputePassTimestampLocation(){return Gq},get RenderPassTimestampLocation(){return Wq},get LoadOp(){return Mh},get StoreOp(){return u_},get QueryType(){return jj},get CanvasAlphaMode(){return Gj},get DeviceLostReason(){return Yq},get ErrorFilter(){return Xq},WebGPUEngine:Xs,WebGPUCacheRenderPipeline:Jo,WebGPUCacheRenderPipelineTree:OM,WebGPUCacheBindGroups:Il,WebGPUCacheSampler:bL,WebGPUDrawContext:xW,WebGPUTintWASM:m_,WebGL2ShaderProcessor:B$,AcquireNativeObjectAsync:Uce,RegisterNativeTypeAsync:kce,NativeEngine:QP,ShaderCodeInliner:uI,PerformanceConfigurator:nu,EngineFactory:nve,ShaderStore:Ue,RenderTargetWrapper:HG,KeyboardEventTypes:i7,KeyboardInfo:oX,KeyboardInfoPre:Eq,PointerEventTypes:mi,PointerInfoBase:k$,PointerInfoPre:tle,PointerInfo:J6,ClipboardEventTypes:lv,ClipboardInfo:zY,get DeviceInputEventType(){return Iq},EventConstants:rD,DaydreamController:yI,GearVRController:MI,GenericController:TI,OculusTouchController:W1,get PoseEnabledControllerType(){return s7},PoseEnabledControllerHelper:oT,PoseEnabledController:GP,ViveController:ZP,WebVRController:QL,WindowsMotionController:v_,XRWindowsMotionController:ove,StickValues:J3e,Gamepad:fc,GenericPad:Kle,GamepadManager:ece,GamepadSystemSceneComponent:tce,get Xbox360Button(){return X3},get Xbox360Dpad(){return mP},Xbox360Pad:Jle,get DualShockButton(){return q6},get DualShockDpad(){return _P},DualShockPad:$le,AxisDragGizmo:tv,AxisScaleGizmo:cj,BoundingBoxGizmo:Xce,get GizmoAnchorPoint(){return zj},get GizmoCoordinatesMode(){return UB},Gizmo:ua,GizmoManager:lve,PlaneRotationGizmo:$5,PositionGizmo:Qce,RotationGizmo:Kce,ScaleGizmo:Zce,LightGizmo:j5,CameraGizmo:eB,PlaneDragGizmo:$N,EnvironmentHelper:UL,PhotoDome:tQ,_forceSceneHelpersToBundle:L5e,VideoDome:aQ,EngineInstrumentation:dhe,SceneInstrumentation:fhe,_TimeToken:Dce,EffectLayer:T_,EffectLayerSceneComponent:phe,GlowLayer:x_,HighlightLayer:j2,Layer:_he,LayerSceneComponent:mhe,LensFlare:oQ,LensFlareSystem:qP,LensFlareSystemSceneComponent:ghe,Light:pr,ShadowLight:wI,ShadowGenerator:Us,CascadedShadowGenerator:wu,ShadowGeneratorSceneComponent:Ahe,DirectionalLight:c4,HemisphericLight:gn,PointLight:cD,SpotLight:tp,DefaultLoadingScreen:rI,_BabylonLoaderRegistered:OCe,BabylonFileLoaderConfiguration:Ej,get SceneLoaderAnimationGroupLoadingMode(){return TM},SceneLoader:As,SceneLoaderFlags:Lh,BackgroundMaterial:Ur,ColorCurves:hl,EffectFallbacks:Fl,Effect:Ws,FresnelParameters:Xj,ImageProcessingConfigurationDefines:$oe,ImageProcessingConfiguration:Dr,Material:Lt,MaterialDefines:ta,addClipPlaneUniforms:lh,prepareStringDefinesForClipPlanes:PI,prepareDefinesForClipPlanes:Lle,bindClipPlane:wc,MaterialHelper:ze,MultiMaterial:g0,OcclusionMaterial:NCe,MaterialAnisotropicDefines:$ce,PBRAnisotropicConfiguration:ZL,PBRMaterialDefines:Kq,PBRBaseMaterial:Fr,PBRBaseSimpleMaterial:ip,MaterialClearCoatDefines:qce,PBRClearCoatConfiguration:Ph,MaterialIridescenceDefines:Jce,PBRIridescenceConfiguration:$1,PBRMaterial:ji,PBRMetallicRoughnessMaterial:$M,PBRSpecularGlossinessMaterial:eT,MaterialSheenDefines:ehe,PBRSheenConfiguration:_C,MaterialSubSurfaceDefines:the,PBRSubSurfaceConfiguration:ec,PushMaterial:Bl,get ShaderLanguage(){return Ao},ShaderMaterial:oh,StandardMaterialDefines:gce,StandardMaterial:jt,BaseTexture:Sn,ColorGradingTexture:LP,CubeTexture:Ic,DynamicTexture:ep,EquiRectangularCubeTexture:GB,ExternalTexture:Bee,HDRFiltering:xhe,HDRCubeTexture:fI,HtmlElementTexture:cQ,get InternalTextureSource(){return hr},InternalTexture:dn,_DDSTextureLoader:ihe,_ENVTextureLoader:she,_KTXTextureLoader:ahe,_TGATextureLoader:yhe,_HDRTextureLoader:Mhe,_BasisTextureLoader:She,MirrorTexture:EW,MultiRenderTarget:CL,TexturePacker:tC,TexturePackerFrame:$q,CustomProceduralTexture:Ihe,NoiseProceduralTexture:Kj,ProceduralTexture:fC,ProceduralTextureSceneComponent:Gle,RawCubeTexture:uQ,RawTexture:Ya,RawTexture2DArray:lQ,RawTexture3D:oAe,RefractionTexture:jee,RenderTargetTexture:Oa,TextureSampler:N$,Texture:Te,ThinTexture:eI,ThinRenderTargetTexture:lAe,VideoTexture:Yj,get SourceTextureFormat(){return Qq},get TranscodeTarget(){return tB},get EngineFormat(){return CX},UniformBuffer:es,MaterialFlags:Xt,get NodeMaterialBlockTargets(){return Pe},get NodeMaterialBlockConnectionPointTypes(){return he},get NodeMaterialBlockConnectionPointMode(){return Gd},get NodeMaterialSystemValues(){return Rr},get NodeMaterialModes(){return Gf},NodeMaterialConnectionPointCustomObject:fl,get NodeMaterialConnectionPointCompatibilityStates(){return c_},get NodeMaterialConnectionPointDirection(){return xo},NodeMaterialConnectionPoint:jP,NodeMaterialBlock:os,NodeMaterialDefines:lj,NodeMaterial:Pl,VertexOutputBlock:vj,BonesBlock:Lhe,InstancesBlock:Rhe,MorphTargetsBlock:Gee,LightInformationBlock:Phe,FragmentOutputBlock:tI,ImageProcessingBlock:Wee,PerturbNormalBlock:DF,DiscardBlock:Dhe,FrontFacingBlock:Ohe,DerivativeBlock:whe,FragCoordBlock:Nhe,ScreenSizeBlock:Bhe,ScreenSpaceBlock:Fhe,TwirlBlock:Vhe,TBNBlock:uD,HeightToNormalBlock:IW,FragDepthBlock:zhe,ShadowMapBlock:Uhe,PrePassOutputBlock:khe,FogBlock:Hhe,LightBlock:MX,TextureBlock:Qj,ReflectionTextureBlock:jhe,CurrentScreenBlock:eee,SceneDepthBlock:LW,ImageSourceBlock:aC,ClipPlanesBlock:Ghe,InputBlock:Er,get AnimatedInputBlockTypes(){return Z9},PrePassTextureBlock:Whe,NodeMaterialTeleportInBlock:Yhe,NodeMaterialTeleportOutBlock:Xhe,MultiplyBlock:dX,AddBlock:Khe,ScaleBlock:Qhe,ClampBlock:dQ,CrossBlock:Zhe,CustomBlock:qhe,DotBlock:Jhe,TransformBlock:uX,RemapBlock:jG,NormalizeBlock:$he,get TrigonometryBlockOperations(){return yh},TrigonometryBlock:nee,ColorMergerBlock:eue,VectorMergerBlock:Cj,ColorSplitterBlock:ree,VectorSplitterBlock:tue,LerpBlock:iue,DivideBlock:sue,SubtractBlock:rue,StepBlock:nue,OneMinusBlock:Yee,ViewDirectionBlock:Xee,FresnelBlock:aue,MaxBlock:oue,MinBlock:lue,DistanceBlock:cue,LengthBlock:hue,NegateBlock:uue,PowBlock:due,RandomNumberBlock:fue,ArcTan2Block:pue,SmoothStepBlock:mue,ReciprocalBlock:_ue,ReplaceColorBlock:gue,PosterizeBlock:vue,get WaveBlockKind(){return CP},WaveBlock:Cue,GradientBlockColorStep:UY,GradientBlock:Aue,NLerpBlock:xue,WorleyNoise3DBlock:Kee,SimplexPerlin3DBlock:bue,NormalBlendBlock:Eue,Rotate2dBlock:yue,ReflectBlock:Mue,RefractBlock:Tue,DesaturateBlock:Sue,PBRMetallicRoughnessBlock:Oh,SheenBlock:dD,AnisotropyBlock:RW,ReflectionBlock:fD,ClearCoatBlock:JP,RefractionBlock:JL,SubSurfaceBlock:WB,ParticleTextureBlock:tee,ParticleRampGradientBlock:iee,ParticleBlendMultiplyBlock:see,ModBlock:Iue,MatrixBuilderBlock:Lue,get ConditionalBlockConditions(){return a_},ConditionalBlock:Rue,CloudBlock:Qee,VoronoiNoiseBlock:Pue,ElbowBlock:Due,TriPlanarBlock:fQ,BiPlanarBlock:Oue,MatrixDeterminantBlock:wue,MatrixTransposeBlock:Nue,get MeshAttributeExistsBlockTypes(){return La},MeshAttributeExistsBlock:Zee,get CurveBlockTypes(){return _o},CurveBlock:Bue,NodeMaterialOptimizer:hAe,get PropertyTypeForEdition(){return Ms},editableInPropertyPage:ws,EffectRenderer:QG,EffectWrapper:KM,ShadowDepthWrapper:dAe,DrawWrapper:ml,MaterialPluginBase:l4,MaterialPluginManager:iI,RegisterMaterialPlugin:D_e,UnregisterMaterialPlugin:O_e,UnregisterAllMaterialPlugins:fee,get MaterialPluginEvent(){return zu},MaterialDetailMapDefines:_ce,DetailMapConfiguration:lT,DecalMapDefines:Fue,DecalMapConfiguration:OF,createPBRAnisotropicPlugin:fAe,createPBRBRDFPlugin:pAe,createPBRClearCoatPlugin:mAe,createPBRIridescencePlugin:_Ae,createPBRSheenPlugin:gAe,createPBRSubSurfacePlugin:vAe,createDetailMapPlugin:CAe,get GreasedLineMeshMaterialType(){return YB},get GreasedLineMeshColorMode(){return wb},get GreasedLineMeshColorDistributionType(){return wL},MaterialGreasedLineDefines:Vue,GreasedLinePluginMaterial:cl,get MeshDebugMode(){return RP},MeshDebugPluginMaterial:du,Scalar:Bt,extractMinAndMaxIndexed:Sle,extractMinAndMax:zB,Polar:F5,Spherical:V5,get Space(){return sr},Axis:Fo,get Coordinate(){return pL},Color3:Ie,Color4:Zt,TmpColors:hn,ToGammaSpace:GN,ToLinearSpace:_j,PHI:sh,Epsilon:Ls,Frustum:p_,get Orientation(){return TP},BezierCurve:vle,Angle:$9,Arc2:Cle,Path2:yF,Path3D:VB,Curve3:Ob,Plane:Zd,Size:__,Vector2:lt,Vector3:O,Vector4:Ui,Quaternion:ke,Matrix:ge,TmpVectors:ue,PositionNormalVertex:J$,PositionNormalTextureVertex:$$,Viewport:hu,SphericalHarmonics:zL,SphericalPolynomial:JM,AbstractMesh:Ir,DracoCompression:J3,MeshoptCompression:wM,CSG:hL,MeshUVSpaceRenderer:dP,Geometry:au,GroundMesh:IF,GoldbergMesh:CW,TrailMesh:$j,InstancedMesh:ov,LinesMesh:n7,InstancedLinesMesh:Mee,_CreationDataStorage:X$,_InstancesBatch:Pq,Mesh:Oe,VertexDataMaterialInfo:gj,VertexData:Jt,MeshBuilder:nl,SimplificationSettings:DAe,SimplificationQueue:Uue,get SimplificationType(){return eG},QuadraticErrorSimplification:kue,SimplicationQueueSceneComponent:Hue,Polygon:rge,PolygonMeshBuilder:yce,_PrimaryIsoTriangle:Ree,PolyhedronData:mX,GeodesicData:vW,SubMesh:_d,MeshLODLevel:Rle,TransformNode:Ki,CreateBoxVertexData:zK,CreateSegmentedBoxVertexData:Ece,CreateBox:pl,BoxBuilder:G_e,CreateTiledBoxVertexData:bee,CreateTiledBox:Eee,TiledBoxBuilder:Z_e,CreateDiscVertexData:jK,CreateDisc:RF,DiscBuilder:K_e,CreateRibbonVertexData:Aee,CreateRibbon:xI,RibbonBuilder:X_e,CreateSphereVertexData:UK,CreateSphere:$d,SphereBuilder:W_e,CreateHemisphere:Wj,HemisphereBuilder:cve,CreateCylinderVertexData:NK,CreateCylinder:J1,CylinderBuilder:F_e,CreateTorusVertexData:BK,CreateTorus:r7,TorusBuilder:V_e,CreateTorusKnotVertexData:yee,CreateTorusKnot:GK,TorusKnotBuilder:q_e,CreateLineSystemVertexData:Tee,CreateDashedLinesVertexData:See,CreateLineSystem:SP,CreateLines:Ga,CreateDashedLines:WK,LinesBuilder:ige,CreatePolygonVertexData:Iee,CreatePolygon:pW,ExtrudePolygon:mW,PolygonBuilder:nge,ExtrudeShape:_W,ExtrudeShapeCustom:gW,ShapeBuilder:age,CreateLathe:YK,LatheBuilder:oge,CreatePlaneVertexData:MK,CreatePlane:Jd,PlaneBuilder:F3e,CreateTiledPlaneVertexData:qN,CreateTiledPlane:xee,TiledPlaneBuilder:Q_e,CreateGroundVertexData:SM,CreateTiledGroundVertexData:gee,CreateGroundFromHeightMapVertexData:vee,CreateGround:aD,CreateTiledGround:FK,CreateGroundFromHeightMap:VK,GroundBuilder:z_e,CreateTube:XK,TubeBuilder:lge,CreatePolyhedronVertexData:Lee,CreatePolyhedron:KP,PolyhedronBuilder:cge,CreateGeodesic:Tce,CreateGoldbergVertexData:Sce,CreateGoldberg:Ice,CreateDecal:KK,DecalBuilder:_ge,CreateIcoSphereVertexData:SK,CreateIcoSphere:ZG,IcoSphereBuilder:Z3e,CreateCapsuleVertexData:kK,CreateCapsule:fW,CapsuleBuilder:Y_e,CreateTextShapePaths:Pee,CreateText:Lce,get GreasedLineMeshColorDistribution(){return RM},get GreasedLineMeshWidthDistribution(){return q9},CreateGreasedLineMaterial:jue,CreateGreasedLine:qee,CompleteGreasedLineWidthTable:Gue,CompleteGreasedLineColorTable:Wue,WebGLDataBuffer:OB,WebGPUDataBuffer:Gce,GreasedLineMesh:ll,NodeGeometry:Q3,NodeGeometryBlock:Vr,get NodeGeometryConnectionPointCompatibilityStates(){return W9},get NodeGeometryConnectionPointDirection(){return XB},NodeGeometryConnectionPoint:tJ,NodeGeometryBuildState:Yue,get NodeGeometryBlockConnectionPointTypes(){return Ge},get NodeGeometryContextualSources(){return Pn},GeometryOptimizeBlock:mQ,GeometryOutputBlock:Jee,GeometryInputBlock:Lc,PlaneBlock:$ee,BoxBlock:pQ,MeshBlock:Xue,IcoSphereBlock:ete,SphereBlock:tte,GridBlock:ite,TorusBlock:ste,CylinderBlock:rte,CapsuleBlock:nte,DiscBlock:ate,NullBlock:Kue,SetPositionsBlock:ote,SetNormalsBlock:lte,SetUVsBlock:_Q,SetColorsBlock:cte,SetTangentsBlock:hte,get MathBlockOperations(){return Kf},MathBlock:ute,MapRangeBlock:Que,get ConditionBlockTests(){return su},ConditionBlock:dte,get RandomBlockLocks(){return Hb},RandomBlock:fte,NoiseBlock:Zue,MergeGeometryBlock:pte,GeometryCollectionBlock:mte,GeometryElbowBlock:que,ComputeNormalsBlock:Jue,VectorConverterBlock:$ue,NormalizeVectorBlock:ede,SetMaterialIDBlock:_te,get GeometryTrigonometryBlockOperations(){return Rn},GeometryTrigonometryBlock:gte,GeometryTransformBlock:vte,RotationXBlock:tde,RotationYBlock:ide,RotationZBlock:sde,ScalingBlock:rde,AlignBlock:nde,TranslationBlock:ade,InstantiateOnVerticesBlock:gQ,InstantiateOnFacesBlock:Cte,InstantiateOnVolumeBlock:Ate,InstantiateBlock:xte,IntFloatConverterBlock:ode,DebugBlock:lde,GeometryInfoBlock:cde,get MappingTypes(){return jb},MappingBlock:bte,MatrixComposeBlock:hde,TeleportInBlock:ude,TeleportOutBlock:dde,GeometryTextureBlock:fde,GeometryTextureFetchBlock:Ete,BoundingBlock:pde,MorphTarget:t7,MorphTargetManager:eC,RecastJSPlugin:UAe,RecastJSCrowd:mde,Node:pn,Database:Yf,BaseParticleSystem:lC,BoxParticleEmitter:PL,ConeParticleEmitter:GG,CylinderParticleEmitter:MF,CylinderDirectedParticleEmitter:WG,HemisphericParticleEmitter:YG,PointParticleEmitter:XG,SphereParticleEmitter:TF,SphereDirectedParticleEmitter:KG,CustomParticleEmitter:DL,MeshParticleEmitter:TK,WebGL2ParticleSystem:gde,ComputeShaderParticleSystem:vde,GPUParticleSystem:iC,Particle:KB,ParticleHelper:eD,ParticleSystem:xr,ParticleSystemSet:$P,SolidParticle:iJ,ModelShape:sJ,DepthSortedParticle:Ade,SolidParticleVertex:xde,SolidParticleSystem:nxe,CloudPoint:bde,PointsGroup:kY,get PointColor(){return jf},PointsCloudSystem:axe,get SubEmitterType(){return QB},SubEmitter:pI,PhysicsEngine:TW,PhysicsImpostor:ys,PhysicsJoint:$n,DistanceJoint:z3e,MotorEnabledJoint:q$,HingeJoint:U3e,Hinge2Joint:k3e,CannonJSPlugin:xX,AmmoJSPlugin:Qb,OimoJSPlugin:Jq,PhysicsEngineV2:vQ,PhysicsBody:CQ,PhysicsShape:cT,PhysicsShapeSphere:Tte,PhysicsShapeCapsule:Ste,PhysicsShapeCylinder:Ite,PhysicsShapeBox:Lte,PhysicsShapeConvexHull:oxe,PhysicsShapeMesh:lxe,PhysicsShapeContainer:cxe,PhysicsConstraint:$L,Physics6DoFLimit:hxe,Physics6DoFConstraint:Ede,BallAndSocketConstraint:uxe,DistanceConstraint:dxe,HingeConstraint:fxe,SliderConstraint:pxe,LockConstraint:mxe,PrismaticConstraint:_xe,SpringConstraint:gxe,get PhysicsMaterialCombineMode(){return EM},PhysicsAggregate:vxe,get PhysicsConstraintAxisLimitMode(){return bM},get PhysicsConstraintAxis(){return Nb},get PhysicsConstraintType(){return qf},get PhysicsShapeType(){return rh},get PhysicsConstraintMotorType(){return AL},get PhysicsEventType(){return U5},get PhysicsMotionType(){return K5},HavokPlugin:Axe,PhysicsHelper:bxe,PhysicsRadialExplosionEventOptions:sB,PhysicsUpdraftEventOptions:Rte,PhysicsVortexEventOptions:Pte,get PhysicsRadialImpulseFalloff(){return tG},get PhysicsUpdraftMode(){return qB},PhysicsRaycastResult:MW,AnaglyphPostProcess:uee,BlackAndWhitePostProcess:PW,BloomEffect:rJ,BloomMergePostProcess:bQ,BlurPostProcess:Rh,ChromaticAberrationPostProcess:c7,CircleOfConfusionPostProcess:pD,ColorCorrectionPostProcess:DW,ConvolutionPostProcess:h7,DepthOfFieldBlurPostProcess:iG,get DepthOfFieldEffectBlurLevel(){return DP},DepthOfFieldEffect:nJ,DepthOfFieldMergePostProcess:yde,DisplayPassPostProcess:EQ,ExtractHighlightsPostProcess:xQ,FilterPostProcess:OW,FxaaPostProcess:mD,GrainPostProcess:_D,HighlightsPostProcess:Jxe,ImageProcessingPostProcess:lW,MotionBlurPostProcess:eR,PassPostProcess:l7,PassCubePostProcess:hee,PostProcess:rs,PostProcessManager:wj,RefractionPostProcess:tR,DefaultRenderingPipeline:xd,LensRenderingPipeline:Abe,SSAO2RenderingPipeline:Dh,SSAORenderingPipeline:wF,StandardRenderingPipeline:On,SSRRenderingPipeline:$a,PostProcessRenderEffect:An,PostProcessRenderPipeline:iR,PostProcessRenderPipelineManager:Sde,PostProcessRenderPipelineManagerSceneComponent:Ide,SharpenPostProcess:gD,StereoscopicInterlacePostProcessI:ace,StereoscopicInterlacePostProcess:a4e,get TonemappingOperator(){return xP},TonemapPostProcess:Ybe,VolumetricLightScatteringPostProcess:S_,VRDistortionCorrectionPostProcess:Dq,VRMultiviewToSingleviewPostProcess:dee,ScreenSpaceReflectionPostProcess:pv,ScreenSpaceCurvaturePostProcess:NF,ReflectionProbe:hD,BoundingBoxRenderer:Lde,DepthRenderer:qL,DepthRendererSceneComponent:Rde,DepthPeelingRenderer:HM,DepthPeelingSceneComponent:Pde,EdgesRenderer:wW,LineEdgesRenderer:Dde,GeometryBufferRenderer:dl,GeometryBufferRendererSceneComponent:Tde,PrePassRenderer:F2,PrePassRendererSceneComponent:Ode,SubSurfaceSceneComponent:wde,OutlineRenderer:JB,RenderingGroup:H5,RenderingGroupInfo:ele,RenderingManager:pd,UtilityLayerRenderer:Mn,FluidRendererSceneComponent:Vde,FluidRenderer:yQ,FluidRenderingObject:Dte,FluidRenderingObjectParticleSystem:Nde,FluidRenderingObjectCustomParticles:Bde,get FluidRenderingDebug(){return o_},FluidRenderingTargetRenderer:aJ,get ScenePerformancePriority(){return Kb},Scene:oi,SceneComponentConstants:ai,Stage:ac,Sprite:MQ,SpriteManager:jM,SpriteMap:fEe,SpritePackedManager:pEe,SpriteSceneComponent:zde,AlphaState:Hoe,DepthCullingState:w$,StencilState:kM,StencilStateComposer:F$,AndOrNotEvaluator:fL,get AssetTaskState(){return NM},AbstractAssetTask:u7,AssetsProgressEvent:Ude,ContainerAssetTask:kde,MeshAssetTask:Hde,AnimationAssetTask:mEe,TextFileAssetTask:jde,BinaryFileAssetTask:Gde,ImageAssetTask:Wde,TextureAssetTask:Yde,CubeTextureAssetTask:Xde,HDRCubeTextureAssetTask:Kde,EquiRectangularCubeTextureAssetTask:Qde,AssetsManager:_Ee,BasisTranscodeConfiguration:eAe,BasisToolsOptions:SI,GetInternalFormatFromBasisFormat:The,TranscodeAsync:EX,LoadTextureFromTranscodeResult:yX,BasisTools:hQ,DDSTools:la,expandToProperty:_t,serialize:X,serializeAsTexture:xs,serializeAsColor3:Br,serializeAsFresnelParameters:AF,serializeAsVector2:FG,serializeAsVector3:bo,serializeAsMeshReference:xF,serializeAsColorCurves:Zoe,serializeAsColor4:bF,serializeAsImageProcessingConfiguration:U$,serializeAsQuaternion:qoe,serializeAsMatrix:vK,serializeAsCameraReference:Joe,SerializationHelper:Kt,nativeOverride:AI,Deferred:BN,GetEnvInfo:ZK,normalizeEnvInfo:AW,CreateEnvTextureAsync:Fce,CreateImageDataArrayBufferViews:qK,UploadEnvLevelsAsync:wee,UploadLevelsAsync:Uj,UploadEnvSpherical:JK,_UpdateRGBDAsync:Vce,EnvironmentTextureTools:Rge,MeshExploder:gEe,FilesInput:Ote,CubeMapToSphericalPolynomialTools:oD,HDRTools:AX,PanoramaToCubeMapTools:NI,KhronosTextureContainer:Zf,EventState:D$,Observer:Foe,Observable:Se,MultiObserver:wte,PerformanceMonitor:sle,RollingAverage:rle,SceneOptimization:hT,TextureOptimization:HY,HardwareScalingOptimization:oJ,ShadowsOptimization:jY,PostProcessesOptimization:GY,LensFlaresOptimization:WY,CustomOptimization:Zde,ParticlesOptimization:YY,RenderTargetsOptimization:lJ,MergeMeshesOptimization:mI,SceneOptimizerOptions:OP,SceneOptimizer:Nte,SceneSerializer:nI,SmartArray:Sc,SmartArrayNoDuplicate:z9,StringDictionary:aX,Tags:Nr,CreateResizedCopy:Bce,ApplyPostProcess:QK,ToHalfFloat:Vb,FromHalfFloat:Pb,TextureTools:BY,GetTGAHeader:SW,UploadContent:Hee,TGATools:Ehe,Tools:Be,className:t3e,AsyncLoop:$6,VideoRecorder:sG,get JoystickAxis(){return eu},VirtualJoystick:Cs,WorkerPool:rhe,AutoReleaseWorkerPool:PF,Logger:Me,RegisterClass:$e,GetClass:Bo,FilesInputStore:MP,DeepCopier:e2,PivotTools:yn,PrecisionDate:Zr,CreateScreenshot:BW,CreateScreenshotAsync:Fte,CreateScreenshotWithResizeAsync:Jde,CreateScreenshotUsingRenderTarget:FW,CreateScreenshotUsingRenderTargetAsync:Vte,ScreenshotTools:CEe,WebRequest:wl,get InspectableType(){return hJ},GetEnvironmentBRDFTexture:yW,BRDFTextureTools:Fve,RGBDTextureTools:_X,ColorGradient:yte,Color3Gradient:Cde,FactorGradient:Mte,GradientHelper:W3,PerfCounter:Tc,RetryStrategy:Voe,LoadFileError:NB,RequestFileError:Oj,ReadFileError:mK,FileToolsOptions:Kd,SetCorsBehavior:_K,LoadImage:vF,ReadFile:BB,LoadFile:CI,RequestFile:gK,IsFileURL:V$,IsBase64DataUrl:BG,TestBase64DataUrl:Yoe,DecodeBase64UrlToBinary:CF,DecodeBase64UrlToString:z$,get FileTools(){return SN},_injectLTSFileTools:Xoe,EndsWith:zoe,StartsWith:Uoe,Decode:O$,EncodeArrayBufferToBase64:wG,DecodeBase64ToString:pK,DecodeBase64ToBinary:NG,PadNumber:koe,StringTools:z0e,DataReader:hj,MinMaxReducer:vhe,DepthReducer:Che,DataStorage:uJ,SceneRecorder:xEe,DefaultKTX2DecoderOptions:nhe,KhronosTextureContainer2:Ou,Trajectory:oa,TrajectoryClassifier:IX,get TimerState(){return vL},setAndStartTimer:qq,AdvancedTimer:uhe,GenerateBase64StringFromPixelData:EK,GenerateBase64StringFromTexture:K$,GenerateBase64StringFromTextureAsync:Q$,CopyTools:w3e,Reflector:nG,IsWindowObjectExist:ql,IsNavigatorAvailable:pP,IsDocumentAvailable:Zb,GetDOMTextContent:OG,DomManagement:B0e,PressureObserverWrapper:TQ,PerformanceViewerCollector:k5,PerfCollectionStrategy:TEe,DynamicFloat32Array:B9,inlineScheduler:Fj,createYieldingScheduler:Mle,runCoroutine:Y$,runCoroutineSync:AK,runCoroutineAsync:xK,makeSyncFunction:Tle,makeAsyncFunction:T3e,RandomGUID:WL,GUID:e3e,BaseError:UP,ErrorCodes:XM,RuntimeError:nC,get ConversionMode(){return SX},CopyTextureToTexture:Fde,DumpTools:Nu,GreasedLineTools:LM,captureEquirectangularFromScene:REe,WebXRCamera:HB,WebXREnterExitUIButton:hhe,WebXREnterExitUIOptions:S5e,WebXREnterExitUI:rQ,WebXRExperienceHelper:sQ,WebXRInput:che,WebXRInputSource:lhe,WebXRManagedOutputCanvasOptions:cW,WebXRManagedOutputCanvas:vce,get WebXRState(){return Ih},get WebXRTrackingState(){return gP},WebXRSessionManager:hW,WebXRDefaultExperienceOptions:I5e,WebXRDefaultExperience:nQ,WebXRFeatureName:$r,WebXRFeaturesManager:_l,WebXRAbstractFeature:ku,WebXRHitTestLegacy:_I,WebXRAnchorSystem:rB,WebXRPlaneDetector:nB,WebXRBackgroundRemover:aB,WebXRMotionControllerTeleportation:IP,WebXRControllerPointerSelection:$b,IWebXRControllerPhysicsOptions:OEe,WebXRControllerPhysics:oB,WebXRHitTest:lB,WebXRFeaturePointSystem:cB,get HandPart(){return U9},get WebXRHandJoint(){return ks},WebXRHand:Wle,WebXRHandTracking:ha,WebXRMeshDetector:hB,WebXRImageTracking:uB,get WebXRNearControllerMode(){return gL},WebXRNearInteraction:e7,WebXRDomOverlay:dB,WebXRControllerMovement:gI,WebXRLightEstimation:fB,WebXREyeTracking:pB,WebXRWalkingLocomotion:XY,WebXRCompositionLayerWrapper:e1e,WebXRProjectionLayerWrapper:t1e,WebXRLayers:mB,WebXRDepthSensing:_B,XRSpaceWarpRenderTarget:i1e,WebXRSpaceWarpRenderTargetTextureProvider:s1e,WebXRSpaceWarp:gB,WebXRAbstractMotionController:lD,WebXRControllerComponent:i4,WebXRGenericHandController:r1e,WebXRGenericTriggerMotionController:jB,WebXRMicrosoftMixedRealityController:vI,WebXRMotionControllerManager:ou,WebXROculusTouchMotionController:sC,WebXRHTCViveMotionController:tD,WebXRProfiledMotionController:ohe,NativeXRLayerWrapper:Cce,NativeXRLayerRenderTargetTextureProvider:Ace,NativeXRRenderTarget:xce,NativeXRFrame:n1e,CompatibilityOptions:fn,FlowGraph:ZEe,FlowGraphBlock:sR,FlowGraphSignalConnection:dJ,FlowGraphExecutionBlock:SQ,FlowGraphEventBlock:VW,FlowGraphEventCoordinator:qEe,RichTypeAny:n4,RichTypeString:zW,RichTypeNumber:as,RichTypeBoolean:d7,RichTypeVector2:Y2,RichTypeVector3:fu,RichTypeVector4:X2,RichTypeMatrix:JEe,RichTypeColor3:$Ee,RichTypeColor4:eye,FlowGraphContext:a1e,FlowGraphForLoopBlock:tye,FlowGraphLogBlock:iye,FlowGraphConditionalBlock:sye,FlowGraphPlayAnimationBlock:rye,FlowGraphSetVariableBlock:nye,FlowGraphSetPropertyBlock:aye,FlowGraphTimerBlock:oye,FlowGraphSendCustomEventBlock:lye,FlowGraphStopAnimationBlock:cye,FlowGraphConditionalDataBlock:hye,FlowGraphGetVariableBlock:uye,FlowGraphAddNumberBlock:dye,FlowGraphSubtractNumberBlock:fye,FlowGraphMultiplyNumberBlock:pye,FlowGraphDivideNumberBlock:mye,FlowGraphModNumberBlock:_ye,FlowGraphPowNumberBlock:gye,FlowGraphIsNaNNumberBlock:vye,FlowGraphIsInfinityNumberBlock:Cye,FlowGraphSqrtNumberBlock:Aye,FlowGraphAbsNumberBlock:xye,FlowGraphNegateNumberBlock:bye,FlowGraphFloorNumberBlock:Eye,FlowGraphCeilNumberBlock:yye,FlowGraphRoundNumberBlock:Mye,FlowGraphTruncNumberBlock:Tye,FlowGraphExpNumberBlock:Sye,FlowGraphLog10NumberBlock:Iye,FlowGraphLogNumberBlock:Lye,FlowGraphLnNumberBlock:Rye,FlowGraphSinNumberBlock:Pye,FlowGraphCosNumberBlock:Dye,FlowGraphTanNumberBlock:Oye,FlowGraphASinNumberBlock:wye,FlowGraphACosNumberBlock:Nye,FlowGraphATanNumberBlock:Bye,FlowGraphENumberBlock:Fye,FlowGraphPiNumberBlock:Vye,FlowGraphATan2NumberBlock:zye,FlowGraphRandomNumberBlock:Uye,FlowGraphMinNumberBlock:kye,FlowGraphMaxNumberBlock:Hye,FlowGraphEqualsNumberBlock:jye,FlowGraphGreaterThanNumberBlock:Gye,FlowGraphGreaterThanOrEqualsNumberBlock:Wye,FlowGraphLessThanNumberBlock:Yye,FlowGraphLessThanOrEqualsNumberBlock:Xye,FlowGraphMixNumberBlock:Kye,FlowGraphAddVector3Block:Qye,FlowGraphSubtractVector3Block:Zye,FlowGraphMultiplyVector3Block:qye,FlowGraphDivideVector3Block:Jye,FlowGraphScaleVector3Block:$ye,FlowGraphLengthVector3Block:eMe,FlowGraphNormalizeVector3Block:tMe,FlowGraphDotVector3Block:iMe,FlowGraphCrossVector3Block:sMe,FlowGraphAddVector2Block:rMe,FlowGraphSubtractVector2Block:nMe,FlowGraphMultiplyVector2Block:aMe,FlowGraphDivideVector2Block:oMe,FlowGraphScaleVector2Block:lMe,FlowGraphLengthVector2Block:cMe,FlowGraphNormalizeVector2Block:hMe,FlowGraphAddVector4Block:uMe,FlowGraphSubtractVector4Block:dMe,FlowGraphMultiplyVector4Block:fMe,FlowGraphDivideVector4Block:pMe,FlowGraphScaleVector4Block:mMe,FlowGraphLengthVector4Block:_Me,FlowGraphNormalizeVector4Block:gMe,FlowGraphMeshPickEventBlock:vMe,FlowGraphSceneReadyEventBlock:CMe,FlowGraphReceiveCustomEventBlock:AMe,FlowGraphSceneTickEventBlock:xMe},Symbol.toStringTag,{value:"Module"})),fJ=UG(bMe),EMe="cellPixelShader",yMe=`precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos; +#endif +#include +#include +vec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow) +{diffuseBase=info.diffuse*shadow; +#ifdef CELLBASIC +float level=1.0;if (info.ndl<0.5) +level=0.5;diffuseBase.rgb*vec3(level,level,level); +#else +float ToonThresholds[4];ToonThresholds[0]=0.95;ToonThresholds[1]=0.5;ToonThresholds[2]=0.2;ToonThresholds[3]=0.03;float ToonBrightnessLevels[5];ToonBrightnessLevels[0]=1.0;ToonBrightnessLevels[1]=0.8;ToonBrightnessLevels[2]=0.6;ToonBrightnessLevels[3]=0.35;ToonBrightnessLevels[4]=0.2;if (info.ndl>ToonThresholds[0]) +{diffuseBase.rgb*=ToonBrightnessLevels[0];} +else if (info.ndl>ToonThresholds[1]) +{diffuseBase.rgb*=ToonBrightnessLevels[1];} +else if (info.ndl>ToonThresholds[2]) +{diffuseBase.rgb*=ToonBrightnessLevels[2];} +else if (info.ndl>ToonThresholds[3]) +{diffuseBase.rgb*=ToonBrightnessLevels[3];} +else +{diffuseBase.rgb*=ToonBrightnessLevels[4];} +#endif +return max(diffuseBase,vec3(0.2));} +#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 DIFFUSE +baseColor=texture2D(diffuseSampler,vDiffuseUV); +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +#include +baseColor.rgb*=vDiffuseInfos.y; +#endif +#ifdef VERTEXCOLOR +baseColor.rgb*=vColor.rgb; +#endif +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(1.0,1.0,1.0); +#endif +lightingInfo info;vec3 diffuseBase=vec3(0.,0.,0.);float shadow=1.;float glossiness=0.; +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +#include[0..maxSimultaneousLights] +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`;Ue.ShadersStore[EMe]=yMe;const MMe="cellVertexShader",TMe=`precision highp float;attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos); +#ifdef NORMAL +vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))); +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef DIFFUSE +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] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[MMe]=TMe;class SMe extends ta{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NDOTL=!0,this.CUSTOMUSERLIGHTING=!0,this.CELLBASIC=!0,this.DEPTHPREPASS=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class b_ extends Bl{constructor(e,t){super(e,t),this.diffuseColor=new Ie(1,1,1),this._computeHighLevel=!1,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new SMe);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,r.texturesEnabled&&this._diffuseTexture&&Xt.DiffuseTextureEnabled))if(this._diffuseTexture.isReady())s._needUVs=!0,s.DIFFUSE=!0;else return!1;if(s.CELLBASIC=!this.computeHighLevel,ze.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=ze.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights,this._disableLighting),ze.PrepareDefinesForFrameBoundValues(r,n,this,s,!!i),ze.PrepareDefinesForAttributes(e,s,!0,!0),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const o=new Fl;s.FOG&&o.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(s,o,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&o.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const l=[se.PositionKind];s.NORMAL&&l.push(se.NormalKind),s.UV1&&l.push(se.UVKind),s.UV2&&l.push(se.UV2Kind),s.VERTEXCOLOR&&l.push(se.ColorKind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="cell",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix"],p=["diffuseSampler"],m=new Array;lh(u),ze.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:h,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),this._mustRebind(s,n)&&(this._diffuseTexture&&Xt.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),wc(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&ze.BindLights(s,t,this._activeEffect,r,this._maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return super.hasTexture(e)?!0:this._diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}getClassName(){return"CellMaterial"}clone(e){return Kt.Clone(()=>new b_(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.CellMaterial",e}static Parse(e,t,i){return Kt.Parse(()=>new b_(e.name,t),e,t,i)}}z([xs("diffuseTexture")],b_.prototype,"_diffuseTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],b_.prototype,"diffuseTexture",void 0);z([Br("diffuse")],b_.prototype,"diffuseColor",void 0);z([X("computeHighLevel")],b_.prototype,"_computeHighLevel",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],b_.prototype,"computeHighLevel",void 0);z([X("disableLighting")],b_.prototype,"_disableLighting",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],b_.prototype,"disableLighting",void 0);z([X("maxSimultaneousLights")],b_.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],b_.prototype,"maxSimultaneousLights",void 0);$e("BABYLON.CellMaterial",b_);class IMe{constructor(){}}class c1e{constructor(){}}class tF extends jt{AttachAfterBind(e,t){if(this._newUniformInstances)for(const i in this._newUniformInstances){const s=i.toString().split("-");s[0]=="vec2"?t.setVector2(s[1],this._newUniformInstances[i]):s[0]=="vec3"?t.setVector3(s[1],this._newUniformInstances[i]):s[0]=="vec4"?t.setVector4(s[1],this._newUniformInstances[i]):s[0]=="mat4"?t.setMatrix(s[1],this._newUniformInstances[i]):s[0]=="float"&&t.setFloat(s[1],this._newUniformInstances[i])}if(this._newSamplerInstances)for(const i in this._newSamplerInstances){const s=i.toString().split("-");s[0]=="sampler2D"&&this._newSamplerInstances[i].isReady&&this._newSamplerInstances[i].isReady()&&t.setTexture(s[1],this._newSamplerInstances[i])}}ReviewUniform(e,t){if(e=="uniform"&&this._newUniforms)for(let i=0;i0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",s),this._isCreatedShader)return this._createdShaderName;this._isCreatedShader=!1,tF.ShaderIndexer++;const o="custom_"+tF.ShaderIndexer,l=this._afterBind.bind(this);return this._afterBind=(c,h)=>{if(!!h){this.AttachAfterBind(c,h);try{l(c,h)}catch{}}},Ws.ShadersStore[o+"VertexShader"]=this.VertexShader.replace("#define CUSTOM_VERTEX_BEGIN",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#define CUSTOM_VERTEX_DEFINITIONS",(this._customUniform?this._customUniform.join(` +`):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#define CUSTOM_VERTEX_MAIN_BEGIN",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#define CUSTOM_VERTEX_UPDATE_POSITION",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#define CUSTOM_VERTEX_UPDATE_NORMAL",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:"").replace("#define CUSTOM_VERTEX_MAIN_END",this.CustomParts.Vertex_MainEnd?this.CustomParts.Vertex_MainEnd:""),this.CustomParts.Vertex_After_WorldPosComputed&&(Ws.ShadersStore[o+"VertexShader"]=Ws.ShadersStore[o+"VertexShader"].replace("#define CUSTOM_VERTEX_UPDATE_WORLDPOS",this.CustomParts.Vertex_After_WorldPosComputed)),Ws.ShadersStore[o+"PixelShader"]=this.FragmentShader.replace("#define CUSTOM_FRAGMENT_BEGIN",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#define CUSTOM_FRAGMENT_MAIN_BEGIN",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#define CUSTOM_FRAGMENT_DEFINITIONS",(this._customUniform?this._customUniform.join(` +`):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE",this.CustomParts.Fragment_Custom_Diffuse?this.CustomParts.Fragment_Custom_Diffuse:"").replace("#define CUSTOM_FRAGMENT_UPDATE_ALPHA",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#define CUSTOM_FRAGMENT_BEFORE_LIGHTS",this.CustomParts.Fragment_Before_Lights?this.CustomParts.Fragment_Before_Lights:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:"").replace("#define CUSTOM_FRAGMENT_MAIN_END",this.CustomParts.Fragment_MainEnd?this.CustomParts.Fragment_MainEnd:""),this.CustomParts.Fragment_Before_Fog&&(Ws.ShadersStore[o+"PixelShader"]=Ws.ShadersStore[o+"PixelShader"].replace("#define CUSTOM_FRAGMENT_BEFORE_FOG",this.CustomParts.Fragment_Before_Fog)),this._isCreatedShader=!0,this._createdShaderName=o,o}constructor(e,t){super(e,t),this.CustomParts=new c1e,this.customShaderNameResolve=this.Builder,this.FragmentShader=Ws.ShadersStore.defaultPixelShader,this.VertexShader=Ws.ShadersStore.defaultVertexShader}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(t.indexOf("sampler")!=-1?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Fragment_Custom_Diffuse(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}tF.ShaderIndexer=1;$e("BABYLON.CustomMaterial",tF);class h1e{constructor(){}}class iF extends ji{AttachAfterBind(e,t){if(this._newUniformInstances)for(const i in this._newUniformInstances){const s=i.toString().split("-");s[0]=="vec2"?t.setVector2(s[1],this._newUniformInstances[i]):s[0]=="vec3"?t.setVector3(s[1],this._newUniformInstances[i]):s[0]=="vec4"?t.setVector4(s[1],this._newUniformInstances[i]):s[0]=="mat4"?t.setMatrix(s[1],this._newUniformInstances[i]):s[0]=="float"&&t.setFloat(s[1],this._newUniformInstances[i])}if(this._newSamplerInstances)for(const i in this._newSamplerInstances){const s=i.toString().split("-");s[0]=="sampler2D"&&this._newSamplerInstances[i].isReady&&this._newSamplerInstances[i].isReady()&&t.setTexture(s[1],this._newSamplerInstances[i])}}ReviewUniform(e,t){if(e=="uniform"&&this._newUniforms)for(let i=0;i{if(u==="vertex")return h?h(u,p):p;const m=new uI(p);return m.inlineToken="#define pbr_inline",m.processCode(),h?h(u,m.code):m.code}}if(n&&this._customAttributes&&this._customAttributes.length>0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",s),this._isCreatedShader)return this._createdShaderName;this._isCreatedShader=!1,iF.ShaderIndexer++;const l="custom_"+iF.ShaderIndexer,c=this._afterBind.bind(this);return this._afterBind=(h,u)=>{if(!!u){this.AttachAfterBind(h,u);try{c(h,u)}catch{}}},Ws.ShadersStore[l+"VertexShader"]=this.VertexShader.replace("#define CUSTOM_VERTEX_BEGIN",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#define CUSTOM_VERTEX_DEFINITIONS",(this._customUniform?this._customUniform.join(` +`):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#define CUSTOM_VERTEX_MAIN_BEGIN",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#define CUSTOM_VERTEX_UPDATE_POSITION",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#define CUSTOM_VERTEX_UPDATE_NORMAL",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:"").replace("#define CUSTOM_VERTEX_MAIN_END",this.CustomParts.Vertex_MainEnd?this.CustomParts.Vertex_MainEnd:""),this.CustomParts.Vertex_After_WorldPosComputed&&(Ws.ShadersStore[l+"VertexShader"]=Ws.ShadersStore[l+"VertexShader"].replace("#define CUSTOM_VERTEX_UPDATE_WORLDPOS",this.CustomParts.Vertex_After_WorldPosComputed)),Ws.ShadersStore[l+"PixelShader"]=this.FragmentShader.replace("#define CUSTOM_FRAGMENT_BEGIN",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#define CUSTOM_FRAGMENT_MAIN_BEGIN",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#define CUSTOM_FRAGMENT_DEFINITIONS",(this._customUniform?this._customUniform.join(` +`):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#define CUSTOM_FRAGMENT_UPDATE_ALBEDO",this.CustomParts.Fragment_Custom_Albedo?this.CustomParts.Fragment_Custom_Albedo:"").replace("#define CUSTOM_FRAGMENT_UPDATE_ALPHA",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#define CUSTOM_FRAGMENT_BEFORE_LIGHTS",this.CustomParts.Fragment_Before_Lights?this.CustomParts.Fragment_Before_Lights:"").replace("#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS",this.CustomParts.Fragment_Custom_MetallicRoughness?this.CustomParts.Fragment_Custom_MetallicRoughness:"").replace("#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE",this.CustomParts.Fragment_Custom_MicroSurface?this.CustomParts.Fragment_Custom_MicroSurface:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION",this.CustomParts.Fragment_Before_FinalColorComposition?this.CustomParts.Fragment_Before_FinalColorComposition:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:"").replace("#define CUSTOM_FRAGMENT_MAIN_END",this.CustomParts.Fragment_MainEnd?this.CustomParts.Fragment_MainEnd:""),this.CustomParts.Fragment_Before_Fog&&(Ws.ShadersStore[l+"PixelShader"]=Ws.ShadersStore[l+"PixelShader"].replace("#define CUSTOM_FRAGMENT_BEFORE_FOG",this.CustomParts.Fragment_Before_Fog)),this._isCreatedShader=!0,this._createdShaderName=l,l}constructor(e,t){super(e,t),this.CustomParts=new h1e,this.customShaderNameResolve=this.Builder,this.FragmentShader=Ws.ShadersStore.pbrPixelShader,this.VertexShader=Ws.ShadersStore.pbrVertexShader,this.FragmentShader=this.FragmentShader.replace(/#include/g,Ws.IncludesShadersStore.pbrBlockAlbedoOpacity),this.FragmentShader=this.FragmentShader.replace(/#include/g,Ws.IncludesShadersStore.pbrBlockReflectivity),this.FragmentShader=this.FragmentShader.replace(/#include/g,Ws.IncludesShadersStore.pbrBlockFinalColorComposition)}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(t.indexOf("sampler")!=-1?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_Custom_Albedo(e){return this.CustomParts.Fragment_Custom_Albedo=e.replace("result","surfaceAlbedo"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Custom_MetallicRoughness(e){return this.CustomParts.Fragment_Custom_MetallicRoughness=e,this}Fragment_Custom_MicroSurface(e){return this.CustomParts.Fragment_Custom_MicroSurface=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FinalColorComposition(e){return this.CustomParts.Fragment_Before_FinalColorComposition=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}iF.ShaderIndexer=1;$e("BABYLON.PBRCustomMaterial",iF);const LMe="firePixelShader",RMe=`precision highp float;uniform vec4 vEyePosition;varying vec3 vPositionW; +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos; +#endif +uniform sampler2D distortionSampler;uniform sampler2D opacitySampler; +#ifdef DIFFUSE +varying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3; +#endif +#include +#include +vec4 bx2(vec4 x) +{return vec4(2.0)*x-vec4(1.0);} +#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.);float alpha=1.0; +#ifdef DIFFUSE +const float distortionAmount0 =0.092;const float distortionAmount1 =0.092;const float distortionAmount2 =0.092;vec2 heightAttenuation=vec2(0.3,0.39);vec4 noise0=texture2D(distortionSampler,vDistortionCoords1);vec4 noise1=texture2D(distortionSampler,vDistortionCoords2);vec4 noise2=texture2D(distortionSampler,vDistortionCoords3);vec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;vec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);vec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy); +#ifdef ALPHATEST +if (opacityColor.r<0.1) +discard; +#endif +#include +baseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;baseColor*=opacityColor;baseColor.rgb*=vDiffuseInfos.y; +#endif +#ifdef VERTEXCOLOR +baseColor.rgb*=vColor.rgb; +#endif +vec3 diffuseBase=vec3(1.0,1.0,1.0); +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +vec4 color=vec4(baseColor.rgb,alpha); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`;Ue.ShadersStore[LMe]=RMe;const PMe="fireVertexShader",DMe=`precision highp float;attribute vec3 position; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef DIFFUSE +varying vec2 vDiffuseUV; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include +uniform float time;uniform float speed; +#ifdef DIFFUSE +varying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos); +#ifdef DIFFUSE +vDiffuseUV=uv;vDiffuseUV.y-=0.2; +#endif +#include +#include +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#ifdef DIFFUSE +vec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;vDistortionCoords1.x=uv.x;vDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;vDistortionCoords2.x=uv.x;vDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;vDistortionCoords3.x=uv.x;vDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[PMe]=DMe;class OMe extends ta{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.UV1=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.BonesPerMesh=0,this.NUM_BONE_INFLUENCERS=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class hv extends Bl{constructor(e,t){super(e,t),this.diffuseColor=new Ie(1,1,1),this.speed=1,this._scaledDiffuse=new Ie,this._lastTime=0}needAlphaBlending(){return!1}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new OMe);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,this._diffuseTexture&&Xt.DiffuseTextureEnabled))if(this._diffuseTexture.isReady())s._needUVs=!0,s.DIFFUSE=!0;else return!1;if(s.ALPHATEST=!!this._opacityTexture,s._areMiscDirty&&(s.POINTSIZE=this.pointsCloud||r.forcePointsCloud,s.FOG=r.fogEnabled&&e.applyFog&&r.fogMode!==oi.FOGMODE_NONE&&this.fogEnabled),ze.PrepareDefinesForFrameBoundValues(r,n,this,s,!!i),ze.PrepareDefinesForAttributes(e,s,!1,!0),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const o=new Fl;s.FOG&&o.addFallback(1,"FOG"),s.NUM_BONE_INFLUENCERS>0&&o.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const l=[se.PositionKind];s.UV1&&l.push(se.UVKind),s.VERTEXCOLOR&&l.push(se.ColorKind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="fire",h=["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","time","speed"];lh(h);const u=s.toString();t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:h,uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:u,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),this._mustRebind(s,n)&&(this._diffuseTexture&&Xt.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),wc(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._lastTime+=s.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTexture===e||this._distortionTexture===e||this._opacityTexture===e)}getClassName(){return"FireMaterial"}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),super.dispose(e)}clone(e){return Kt.Clone(()=>new hv(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e}static Parse(e,t,i){const s=new hv(e.name,t);return s.diffuseColor=Ie.FromArray(e.diffuseColor),s.speed=e.speed,s.alpha=e.alpha,s.id=e.id,Nr.AddTagsTo(s,e.tags),s.backFaceCulling=e.backFaceCulling,s.wireframe=e.wireframe,e._diffuseTexture&&(s._diffuseTexture=Te.Parse(e._diffuseTexture,t,i)),e._distortionTexture&&(s._distortionTexture=Te.Parse(e._distortionTexture,t,i)),e._opacityTexture&&(s._opacityTexture=Te.Parse(e._opacityTexture,t,i)),s}}z([xs("diffuseTexture")],hv.prototype,"_diffuseTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],hv.prototype,"diffuseTexture",void 0);z([xs("distortionTexture")],hv.prototype,"_distortionTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],hv.prototype,"distortionTexture",void 0);z([xs("opacityTexture")],hv.prototype,"_opacityTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],hv.prototype,"opacityTexture",void 0);z([Br("diffuse")],hv.prototype,"diffuseColor",void 0);z([X()],hv.prototype,"speed",void 0);$e("BABYLON.FireMaterial",hv);const wMe="furPixelShader",NMe=`precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 furColor;uniform float furLength;varying vec3 vPositionW;varying float vfur_length; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos; +#endif +#ifdef HIGHLEVEL +uniform float furOffset;uniform float furOcclusion;uniform sampler2D furTexture;varying vec2 vFurUV; +#endif +#include +#include +#include +#include +float Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=furColor;vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; +#ifdef DIFFUSE +baseColor*=texture2D(diffuseSampler,vDiffuseUV); +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +#include +baseColor.rgb*=vDiffuseInfos.y; +#endif +#ifdef VERTEXCOLOR +baseColor.rgb*=vColor.rgb; +#endif +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(1.0,1.0,1.0); +#endif +#ifdef HIGHLEVEL +vec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));if (furTextureColor.a<=0.0 || furTextureColor.g[0..maxSimultaneousLights] +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +vec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0); +#ifdef HIGHLEVEL +vec4 color=vec4(finalDiffuse,alpha); +#else +float r=vfur_length/furLength*0.5;vec4 color=vec4(finalDiffuse*(0.5+r),alpha); +#endif +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`;Ue.ShadersStore[wMe]=NMe;const BMe="furVertexShader",FMe=`precision highp float;attribute vec3 position;attribute vec3 normal; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +uniform float furLength;uniform float furAngle; +#ifdef HIGHLEVEL +uniform float furOffset;uniform vec3 furGravity;uniform float furTime;uniform float furSpacing;uniform float furDensity; +#endif +#ifdef HEIGHTMAP +uniform sampler2D heightTexture; +#endif +#ifdef HIGHLEVEL +varying vec2 vFurUV; +#endif +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +varying float vfur_length; +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +float Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);} +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +float r=Rand(position); +#ifdef HEIGHTMAP +#if __VERSION__>100 +vfur_length=furLength*texture(heightTexture,uv).x; +#else +vfur_length=furLength*texture2D(heightTexture,uv).r; +#endif +#else +vfur_length=(furLength*r); +#endif +vec3 tangent1=vec3(normal.y,-normal.x,0);vec3 tangent2=vec3(-normal.z,0,normal.x);r=Rand(tangent1*r);float J=(2.0+4.0*r);r=Rand(tangent2*r);float K=(2.0+2.0*r);tangent1=tangent1*J+tangent2*K;tangent1=normalize(tangent1);vec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle); +#ifdef HIGHLEVEL +vec3 forceDirection=vec3(0.0,0.0,0.0);forceDirection.x=sin(furTime+position.x*0.05)*0.2;forceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;forceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;vec3 displacement=vec3(0.0,0.0,0.0);displacement=furGravity+forceDirection;float displacementFactor=pow(furOffset,3.0);vec3 aNormal=normal;aNormal.xyz+=displacement*displacementFactor;newPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing); +#endif +#ifdef NORMAL +vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))); +#endif +gl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos); +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef DIFFUSE +if (vDiffuseInfos.x==0.) +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} +else +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} +#ifdef HIGHLEVEL +vFurUV=vDiffuseUV*furDensity; +#endif +#else +#ifdef HIGHLEVEL +vFurUV=uv*furDensity; +#endif +#endif +#include +#include +#include[0..maxSimultaneousLights] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[BMe]=FMe;class VMe extends ta{constructor(){super(),this.DIFFUSE=!1,this.HEIGHTMAP=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.HIGHLEVEL=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class Ol extends Bl{constructor(e,t){super(e,t),this.diffuseColor=new Ie(1,1,1),this.furLength=1,this.furAngle=0,this.furColor=new Ie(.44,.21,.02),this.furOffset=0,this.furSpacing=12,this.furGravity=new O(0,0,0),this.furSpeed=100,this.furDensity=20,this.furOcclusion=0,this._disableLighting=!1,this._maxSimultaneousLights=4,this.highLevelFur=!0,this._furTime=0}get furTime(){return this._furTime}set furTime(e){this._furTime=e}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}updateFur(){for(let e=1;e0&&o.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const l=[se.PositionKind];s.NORMAL&&l.push(se.NormalKind),s.UV1&&l.push(se.UVKind),s.UV2&&l.push(se.UV2Kind),s.VERTEXCOLOR&&l.push(se.ColorKind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="fur",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity","furOcclusion"];lh(u);const p=["diffuseSampler","heightTexture","furTexture"],m=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:h,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),s.getCachedMaterial()!==this&&(this._diffuseTexture&&Xt.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),wc(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&ze.BindLights(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._activeEffect.setFloat("furOcclusion",this.furOcclusion),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this.diffuseTexture===e||this._heightTexture===e)}dispose(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(let t=1;tnew Ol(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FurMaterial",this._meshes&&(e.sourceMeshName=this._meshes[0].name,e.quality=this._meshes.length),e}getClassName(){return"FurMaterial"}static Parse(e,t,i){const s=Kt.Parse(()=>new Ol(e.name,t),e,t,i);return e.sourceMeshName&&s.highLevelFur&&t.executeWhenReady(()=>{const r=t.getMeshByName(e.sourceMeshName);if(r){const n=Ol.GenerateTexture("Fur Texture",t);s.furTexture=n,Ol.FurifyMesh(r,e.quality)}}),s}static GenerateTexture(e,t){const i=new ep("FurTexture "+e,256,t,!0),s=i.getContext();for(let r=0;r<2e4;++r)s.fillStyle="rgba(255, "+Math.floor(Math.random()*255)+", "+Math.floor(Math.random()*255)+", 1)",s.fillRect(Math.random()*i.getSize().width,Math.random()*i.getSize().height,2,2);return i.update(!1),i.wrapU=Te.WRAP_ADDRESSMODE,i.wrapV=Te.WRAP_ADDRESSMODE,i}static FurifyMesh(e,t){const i=[e],s=e.material;let r;if(!(s instanceof Ol))throw"The material of the source mesh must be a Fur Material";for(r=1;r +#include<__decl__lightFragment>[0] +#include<__decl__lightFragment>[1] +#include<__decl__lightFragment>[2] +#include<__decl__lightFragment>[3] +#include +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);float h=vPosition.y*scale+offset;float mysmoothness=clamp(smoothness,0.01,max(smoothness,10.));vec4 baseColor=mix(bottomColor,topColor,max(pow(max(h,0.0),mysmoothness),0.0));vec3 diffuseColor=baseColor.rgb;float alpha=baseColor.a; +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +#include +#ifdef VERTEXCOLOR +baseColor.rgb*=vColor.rgb; +#endif +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(1.0,1.0,1.0); +#endif +#ifdef EMISSIVE +vec3 diffuseBase=baseColor.rgb; +#else +vec3 diffuseBase=vec3(0.,0.,0.); +#endif +lightingInfo info;float shadow=1.;float glossiness=0.; +#include[0..maxSimultaneousLights] +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`;Ue.ShadersStore[zMe]=UMe;const kMe="gradientVertexShader",HMe=`precision highp float;attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW;varying vec3 vPosition; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);vPosition=position; +#ifdef NORMAL +vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))); +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#include +#include +#include[0..maxSimultaneousLights] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[kMe]=HMe;class jMe extends ta{constructor(){super(),this.EMISSIVE=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class C0 extends Bl{constructor(e,t){super(e,t),this._maxSimultaneousLights=4,this.topColor=new Ie(1,0,0),this.topColorAlpha=1,this.bottomColor=new Ie(0,0,1),this.bottomColorAlpha=1,this.offset=0,this.scale=1,this.smoothness=1,this._disableLighting=!1}needAlphaBlending(){return this.alpha<1||this.topColorAlpha<1||this.bottomColorAlpha<1}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new jMe);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ze.PrepareDefinesForFrameBoundValues(r,n,this,s,!!i),ze.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=ze.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights,this._disableLighting),s.EMISSIVE=this._disableLighting,ze.PrepareDefinesForAttributes(e,s,!1,!0),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const o=new Fl;s.FOG&&o.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(s,o),s.NUM_BONE_INFLUENCERS>0&&o.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const l=[se.PositionKind];s.NORMAL&&l.push(se.NormalKind),s.UV1&&l.push(se.UVKind),s.UV2&&l.push(se.UV2Kind),s.VERTEXCOLOR&&l.push(se.ColorKind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="gradient",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","topColor","bottomColor","offset","smoothness","scale"];lh(u);const p=[],m=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:h,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,n),this._mustRebind(s,n)&&(wc(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),s.lightsEnabled&&!this.disableLighting&&ze.BindLights(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("scale",this.scale),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return Kt.Clone(()=>new C0(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GradientMaterial",e}getClassName(){return"GradientMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new C0(e.name,t),e,t,i)}}z([X("maxSimultaneousLights")],C0.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],C0.prototype,"maxSimultaneousLights",void 0);z([Br()],C0.prototype,"topColor",void 0);z([X()],C0.prototype,"topColorAlpha",void 0);z([Br()],C0.prototype,"bottomColor",void 0);z([X()],C0.prototype,"bottomColorAlpha",void 0);z([X()],C0.prototype,"offset",void 0);z([X()],C0.prototype,"scale",void 0);z([X()],C0.prototype,"smoothness",void 0);z([X("disableLighting")],C0.prototype,"_disableLighting",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],C0.prototype,"disableLighting",void 0);$e("BABYLON.GradientMaterial",C0);const GMe="gridPixelShader",WMe=`#extension GL_OES_standard_derivatives : enable +#define SQRT2 1.41421356 +#define PI 3.14159 +precision highp float;uniform float visibility;uniform vec3 mainColor;uniform vec3 lineColor;uniform vec4 gridControl;uniform vec3 gridOffset;varying vec3 vPosition;varying vec3 vNormal; +#include +#ifdef OPACITY +varying vec2 vOpacityUV;uniform sampler2D opacitySampler;uniform vec2 vOpacityInfos; +#endif +float getDynamicVisibility(float position) {float majorGridFrequency=gridControl.y;if (floor(position+0.5)==floor(position/majorGridFrequency+0.5)*majorGridFrequency) +{return 1.0;} +return gridControl.z;} +float getAnisotropicAttenuation(float differentialLength) {const float maxNumberOfLines=10.0;return clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);} +float isPointOnLine(float position,float differentialLength) {float fractionPartOfPosition=position-floor(position+0.5); +fractionPartOfPosition/=differentialLength; +fractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);float result=0.5+0.5*cos(fractionPartOfPosition*PI); +return result; } +float contributionOnAxis(float position) {float differentialLength=length(vec2(dFdx(position),dFdy(position)));differentialLength*=SQRT2; +float result=isPointOnLine(position,differentialLength);float dynamicVisibility=getDynamicVisibility(position);result*=dynamicVisibility;float anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);result*=anisotropicAttenuation;return result;} +float normalImpactOnAxis(float x) {float normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);return normalImpact;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +float gridRatio=gridControl.x;vec3 gridPos=(vPosition+gridOffset.xyz)/gridRatio;float x=contributionOnAxis(gridPos.x);float y=contributionOnAxis(gridPos.y);float z=contributionOnAxis(gridPos.z);vec3 normal=normalize(vNormal);x*=normalImpactOnAxis(normal.x);y*=normalImpactOnAxis(normal.y);z*=normalImpactOnAxis(normal.z); +#ifdef MAX_LINE +float grid=clamp(max(max(x,y),z),0.,1.); +#else +float grid=clamp(x+y+z,0.,1.); +#endif +vec3 color=mix(mainColor,lineColor,grid); +#ifdef FOG +#include +#endif +float opacity=1.0; +#ifdef TRANSPARENT +opacity=clamp(grid,0.08,gridControl.w*grid); +#endif +#ifdef OPACITY +opacity*=texture2D(opacitySampler,vOpacityUV).a; +#endif +gl_FragColor=vec4(color.rgb,opacity*visibility); +#ifdef TRANSPARENT +#ifdef PREMULTIPLYALPHA +gl_FragColor.rgb*=opacity; +#endif +#else +#endif +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`;Ue.ShadersStore[GMe]=WMe;const YMe="gridVertexShader",XMe=`precision highp float;attribute vec3 position;attribute vec3 normal; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#include +uniform mat4 projection;uniform mat4 view;varying vec3 vPosition;varying vec3 vNormal; +#include +#ifdef OPACITY +varying vec2 vOpacityUV;uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +vec4 worldPos=finalWorld*vec4(position,1.0); +#include +vec4 cameraSpacePosition=view*worldPos;gl_Position=projection*cameraSpacePosition; +#ifdef OPACITY +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +if (vOpacityInfos.x==0.) +{vOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));} +else +{vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));} +#endif +vPosition=position;vNormal=normal; +#define CUSTOM_VERTEX_MAIN_END +}`;Ue.ShadersStore[YMe]=XMe;class KMe extends ta{constructor(){super(),this.OPACITY=!1,this.TRANSPARENT=!1,this.FOG=!1,this.PREMULTIPLYALPHA=!1,this.MAX_LINE=!1,this.UV1=!1,this.UV2=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class A0 extends Bl{constructor(e,t){super(e,t),this.mainColor=Ie.Black(),this.lineColor=Ie.Teal(),this.gridRatio=1,this.gridOffset=O.Zero(),this.majorUnitFrequency=10,this.minorUnitVisibility=.33,this.opacity=1,this.preMultiplyAlpha=!1,this.useMaxLine=!1,this._gridControl=new Ui(this.gridRatio,this.majorUnitFrequency,this.minorUnitVisibility,this.opacity)}needAlphaBlending(){return this.opacity<1||this._opacityTexture&&this._opacityTexture.isReady()}needAlphaBlendingForMesh(e){return e.visibility<1||this.needAlphaBlending()}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new KMe);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(s.TRANSPARENT!==this.opacity<1&&(s.TRANSPARENT=!s.TRANSPARENT,s.markAsUnprocessed()),s.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(s.PREMULTIPLYALPHA=!s.PREMULTIPLYALPHA,s.markAsUnprocessed()),s.MAX_LINE!==this.useMaxLine&&(s.MAX_LINE=!s.MAX_LINE,s.markAsUnprocessed()),s._areTexturesDirty&&(s._needUVs=!1,r.texturesEnabled&&this._opacityTexture&&Xt.OpacityTextureEnabled))if(this._opacityTexture.isReady())s._needUVs=!0,s.OPACITY=!0;else return!1;if(ze.PrepareDefinesForMisc(e,r,!1,!1,this.fogEnabled,!1,s),ze.PrepareDefinesForFrameBoundValues(r,r.getEngine(),this,s,!!i),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial(),ze.PrepareDefinesForAttributes(e,s,!1,!1);const n=[se.PositionKind,se.NormalKind];s.UV1&&n.push(se.UVKind),s.UV2&&n.push(se.UV2Kind),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess,ze.PrepareAttributesForInstances(n,s);const o=s.toString();t.setEffect(r.getEngine().createEffect("grid",n,["projection","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view","opacityMatrix","vOpacityInfos","visibility"],["opacitySampler"],o,void 0,this.onCompiled,this.onError),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;!n||(this._activeEffect=n,this._activeEffect.setFloat("visibility",t.visibility),(!r.INSTANCES||r.THIN_INSTANCE)&&this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",s.getViewMatrix()),this._activeEffect.setMatrix("projection",s.getProjectionMatrix()),this._mustRebind(s,n)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl),this._opacityTexture&&Xt.OpacityTextureEnabled&&(this._activeEffect.setTexture("opacitySampler",this._opacityTexture),this._activeEffect.setFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._activeEffect.setMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix()))),ze.BindFogParameters(s,t,this._activeEffect),this._afterBind(t,this._activeEffect))}dispose(e){super.dispose(e)}clone(e){return Kt.Clone(()=>new A0(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new A0(e.name,t),e,t,i)}}z([Br()],A0.prototype,"mainColor",void 0);z([Br()],A0.prototype,"lineColor",void 0);z([X()],A0.prototype,"gridRatio",void 0);z([bo()],A0.prototype,"gridOffset",void 0);z([X()],A0.prototype,"majorUnitFrequency",void 0);z([X()],A0.prototype,"minorUnitVisibility",void 0);z([X()],A0.prototype,"opacity",void 0);z([X()],A0.prototype,"preMultiplyAlpha",void 0);z([X()],A0.prototype,"useMaxLine",void 0);z([xs("opacityTexture")],A0.prototype,"_opacityTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],A0.prototype,"opacityTexture",void 0);$e("BABYLON.GridMaterial",A0);const QMe="lavaPixelShader",ZMe=`precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;uniform float time;uniform float speed;uniform float movingSpeed;uniform vec3 fogColor;uniform sampler2D noiseTexture;uniform float fogDensity;varying float noise; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include<__decl__lightFragment>[0] +#include<__decl__lightFragment>[1] +#include<__decl__lightFragment>[2] +#include<__decl__lightFragment>[3] +#include +#include +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos; +#endif +#include +#include +float random( vec3 scale,float seed ){return fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;} +#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 DIFFUSE +vec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );vec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time *0.02;vec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;T1.x+=noiseTex.x*2.0;T1.y+=noiseTex.y*2.0;T2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;T2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;float p=texture2D( noiseTexture,T1*3.0 ).a;vec4 lavaColor=texture2D( diffuseSampler,T2*4.0);vec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );baseColor=temp;float depth=gl_FragCoord.z*4.0;const float LOG2=1.442695;float fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );fogFactor=1.0-clamp( fogFactor,0.0,1.0 );baseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );diffuseColor=baseColor.rgb; +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +#include +baseColor.rgb*=vDiffuseInfos.y; +#endif +#ifdef VERTEXCOLOR +baseColor.rgb*=vColor.rgb; +#endif +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(1.0,1.0,1.0); +#endif +#ifdef UNLIT +vec3 diffuseBase=vec3(1.,1.,1.); +#else +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.; +#include[0] +#include[1] +#include[2] +#include[3] +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`;Ue.ShadersStore[QMe]=ZMe;const qMe="lavaVertexShader",JMe=`precision highp float;uniform float time;uniform float lowFrequencySpeed;varying float noise;attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +/* NOISE FUNCTIONS */ +vec3 mod289(vec3 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 permute(vec4 x) +{return mod289(((x*34.0)+1.0)*x);} +vec4 taylorInvSqrt(vec4 r) +{return 1.79284291400159-0.85373472095314*r;} +vec3 fade(vec3 t) {return t*t*t*(t*(t*6.0-15.0)+10.0);} +float pnoise(vec3 P,vec3 rep) +{vec3 Pi0=mod(floor(P),rep); +vec3 Pi1=mod(Pi0+vec3(1.0),rep); +Pi0=mod289(Pi0);Pi1=mod289(Pi1);vec3 Pf0=fract(P); +vec3 Pf1=Pf0-vec3(1.0); +vec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);vec4 iy=vec4(Pi0.yy,Pi1.yy);vec4 iz0=Pi0.zzzz;vec4 iz1=Pi1.zzzz;vec4 ixy=permute(permute(ix)+iy);vec4 ixy0=permute(ixy+iz0);vec4 ixy1=permute(ixy+iz1);vec4 gx0=ixy0*(1.0/7.0);vec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;gx0=fract(gx0);vec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);vec4 sz0=step(gz0,vec4(0.0));gx0-=sz0*(step(0.0,gx0)-0.5);gy0-=sz0*(step(0.0,gy0)-0.5);vec4 gx1=ixy1*(1.0/7.0);vec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;gx1=fract(gx1);vec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);vec4 sz1=step(gz1,vec4(0.0));gx1-=sz1*(step(0.0,gx1)-0.5);gy1-=sz1*(step(0.0,gy1)-0.5);vec3 g000=vec3(gx0.x,gy0.x,gz0.x);vec3 g100=vec3(gx0.y,gy0.y,gz0.y);vec3 g010=vec3(gx0.z,gy0.z,gz0.z);vec3 g110=vec3(gx0.w,gy0.w,gz0.w);vec3 g001=vec3(gx1.x,gy1.x,gz1.x);vec3 g101=vec3(gx1.y,gy1.y,gz1.y);vec3 g011=vec3(gx1.z,gy1.z,gz1.z);vec3 g111=vec3(gx1.w,gy1.w,gz1.w);vec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));g000*=norm0.x;g010*=norm0.y;g100*=norm0.z;g110*=norm0.w;vec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));g001*=norm1.x;g011*=norm1.y;g101*=norm1.z;g111*=norm1.w;float n000=dot(g000,Pf0);float n100=dot(g100,vec3(Pf1.x,Pf0.yz));float n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));float n110=dot(g110,vec3(Pf1.xy,Pf0.z));float n001=dot(g001,vec3(Pf0.xy,Pf1.z));float n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));float n011=dot(g011,vec3(Pf0.x,Pf1.yz));float n111=dot(g111,Pf1);vec3 fade_xyz=fade(Pf0);vec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);vec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);float n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);return 2.2*n_xyz;} +/* END FUNCTION */ +float turbulence( vec3 p ) {float w=100.0;float t=-.5;for (float f=1.0 ; f<=10.0 ; f++ ){float power=pow( 2.0,f );t+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );} +return t;} +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +#ifdef NORMAL +noise=10.0* -.10*turbulence( .5*normal+time*1.15 );float b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );float displacement=- 1.5*noise+b;vec3 newPosition=position+normal*displacement;gl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))); +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef DIFFUSE +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] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;Ue.ShadersStore[qMe]=JMe;class $Me extends ta{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.UNLIT=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class s1 extends Bl{constructor(e,t){super(e,t),this.speed=1,this.movingSpeed=1,this.lowFrequencySpeed=1,this.fogDensity=.15,this._lastTime=0,this.diffuseColor=new Ie(1,1,1),this._disableLighting=!1,this._unlit=!1,this._maxSimultaneousLights=4,this._scaledDiffuse=new Ie}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new $Me);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,r.texturesEnabled&&this._diffuseTexture&&Xt.DiffuseTextureEnabled))if(this._diffuseTexture.isReady())s._needUVs=!0,s.DIFFUSE=!0;else return!1;if(ze.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=!0,ze.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights,this._disableLighting),ze.PrepareDefinesForFrameBoundValues(r,n,this,s,!!i),ze.PrepareDefinesForAttributes(e,s,!0,!0),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const o=new Fl;s.FOG&&o.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(s,o),s.NUM_BONE_INFLUENCERS>0&&o.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const l=[se.PositionKind];s.NORMAL&&l.push(se.NormalKind),s.UV1&&l.push(se.UVKind),s.UV2&&l.push(se.UV2Kind),s.VERTEXCOLOR&&l.push(se.ColorKind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="lava",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"];lh(u);const p=["diffuseSampler","noiseTexture"],m=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:h,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;!n||(this._activeEffect=n,r.UNLIT=this._unlit,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),this._mustRebind(s,n)&&(this.diffuseTexture&&Xt.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),wc(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&ze.BindLights(s,t,this._activeEffect,r),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._lastTime+=s.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=Ie.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this.diffuseTexture===e)}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),super.dispose(e)}clone(e){return Kt.Clone(()=>new s1(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.LavaMaterial",e}getClassName(){return"LavaMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new s1(e.name,t),e,t,i)}}z([xs("diffuseTexture")],s1.prototype,"_diffuseTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],s1.prototype,"diffuseTexture",void 0);z([xs()],s1.prototype,"noiseTexture",void 0);z([Br()],s1.prototype,"fogColor",void 0);z([X()],s1.prototype,"speed",void 0);z([X()],s1.prototype,"movingSpeed",void 0);z([X()],s1.prototype,"lowFrequencySpeed",void 0);z([X()],s1.prototype,"fogDensity",void 0);z([Br()],s1.prototype,"diffuseColor",void 0);z([X("disableLighting")],s1.prototype,"_disableLighting",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],s1.prototype,"disableLighting",void 0);z([X("unlit")],s1.prototype,"_unlit",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],s1.prototype,"unlit",void 0);z([X("maxSimultaneousLights")],s1.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],s1.prototype,"maxSimultaneousLights",void 0);$e("BABYLON.LavaMaterial",s1);const eTe="mixPixelShader",tTe=`precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; +#ifdef SPECULARTERM +uniform vec4 vSpecularColor; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#ifdef DIFFUSE +varying vec2 vTextureUV;uniform sampler2D mixMap1Sampler;uniform vec2 vTextureInfos; +#ifdef MIXMAP2 +uniform sampler2D mixMap2Sampler; +#endif +uniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform sampler2D diffuse4Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;uniform vec2 diffuse4Infos; +#ifdef MIXMAP2 +uniform sampler2D diffuse5Sampler;uniform sampler2D diffuse6Sampler;uniform sampler2D diffuse7Sampler;uniform sampler2D diffuse8Sampler;uniform vec2 diffuse5Infos;uniform vec2 diffuse6Infos;uniform vec2 diffuse7Infos;uniform vec2 diffuse8Infos; +#endif +#endif +#include +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 finalMixColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb; +#ifdef MIXMAP2 +vec4 mixColor2=vec4(1.,1.,1.,1.); +#endif +#ifdef SPECULARTERM +float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; +#else +float glossiness=0.; +#endif +float alpha=vDiffuseColor.a; +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(1.0,1.0,1.0); +#endif +#ifdef DIFFUSE +vec4 mixColor=texture2D(mixMap1Sampler,vTextureUV); +#include +mixColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);vec4 diffuse4Color=texture2D(diffuse4Sampler,vTextureUV*diffuse4Infos);diffuse1Color.rgb*=mixColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,mixColor.g);diffuse3Color.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse3Color.rgb,diffuse4Color.rgb,1.0-mixColor.a); +#ifdef MIXMAP2 +mixColor=texture2D(mixMap2Sampler,vTextureUV);mixColor.rgb*=vTextureInfos.y;vec4 diffuse5Color=texture2D(diffuse5Sampler,vTextureUV*diffuse5Infos);vec4 diffuse6Color=texture2D(diffuse6Sampler,vTextureUV*diffuse6Infos);vec4 diffuse7Color=texture2D(diffuse7Sampler,vTextureUV*diffuse7Infos);vec4 diffuse8Color=texture2D(diffuse8Sampler,vTextureUV*diffuse8Infos);diffuse5Color.rgb=mix(finalMixColor.rgb,diffuse5Color.rgb,mixColor.r);diffuse6Color.rgb=mix(diffuse5Color.rgb,diffuse6Color.rgb,mixColor.g);diffuse7Color.rgb=mix(diffuse6Color.rgb,diffuse7Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse7Color.rgb,diffuse8Color.rgb,1.0-mixColor.a); +#endif +#endif +#ifdef VERTEXCOLOR +finalMixColor.rgb*=vColor.rgb; +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.; +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +#include[0..maxSimultaneousLights] +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase*specularColor; +#else +vec3 finalSpecular=vec3(0.0); +#endif +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor*finalMixColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`;Ue.ShadersStore[eTe]=tTe;const iTe="mixVertexShader",sTe=`precision highp float;attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef DIFFUSE +varying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos); +#ifdef NORMAL +vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))); +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef DIFFUSE +if (vTextureInfos.x==0.) +{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));} +else +{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));} +#endif +#include +#include +#include[0..maxSimultaneousLights] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[iTe]=sTe;class rTe extends ta{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.MIXMAP2=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class zo extends Bl{constructor(e,t){super(e,t),this.diffuseColor=new Ie(1,1,1),this.specularColor=new Ie(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new rTe);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(r.texturesEnabled&&(!this._mixTexture1||!this._mixTexture1.isReady()||(s._needUVs=!0,Xt.DiffuseTextureEnabled&&(!this._diffuseTexture1||!this._diffuseTexture1.isReady()||(s.DIFFUSE=!0,!this._diffuseTexture2||!this._diffuseTexture2.isReady())||!this._diffuseTexture3||!this._diffuseTexture3.isReady()||!this._diffuseTexture4||!this._diffuseTexture4.isReady()||this._mixTexture2&&(!this._mixTexture2.isReady()||(s.MIXMAP2=!0,!this._diffuseTexture5||!this._diffuseTexture5.isReady())||!this._diffuseTexture6||!this._diffuseTexture6.isReady()||!this._diffuseTexture7||!this._diffuseTexture7.isReady()||!this._diffuseTexture8||!this._diffuseTexture8.isReady())))))return!1;if(ze.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=ze.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights,this._disableLighting),ze.PrepareDefinesForFrameBoundValues(r,n,this,s,!!i),ze.PrepareDefinesForAttributes(e,s,!0,!0),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const o=new Fl;s.FOG&&o.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(s,o,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&o.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const l=[se.PositionKind];s.NORMAL&&l.push(se.NormalKind),s.UV1&&l.push(se.UVKind),s.UV2&&l.push(se.UV2Kind),s.VERTEXCOLOR&&l.push(se.ColorKind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="mix",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos","diffuse4Infos","diffuse5Infos","diffuse6Infos","diffuse7Infos","diffuse8Infos"],p=["mixMap1Sampler","mixMap2Sampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","diffuse4Sampler","diffuse5Sampler","diffuse6Sampler","diffuse7Sampler","diffuse8Sampler"],m=new Array;lh(u),ze.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:h,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),this._mustRebind(s,n)&&(this._mixTexture1&&(this._activeEffect.setTexture("mixMap1Sampler",this._mixTexture1),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture1.coordinatesIndex,this._mixTexture1.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture1.getTextureMatrix()),Xt.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale)),this._diffuseTexture4&&(this._activeEffect.setTexture("diffuse4Sampler",this._diffuseTexture4),this._activeEffect.setFloat2("diffuse4Infos",this._diffuseTexture4.uScale,this._diffuseTexture4.vScale)))),this._mixTexture2&&(this._activeEffect.setTexture("mixMap2Sampler",this._mixTexture2),Xt.DiffuseTextureEnabled&&(this._diffuseTexture5&&(this._activeEffect.setTexture("diffuse5Sampler",this._diffuseTexture5),this._activeEffect.setFloat2("diffuse5Infos",this._diffuseTexture5.uScale,this._diffuseTexture5.vScale)),this._diffuseTexture6&&(this._activeEffect.setTexture("diffuse6Sampler",this._diffuseTexture6),this._activeEffect.setFloat2("diffuse6Infos",this._diffuseTexture6.uScale,this._diffuseTexture6.vScale)),this._diffuseTexture7&&(this._activeEffect.setTexture("diffuse7Sampler",this._diffuseTexture7),this._activeEffect.setFloat2("diffuse7Infos",this._diffuseTexture7.uScale,this._diffuseTexture7.vScale)),this._diffuseTexture8&&(this._activeEffect.setTexture("diffuse8Sampler",this._diffuseTexture8),this._activeEffect.setFloat2("diffuse8Infos",this._diffuseTexture8.uScale,this._diffuseTexture8.vScale)))),wc(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&ze.BindLights(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this._mixTexture1&&this._mixTexture1.animations&&this._mixTexture1.animations.length>0&&e.push(this._mixTexture1),this._mixTexture2&&this._mixTexture2.animations&&this._mixTexture2.animations.length>0&&e.push(this._mixTexture2),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture1&&e.push(this._mixTexture1),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._diffuseTexture4&&e.push(this._diffuseTexture4),this._mixTexture2&&e.push(this._mixTexture2),this._diffuseTexture5&&e.push(this._diffuseTexture5),this._diffuseTexture6&&e.push(this._diffuseTexture6),this._diffuseTexture7&&e.push(this._diffuseTexture7),this._diffuseTexture8&&e.push(this._diffuseTexture8),e}hasTexture(e){return!!(super.hasTexture(e)||this._mixTexture1===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._diffuseTexture4===e||this._mixTexture2===e||this._diffuseTexture5===e||this._diffuseTexture6===e||this._diffuseTexture7===e||this._diffuseTexture8===e)}dispose(e){this._mixTexture1&&this._mixTexture1.dispose(),super.dispose(e)}clone(e){return Kt.Clone(()=>new zo(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MixMaterial",e}getClassName(){return"MixMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new zo(e.name,t),e,t,i)}}z([xs("mixTexture1")],zo.prototype,"_mixTexture1",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],zo.prototype,"mixTexture1",void 0);z([xs("mixTexture2")],zo.prototype,"_mixTexture2",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],zo.prototype,"mixTexture2",void 0);z([xs("diffuseTexture1")],zo.prototype,"_diffuseTexture1",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],zo.prototype,"diffuseTexture1",void 0);z([xs("diffuseTexture2")],zo.prototype,"_diffuseTexture2",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],zo.prototype,"diffuseTexture2",void 0);z([xs("diffuseTexture3")],zo.prototype,"_diffuseTexture3",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],zo.prototype,"diffuseTexture3",void 0);z([xs("diffuseTexture4")],zo.prototype,"_diffuseTexture4",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],zo.prototype,"diffuseTexture4",void 0);z([xs("diffuseTexture1")],zo.prototype,"_diffuseTexture5",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],zo.prototype,"diffuseTexture5",void 0);z([xs("diffuseTexture2")],zo.prototype,"_diffuseTexture6",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],zo.prototype,"diffuseTexture6",void 0);z([xs("diffuseTexture3")],zo.prototype,"_diffuseTexture7",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],zo.prototype,"diffuseTexture7",void 0);z([xs("diffuseTexture4")],zo.prototype,"_diffuseTexture8",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],zo.prototype,"diffuseTexture8",void 0);z([Br()],zo.prototype,"diffuseColor",void 0);z([Br()],zo.prototype,"specularColor",void 0);z([X()],zo.prototype,"specularPower",void 0);z([X("disableLighting")],zo.prototype,"_disableLighting",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],zo.prototype,"disableLighting",void 0);z([X("maxSimultaneousLights")],zo.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],zo.prototype,"maxSimultaneousLights",void 0);$e("BABYLON.MixMaterial",zo);const nTe="normalPixelShader",aTe=`precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef LIGHTING +#include +#include<__decl__lightFragment>[0] +#include<__decl__lightFragment>[1] +#include<__decl__lightFragment>[2] +#include<__decl__lightFragment>[3] +#include +#include +#endif +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos; +#endif +#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 DIFFUSE +baseColor=texture2D(diffuseSampler,vDiffuseUV); +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +#include +baseColor.rgb*=vDiffuseInfos.y; +#endif +#ifdef NORMAL +baseColor=mix(baseColor,vec4(vNormalW,1.0),0.5); +#endif +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(1.0,1.0,1.0); +#endif +#ifdef LIGHTING +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.; +#include[0] +#include[1] +#include[2] +#include[3] +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb; +#else +vec3 finalDiffuse= baseColor.rgb; +#endif +vec4 color=vec4(finalDiffuse,alpha); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`;Ue.ShadersStore[nTe]=aTe;const oTe="normalVertexShader",lTe=`precision highp float;attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos); +#ifdef NORMAL +vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))); +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef DIFFUSE +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] +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[oTe]=lTe;class cTe extends ta{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.LIGHTING=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class cC extends Bl{constructor(e,t){super(e,t),this.diffuseColor=new Ie(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaBlendingForMesh(e){return this.needAlphaBlending()||e.visibility<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new cTe);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,r.texturesEnabled&&this._diffuseTexture&&Xt.DiffuseTextureEnabled))if(this._diffuseTexture.isReady())s._needUVs=!0,s.DIFFUSE=!0;else return!1;if(ze.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=!0,ze.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights,this._disableLighting),ze.PrepareDefinesForFrameBoundValues(r,n,this,s,!!i),s.LIGHTING=!this._disableLighting,ze.PrepareDefinesForAttributes(e,s,!0,!0),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const o=new Fl;s.FOG&&o.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(s,o),s.NUM_BONE_INFLUENCERS>0&&o.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const l=[se.PositionKind];s.NORMAL&&l.push(se.NormalKind),s.UV1&&l.push(se.UVKind),s.UV2&&l.push(se.UV2Kind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="normal",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix"],p=["diffuseSampler"],m=new Array;lh(u),ze.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:h,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),this._mustRebind(s,n)&&(this.diffuseTexture&&Xt.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),wc(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&ze.BindLights(s,t,this._activeEffect,r),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this.diffuseTexture===e)}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),super.dispose(e)}clone(e){return Kt.Clone(()=>new cC(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.NormalMaterial",e}getClassName(){return"NormalMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new cC(e.name,t),e,t,i)}}z([xs("diffuseTexture")],cC.prototype,"_diffuseTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],cC.prototype,"diffuseTexture",void 0);z([Br()],cC.prototype,"diffuseColor",void 0);z([X("disableLighting")],cC.prototype,"_disableLighting",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],cC.prototype,"disableLighting",void 0);z([X("maxSimultaneousLights")],cC.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],cC.prototype,"maxSimultaneousLights",void 0);$e("BABYLON.NormalMaterial",cC);const hTe="shadowOnlyPixelShader",uTe=`precision highp float;uniform vec4 vEyePosition;uniform float alpha;uniform vec3 shadowColor;varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(1.0,1.0,1.0); +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.; +#include[0..1] +vec4 color=vec4(shadowColor,(1.0-clamp(shadow,0.,1.))*alpha); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`;Ue.ShadersStore[hTe]=uTe;const dTe="shadowOnlyVertexShader",fTe=`precision highp float;attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos); +#ifdef NORMAL +vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))); +#endif +#include +#include +#include[0..maxSimultaneousLights] +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[dTe]=fTe;class pTe extends ta{constructor(){super(),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.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class aG extends Bl{constructor(e,t){super(e,t),this._needAlphaBlending=!0,this.shadowColor=Ie.Black()}needAlphaBlending(){return this._needAlphaBlending}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}get activeLight(){return this._activeLight}set activeLight(e){this._activeLight=e}_getFirstShadowLightForMesh(e){for(const t of e.lightSources)if(t.shadowEnabled)return t;return null}isReadyForSubMesh(e,t,i){var s;if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new pTe);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(this._activeLight){for(const c of e.lightSources)if(c.shadowEnabled){if(this._activeLight===c)break;const h=e.lightSources.indexOf(this._activeLight);h!==-1&&(e.lightSources.splice(h,1),e.lightSources.splice(0,0,this._activeLight));break}}ze.PrepareDefinesForFrameBoundValues(n,o,this,r,!!i),ze.PrepareDefinesForMisc(e,n,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=ze.PrepareDefinesForLights(n,e,r,!1,1);const l=(s=this._getFirstShadowLightForMesh(e))===null||s===void 0?void 0:s.getShadowGenerator();if(this._needAlphaBlending=!0,l&&l.getClassName&&l.getClassName()==="CascadedShadowGenerator"){const c=l;this._needAlphaBlending=!c.autoCalcDepthBounds}if(ze.PrepareDefinesForAttributes(e,r,!1,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const c=new Fl;r.FOG&&c.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(r,c,1),r.NUM_BONE_INFLUENCERS>0&&c.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const h=[se.PositionKind];r.NORMAL&&h.push(se.NormalKind),ze.PrepareAttributesForBones(h,e,r,c),ze.PrepareAttributesForInstances(h,r);const u="shadowOnly",p=r.toString(),m=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","shadowColor","mBones"],_=new Array,f=new Array;lh(m),ze.PrepareUniformsAndSamplersList({uniformsNames:m,uniformBuffersNames:f,samplers:_,defines:r,maxSimultaneousLights:1}),t.setEffect(n.getEngine().createEffect(u,{attributes:h,uniformsNames:m,uniformBuffersNames:f,samplers:_,defines:p,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},o),r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!!n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),this._mustRebind(s,n)&&(wc(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),this._activeEffect.setColor3("shadowColor",this.shadowColor),s.bindEyePosition(n)),s.lightsEnabled){ze.BindLights(s,t,this._activeEffect,r,1);const o=this._getFirstShadowLightForMesh(t);o&&(o._renderId=-1)}(s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE||r.SHADOWCSM0)&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._afterBind(t,this._activeEffect)}}clone(e){return Kt.Clone(()=>new aG(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.ShadowOnlyMaterial",e}getClassName(){return"ShadowOnlyMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new aG(e.name,t),e,t,i)}}$e("BABYLON.ShadowOnlyMaterial",aG);const mTe="simplePixelShader",_Te=`precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos; +#endif +#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 DIFFUSE +baseColor=texture2D(diffuseSampler,vDiffuseUV); +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +#include +baseColor.rgb*=vDiffuseInfos.y; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor.rgb*=vColor.rgb; +#endif +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(1.0,1.0,1.0); +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.; +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +#include[0..maxSimultaneousLights] +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`;Ue.ShadersStore[mTe]=_Te;const gTe="simpleVertexShader",vTe=`precision highp float;attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef DIFFUSE +varying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos); +#ifdef NORMAL +vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))); +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef DIFFUSE +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] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[gTe]=vTe;class CTe extends ta{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class hC extends Bl{constructor(e,t){super(e,t),this.diffuseColor=new Ie(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new CTe);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,r.texturesEnabled&&this._diffuseTexture&&Xt.DiffuseTextureEnabled))if(this._diffuseTexture.isReady())s._needUVs=!0,s.DIFFUSE=!0;else return!1;if(ze.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=ze.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights,this._disableLighting),ze.PrepareDefinesForFrameBoundValues(r,n,this,s,!!i),ze.PrepareDefinesForAttributes(e,s,!0,!0),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const o=new Fl;s.FOG&&o.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(s,o,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&o.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const l=[se.PositionKind];s.NORMAL&&l.push(se.NormalKind),s.UV1&&l.push(se.UVKind),s.UV2&&l.push(se.UV2Kind),s.VERTEXCOLOR&&l.push(se.ColorKind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="simple",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix"],p=["diffuseSampler"],m=new Array;lh(u),ze.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:h,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),this._mustRebind(s,n)&&(this._diffuseTexture&&Xt.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),wc(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&ze.BindLights(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this.diffuseTexture===e)}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}clone(e){return Kt.Clone(()=>new hC(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SimpleMaterial",e}getClassName(){return"SimpleMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new hC(e.name,t),e,t,i)}}z([xs("diffuseTexture")],hC.prototype,"_diffuseTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],hC.prototype,"diffuseTexture",void 0);z([Br("diffuse")],hC.prototype,"diffuseColor",void 0);z([X("disableLighting")],hC.prototype,"_disableLighting",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],hC.prototype,"disableLighting",void 0);z([X("maxSimultaneousLights")],hC.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],hC.prototype,"maxSimultaneousLights",void 0);$e("BABYLON.SimpleMaterial",hC);const ATe="skyPixelShader",xTe=`precision highp float;varying vec3 vPositionW; +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +uniform vec3 cameraPosition;uniform vec3 cameraOffset;uniform vec3 up;uniform float luminance;uniform float turbidity;uniform float rayleigh;uniform float mieCoefficient;uniform float mieDirectionalG;uniform vec3 sunPosition; +#include +const float e=2.71828182845904523536028747135266249775724709369995957;const float pi=3.141592653589793238462643383279502884197169;const float n=1.0003;const float N=2.545E25;const float pn=0.035;const vec3 lambda=vec3(680E-9,550E-9,450E-9);const vec3 K=vec3(0.686,0.678,0.666);const float v=4.0;const float rayleighZenithLength=8.4E3;const float mieZenithLength=1.25E3;const float EE=1000.0;const float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;const float cutoffAngle=pi/1.95;const float steepness=1.5;vec3 totalRayleigh(vec3 lambda) +{return (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));} +vec3 simplifiedRayleigh() +{return 0.0005/vec3(94,40,18);} +float rayleighPhase(float cosTheta) +{ +return (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));} +vec3 totalMie(vec3 lambda,vec3 K,float T) +{float c=(0.2*T )*10E-18;return 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;} +float hgPhase(float cosTheta,float g) +{return (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));} +float sunIntensity(float zenithAngleCos) +{return EE*max(0.0,1.0-exp((-(cutoffAngle-acos(zenithAngleCos))/steepness)));} +float A=0.15;float B=0.50;float C=0.10;float D=0.20;float EEE=0.02;float F=0.30;float W=1000.0;vec3 Uncharted2Tonemap(vec3 x) +{return ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;} +#if DITHER +#include +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +/** +*-------------------------------------------------------------------------------------------------- +* Sky Color +*-------------------------------------------------------------------------------------------------- +*/ +float sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);float rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));vec3 sunDirection=normalize(sunPosition);float sunE=sunIntensity(dot(sunDirection,up));vec3 betaR=simplifiedRayleigh()*rayleighCoefficient;vec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;float zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition+cameraOffset))));float sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));float sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));vec3 Fex=exp(-(betaR*sR+betaM*sM));float cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);float rPhase=rayleighPhase(cosTheta*0.5+0.5);vec3 betaRTheta=betaR*rPhase;float mPhase=hgPhase(cosTheta,mieDirectionalG);vec3 betaMTheta=betaM*mPhase;vec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));Lin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));vec3 direction=normalize(vPositionW-cameraPosition);float theta=acos(direction.y);float phi=atan(direction.z,direction.x);vec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);vec3 L0=vec3(0.1)*Fex;float sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);L0+=(sunE*19000.0*Fex)*sundisk;vec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));vec3 texColor=(Lin+L0);texColor*=0.04 ;texColor+=vec3(0.0,0.001,0.0025)*0.3;float g_fMaxLuminance=1.0;float fLumScaled=0.1/luminance; +float fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); +float ExposureBias=fLumCompressed;vec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);vec3 retColor=curr*whiteScale;/** +*-------------------------------------------------------------------------------------------------- +* Sky Color +*-------------------------------------------------------------------------------------------------- +*/ +float alpha=1.0; +#ifdef VERTEXCOLOR +retColor.rgb*=vColor.rgb; +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#if DITHER +retColor.rgb+=dither(gl_FragCoord.xy,0.5); +#endif +vec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`;Ue.ShadersStore[ATe]=xTe;const bTe="skyVertexShader",ETe=`precision highp float;attribute vec3 position; +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +uniform mat4 world;uniform mat4 view;uniform mat4 viewProjection; +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef VERTEXCOLOR +varying vec4 vColor; +#endif +#include +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +gl_Position=viewProjection*world*vec4(position,1.0);vec4 worldPos=world*vec4(position,1.0);vPositionW=vec3(worldPos); +#include +#include +#ifdef VERTEXCOLOR +vColor=color; +#endif +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[bTe]=ETe;class yTe extends ta{constructor(){super(),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.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.DITHER=!1,this.rebuild()}}class Q2 extends Bl{constructor(e,t){super(e,t),this.luminance=1,this.turbidity=10,this.rayleigh=2,this.mieCoefficient=.005,this.mieDirectionalG=.8,this.distance=500,this.inclination=.49,this.azimuth=.25,this.sunPosition=new O(0,100,0),this.useSunPosition=!1,this.cameraOffset=O.Zero(),this.up=O.Up(),this.dithering=!1,this._cameraPosition=O.Zero(),this._skyOrientation=new ke}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new yTe);const i=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(ze.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,!1,i),ze.PrepareDefinesForAttributes(e,i,!0,!1),i.IMAGEPROCESSINGPOSTPROCESS!==s.imageProcessingConfiguration.applyByPostProcess&&i.markAsMiscDirty(),i.DITHER!==this.dithering&&i.markAsMiscDirty(),i.isDirty){i.markAsProcessed(),s.resetCachedMaterial();const r=new Fl;i.FOG&&r.addFallback(1,"FOG"),i.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess,i.DITHER=this.dithering;const n=[se.PositionKind];i.VERTEXCOLOR&&n.push(se.ColorKind);const o="sky",l=["world","viewProjection","view","vFogInfos","vFogColor","pointSize","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition","cameraOffset","up"];lh(l);const c=i.toString();t.setEffect(s.getEngine().createEffect(o,n,l,[],c,r,this.onCompiled,this.onError),i,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(i._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._mustRebind(s,n)&&(wc(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize)),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect);const o=s.activeCamera;if(o){const l=o.getWorldMatrix();this._cameraPosition.x=l.m[12],this._cameraPosition.y=l.m[13],this._cameraPosition.z=l.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}if(this._activeEffect.setVector3("cameraOffset",this.cameraOffset),this._activeEffect.setVector3("up",this.up),this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){const l=Math.PI*(this.inclination-.5),c=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(c)*Math.cos(l),this.sunPosition.y=this.distance*Math.sin(-l),this.sunPosition.z=this.distance*Math.sin(c)*Math.cos(l),ke.FromUnitVectorsToRef(O.UpReadOnly,this.up,this._skyOrientation),this.sunPosition.rotateByQuaternionToRef(this._skyOrientation,this.sunPosition)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect)}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return Kt.Clone(()=>new Q2(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SkyMaterial",e}getClassName(){return"SkyMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new Q2(e.name,t),e,t,i)}}z([X()],Q2.prototype,"luminance",void 0);z([X()],Q2.prototype,"turbidity",void 0);z([X()],Q2.prototype,"rayleigh",void 0);z([X()],Q2.prototype,"mieCoefficient",void 0);z([X()],Q2.prototype,"mieDirectionalG",void 0);z([X()],Q2.prototype,"distance",void 0);z([X()],Q2.prototype,"inclination",void 0);z([X()],Q2.prototype,"azimuth",void 0);z([bo()],Q2.prototype,"sunPosition",void 0);z([X()],Q2.prototype,"useSunPosition",void 0);z([bo()],Q2.prototype,"cameraOffset",void 0);z([bo()],Q2.prototype,"up",void 0);z([X()],Q2.prototype,"dithering",void 0);$e("BABYLON.SkyMaterial",Q2);const MTe="terrainPixelShader",TTe=`precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; +#ifdef SPECULARTERM +uniform vec4 vSpecularColor; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#ifdef DIFFUSE +varying vec2 vTextureUV;uniform sampler2D textureSampler;uniform vec2 vTextureInfos;uniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos; +#endif +#ifdef BUMP +uniform sampler2D bump1Sampler;uniform sampler2D bump2Sampler;uniform sampler2D bump3Sampler; +#endif +#include +#include +#include +#include +#ifdef BUMP +#extension GL_OES_standard_derivatives : enable +mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv) +{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;float invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));return mat3(tangent*invmax,binormal*invmax,normal);} +vec3 perturbNormal(vec3 viewDir,vec3 mixColor) +{vec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;vec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;vec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;bump1Color.rgb*=mixColor.r;bump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);vec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);map=map*255./127.-128./127.;mat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);return normalize(TBN*map);} +#endif +#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; +#ifdef SPECULARTERM +float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; +#else +float glossiness=0.; +#endif +float alpha=vDiffuseColor.a; +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(1.0,1.0,1.0); +#endif +#ifdef DIFFUSE +baseColor=texture2D(textureSampler,vTextureUV); +#if defined(BUMP) && defined(DIFFUSE) +normalW=perturbNormal(viewDirectionW,baseColor.rgb); +#endif +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +#include +baseColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);diffuse1Color.rgb*=baseColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);baseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b); +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor.rgb*=vColor.rgb; +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.; +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +#include[0..maxSimultaneousLights] +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase*specularColor; +#else +vec3 finalSpecular=vec3(0.0); +#endif +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`;Ue.ShadersStore[MTe]=TTe;const STe="terrainVertexShader",ITe=`precision highp float;attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef DIFFUSE +varying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos); +#ifdef NORMAL +vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))); +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef DIFFUSE +if (vTextureInfos.x==0.) +{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));} +else +{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));} +#endif +#include +#include +#include[0..maxSimultaneousLights] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[STe]=ITe;class LTe extends ta{constructor(){super(),this.DIFFUSE=!1,this.BUMP=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class Dc extends Bl{constructor(e,t){super(e,t),this.diffuseColor=new Ie(1,1,1),this.specularColor=new Ie(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new LTe);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(r.texturesEnabled){if(!this.mixTexture||!this.mixTexture.isReady())return!1;if(s._needUVs=!0,Xt.DiffuseTextureEnabled){if(!this.diffuseTexture1||!this.diffuseTexture1.isReady()||!this.diffuseTexture2||!this.diffuseTexture2.isReady()||!this.diffuseTexture3||!this.diffuseTexture3.isReady())return!1;s.DIFFUSE=!0}if(this.bumpTexture1&&this.bumpTexture2&&this.bumpTexture3&&Xt.BumpTextureEnabled){if(!this.bumpTexture1.isReady()||!this.bumpTexture2.isReady()||!this.bumpTexture3.isReady())return!1;s._needNormals=!0,s.BUMP=!0}}if(ze.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=ze.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights,this._disableLighting),ze.PrepareDefinesForFrameBoundValues(r,n,this,s,!!i),ze.PrepareDefinesForAttributes(e,s,!0,!0),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const o=new Fl;s.FOG&&o.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(s,o,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&o.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const l=[se.PositionKind];s.NORMAL&&l.push(se.NormalKind),s.UV1&&l.push(se.UVKind),s.UV2&&l.push(se.UV2Kind),s.VERTEXCOLOR&&l.push(se.ColorKind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="terrain",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],p=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler"],m=new Array;lh(u),ze.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:h,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),this._mustRebind(s,n)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),Xt.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),Xt.BumpTextureEnabled&&s.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),wc(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&ze.BindLights(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e}hasTexture(e){return!!(super.hasTexture(e)||this._mixTexture===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._bumpTexture1===e||this._bumpTexture2===e||this._bumpTexture3===e)}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return Kt.Clone(()=>new Dc(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TerrainMaterial",e}getClassName(){return"TerrainMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new Dc(e.name,t),e,t,i)}}z([xs("mixTexture")],Dc.prototype,"_mixTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Dc.prototype,"mixTexture",void 0);z([xs("diffuseTexture1")],Dc.prototype,"_diffuseTexture1",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Dc.prototype,"diffuseTexture1",void 0);z([xs("diffuseTexture2")],Dc.prototype,"_diffuseTexture2",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Dc.prototype,"diffuseTexture2",void 0);z([xs("diffuseTexture3")],Dc.prototype,"_diffuseTexture3",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Dc.prototype,"diffuseTexture3",void 0);z([xs("bumpTexture1")],Dc.prototype,"_bumpTexture1",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Dc.prototype,"bumpTexture1",void 0);z([xs("bumpTexture2")],Dc.prototype,"_bumpTexture2",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Dc.prototype,"bumpTexture2",void 0);z([xs("bumpTexture3")],Dc.prototype,"_bumpTexture3",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Dc.prototype,"bumpTexture3",void 0);z([Br()],Dc.prototype,"diffuseColor",void 0);z([Br()],Dc.prototype,"specularColor",void 0);z([X()],Dc.prototype,"specularPower",void 0);z([X("disableLighting")],Dc.prototype,"_disableLighting",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],Dc.prototype,"disableLighting",void 0);z([X("maxSimultaneousLights")],Dc.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],Dc.prototype,"maxSimultaneousLights",void 0);$e("BABYLON.TerrainMaterial",Dc);const RTe="triplanarPixelShader",PTe=`precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; +#ifdef SPECULARTERM +uniform vec4 vSpecularColor; +#endif +varying vec3 vPositionW; +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#ifdef DIFFUSEX +varying vec2 vTextureUVX;uniform sampler2D diffuseSamplerX; +#ifdef BUMPX +uniform sampler2D normalSamplerX; +#endif +#endif +#ifdef DIFFUSEY +varying vec2 vTextureUVY;uniform sampler2D diffuseSamplerY; +#ifdef BUMPY +uniform sampler2D normalSamplerY; +#endif +#endif +#ifdef DIFFUSEZ +varying vec2 vTextureUVZ;uniform sampler2D diffuseSamplerZ; +#ifdef BUMPZ +uniform sampler2D normalSamplerZ; +#endif +#endif +#ifdef NORMAL +varying mat3 tangentSpace; +#endif +#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(0.,0.,0.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; +#ifdef NORMAL +vec3 normalW=tangentSpace[2]; +#else +vec3 normalW=vec3(1.0,1.0,1.0); +#endif +vec4 baseNormal=vec4(0.0,0.0,0.0,1.0);normalW*=normalW; +#ifdef DIFFUSEX +baseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x; +#ifdef BUMPX +baseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x; +#endif +#endif +#ifdef DIFFUSEY +baseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y; +#ifdef BUMPY +baseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y; +#endif +#endif +#ifdef DIFFUSEZ +baseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z; +#ifdef BUMPZ +baseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z; +#endif +#endif +#ifdef NORMAL +normalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace); +#endif +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +#include +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor.rgb*=vColor.rgb; +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.; +#ifdef SPECULARTERM +float glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb; +#else +float glossiness=0.; +#endif +#include[0..maxSimultaneousLights] +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase*specularColor; +#else +vec3 finalSpecular=vec3(0.0); +#endif +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse+finalSpecular,alpha); +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`;Ue.ShadersStore[RTe]=PTe;const DTe="triplanarVertexShader",OTe=`precision highp float;attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef DIFFUSEX +varying vec2 vTextureUVX; +#endif +#ifdef DIFFUSEY +varying vec2 vTextureUVY; +#endif +#ifdef DIFFUSEZ +varying vec2 vTextureUVZ; +#endif +uniform float tileSize; +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying mat3 tangentSpace; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{ +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos); +#ifdef DIFFUSEX +vTextureUVX=worldPos.zy/tileSize; +#endif +#ifdef DIFFUSEY +vTextureUVY=worldPos.xz/tileSize; +#endif +#ifdef DIFFUSEZ +vTextureUVZ=worldPos.xy/tileSize; +#endif +#ifdef NORMAL +vec3 xtan=vec3(0,0,1);vec3 xbin=vec3(0,1,0);vec3 ytan=vec3(1,0,0);vec3 ybin=vec3(0,0,1);vec3 ztan=vec3(1,0,0);vec3 zbin=vec3(0,1,0);vec3 normalizedNormal=normalize(normal);normalizedNormal*=normalizedNormal;vec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);vec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);mat3 normalWorld=mat3(world); +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +worldTangent=normalize((normalWorld*worldTangent).xyz);worldBinormal=normalize((normalWorld*worldBinormal).xyz);vec3 worldNormal=normalize((normalWorld*normalize(normal)).xyz);tangentSpace[0]=worldTangent;tangentSpace[1]=worldBinormal;tangentSpace[2]=worldNormal; +#endif +#include +#include +#include[0..maxSimultaneousLights] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[DTe]=OTe;class wTe extends ta{constructor(){super(),this.DIFFUSEX=!1,this.DIFFUSEY=!1,this.DIFFUSEZ=!1,this.BUMPX=!1,this.BUMPY=!1,this.BUMPZ=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.NONUNIFORMSCALING=!1,this.rebuild()}}class Oc extends Bl{constructor(e,t){super(e,t),this.tileSize=1,this.diffuseColor=new Ie(1,1,1),this.specularColor=new Ie(.2,.2,.2),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new wTe);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(s._areTexturesDirty&&r.texturesEnabled){if(Xt.DiffuseTextureEnabled){const o=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],l=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"];for(let c=0;c0&&o.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const l=[se.PositionKind];s.NORMAL&&l.push(se.NormalKind),s.VERTEXCOLOR&&l.push(se.ColorKind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="triplanar",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","tileSize"],p=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ"],m=new Array;lh(u),ze.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:h,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),s.getCachedMaterial()!==this&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),wc(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&ze.BindLights(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTextureX===e||this._diffuseTextureY===e||this._diffuseTextureZ===e||this._normalTextureX===e||this._normalTextureY===e||this._normalTextureZ===e)}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return Kt.Clone(()=>new Oc(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TriPlanarMaterial",e}getClassName(){return"TriPlanarMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new Oc(e.name,t),e,t,i)}}z([xs()],Oc.prototype,"mixTexture",void 0);z([xs("diffuseTextureX")],Oc.prototype,"_diffuseTextureX",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Oc.prototype,"diffuseTextureX",void 0);z([xs("diffuseTexturY")],Oc.prototype,"_diffuseTextureY",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Oc.prototype,"diffuseTextureY",void 0);z([xs("diffuseTextureZ")],Oc.prototype,"_diffuseTextureZ",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Oc.prototype,"diffuseTextureZ",void 0);z([xs("normalTextureX")],Oc.prototype,"_normalTextureX",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Oc.prototype,"normalTextureX",void 0);z([xs("normalTextureY")],Oc.prototype,"_normalTextureY",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Oc.prototype,"normalTextureY",void 0);z([xs("normalTextureZ")],Oc.prototype,"_normalTextureZ",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Oc.prototype,"normalTextureZ",void 0);z([X()],Oc.prototype,"tileSize",void 0);z([Br()],Oc.prototype,"diffuseColor",void 0);z([Br()],Oc.prototype,"specularColor",void 0);z([X()],Oc.prototype,"specularPower",void 0);z([X("disableLighting")],Oc.prototype,"_disableLighting",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],Oc.prototype,"disableLighting",void 0);z([X("maxSimultaneousLights")],Oc.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],Oc.prototype,"maxSimultaneousLights",void 0);$e("BABYLON.TriPlanarMaterial",Oc);const NTe="waterPixelShader",BTe=`#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; +#ifdef SPECULARTERM +uniform vec4 vSpecularColor; +#endif +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__lightFragment>[0..maxSimultaneousLights] +#include +#include +#ifdef BUMP +varying vec2 vNormalUV; +#ifdef BUMPSUPERIMPOSE +varying vec2 vNormalUV2; +#endif +uniform sampler2D normalSampler;uniform vec2 vNormalInfos; +#endif +uniform sampler2D refractionSampler;uniform sampler2D reflectionSampler;const float LOG2=1.442695;uniform vec3 cameraPosition;uniform vec4 waterColor;uniform float colorBlendFactor;uniform vec4 waterColor2;uniform float colorBlendFactor2;uniform float bumpHeight;uniform float time;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord; +#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 BUMP +#ifdef BUMPSUPERIMPOSE +baseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y)); +#else +baseColor=texture2D(normalSampler,vNormalUV); +#endif +vec3 bumpColor=baseColor.rgb; +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +baseColor.rgb*=vNormalInfos.y; +#else +vec3 bumpColor=vec3(1.0); +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor.rgb*=vColor.rgb; +#endif +#ifdef NORMAL +vec2 perturbation=bumpHeight*(baseColor.rg-0.5); +#ifdef BUMPAFFECTSREFLECTION +vec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));if (normalW.y<0.0) {normalW.y=-normalW.y;} +#else +vec3 normalW=normalize(vNormalW); +#endif +#else +vec3 normalW=vec3(1.0,1.0,1.0);vec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5); +#endif +#ifdef FRESNELSEPARATE +#ifdef REFLECTION +vec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords); +#ifdef IS_REFRACTION_LINEAR +refractiveColor.rgb=toGammaSpace(refractiveColor.rgb); +#endif +vec2 projectedReflectionTexCoords=clamp(vec2( +vReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3, +vReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y +),0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords); +#ifdef IS_REFLECTION_LINEAR +reflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb); +#endif +vec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=clamp(abs(pow(dot(viewDirectionW,upVector),3.0)),0.05,0.65);float IfresnelTerm=1.0-fresnelTerm;refractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;reflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;baseColor=combinedColor; +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.; +#ifdef SPECULARTERM +float glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb; +#else +float glossiness=0.; +#endif +#include[0..maxSimultaneousLights] +vec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0); +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase*specularColor; +#else +vec3 finalSpecular=vec3(0.0); +#endif +#else +#ifdef REFLECTION +vec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords); +#ifdef IS_REFRACTION_LINEAR +refractiveColor.rgb=toGammaSpace(refractiveColor.rgb); +#endif +vec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords); +#ifdef IS_REFLECTION_LINEAR +reflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb); +#endif +vec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=max(dot(viewDirectionW,upVector),0.0);vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);baseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor; +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.; +#ifdef SPECULARTERM +float glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb; +#else +float glossiness=0.; +#endif +#include[0..maxSimultaneousLights] +vec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0); +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase*specularColor; +#else +vec3 finalSpecular=vec3(0.0); +#endif +#endif +vec4 color=vec4(finalDiffuse+finalSpecular,alpha); +#include +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +color.rgb=toLinearSpace(color.rgb); +#elif defined(IMAGEPROCESSING) +color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); +#endif +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +} +`;Ue.ShadersStore[NTe]=BTe;const FTe="waterVertexShader",VTe=`precision highp float;attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +uniform mat4 view;uniform mat4 viewProjection; +#ifdef BUMP +varying vec2 vNormalUV; +#ifdef BUMPSUPERIMPOSE +varying vec2 vNormalUV2; +#endif +uniform mat4 normalMatrix;uniform vec2 vNormalInfos; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +uniform mat4 reflectionViewProjection;uniform vec2 windDirection;uniform float waveLength;uniform float time;uniform float windForce;uniform float waveHeight;uniform float waveSpeed;uniform float waveCount;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); +#ifdef NORMAL +vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))); +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef BUMP +if (vNormalInfos.x==0.) +{vNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0)); +#ifdef BUMPSUPERIMPOSE +vNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0)); +#endif +} +else +{vNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0)); +#ifdef BUMPSUPERIMPOSE +vNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0)); +#endif +} +#endif +#include +#include +#include[0..maxSimultaneousLights] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +float finalWaveCount=1.0/(waveCount*0.5); +#ifdef USE_WORLD_COORDINATES +vec3 p=worldPos.xyz; +#else +vec3 p=position; +#endif +float newY=(sin(((p.x/finalWaveCount)+time*waveSpeed))*waveHeight*windDirection.x*5.0) ++ (cos(((p.z/finalWaveCount)+ time*waveSpeed))*waveHeight*windDirection.y*5.0);p.y+=abs(newY); +#ifdef USE_WORLD_COORDINATES +gl_Position=viewProjection*vec4(p,1.0); +#else +gl_Position=viewProjection*finalWorld*vec4(p,1.0); +#endif +#ifdef REFLECTION +vRefractionMapTexCoord.x=0.5*(gl_Position.w+gl_Position.x);vRefractionMapTexCoord.y=0.5*(gl_Position.w+gl_Position.y);vRefractionMapTexCoord.z=gl_Position.w;worldPos=reflectionViewProjection*finalWorld*vec4(position,1.0);vReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);vReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);vReflectionMapTexCoord.z=worldPos.w; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +} +`;Ue.ShadersStore[FTe]=VTe;class zTe extends ta{constructor(){super(),this.BUMP=!1,this.REFLECTION=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.SPECULARTERM=!1,this.LOGARITHMICDEPTH=!1,this.USE_REVERSE_DEPTHBUFFER=!1,this.FRESNELSEPARATE=!1,this.BUMPSUPERIMPOSE=!1,this.BUMPAFFECTSREFLECTION=!1,this.USE_WORLD_COORDINATES=!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.rebuild()}}class Za extends Bl{get hasRenderTargetTextures(){return!0}constructor(e,t,i=new lt(512,512)){super(e,t),this.renderTargetSize=i,this.diffuseColor=new Ie(1,1,1),this.specularColor=new Ie(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4,this.windForce=6,this.windDirection=new lt(0,1),this.waveHeight=.4,this.bumpHeight=.4,this._bumpSuperimpose=!1,this._fresnelSeparate=!1,this._bumpAffectsReflection=!1,this.waterColor=new Ie(.1,.1,.6),this.colorBlendFactor=.2,this.waterColor2=new Ie(.1,.1,.6),this.colorBlendFactor2=.2,this.waveLength=.1,this.waveSpeed=1,this.waveCount=20,this.disableClipPlane=!1,this._useWorldCoordinatesForWaveDeformation=!1,this._renderTargets=new Sc(16),this._mesh=null,this._reflectionTransform=ge.Zero(),this._lastTime=0,this._lastDeltaTime=0,this._createRenderTargets(this.getScene(),i),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._renderTargets.push(this._reflectionRTT),this._renderTargets.push(this._refractionRTT),this._renderTargets),this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()}))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()}get refractionTexture(){return this._refractionRTT}get reflectionTexture(){return this._reflectionRTT}addToRenderList(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)}removeFromRenderList(e){if(this._refractionRTT&&this._refractionRTT.renderList){const t=this._refractionRTT.renderList.indexOf(e);t!==-1&&this._refractionRTT.renderList.splice(t,1)}if(this._reflectionRTT&&this._reflectionRTT.renderList){const t=this._reflectionRTT.renderList.indexOf(e);t!==-1&&this._reflectionRTT.renderList.splice(t,1)}}enableRenderTargets(e){const t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)}getRenderList(){return this._refractionRTT?this._refractionRTT.renderList:[]}get renderTargetsEnabled(){return!(this._refractionRTT&&this._refractionRTT.refreshRate===0)}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new zTe);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,r.texturesEnabled)){if(this.bumpTexture&&Xt.BumpTextureEnabled)if(this.bumpTexture.isReady())s._needUVs=!0,s.BUMP=!0;else return!1;Xt.ReflectionTextureEnabled&&(s.REFLECTION=!0)}if(ze.PrepareDefinesForFrameBoundValues(r,n,this,s,!!i),ze.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._areMiscDirty&&(s.FRESNELSEPARATE=this._fresnelSeparate,s.BUMPSUPERIMPOSE=this._bumpSuperimpose,s.BUMPAFFECTSREFLECTION=this._bumpAffectsReflection,s.USE_WORLD_COORDINATES=this._useWorldCoordinatesForWaveDeformation),s._needNormals=ze.PrepareDefinesForLights(r,e,s,!0,this._maxSimultaneousLights,this._disableLighting),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}if(ze.PrepareDefinesForAttributes(e,s,!0,!0),this._mesh=e,this._waitingRenderList){for(let o=0;o0&&o.addCPUSkinningFallback(0,e);const l=[se.PositionKind];s.NORMAL&&l.push(se.NormalKind),s.UV1&&l.push(se.UVKind),s.UV2&&l.push(se.UV2Kind),s.VERTEXCOLOR&&l.push(se.ColorKind),ze.PrepareAttributesForBones(l,e,s,o),ze.PrepareAttributesForInstances(l,s);const c="water",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","normalMatrix","logarithmicDepthConstant","reflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed","waveCount"],p=["normalSampler","refractionSampler","reflectionSampler"],m=new Array;Dr&&(Dr.PrepareUniforms(u,s),Dr.PrepareSamplers(p,s)),lh(u),ze.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(r.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:m,samplers:p,defines:h,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},n),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n||!this._mesh)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),ze.BindBonesParameters(t,this._activeEffect),this._mustRebind(s,n)&&(this.bumpTexture&&Xt.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),wc(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&ze.BindLights(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==oi.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),ze.BindFogParameters(s,t,this._activeEffect),ze.BindLogDepth(r,this._activeEffect,s),Xt.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));const o=this._reflectionTransform.multiply(s.getProjectionMatrix()),l=s.getEngine().getDeltaTime();l!==this._lastDeltaTime&&(this._lastDeltaTime=l,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("reflectionViewProjection",o),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._activeEffect.setFloat("waveCount",this.waveCount),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect)}_createRenderTargets(e,t){this._refractionRTT=new Oa(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=it.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=it.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0,this._reflectionRTT=new Oa(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=it.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=it.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;let i,s=null,r;const n=ge.Zero();this._refractionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){s=e.clipPlane;const o=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Zd.FromPositionAndNormal(new O(0,o+.05,0),new O(0,1,0))}},this._refractionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),this.disableClipPlane||(e.clipPlane=s)},this._reflectionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){s=e.clipPlane;const o=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Zd.FromPositionAndNormal(new O(0,o-.05,0),new O(0,-1,0)),ge.ReflectionToRef(e.clipPlane,n)}r=e.getViewMatrix(),n.multiplyToRef(r,this._reflectionTransform),e.setTransformMatrix(this._reflectionTransform,e.getProjectionMatrix()),e._mirroredCameraPosition=O.TransformCoordinates(e.activeCamera.position,n)},this._reflectionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),e.clipPlane=s,e.setTransformMatrix(r,e.getProjectionMatrix()),e._mirroredCameraPosition=null}}getAnimatables(){const e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e}getActiveTextures(){const e=super.getActiveTextures();return this._bumpTexture&&e.push(this._bumpTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._bumpTexture===e)}dispose(e){this.bumpTexture&&this.bumpTexture.dispose();let t=this.getScene().customRenderTargets.indexOf(this._refractionRTT);t!=-1&&this.getScene().customRenderTargets.splice(t,1),t=-1,t=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),t!=-1&&this.getScene().customRenderTargets.splice(t,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return Kt.Clone(()=>new Za(e,this.getScene()),this)}serialize(){const e=super.serialize();if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(let t=0;tnew Za(e.name,t),e,t,i);return s._waitingRenderList=e.renderList,s}static CreateDefaultMesh(e,t){return aD(e,{width:512,height:512,subdivisions:32,updatable:!1},t)}}z([xs("bumpTexture")],Za.prototype,"_bumpTexture",void 0);z([_t("_markAllSubMeshesAsTexturesDirty")],Za.prototype,"bumpTexture",void 0);z([Br()],Za.prototype,"diffuseColor",void 0);z([Br()],Za.prototype,"specularColor",void 0);z([X()],Za.prototype,"specularPower",void 0);z([X("disableLighting")],Za.prototype,"_disableLighting",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],Za.prototype,"disableLighting",void 0);z([X("maxSimultaneousLights")],Za.prototype,"_maxSimultaneousLights",void 0);z([_t("_markAllSubMeshesAsLightsDirty")],Za.prototype,"maxSimultaneousLights",void 0);z([X()],Za.prototype,"windForce",void 0);z([FG()],Za.prototype,"windDirection",void 0);z([X()],Za.prototype,"waveHeight",void 0);z([X()],Za.prototype,"bumpHeight",void 0);z([X("bumpSuperimpose")],Za.prototype,"_bumpSuperimpose",void 0);z([_t("_markAllSubMeshesAsMiscDirty")],Za.prototype,"bumpSuperimpose",void 0);z([X("fresnelSeparate")],Za.prototype,"_fresnelSeparate",void 0);z([_t("_markAllSubMeshesAsMiscDirty")],Za.prototype,"fresnelSeparate",void 0);z([X("bumpAffectsReflection")],Za.prototype,"_bumpAffectsReflection",void 0);z([_t("_markAllSubMeshesAsMiscDirty")],Za.prototype,"bumpAffectsReflection",void 0);z([Br()],Za.prototype,"waterColor",void 0);z([X()],Za.prototype,"colorBlendFactor",void 0);z([Br()],Za.prototype,"waterColor2",void 0);z([X()],Za.prototype,"colorBlendFactor2",void 0);z([X()],Za.prototype,"waveLength",void 0);z([X()],Za.prototype,"waveSpeed",void 0);z([X()],Za.prototype,"waveCount",void 0);z([X()],Za.prototype,"disableClipPlane",void 0);z([X("useWorldCoordinatesForWaveDeformation")],Za.prototype,"_useWorldCoordinatesForWaveDeformation",void 0);z([_t("_markAllSubMeshesAsMiscDirty")],Za.prototype,"useWorldCoordinatesForWaveDeformation",void 0);z([X()],Za.prototype,"useLogarithmicDepth",null);$e("BABYLON.WaterMaterial",Za);const UTe=Object.freeze(Object.defineProperty({__proto__:null,CellMaterial:b_,CustomShaderStructure:IMe,ShaderSpecialParts:c1e,CustomMaterial:tF,ShaderAlebdoParts:h1e,PBRCustomMaterial:iF,FireMaterial:hv,FurMaterial:Ol,GradientMaterial:C0,GridMaterial:A0,LavaMaterial:s1,MixMaterial:zo,NormalMaterial:cC,ShadowOnlyMaterial:aG,SimpleMaterial:hC,SkyMaterial:Q2,TerrainMaterial:Dc,TriPlanarMaterial:Oc,WaterMaterial:Za},Symbol.toStringTag,{value:"Module"})),kTe=UG(UTe);class mr{constructor(e,t=mr.UNITMODE_PIXEL,i=!0){this.negativeValueAllowed=i,this._value=1,this._unit=mr.UNITMODE_PIXEL,this.ignoreAdaptiveScaling=!1,this.onChangedObservable=new Se,this._value=e,this._unit=t,this._originalUnit=t}get isPercentage(){return this._unit===mr.UNITMODE_PERCENTAGE}get isPixel(){return this._unit===mr.UNITMODE_PIXEL}get internalValue(){return this._value}get value(){return this._value}set value(e){e!==this._value&&(this._value=e,this.onChangedObservable.notifyObservers())}get unit(){return this._unit}set unit(e){e!==this._unit&&(this._unit=e,this.onChangedObservable.notifyObservers())}getValueInPixel(e,t){return this.isPixel?this.getValue(e):this.getValue(e)*t}updateInPlace(e,t=mr.UNITMODE_PIXEL){return(this.value!==e||this.unit!==t)&&(this._value=e,this._unit=t,this.onChangedObservable.notifyObservers()),this}getValue(e){if(e&&!this.ignoreAdaptiveScaling&&this.unit!==mr.UNITMODE_PERCENTAGE){let t=0,i=0;if(e.idealWidth&&(t=Math.ceil(this._value*e.getSize().width/e.idealWidth)),e.idealHeight&&(i=Math.ceil(this._value*e.getSize().height/e.idealHeight)),e.useSmallestIdeal&&e.idealWidth&&e.idealHeight)return window.innerWidth{this._markAsDirty(),this._resetFontCache()})),this._markAsDirty(),this._resetFontCache()}get _isFontSizeInPercentage(){return this._fontSize.isPercentage}get fontSizeInPixels(){const e=this._style?this._style._fontSize:this._fontSize;return e.isPixel?e.getValue(this._host):e.getValueInPixel(this._host,this._tempParentMeasure.height||this._cachedParentMeasure.height)}set fontSizeInPixels(e){isNaN(e)||(this.fontSize=e+"px")}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&(this._markAsDirty(),this._resetFontCache())}get color(){return this._color}set color(e){this._color!==e&&(this._color=e,this._markAsDirty())}get gradient(){return this._gradient}set gradient(e){this._gradient!==e&&(this._gradient=e,this._markAsDirty())}get zIndex(){return this._zIndex}set zIndex(e){this.zIndex!==e&&(this._zIndex=e,this.parent&&this.parent._reOrderControl(this))}get notRenderable(){return this._doNotRender}set notRenderable(e){this._doNotRender!==e&&(this._doNotRender=e,this._markAsDirty())}get isVisible(){return this._isVisible}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this._markAsDirty(!0),this.onIsVisibleChangedObservable.notifyObservers(e))}get isDirty(){return this._isDirty}get linkedMesh(){return this._linkedMesh}get descendantsOnlyPadding(){return this._descendantsOnlyPadding}set descendantsOnlyPadding(e){this._descendantsOnlyPadding!==e&&(this._descendantsOnlyPadding=e,this._markAsDirty())}get paddingLeft(){return this._paddingLeft.toString(this._host)}set paddingLeft(e){this._paddingLeft.fromString(e)&&this._markAsDirty()}get paddingLeftInPixels(){return this._paddingLeft.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingLeftInPixels(e){isNaN(e)||(this.paddingLeft=e+"px")}get _paddingLeftInPixels(){return this._descendantsOnlyPadding?0:this.paddingLeftInPixels}get paddingRight(){return this._paddingRight.toString(this._host)}set paddingRight(e){this._paddingRight.fromString(e)&&this._markAsDirty()}get paddingRightInPixels(){return this._paddingRight.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingRightInPixels(e){isNaN(e)||(this.paddingRight=e+"px")}get _paddingRightInPixels(){return this._descendantsOnlyPadding?0:this.paddingRightInPixels}get paddingTop(){return this._paddingTop.toString(this._host)}set paddingTop(e){this._paddingTop.fromString(e)&&this._markAsDirty()}get paddingTopInPixels(){return this._paddingTop.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingTopInPixels(e){isNaN(e)||(this.paddingTop=e+"px")}get _paddingTopInPixels(){return this._descendantsOnlyPadding?0:this.paddingTopInPixels}get paddingBottom(){return this._paddingBottom.toString(this._host)}set paddingBottom(e){this._paddingBottom.fromString(e)&&this._markAsDirty()}get paddingBottomInPixels(){return this._paddingBottom.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingBottomInPixels(e){isNaN(e)||(this.paddingBottom=e+"px")}get _paddingBottomInPixels(){return this._descendantsOnlyPadding?0:this.paddingBottomInPixels}get left(){return this._left.toString(this._host)}set left(e){this._left.fromString(e)&&this._markAsDirty()}get leftInPixels(){return this._left.getValueInPixel(this._host,this._cachedParentMeasure.width)}set leftInPixels(e){isNaN(e)||(this.left=e+"px")}get top(){return this._top.toString(this._host)}set top(e){this._top.fromString(e)&&this._markAsDirty()}get topInPixels(){return this._top.getValueInPixel(this._host,this._cachedParentMeasure.height)}set topInPixels(e){isNaN(e)||(this.top=e+"px")}get linkOffsetX(){return this._linkOffsetX.toString(this._host)}set linkOffsetX(e){this._linkOffsetX.fromString(e)&&this._markAsDirty()}get linkOffsetXInPixels(){return this._linkOffsetX.getValueInPixel(this._host,this._cachedParentMeasure.width)}set linkOffsetXInPixels(e){isNaN(e)||(this.linkOffsetX=e+"px")}get linkOffsetY(){return this._linkOffsetY.toString(this._host)}set linkOffsetY(e){this._linkOffsetY.fromString(e)&&this._markAsDirty()}get linkOffsetYInPixels(){return this._linkOffsetY.getValueInPixel(this._host,this._cachedParentMeasure.height)}set linkOffsetYInPixels(e){isNaN(e)||(this.linkOffsetY=e+"px")}get centerX(){return this._currentMeasure.left+this._currentMeasure.width/2}get centerY(){return this._currentMeasure.top+this._currentMeasure.height/2}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled===e)return;this._isEnabled=e,this._markAsDirty();const t=i=>{if(!!i.host){for(const s in i.host._lastControlOver)i===this.host._lastControlOver[s]&&(i._onPointerOut(i,null,!0),delete i.host._lastControlOver[s]);i.children!==void 0&&i.children.forEach(t)}};t(this)}get disabledColor(){return this._disabledColor}set disabledColor(e){this._disabledColor!==e&&(this._disabledColor=e,this._markAsDirty())}get disabledColorItem(){return this._disabledColorItem}set disabledColorItem(e){this._disabledColorItem!==e&&(this._disabledColorItem=e,this._markAsDirty())}constructor(e){this.name=e,this._alpha=1,this._alphaSet=!1,this._zIndex=0,this._currentMeasure=ru.Empty(),this._tempPaddingMeasure=ru.Empty(),this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new mr(18,mr.UNITMODE_PIXEL,!1),this._width=new mr(1,mr.UNITMODE_PERCENTAGE,!1),this._height=new mr(1,mr.UNITMODE_PERCENTAGE,!1),this._color="",this._style=null,this._horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_CENTER,this._verticalAlignment=zt.VERTICAL_ALIGNMENT_CENTER,this._isDirty=!0,this._wasDirty=!1,this._tempParentMeasure=ru.Empty(),this._prevCurrentMeasureTransformedIntoGlobalSpace=ru.Empty(),this._cachedParentMeasure=ru.Empty(),this._descendantsOnlyPadding=!1,this._paddingLeft=new mr(0),this._paddingRight=new mr(0),this._paddingTop=new mr(0),this._paddingBottom=new mr(0),this._left=new mr(0),this._top=new mr(0),this._scaleX=1,this._scaleY=1,this._rotation=0,this._transformCenterX=.5,this._transformCenterY=.5,this._transformMatrix=Wn.Identity(),this._invertTransformMatrix=Wn.Identity(),this._transformedPosition=lt.Zero(),this._isMatrixDirty=!0,this._isVisible=!0,this._isHighlighted=!1,this._highlightColor="#4affff",this._highlightLineWidth=2,this._fontSet=!1,this._dummyVector2=lt.Zero(),this._downCount=0,this._enterCount=-1,this._doNotRender=!1,this._downPointerIds={},this._evaluatedMeasure=new ru(0,0,0,0),this._evaluatedParentMeasure=new ru(0,0,0,0),this._isEnabled=!0,this._disabledColor="#9a9a9a",this._disabledColorItem="#6a6a6a",this._isReadOnly=!1,this._gradient=null,this._rebuildLayout=!1,this._customData={},this._isClipped=!1,this._automaticSize=!1,this.metadata=null,this.isHitTestVisible=!0,this.isPointerBlocker=!1,this.isFocusInvisible=!1,this._clipChildren=!0,this._clipContent=!0,this.useBitmapCache=!1,this._shadowOffsetX=0,this._shadowOffsetY=0,this._shadowBlur=0,this._previousShadowBlur=0,this._shadowColor="black",this.hoverCursor="",this._linkOffsetX=new mr(0),this._linkOffsetY=new mr(0),this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new Se,this.onWheelObservable=new Se,this.onPointerMoveObservable=new Se,this.onPointerOutObservable=new Se,this.onPointerDownObservable=new Se,this.onPointerUpObservable=new Se,this.onPointerClickObservable=new Se,this.onPointerEnterObservable=new Se,this.onDirtyObservable=new Se,this.onBeforeDrawObservable=new Se,this.onAfterDrawObservable=new Se,this.onDisposeObservable=new Se,this.onIsVisibleChangedObservable=new Se,this._fixedRatio=0,this._fixedRatioMasterIsWidth=!0,this.animations=null,this._tmpMeasureA=new ru(0,0,0,0)}_getTypeName(){return"Control"}getAscendantOfClass(e){return this.parent?this.parent.getClassName()===e?this.parent:this.parent.getAscendantOfClass(e):null}markAsDirty(e=!1){this._markAsDirty(e)}markAllAsDirty(){this._markAllAsDirty()}_resetFontCache(){this._fontSet=!0,this._markAsDirty()}isAscendant(e){return this.parent?this.parent===e?!0:this.parent.isAscendant(e):!1}getLocalCoordinates(e){const t=lt.Zero();return this.getLocalCoordinatesToRef(e,t),t}getLocalCoordinatesToRef(e,t){return t.x=e.x-this._currentMeasure.left,t.y=e.y-this._currentMeasure.top,this}getParentLocalCoordinates(e){const t=lt.Zero();return t.x=e.x-this._cachedParentMeasure.left,t.y=e.y-this._cachedParentMeasure.top,t}moveToVector3(e,t){if(!this._host||this.parent!==this._host._rootContainer){Be.Error("Cannot move a control to a vector3 if the control is not at root level");return}this.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=zt.VERTICAL_ALIGNMENT_TOP;const i=this._host._getGlobalViewport(),s=O.Project(e,ge.IdentityReadOnly,t.getTransformMatrix(),i);if(this._moveToProjectedPosition(s),s.z<0||s.z>1){this.notRenderable=!0;return}this.notRenderable=!1}getDescendantsToRef(e,t=!1,i){}getDescendants(e,t){const i=new Array;return this.getDescendantsToRef(i,e,t),i}linkWithMesh(e){if(!this._host||this.parent&&this.parent!==this._host._rootContainer){e&&Be.Error("Cannot link a control to a mesh if the control is not at root level");return}const t=this._host._linkedControls.indexOf(this);if(t!==-1){this._linkedMesh=e,e||this._host._linkedControls.splice(t,1);return}else if(!e)return;this.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=zt.VERTICAL_ALIGNMENT_TOP,this._linkedMesh=e,this._host._linkedControls.push(this)}setPadding(e,t,i,s){const r=e,n=t??r,o=i??r,l=s??n;this.paddingTop=r,this.paddingRight=n,this.paddingBottom=o,this.paddingLeft=l}setPaddingInPixels(e,t,i,s){const r=e,n=t??r,o=i??r,l=s??n;this.paddingTopInPixels=r,this.paddingRightInPixels=n,this.paddingBottomInPixels=o,this.paddingLeftInPixels=l}_moveToProjectedPosition(e){var t;const i=this._left.getValue(this._host),s=this._top.getValue(this._host),r=(t=this.parent)===null||t===void 0?void 0:t._currentMeasure;r&&this._processMeasures(r,this._host.getContext());let n=e.x+this._linkOffsetX.getValue(this._host)-this._currentMeasure.width/2,o=e.y+this._linkOffsetY.getValue(this._host)-this._currentMeasure.height/2;const l=this._left.ignoreAdaptiveScaling&&this._top.ignoreAdaptiveScaling;l&&(Math.abs(n-i)<.5&&(n=i),Math.abs(o-s)<.5&&(o=s)),!(!l&&i===n&&s===o)&&(this.left=n+"px",this.top=o+"px",this._left.ignoreAdaptiveScaling=!0,this._top.ignoreAdaptiveScaling=!0,this._markAsDirty())}_offsetLeft(e){this._isDirty=!0,this._currentMeasure.left+=e}_offsetTop(e){this._isDirty=!0,this._currentMeasure.top+=e}_markMatrixAsDirty(){this._isMatrixDirty=!0,this._flagDescendantsAsMatrixDirty()}_flagDescendantsAsMatrixDirty(){}_intersectsRect(e,t){return this._transform(t),!(this._evaluatedMeasure.left>=e.left+e.width||this._evaluatedMeasure.top>=e.top+e.height||this._evaluatedMeasure.left+this._evaluatedMeasure.width<=e.left||this._evaluatedMeasure.top+this._evaluatedMeasure.height<=e.top)}_computeAdditionalOffsetX(){return 0}_computeAdditionalOffsetY(){return 0}invalidateRect(){if(this._transform(),this.host&&this.host.useInvalidateRectOptimization){this._currentMeasure.transformToRef(this._transformMatrix,this._tmpMeasureA),ru.CombineToRef(this._tmpMeasureA,this._prevCurrentMeasureTransformedIntoGlobalSpace,this._tmpMeasureA);const e=this.shadowOffsetX,t=this.shadowOffsetY,i=Math.max(this._previousShadowBlur,this.shadowBlur),s=Math.min(Math.min(e,0)-i*2,0),r=Math.max(Math.max(e,0)+i*2,0),n=Math.min(Math.min(t,0)-i*2,0),o=Math.max(Math.max(t,0)+i*2,0),l=this._computeAdditionalOffsetX(),c=this._computeAdditionalOffsetY();this.host.invalidateRect(Math.floor(this._tmpMeasureA.left+s-l),Math.floor(this._tmpMeasureA.top+n-c),Math.ceil(this._tmpMeasureA.left+this._tmpMeasureA.width+r+l),Math.ceil(this._tmpMeasureA.top+this._tmpMeasureA.height+o+c))}}_markAsDirty(e=!1){!this._isVisible&&!e||(this._isDirty=!0,this._markMatrixAsDirty(),this._host&&this._host.markAsDirty())}_markAllAsDirty(){this._markAsDirty(),this._font&&this._prepareFont()}_link(e){this._host=e,this._host&&(this.uniqueId=this._host.getScene().getUniqueId())}_transform(e){if(!this._isMatrixDirty&&this._scaleX===1&&this._scaleY===1&&this._rotation===0)return;const t=this._currentMeasure.width*this._transformCenterX+this._currentMeasure.left,i=this._currentMeasure.height*this._transformCenterY+this._currentMeasure.top;e&&(e.translate(t,i),e.rotate(this._rotation),e.scale(this._scaleX,this._scaleY),e.translate(-t,-i)),(this._isMatrixDirty||this._cachedOffsetX!==t||this._cachedOffsetY!==i)&&(this._cachedOffsetX=t,this._cachedOffsetY=i,this._isMatrixDirty=!1,this._flagDescendantsAsMatrixDirty(),Wn.ComposeToRef(-t,-i,this._rotation,this._scaleX,this._scaleY,this.parent?this.parent._transformMatrix:null,this._transformMatrix),this._transformMatrix.invertToRef(this._invertTransformMatrix),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure))}_renderHighlight(e){!this.isHighlighted||(e.save(),e.strokeStyle=this._highlightColor,e.lineWidth=this._highlightLineWidth,this._renderHighlightSpecific(e),e.restore())}_renderHighlightSpecific(e){e.strokeRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)}_getColor(e){return this.gradient?this.gradient.getCanvasGradient(e):this.color}_applyStates(e){this._isFontSizeInPercentage&&(this._fontSet=!0),this._host&&this._host.useSmallestIdeal&&!this._font&&(this._fontSet=!0),this._fontSet&&(this._prepareFont(),this._fontSet=!1),this._font&&(e.font=this._font),(this._color||this.gradient)&&(e.fillStyle=this._getColor(e)),zt.AllowAlphaInheritance?e.globalAlpha*=this._alpha:this._alphaSet&&(e.globalAlpha=this.parent&&!this.parent.renderToIntermediateTexture?this.parent.alpha*this._alpha:this._alpha)}_layout(e,t){if(!this.isDirty&&(!this.isVisible||this.notRenderable))return!1;if(this._isDirty||!this._cachedParentMeasure.isEqualsTo(e)){this.host._numLayoutCalls++,this._currentMeasure.addAndTransformToRef(this._transformMatrix,-this._paddingLeftInPixels|0,-this._paddingTopInPixels|0,this._paddingRightInPixels|0,this._paddingBottomInPixels|0,this._prevCurrentMeasureTransformedIntoGlobalSpace),t.save(),this._applyStates(t);let i=0;do this._rebuildLayout=!1,this._processMeasures(e,t),i++;while(this._rebuildLayout&&i<3);i>=3&&Me.Error(`Layout cycle detected in GUI (Control name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this.invalidateRect(),this._evaluateClippingState(e)}return this._wasDirty=this._isDirty,this._isDirty=!1,!0}_processMeasures(e,t){this._tempPaddingMeasure.copyFrom(e),this.parent&&this.parent.descendantsOnlyPadding&&(this._tempPaddingMeasure.left+=this.parent.paddingLeftInPixels,this._tempPaddingMeasure.top+=this.parent.paddingTopInPixels,this._tempPaddingMeasure.width-=this.parent.paddingLeftInPixels+this.parent.paddingRightInPixels,this._tempPaddingMeasure.height-=this.parent.paddingTopInPixels+this.parent.paddingBottomInPixels),this._currentMeasure.copyFrom(this._tempPaddingMeasure),this._preMeasure(this._tempPaddingMeasure,t),this._measure(),this._computeAlignment(this._tempPaddingMeasure,t),this._currentMeasure.left=this._currentMeasure.left|0,this._currentMeasure.top=this._currentMeasure.top|0,this._currentMeasure.width=this._currentMeasure.width|0,this._currentMeasure.height=this._currentMeasure.height|0,this._additionalProcessing(this._tempPaddingMeasure,t),this._cachedParentMeasure.copyFrom(this._tempPaddingMeasure),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.onDirtyObservable.hasObservers()&&this.onDirtyObservable.notifyObservers(this)}_evaluateClippingState(e){if(this._transform(),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.parent&&this.parent.clipChildren){if(e.transformToRef(this.parent._transformMatrix,this._evaluatedParentMeasure),this._evaluatedMeasure.left>this._evaluatedParentMeasure.left+this._evaluatedParentMeasure.width){this._isClipped=!0;return}if(this._evaluatedMeasure.left+this._evaluatedMeasure.widththis._evaluatedParentMeasure.top+this._evaluatedParentMeasure.height){this._isClipped=!0;return}if(this._evaluatedMeasure.top+this._evaluatedMeasure.heightthis._currentMeasure.left+this._currentMeasure.width||tthis._currentMeasure.top+this._currentMeasure.height?!1:(this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),!0)}_processPicking(e,t,i,s,r,n,o,l){return!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this._doNotRender||!this.contains(e,t)?!1:(this._processObservables(s,e,t,i,r,n,o,l),!0)}_onPointerMove(e,t,i,s){this.onPointerMoveObservable.notifyObservers(t,-1,e,this,s)&&this.parent!=null&&!this.isPointerBlocker&&this.parent._onPointerMove(e,t,i,s)}_onPointerEnter(e,t){return!this._isEnabled||this._enterCount>0?!1:(this._enterCount===-1&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,e,this,t)&&this.parent!=null&&!this.isPointerBlocker&&this.parent._onPointerEnter(e,t),!0)}_onPointerOut(e,t,i=!1){if(!i&&(!this._isEnabled||e===this))return;this._enterCount=0;let s=!0;e.isAscendant(this)||(s=this.onPointerOutObservable.notifyObservers(this,-1,e,this,t)),s&&this.parent!=null&&!this.isPointerBlocker&&this.parent._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return this._onPointerEnter(this,r),this._downCount!==0?!1:(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new KY(t,s),-1,e,this,r)&&this.parent!=null&&!this.isPointerBlocker&&this.parent._onPointerDown(e,t,i,s,r),r&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.add(r.event.pointerId),!0)}_onPointerUp(e,t,i,s,r,n){if(!this._isEnabled)return;this._downCount=0,delete this._downPointerIds[i];let o=r;r&&(this._enterCount>0||this._enterCount===-1)&&(o=this.onPointerClickObservable.notifyObservers(new KY(t,s),-1,e,this,n)),this.onPointerUpObservable.notifyObservers(new KY(t,s),-1,e,this,n)&&this.parent!=null&&!this.isPointerBlocker&&this.parent._onPointerUp(e,t,i,s,o,n),n&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.delete(n.event.pointerId)}_forcePointerUp(e=null){if(e!==null)this._onPointerUp(this,lt.Zero(),e,0,!0);else for(const t in this._downPointerIds)this._onPointerUp(this,lt.Zero(),+t,0,!0)}_onWheelScroll(e,t){if(!this._isEnabled)return;this.onWheelObservable.notifyObservers(new lt(e,t))&&this.parent!=null&&this.parent._onWheelScroll(e,t)}_onCanvasBlur(){}_processObservables(e,t,i,s,r,n,o,l){if(!this._isEnabled)return!1;if(this._dummyVector2.copyFromFloats(t,i),e===mi.POINTERMOVE){this._onPointerMove(this,this._dummyVector2,r,s);const c=this._host._lastControlOver[r];return c&&c!==this&&c._onPointerOut(this,s),c!==this&&this._onPointerEnter(this,s),this._host._lastControlOver[r]=this,!0}return e===mi.POINTERDOWN?(this._onPointerDown(this,this._dummyVector2,r,n,s),this._host._registerLastControlDown(this,r),this._host._lastPickedControl=this,!0):e===mi.POINTERUP?(this._host._lastControlDown[r]&&this._host._lastControlDown[r]._onPointerUp(this,this._dummyVector2,r,n,!0,s),delete this._host._lastControlDown[r],!0):e===mi.POINTERWHEEL&&this._host._lastControlOver[r]?(this._host._lastControlOver[r]._onWheelScroll(o,l),!0):!1}_prepareFont(){!this._font&&!this._fontSet||(this._style?this._font=this._style.fontStyle+" "+this._style.fontWeight+" "+this.fontSizeInPixels+"px "+this._style.fontFamily:this._font=this._fontStyle+" "+this._fontWeight+" "+this.fontSizeInPixels+"px "+this._fontFamily,this._fontOffset=zt._GetFontOffset(this._font),this.getDescendants().forEach(e=>e._markAllAsDirty()))}clone(e){const t={};this.serialize(t);const i=Be.Instantiate("BABYLON.GUI."+t.className),s=new i;return s.parse(t,e),s}parse(e,t){return Kt.Parse(()=>this,e,null),this.name=e.name,this._parseFromContent(e,t??this._host),this}serialize(e){Kt.Serialize(this,e),e.name=this.name,e.className=this.getClassName(),this._prepareFont(),this._font&&(e.fontFamily=this._fontFamily,e.fontSize=this.fontSize,e.fontWeight=this.fontWeight,e.fontStyle=this.fontStyle),this._gradient&&(e.gradient={},this._gradient.serialize(e.gradient)),Kt.AppendSerializedAnimations(this,e)}_parseFromContent(e,t){var i,s;if(e.fontFamily&&(this.fontFamily=e.fontFamily),e.fontSize&&(this.fontSize=e.fontSize),e.fontWeight&&(this.fontWeight=e.fontWeight),e.fontStyle&&(this.fontStyle=e.fontStyle),e.gradient){const r=Be.Instantiate("BABYLON.GUI."+e.gradient.className);this._gradient=new r,(i=this._gradient)===null||i===void 0||i.parse(e.gradient)}if(e.animations){this.animations=[];for(let r=0;r-1&&this.linkWithMesh(null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}static get HORIZONTAL_ALIGNMENT_LEFT(){return zt._HORIZONTAL_ALIGNMENT_LEFT}static get HORIZONTAL_ALIGNMENT_RIGHT(){return zt._HORIZONTAL_ALIGNMENT_RIGHT}static get HORIZONTAL_ALIGNMENT_CENTER(){return zt._HORIZONTAL_ALIGNMENT_CENTER}static get VERTICAL_ALIGNMENT_TOP(){return zt._VERTICAL_ALIGNMENT_TOP}static get VERTICAL_ALIGNMENT_BOTTOM(){return zt._VERTICAL_ALIGNMENT_BOTTOM}static get VERTICAL_ALIGNMENT_CENTER(){return zt._VERTICAL_ALIGNMENT_CENTER}static _GetFontOffset(e){if(zt._FontHeightSizes[e])return zt._FontHeightSizes[e];const t=Ii.LastCreatedEngine;if(!t)throw new Error("Invalid engine. Unable to create a canvas.");const i=t.getFontOffset(e);return zt._FontHeightSizes[e]=i,i}static Parse(e,t){const i=Be.Instantiate("BABYLON.GUI."+e.className),s=Kt.Parse(()=>new i,e,null);return s.name=e.name,s._parseFromContent(e,t),s}static drawEllipse(e,t,i,s,r){r.translate(e,t),r.scale(i,s),r.beginPath(),r.arc(0,0,1,0,2*Math.PI),r.closePath(),r.scale(1/i,1/s),r.translate(-e,-t)}isReady(){return!0}}zt.AllowAlphaInheritance=!1;zt._ClipMeasure=new ru(0,0,0,0);zt._HORIZONTAL_ALIGNMENT_LEFT=0;zt._HORIZONTAL_ALIGNMENT_RIGHT=1;zt._HORIZONTAL_ALIGNMENT_CENTER=2;zt._VERTICAL_ALIGNMENT_TOP=0;zt._VERTICAL_ALIGNMENT_BOTTOM=1;zt._VERTICAL_ALIGNMENT_CENTER=2;zt._FontHeightSizes={};zt.AddHeader=()=>{};z([X()],zt.prototype,"metadata",void 0);z([X()],zt.prototype,"isHitTestVisible",void 0);z([X()],zt.prototype,"isPointerBlocker",void 0);z([X()],zt.prototype,"isFocusInvisible",void 0);z([X()],zt.prototype,"clipChildren",null);z([X()],zt.prototype,"clipContent",null);z([X()],zt.prototype,"useBitmapCache",void 0);z([X()],zt.prototype,"shadowOffsetX",null);z([X()],zt.prototype,"shadowOffsetY",null);z([X()],zt.prototype,"shadowBlur",null);z([X()],zt.prototype,"shadowColor",null);z([X()],zt.prototype,"hoverCursor",void 0);z([X()],zt.prototype,"fontOffset",null);z([X()],zt.prototype,"alpha",null);z([X()],zt.prototype,"scaleX",null);z([X()],zt.prototype,"scaleY",null);z([X()],zt.prototype,"rotation",null);z([X()],zt.prototype,"transformCenterY",null);z([X()],zt.prototype,"transformCenterX",null);z([X()],zt.prototype,"horizontalAlignment",null);z([X()],zt.prototype,"verticalAlignment",null);z([X()],zt.prototype,"fixedRatio",null);z([X()],zt.prototype,"fixedRatioMasterIsWidth",null);z([X()],zt.prototype,"width",null);z([X()],zt.prototype,"height",null);z([X()],zt.prototype,"style",null);z([X()],zt.prototype,"color",null);z([X()],zt.prototype,"gradient",null);z([X()],zt.prototype,"zIndex",null);z([X()],zt.prototype,"notRenderable",null);z([X()],zt.prototype,"isVisible",null);z([X()],zt.prototype,"descendantsOnlyPadding",null);z([X()],zt.prototype,"paddingLeft",null);z([X()],zt.prototype,"paddingRight",null);z([X()],zt.prototype,"paddingTop",null);z([X()],zt.prototype,"paddingBottom",null);z([X()],zt.prototype,"left",null);z([X()],zt.prototype,"top",null);z([X()],zt.prototype,"linkOffsetX",null);z([X()],zt.prototype,"linkOffsetY",null);z([X()],zt.prototype,"isEnabled",null);z([X()],zt.prototype,"disabledColor",null);z([X()],zt.prototype,"disabledColorItem",null);z([X()],zt.prototype,"overlapGroup",void 0);z([X()],zt.prototype,"overlapDeltaMultiplier",void 0);$e("BABYLON.GUI.Control",zt);class Z1 extends zt{get renderToIntermediateTexture(){return this._renderToIntermediateTexture}set renderToIntermediateTexture(e){this._renderToIntermediateTexture!==e&&(this._renderToIntermediateTexture=e,this._markAsDirty())}get adaptHeightToChildren(){return this._adaptHeightToChildren}set adaptHeightToChildren(e){this._adaptHeightToChildren!==e&&(this._adaptHeightToChildren=e,e&&(this.height="100%"),this._markAsDirty())}get adaptWidthToChildren(){return this._adaptWidthToChildren}set adaptWidthToChildren(e){this._adaptWidthToChildren!==e&&(this._adaptWidthToChildren=e,e&&(this.width="100%"),this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get backgroundGradient(){return this._backgroundGradient}set backgroundGradient(e){this._backgroundGradient!==e&&(this._backgroundGradient=e,this._markAsDirty())}get children(){return this._children}get isReadOnly(){return this._isReadOnly}set isReadOnly(e){this._isReadOnly=e;for(const t of this._children)t.isReadOnly=e}constructor(e){super(e),this.name=e,this._children=new Array,this._measureForChildren=ru.Empty(),this._background="",this._backgroundGradient=null,this._adaptWidthToChildren=!1,this._adaptHeightToChildren=!1,this._renderToIntermediateTexture=!1,this._intermediateTexture=null,this.logLayoutCycleErrors=!1,this.maxLayoutCycle=3,this.onControlAddedObservable=new Se,this.onControlRemovedObservable=new Se,this._inverseTransformMatrix=Wn.Identity(),this._inverseMeasure=new ru(0,0,0,0)}_getTypeName(){return"Container"}_flagDescendantsAsMatrixDirty(){for(const e of this.children)e._isClipped=!1,e._markMatrixAsDirty()}getChildByName(e){for(const t of this.children)if(t.name===e)return t;return null}getChildByType(e,t){for(const i of this.children)if(i.typeName===t)return i;return null}containsControl(e){return this.children.indexOf(e)!==-1}addControl(e){return e?this._children.indexOf(e)!==-1?this:(e._link(this._host),e._markAllAsDirty(),this._reOrderControl(e),this._markAsDirty(),this.onControlAddedObservable.notifyObservers(e),this):this}clearControls(){const e=this.children.slice();for(const t of e)this.removeControl(t);return this}removeControl(e){const t=this._children.indexOf(e);return t!==-1&&(this._children.splice(t,1),e.parent=null),e.linkWithMesh(null),this._host&&this._host._cleanControlAfterRemoval(e),this._markAsDirty(),this.onControlRemovedObservable.notifyObservers(e),this}_reOrderControl(e){const t=e.linkedMesh;this.removeControl(e);let i=!1;for(let s=0;se.zIndex){this._children.splice(s,0,e),i=!0;break}i||this._children.push(e),e.parent=this,t&&e.linkWithMesh(t),this._markAsDirty()}_offsetLeft(e){super._offsetLeft(e);for(const t of this._children)t._offsetLeft(e)}_offsetTop(e){super._offsetTop(e);for(const t of this._children)t._offsetTop(e)}_markAllAsDirty(){super._markAllAsDirty();for(let e=0;e=0&&(n+=this.paddingLeftInPixels+this.paddingRightInPixels,this.width!==n+"px"&&((i=this.parent)===null||i===void 0||i._markAsDirty(),this.width=n+"px",this._width.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this.adaptHeightToChildren&&o>=0&&(o+=this.paddingTopInPixels+this.paddingBottomInPixels,this.height!==o+"px"&&((s=this.parent)===null||s===void 0||s._markAsDirty(),this.height=o+"px",this._height.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this._postMeasure()}r++}while(this._rebuildLayout&&r=3&&this.logLayoutCycleErrors&&Me.Error(`Layout cycle detected in GUI (Container name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this._isDirty&&(this.invalidateRect(),this._isDirty=!1),!0}_postMeasure(){}_draw(e,t){const i=this._renderToIntermediateTexture&&this._intermediateTexture,s=i?this._intermediateTexture.getContext():e;i&&(s.save(),s.translate(-this._currentMeasure.left,-this._currentMeasure.top),t?(this._transformMatrix.invertToRef(this._inverseTransformMatrix),t.transformToRef(this._inverseTransformMatrix,this._inverseMeasure),s.clearRect(this._inverseMeasure.left,this._inverseMeasure.top,this._inverseMeasure.width,this._inverseMeasure.height)):s.clearRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._localDraw(s),e.save(),this.clipChildren&&this._clipForChildren(s);for(const r of this._children)t&&!r._intersectsRect(t)||r._render(s,t);i&&(s.restore(),e.save(),e.globalAlpha=this.alpha,e.drawImage(s.canvas,this._currentMeasure.left,this._currentMeasure.top),e.restore()),e.restore()}getDescendantsToRef(e,t=!1,i){if(!!this.children)for(let s=0;s=0;h--){const u=this._children[h];if(u._processPicking(e,t,i,s,r,n,o,l))return u.hoverCursor&&this._host._changeCursor(u.hoverCursor),!0}return!c||!this.isHitTestVisible?!1:this._processObservables(s,e,t,i,r,n,o,l)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(this._currentMeasure)}serialize(e){if(super.serialize(e),this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient)),!!this.children.length){e.children=[];for(const t of this.children){const i={};t.serialize(i),e.children.push(i)}}}dispose(){var e;super.dispose();for(let t=this.children.length-1;t>=0;t--)this.children[t].dispose();(e=this._intermediateTexture)===null||e===void 0||e.dispose()}_parseFromContent(e,t){var i;if(super._parseFromContent(e,t),this._link(t),e.backgroundGradient){const s=Be.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this._backgroundGradient=new s,(i=this._backgroundGradient)===null||i===void 0||i.parse(e.backgroundGradient)}if(!!e.children)for(const s of e.children)this.addControl(zt.Parse(s,t))}isReady(){for(const e of this.children)if(!e.isReady())return!1;return!0}}z([X()],Z1.prototype,"renderToIntermediateTexture",null);z([X()],Z1.prototype,"maxLayoutCycle",void 0);z([X()],Z1.prototype,"adaptHeightToChildren",null);z([X()],Z1.prototype,"adaptWidthToChildren",null);z([X()],Z1.prototype,"background",null);z([X()],Z1.prototype,"backgroundGradient",null);$e("BABYLON.GUI.Container",Z1);class Uu extends Z1{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get cornerRadius(){return this._cornerRadius[0]}set cornerRadius(e){e<0&&(e=0),!(this._cornerRadius[0]===e&&this._cornerRadius[1]===e&&this._cornerRadius[2]===e&&this._cornerRadius[3]===e)&&(this._cornerRadius[0]=this._cornerRadius[1]=this._cornerRadius[2]=this._cornerRadius[3]=e,this._markAsDirty())}get cornerRadiusX(){return this._cornerRadius[0]}set cornerRadiusX(e){this._cornerRadius[0]!==e&&(this._cornerRadius[0]=e)}get cornerRadiusY(){return this._cornerRadius[1]}set cornerRadiusY(e){this._cornerRadius[1]!==e&&(this._cornerRadius[1]=e)}get cornerRadiusZ(){return this._cornerRadius[2]}set cornerRadiusZ(e){this._cornerRadius[2]!==e&&(this._cornerRadius[2]=e)}get cornerRadiusW(){return this._cornerRadius[3]}set cornerRadiusW(e){this._cornerRadius[3]!==e&&(this._cornerRadius[3]=e)}constructor(e){super(e),this.name=e,this._thickness=1,this._cornerRadius=[0,0,0,0],this._cachedRadius=[0,0,0,0]}_getTypeName(){return"Rectangle"}_computeAdditionalOffsetX(){let e=0;return(this._cornerRadius[0]!==0||this._cornerRadius[1]!==0||this._cornerRadius[2]!==0||this._cornerRadius[3]!==0)&&(e+=1),this.thickness&&(e+=this.thickness/2),e}_computeAdditionalOffsetY(){let e=0;return(this._cornerRadius[0]!==0||this._cornerRadius[1]!==0||this._cornerRadius[2]!==0||this._cornerRadius[3]!==0)&&(e+=1),this.thickness&&(e+=this.thickness/2),e}_getRectangleFill(e){return this._getBackgroundColor(e)}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),(this._background||this._backgroundGradient)&&(e.fillStyle=this._getRectangleFill(e),this._cornerRadius[0]!==0||this._cornerRadius[1]!==0||this._cornerRadius[2]!==0||this._cornerRadius[3]!==0?(this._drawRoundedRect(e,this._thickness/2),e.fill()):e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._thickness&&((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),(this.color||this.gradient)&&(e.strokeStyle=this.gradient?this.gradient.getCanvasGradient(e):this.color),e.lineWidth=this._thickness,this._cornerRadius[0]!==0||this._cornerRadius[1]!==0||this._cornerRadius[2]!==0||this._cornerRadius[3]!==0?(this._drawRoundedRect(e,this._thickness/2),e.stroke()):e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness)),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_drawRoundedRect(e,t=0){const i=this._currentMeasure.left+t,s=this._currentMeasure.top+t,r=this._currentMeasure.width-t*2,n=this._currentMeasure.height-t*2;for(let o=0;oi&&(i=r.width)}if(this._resizeToFit){if(this._textWrapping===FM.Clip||this._forceResizeWidth){const r=Math.ceil(this._paddingLeftInPixels)+Math.ceil(this._paddingRightInPixels)+Math.ceil(i);r!==this._width.getValueInPixel(this._host,this._tempParentMeasure.width)&&(this._width.updateInPlace(r,mr.UNITMODE_PIXEL),this._rebuildLayout=!0)}let s=this._paddingTopInPixels+this._paddingBottomInPixels+this._fontOffset.height*this._lines.length|0;if(this._lines.length>0&&this._lineSpacing.internalValue!==0){let r=0;this._lineSpacing.isPixel?r=this._lineSpacing.getValue(this._host):r=this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),s+=(this._lines.length-1)*r}s!==this._height.internalValue&&(this._height.updateInPlace(s,mr.UNITMODE_PIXEL),this._rebuildLayout=!0)}}_drawText(e,t,i,s){const r=this._currentMeasure.width;let n=0;switch(this._textHorizontalAlignment){case zt.HORIZONTAL_ALIGNMENT_LEFT:n=0;break;case zt.HORIZONTAL_ALIGNMENT_RIGHT:n=r-t;break;case zt.HORIZONTAL_ALIGNMENT_CENTER:n=(r-t)/2;break}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(s.shadowColor=this.shadowColor,s.shadowBlur=this.shadowBlur,s.shadowOffsetX=this.shadowOffsetX,s.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&s.strokeText(e,this._currentMeasure.left+n,i),s.fillText(e,this._currentMeasure.left+n,i),this._underline&&this._drawLine(this._currentMeasure.left+n,i+3,this._currentMeasure.left+n+t,i+3,s),this._lineThrough&&this._drawLine(this._currentMeasure.left+n,i-this.fontSizeInPixels/3,this._currentMeasure.left+n+t,i-this.fontSizeInPixels/3,s)}_drawLine(e,t,i,s,r){if(r.beginPath(),r.lineWidth=Math.round(this.fontSizeInPixels*.05),r.moveTo(e,t),r.lineTo(i,s),this.outlineWidth&&this.applyOutlineToUnderline)r.stroke(),r.fill();else{const n=r.strokeStyle;r.strokeStyle=r.fillStyle,r.stroke(),r.strokeStyle=n}r.closePath()}_draw(e){e.save(),this._applyStates(e),this._renderLines(e),e.restore()}_applyStates(e){super._applyStates(e),this.outlineWidth&&(e.lineWidth=this.outlineWidth,e.strokeStyle=this.outlineColor,e.lineJoin="miter",e.miterLimit=2)}_breakLines(e,t,i){this._linesTemp.length=0;const s=this.text.split(` +`);if(this._textWrapping===FM.Ellipsis)for(const r of s)this._linesTemp.push(this._parseLineEllipsis(r,e,i));else if(this._textWrapping===FM.WordWrap)for(const r of s)this._linesTemp.push(...this._parseLineWordWrap(r,e,i));else if(this._textWrapping===FM.WordWrapEllipsis)for(const r of s)this._linesTemp.push(...this._parseLineWordWrapEllipsis(r,e,t,i));else for(const r of s)this._linesTemp.push(this._parseLine(r,i));return this._linesTemp}_parseLine(e="",t){return{text:e,width:this._getTextMetricsWidth(t.measureText(e))}}_getCharsToRemove(e,t,i){const s=e>t?e-t:0,r=e/i;return Math.max(Math.floor(s/r),1)}_parseLineEllipsis(e="",t,i){let s=this._getTextMetricsWidth(i.measureText(e)),r=this._getCharsToRemove(s,t,e.length);const n=Array.from&&Array.from(e);if(n)for(;n.length&&s>t;)n.splice(n.length-r,r),e=`${n.join("")}\u2026`,s=this._getTextMetricsWidth(i.measureText(e)),r=this._getCharsToRemove(s,t,e.length);else{for(;e.length>2&&s>t;)e=e.slice(0,-r),s=this._getTextMetricsWidth(i.measureText(e+"\u2026")),r=this._getCharsToRemove(s,t,e.length);e+="\u2026"}return{text:e,width:s}}_getTextMetricsWidth(e){return e.actualBoundingBoxLeft!==void 0?Math.abs(e.actualBoundingBoxLeft)+Math.abs(e.actualBoundingBoxRight):e.width}_parseLineWordWrap(e="",t,i){const s=[],r=this.wordSplittingFunction?this.wordSplittingFunction(e):e.split(this._wordDivider);let n=this._getTextMetricsWidth(i.measureText(e));for(let o=0;o0?e+this._wordDivider+r[o]:r[0],c=this._getTextMetricsWidth(i.measureText(l));c>t&&o>0?(s.push({text:e,width:n}),e=r[o],n=this._getTextMetricsWidth(i.measureText(e))):(n=c,e=l)}return s.push({text:e,width:n}),s}_parseLineWordWrapEllipsis(e="",t,i,s){const r=this._parseLineWordWrap(e,t,s);for(let n=1;n<=r.length;n++)if(this._computeHeightForLinesOf(n)>i&&n>1){const l=r[n-2],c=r[n-1];r[n-2]=this._parseLineEllipsis(l.text+this._wordDivider+c.text,t,s);const h=r.length-n+1;for(let u=0;u0&&this._lineSpacing.internalValue!==0){let i=0;this._lineSpacing.isPixel?i=this._lineSpacing.getValue(this._host):i=this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),t+=(e-1)*i}return t}computeExpectedHeight(){var e;if(this.text&&this.widthInPixels){const t=(e=Ii.LastCreatedEngine)===null||e===void 0?void 0:e.createCanvas(0,0).getContext("2d");if(t){this._applyStates(t),this._fontOffset||(this._fontOffset=zt._GetFontOffset(t.font));const i=this._lines?this._lines:this._breakLines(this.widthInPixels-this._paddingLeftInPixels-this._paddingRightInPixels,this.heightInPixels-this._paddingTopInPixels-this._paddingBottomInPixels,t);return this._computeHeightForLinesOf(i.length)}}return 0}dispose(){super.dispose(),this.onTextChangedObservable.clear()}}z([X()],Ka.prototype,"resizeToFit",null);z([X()],Ka.prototype,"textWrapping",null);z([X()],Ka.prototype,"text",null);z([X()],Ka.prototype,"textHorizontalAlignment",null);z([X()],Ka.prototype,"textVerticalAlignment",null);z([X()],Ka.prototype,"lineSpacing",null);z([X()],Ka.prototype,"outlineWidth",null);z([X()],Ka.prototype,"underline",null);z([X()],Ka.prototype,"lineThrough",null);z([X()],Ka.prototype,"applyOutlineToUnderline",null);z([X()],Ka.prototype,"outlineColor",null);z([X()],Ka.prototype,"wordDivider",null);z([X()],Ka.prototype,"forceResizeWidth",null);$e("BABYLON.GUI.TextBlock",Ka);class wr extends zt{get isLoaded(){return this._loaded}isReady(){return this.isLoaded}get detectPointerOnOpaqueOnly(){return this._detectPointerOnOpaqueOnly}set detectPointerOnOpaqueOnly(e){this._detectPointerOnOpaqueOnly!==e&&(this._detectPointerOnOpaqueOnly=e)}get sliceLeft(){return this._sliceLeft}set sliceLeft(e){this._sliceLeft!==e&&(this._sliceLeft=e,this._markAsDirty())}get sliceRight(){return this._sliceRight}set sliceRight(e){this._sliceRight!==e&&(this._sliceRight=e,this._markAsDirty())}get sliceTop(){return this._sliceTop}set sliceTop(e){this._sliceTop!==e&&(this._sliceTop=e,this._markAsDirty())}get sliceBottom(){return this._sliceBottom}set sliceBottom(e){this._sliceBottom!==e&&(this._sliceBottom=e,this._markAsDirty())}get sourceLeft(){return this._sourceLeft}set sourceLeft(e){this._sourceLeft!==e&&(this._sourceLeft=e,this._markAsDirty())}get sourceTop(){return this._sourceTop}set sourceTop(e){this._sourceTop!==e&&(this._sourceTop=e,this._markAsDirty())}get sourceWidth(){return this._sourceWidth}set sourceWidth(e){this._sourceWidth!==e&&(this._sourceWidth=e,this._markAsDirty())}get sourceHeight(){return this._sourceHeight}set sourceHeight(e){this._sourceHeight!==e&&(this._sourceHeight=e,this._markAsDirty())}get imageWidth(){return this._imageWidth}get imageHeight(){return this._imageHeight}get populateNinePatchSlicesFromImage(){return this._populateNinePatchSlicesFromImage}set populateNinePatchSlicesFromImage(e){this._populateNinePatchSlicesFromImage!==e&&(this._populateNinePatchSlicesFromImage=e,this._populateNinePatchSlicesFromImage&&this._loaded&&this._extractNinePatchSliceDataFromImage())}get isSVG(){return this._isSVG}get svgAttributesComputationCompleted(){return this._svgAttributesComputationCompleted}get autoScale(){return this._autoScale}set autoScale(e){this._autoScale!==e&&(this._autoScale=e,e&&this._loaded&&this.synchronizeSizeWithContent())}get stretch(){return this._stretch}set stretch(e){this._stretch!==e&&(this._stretch=e,this._markAsDirty())}_rotate90(e,t=!1){var i,s;const r=this._domImage.width,n=this._domImage.height,o=((s=(i=this._host)===null||i===void 0?void 0:i.getScene())===null||s===void 0?void 0:s.getEngine())||Ii.LastCreatedEngine;if(!o)throw new Error("Invalid engine. Unable to create a canvas.");const l=o.createCanvas(n,r),c=l.getContext("2d");c.translate(l.width/2,l.height/2),c.rotate(e*Math.PI/2),c.drawImage(this._domImage,0,0,r,n,-r/2,-n/2,r,n);const h=l.toDataURL("image/jpg"),u=new wr(this.name+"rotated",h);return t&&(u._stretch=this._stretch,u._autoScale=this._autoScale,u._cellId=this._cellId,u._cellWidth=e%1?this._cellHeight:this._cellWidth,u._cellHeight=e%1?this._cellWidth:this._cellHeight),this._handleRotationForSVGImage(this,u,e),this._imageDataCache.data=null,u}_handleRotationForSVGImage(e,t,i){!e._isSVG||(e._svgAttributesComputationCompleted?(this._rotate90SourceProperties(e,t,i),this._markAsDirty()):e.onSVGAttributesComputedObservable.addOnce(()=>{this._rotate90SourceProperties(e,t,i),this._markAsDirty()}))}_rotate90SourceProperties(e,t,i){let s=e.sourceLeft,r=e.sourceTop,n=e.domImage.width,o=e.domImage.height,l=s,c=r,h=e.sourceWidth,u=e.sourceHeight;if(i!=0){const p=i<0?-1:1;i=i%4;for(let m=0;m127&&this._sliceLeft===-1){this._sliceLeft=l;continue}if(c<127&&this._sliceLeft>-1){this._sliceRight=l;break}}this._sliceTop=-1,this._sliceBottom=-1;for(let l=0;l127&&this._sliceTop===-1){this._sliceTop=l;continue}if(c<127&&this._sliceTop>-1){this._sliceBottom=l;break}}}set domImage(e){this._domImage=e,this._loaded=!1,this._imageDataCache.data=null,this._domImage.width?this._onImageLoaded():this._domImage.onload=()=>{this._onImageLoaded()}}get domImage(){return this._domImage}_onImageLoaded(){this._imageDataCache.data=null,this._imageWidth=this._domImage.width,this._imageHeight=this._domImage.height,this._loaded=!0,this._populateNinePatchSlicesFromImage&&this._extractNinePatchSliceDataFromImage(),this._autoScale&&this.synchronizeSizeWithContent(),this.onImageLoadedObservable.notifyObservers(this),this._markAsDirty()}get source(){return this._source}static ResetImageCache(){wr.SourceImgCache.clear()}_removeCacheUsage(e){const t=e&&wr.SourceImgCache.get(e);t&&(t.timesUsed-=1,t.timesUsed===0&&wr.SourceImgCache.delete(e))}set source(e){var t,i;if(this._source===e)return;this._removeCacheUsage(this._source),this._loaded=!1,this._source=e,this._imageDataCache.data=null,e&&(e=this._svgCheck(e));const s=((i=(t=this._host)===null||t===void 0?void 0:t.getScene())===null||i===void 0?void 0:i.getEngine())||Ii.LastCreatedEngine;if(!s)throw new Error("Invalid engine. Unable to create a canvas.");if(e&&wr.SourceImgCache.has(e)){const r=wr.SourceImgCache.get(e);this._domImage=r.img,r.timesUsed+=1,r.loaded?this._onImageLoaded():r.waitingForLoadCallback.push(this._onImageLoaded.bind(this));return}this._domImage=s.createCanvasImage(),e&&wr.SourceImgCache.set(e,{img:this._domImage,timesUsed:1,loaded:!1,waitingForLoadCallback:[this._onImageLoaded.bind(this)]}),this._domImage.onload=()=>{if(e){const r=wr.SourceImgCache.get(e);if(r){r.loaded=!0;for(const n of r.waitingForLoadCallback)n();r.waitingForLoadCallback.length=0;return}}this._onImageLoaded()},e&&(Be.SetCorsBehavior(e,this._domImage),Be.SetReferrerPolicyBehavior(this.referrerPolicy,this._domImage),this._domImage.src=e)}_svgCheck(e){if(window.SVGSVGElement&&e.search(/.svg#/gi)!==-1&&e.indexOf("#")===e.lastIndexOf("#")){this._isSVG=!0;const t=e.split("#")[0],i=e.split("#")[1],s=document.body.querySelector('object[data="'+t+'"]');if(s){const r=s.contentDocument;if(r&&r.documentElement){const n=r.documentElement.getAttribute("viewBox"),o=Number(r.documentElement.getAttribute("width")),l=Number(r.documentElement.getAttribute("height"));if(r.getElementById(i)&&n&&o&&l)return this._getSVGAttribs(s,i),e}s.addEventListener("load",()=>{this._getSVGAttribs(s,i)})}else{const r=document.createElement("object");r.data=t,r.type="image/svg+xml",r.width="0%",r.height="0%",document.body.appendChild(r),r.onload=()=>{const n=document.body.querySelector('object[data="'+t+'"]');n&&this._getSVGAttribs(n,i)}}return t}else return e}_getSVGAttribs(e,t){const i=e.contentDocument;if(i&&i.documentElement){const s=i.documentElement.getAttribute("viewBox"),r=Number(i.documentElement.getAttribute("width")),n=Number(i.documentElement.getAttribute("height")),o=i.getElementById(t);if(s&&r&&n&&o){const l=Number(s.split(" ")[2]),c=Number(s.split(" ")[3]),h=o.getBBox();let u=1,p=1,m=0,_=0;const f=o.transform.baseVal.consolidate().matrix;o.transform&&o.transform.baseVal.consolidate()&&(u=f.a,p=f.d,m=f.e,_=f.f),this.sourceLeft=(u*h.x+m)*r/l,this.sourceTop=(p*h.y+_)*n/c,this.sourceWidth=h.width*u*(r/l),this.sourceHeight=h.height*p*(n/c),this._svgAttributesComputationCompleted=!0,this.onSVGAttributesComputedObservable.notifyObservers(this)}}}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth!==e&&(this._cellWidth=e,this._markAsDirty())}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight!==e&&(this._cellHeight=e,this._markAsDirty())}get cellId(){return this._cellId}set cellId(e){this._cellId!==e&&(this._cellId=e,this._markAsDirty())}constructor(e,t=null){super(e),this.name=e,this._workingCanvas=null,this._loaded=!1,this._stretch=wr.STRETCH_FILL,this._autoScale=!1,this._sourceLeft=0,this._sourceTop=0,this._sourceWidth=0,this._sourceHeight=0,this._svgAttributesComputationCompleted=!1,this._isSVG=!1,this._cellWidth=0,this._cellHeight=0,this._cellId=-1,this._populateNinePatchSlicesFromImage=!1,this._imageDataCache={data:null,key:""},this.onImageLoadedObservable=new Se,this.onSVGAttributesComputedObservable=new Se,this.source=t}contains(e,t){if(!super.contains(e,t))return!1;if(!this._detectPointerOnOpaqueOnly||!this._workingCanvas)return!0;const i=this._currentMeasure.width|0,s=this._currentMeasure.height|0,r=i+"_"+s;let n=this._imageDataCache.data;if(!n||this._imageDataCache.key!==r){const c=this._workingCanvas.getContext("2d");this._imageDataCache.data=n=c.getImageData(0,0,i,s).data,this._imageDataCache.key=r}return e=e-this._currentMeasure.left|0,t=t-this._currentMeasure.top|0,n[(e+t*i)*4+3]>0}_getTypeName(){return"Image"}synchronizeSizeWithContent(){!this._loaded||(this.width=this._domImage.width+"px",this.height=this._domImage.height+"px")}_processMeasures(e,t){if(this._loaded)switch(this._stretch){case wr.STRETCH_NONE:break;case wr.STRETCH_FILL:break;case wr.STRETCH_UNIFORM:break;case wr.STRETCH_NINE_PATCH:break;case wr.STRETCH_EXTEND:this._autoScale&&this.synchronizeSizeWithContent(),this.parent&&this.parent.parent&&(this.parent.adaptWidthToChildren=!0,this.parent.adaptHeightToChildren=!0);break}super._processMeasures(e,t)}_prepareWorkingCanvasForOpaqueDetection(){var e,t;if(!this._detectPointerOnOpaqueOnly)return;const i=this._currentMeasure.width,s=this._currentMeasure.height;if(!this._workingCanvas){const o=((t=(e=this._host)===null||e===void 0?void 0:e.getScene())===null||t===void 0?void 0:t.getEngine())||Ii.LastCreatedEngine;if(!o)throw new Error("Invalid engine. Unable to create a canvas.");this._workingCanvas=o.createCanvas(i,s)}this._workingCanvas.getContext("2d").clearRect(0,0,i,s)}_drawImage(e,t,i,s,r,n,o,l,c){if(e.drawImage(this._domImage,t,i,s,r,n,o,l,c),!this._detectPointerOnOpaqueOnly)return;e=this._workingCanvas.getContext("2d"),e.drawImage(this._domImage,t,i,s,r,n-this._currentMeasure.left,o-this._currentMeasure.top,l,c)}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY);let t,i,s,r;if(this.cellId==-1)t=this._sourceLeft,i=this._sourceTop,s=this._sourceWidth?this._sourceWidth:this._imageWidth,r=this._sourceHeight?this._sourceHeight:this._imageHeight;else{const n=this._domImage.naturalWidth/this.cellWidth,o=this.cellId/n>>0,l=this.cellId%n;t=this.cellWidth*l,i=this.cellHeight*o,s=this.cellWidth,r=this.cellHeight}if(this._prepareWorkingCanvasForOpaqueDetection(),this._applyStates(e),this._loaded)switch(this._stretch){case wr.STRETCH_NONE:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case wr.STRETCH_FILL:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case wr.STRETCH_UNIFORM:{const n=this._currentMeasure.width/s,o=this._currentMeasure.height/r,l=Math.min(n,o),c=(this._currentMeasure.width-s*l)/2,h=(this._currentMeasure.height-r*l)/2;this._drawImage(e,t,i,s,r,this._currentMeasure.left+c,this._currentMeasure.top+h,s*l,r*l);break}case wr.STRETCH_EXTEND:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case wr.STRETCH_NINE_PATCH:this._renderNinePatch(e);break}e.restore()}_renderNinePatch(e){const t=this._sliceLeft,i=this._sliceTop,s=this._imageHeight-this._sliceBottom,r=this._imageWidth-this._sliceRight,n=this._sliceRight-this._sliceLeft,o=this._sliceBottom-this._sliceTop,l=this._currentMeasure.width-r-t+2,c=this._currentMeasure.height-s-i+2,h=this._currentMeasure.left+t-1,u=this._currentMeasure.top+i-1,p=this._currentMeasure.left+this._currentMeasure.width-r,m=this._currentMeasure.top+this._currentMeasure.height-s;this._drawImage(e,0,0,t,i,this._currentMeasure.left,this._currentMeasure.top,t,i),e.clearRect(h,this._currentMeasure.top,l,i),this._drawImage(e,this._sliceLeft,0,n,i,h,this._currentMeasure.top,l,i),e.clearRect(p,this._currentMeasure.top,r,i),this._drawImage(e,this._sliceRight,0,r,i,p,this._currentMeasure.top,r,i),e.clearRect(this._currentMeasure.left,u,t,c),this._drawImage(e,0,this._sliceTop,t,o,this._currentMeasure.left,u,t,c),e.clearRect(h,u,l,c),this._drawImage(e,this._sliceLeft,this._sliceTop,n,o,h,u,l,c),e.clearRect(p,u,r,c),this._drawImage(e,this._sliceRight,this._sliceTop,r,o,p,u,r,c),e.clearRect(this._currentMeasure.left,m,t,s),this._drawImage(e,0,this._sliceBottom,t,s,this._currentMeasure.left,m,t,s),e.clearRect(h,m,l,s),this._drawImage(e,this.sliceLeft,this._sliceBottom,n,s,h,m,l,s),e.clearRect(p,m,r,s),this._drawImage(e,this._sliceRight,this._sliceBottom,r,s,p,m,r,s)}dispose(){super.dispose(),this.onImageLoadedObservable.clear(),this.onSVGAttributesComputedObservable.clear(),this._removeCacheUsage(this._source)}}wr.SourceImgCache=new Map;wr.STRETCH_NONE=0;wr.STRETCH_FILL=1;wr.STRETCH_UNIFORM=2;wr.STRETCH_EXTEND=3;wr.STRETCH_NINE_PATCH=4;z([X()],wr.prototype,"detectPointerOnOpaqueOnly",null);z([X()],wr.prototype,"sliceLeft",null);z([X()],wr.prototype,"sliceRight",null);z([X()],wr.prototype,"sliceTop",null);z([X()],wr.prototype,"sliceBottom",null);z([X()],wr.prototype,"sourceLeft",null);z([X()],wr.prototype,"sourceTop",null);z([X()],wr.prototype,"sourceWidth",null);z([X()],wr.prototype,"sourceHeight",null);z([X()],wr.prototype,"populateNinePatchSlicesFromImage",null);z([X()],wr.prototype,"autoScale",null);z([X()],wr.prototype,"stretch",null);z([X()],wr.prototype,"source",null);z([X()],wr.prototype,"cellWidth",null);z([X()],wr.prototype,"cellHeight",null);z([X()],wr.prototype,"cellId",null);$e("BABYLON.GUI.Image",wr);class Bb extends Uu{get image(){return this._image}get textBlock(){return this._textBlock}constructor(e){super(e),this.name=e,this.delegatePickingToChildren=!1,this.thickness=1,this.isPointerBlocker=!0;let t=null;this.pointerEnterAnimation=()=>{t=this.alpha,this.alpha-=.1},this.pointerOutAnimation=()=>{t!==null&&(this.alpha=t)},this.pointerDownAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"Button"}_processPicking(e,t,i,s,r,n,o,l){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable||!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let c=!1;for(let h=this._children.length-1;h>=0;h--){const u=this._children[h];if(u.isEnabled&&u.isHitTestVisible&&u.isVisible&&!u.notRenderable&&u.contains(e,t)){c=!0;break}}if(!c)return!1}return this._processObservables(s,e,t,i,r,n,o,l),!0}_onPointerEnter(e,t){return super._onPointerEnter(e,t)?(!this.isReadOnly&&this.pointerEnterAnimation&&this.pointerEnterAnimation(),!0):!1}_onPointerOut(e,t,i=!1){!this.isReadOnly&&this.pointerOutAnimation&&this.pointerOutAnimation(),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return super._onPointerDown(e,t,i,s,r)?(!this.isReadOnly&&this.pointerDownAnimation&&this.pointerDownAnimation(),!0):!1}_getRectangleFill(e){return this.isEnabled?this._getBackgroundColor(e):this._disabledColor}_onPointerUp(e,t,i,s,r,n){!this.isReadOnly&&this.pointerUpAnimation&&this.pointerUpAnimation(),super._onPointerUp(e,t,i,s,r,n)}serialize(e){super.serialize(e),this._textBlock&&(e.textBlockName=this._textBlock.name),this._image&&(e.imageName=this._image.name)}_parseFromContent(e,t){super._parseFromContent(e,t),e.textBlockName&&(this._textBlock=this.getChildByName(e.textBlockName)),e.imageName&&(this._image=this.getChildByName(e.imageName))}static CreateImageButton(e,t,i){const s=new this(e),r=new Ka(e+"_button",t);r.textWrapping=!0,r.textHorizontalAlignment=zt.HORIZONTAL_ALIGNMENT_CENTER,r.paddingLeft="20%",s.addControl(r);const n=new wr(e+"_icon",i);return n.width="20%",n.stretch=wr.STRETCH_UNIFORM,n.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,s.addControl(n),s._image=n,s._textBlock=r,s}static CreateImageOnlyButton(e,t){const i=new this(e),s=new wr(e+"_icon",t);return s.stretch=wr.STRETCH_FILL,s.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,i.addControl(s),i._image=s,i}static CreateSimpleButton(e,t){const i=new this(e),s=new Ka(e+"_button",t);return s.textWrapping=!0,s.textHorizontalAlignment=zt.HORIZONTAL_ALIGNMENT_CENTER,i.addControl(s),i._textBlock=s,i}static CreateImageWithCenterTextButton(e,t,i){const s=new this(e),r=new wr(e+"_icon",i);r.stretch=wr.STRETCH_FILL,s.addControl(r);const n=new Ka(e+"_button",t);return n.textWrapping=!0,n.textHorizontalAlignment=zt.HORIZONTAL_ALIGNMENT_CENTER,s.addControl(n),s._image=r,s._textBlock=n,s}}$e("BABYLON.GUI.Button",Bb);class Z2 extends Z1{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get spacing(){return this._spacing}set spacing(e){this._spacing!==e&&(this._spacing=e,this._markAsDirty())}set width(e){this._doNotTrackManualChanges||(this._manualWidth=!0),this._width.toString(this._host)!==e&&this._width.fromString(e)&&this._markAsDirty()}get width(){return this._width.toString(this._host)}set height(e){this._doNotTrackManualChanges||(this._manualHeight=!0),this._height.toString(this._host)!==e&&this._height.fromString(e)&&this._markAsDirty()}get height(){return this._height.toString(this._host)}constructor(e){super(e),this.name=e,this._isVertical=!0,this._manualWidth=!1,this._manualHeight=!1,this._doNotTrackManualChanges=!1,this._spacing=0,this.ignoreLayoutWarnings=!1}_getTypeName(){return"StackPanel"}_preMeasure(e,t){for(const i of this._children)this._isVertical?i.verticalAlignment=zt.VERTICAL_ALIGNMENT_TOP:i.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT;super._preMeasure(e,t)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(e),this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,(!this.isVertical||this._manualWidth)&&(this._measureForChildren.width=this._currentMeasure.width),(this.isVertical||this._manualHeight)&&(this._measureForChildren.height=this._currentMeasure.height)}_postMeasure(){let e=0,t=0;const i=this._children.length;for(let n=0;n=0?e=Math.min(e,this._characters.length):e=this._characters.length+Math.max(e,-this._characters.length),t===void 0?t=this._characters.length-e:(isNaN(t)||t<0)&&(t=0);const i=[];for(;--t>=0;)i[t]=this._characters[e+t];return i.join("")}return this._text.substr(e,t)}substring(e,t){if(this._characters){isNaN(e)?e=0:e>this._characters.length?e=this._characters.length:e<0&&(e=0),t===void 0?t=this._characters.length:isNaN(t)?t=0:t>this._characters.length?t=this._characters.length:t<0&&(t=0);const i=[];let s=0;for(;e{switch(t.type){case lv.COPY:this._onCopyText(t.event),this.onTextCopyObservable.notifyObservers(this);break;case lv.CUT:this._onCutText(t.event),this.onTextCutObservable.notifyObservers(this);break;case lv.PASTE:this._onPasteText(t.event),this.onTextPasteObservable.notifyObservers(this);break;default:return}});const e=this._host.getScene();e&&(this._onPointerDblTapObserver=e.onPointerObservable.add(t=>{!this._isFocused||t.type===mi.POINTERDOUBLETAP&&this._processDblClick(t)})),this._onFocusSelectAll&&this._selectAllText()}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}_getTypeName(){return"InputText"}keepsFocusWith(){return this._connectedVirtualKeyboard?[this._connectedVirtualKeyboard]:null}processKey(e,t,i){var s;if(!this.isReadOnly&&!(i&&(i.ctrlKey||i.metaKey)&&(e===67||e===86||e===88))){if(i&&(i.ctrlKey||i.metaKey)&&e===65){this._selectAllText(),i.preventDefault();return}switch(e){case 32:t=" ";break;case 191:i&&i.preventDefault();break;case 8:if(this._textWrapper.text&&this._textWrapper.length>0){if(this.isTextHighlightOn){this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this._blinkIsEven=!1,i&&i.preventDefault();return}if(this._cursorOffset===0)this.text=this._textWrapper.substr(0,this._textWrapper.length-1);else{const r=this._textWrapper.length-this._cursorOffset;r>0&&(this._textWrapper.removePart(r-1,r),this._textHasChanged())}}i&&i.preventDefault();return;case 46:if(this.isTextHighlightOn){this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,i&&i.preventDefault();return}if(this._textWrapper.text&&this._textWrapper.length>0&&this._cursorOffset>0){const r=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(r,r+1),this._textHasChanged(),this._cursorOffset--}i&&i.preventDefault();return;case 13:this._host.focusedControl=null,this.isTextHighlightOn=!1;return;case 35:this._cursorOffset=0,this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._markAsDirty();return;case 36:this._cursorOffset=this._textWrapper.length,this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._markAsDirty();return;case 37:if(this._cursorOffset++,this._cursorOffset>this._textWrapper.length&&(this._cursorOffset=this._textWrapper.length),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(this._textWrapper.length===this._cursorOffset)return;this._endHighlightIndex=this._textWrapper.length-this._cursorOffset+1}this._startHighlightIndex=0,this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=this._textWrapper.length,this.isTextHighlightOn=!0,this._markAsDirty();return}this.isTextHighlightOn?this._cursorIndex===-1&&(this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=this._startHighlightIndex===0?this._textWrapper.length:this._textWrapper.length-this._startHighlightIndex+1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset>=this._textWrapper.length?this._textWrapper.length:this._cursorOffset-1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,this._markAsDirty();return}this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=this._textWrapper.length,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,this._markAsDirty();return;case 39:if(this._cursorOffset--,this._cursorOffset<0&&(this._cursorOffset=0),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(this._cursorOffset===0)return;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset-1}this._endHighlightIndex=this._textWrapper.length,this.isTextHighlightOn=!0,this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=0,this._markAsDirty();return}this.isTextHighlightOn?this._cursorIndex===-1&&(this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=this._textWrapper.length===this._endHighlightIndex?0:this._textWrapper.length-this._endHighlightIndex-1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset<=0?0:this._cursorOffset+1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,this._markAsDirty();return}this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._endHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=0,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,this._markAsDirty();return}if(e===32&&(t=(s=i?.key)!==null&&s!==void 0?s:" "),this._deadKey=t==="Dead",t&&(e===-1||e===32||e===34||e===39||e>47&&e<64||e>64&&e<91||e>159&&e<193||e>218&&e<223||e>95&&e<112)&&(this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&!this._deadKey))if(this.isTextHighlightOn)this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex,t),this._textHasChanged(),this._cursorOffset=this._textWrapper.length-(this._startHighlightIndex+1),this.isTextHighlightOn=!1,this._blinkIsEven=!1,this._markAsDirty();else if(this._cursorOffset===0)this.text+=this._deadKey&&i?.key?i.key:t;else{const r=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(r,r,t),this._textHasChanged()}}}_updateValueFromCursorIndex(e){if(this._blinkIsEven=!1,this._cursorIndex===-1)this._cursorIndex=e;else if(this._cursorIndexthis._cursorOffset)this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex;else{this.isTextHighlightOn=!1,this._markAsDirty();return}this.isTextHighlightOn=!0,this._markAsDirty()}_processDblClick(e){this._startHighlightIndex=this._textWrapper.length-this._cursorOffset,this._endHighlightIndex=this._startHighlightIndex;let t,i;do i=this._endHighlightIndex0&&this._textWrapper.isWord(this._startHighlightIndex-1)?--this._startHighlightIndex:0;while(t||i);this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!0,this._clickedCoordinate=null,this._blinkIsEven=!0,this._cursorIndex=-1,this._markAsDirty()}_selectAllText(){this._blinkIsEven=!0,this.isTextHighlightOn=!0,this._startHighlightIndex=0,this._endHighlightIndex=this._textWrapper.length,this._cursorOffset=this._textWrapper.length,this._cursorIndex=-1,this._markAsDirty()}processKeyboard(e){this.processKey(e.keyCode,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e)}_onCopyText(e){this.isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(!!this._highlightedText){this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._highlightedText=""}}_onPasteText(e){let t="";e.clipboardData&&e.clipboardData.types.indexOf("text/plain")!==-1?t=e.clipboardData.getData("text/plain"):t=this._host.clipboardData;const i=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(i,i,t),this._textHasChanged()}_draw(e){e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),(!this._fontOffset||this._wasDirty)&&(this._fontOffset=zt._GetFontOffset(e.font));const t=this._currentMeasure.left+this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this.color&&(e.fillStyle=this.color);let i=this._beforeRenderText(this._textWrapper);!this._isFocused&&!this._textWrapper.text&&this._placeholderText&&(i=new LX,i.text=this._placeholderText,this._placeholderColor&&(e.fillStyle=this._placeholderColor)),this._textWidth=e.measureText(i.text).width;const s=this._margin.getValueInPixel(this._host,this._tempParentMeasure.width)*2;this._autoStretchWidth&&(this.width=Math.min(this._maxWidth.getValueInPixel(this._host,this._tempParentMeasure.width),this._textWidth+s)+"px",this._autoStretchWidth=!0);const r=this._fontOffset.ascent+(this._currentMeasure.height-this._fontOffset.height)/2,n=this._width.getValueInPixel(this._host,this._tempParentMeasure.width)-s;if(e.save(),e.beginPath(),e.rect(t,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,n+2,this._currentMeasure.height),e.clip(),this._isFocused&&this._textWidth>n){const o=t-this._textWidth+n;this._scrollLeft||(this._scrollLeft=o)}else this._scrollLeft=t;if(e.fillText(i.text,this._scrollLeft,this._currentMeasure.top+r),this._isFocused){if(this._clickedCoordinate){const l=this._scrollLeft+this._textWidth-this._clickedCoordinate;let c=0;this._cursorOffset=0;let h=0;do this._cursorOffset&&(h=Math.abs(l-c)),this._cursorOffset++,c=e.measureText(i.substr(i.length-this._cursorOffset,this._cursorOffset)).width;while(c=this._cursorOffset);Math.abs(l-c)>h&&this._cursorOffset--,this._blinkIsEven=!1,this._clickedCoordinate=null}if(!this._blinkIsEven){const o=i.substr(i.length-this._cursorOffset),l=e.measureText(o).width;let c=this._scrollLeft+this._textWidth-l;ct+n&&(this._scrollLeft+=t+n-c,c=t+n,this._markAsDirty()),this.isTextHighlightOn||e.fillRect(c,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,2,this._fontOffset.height)}if(clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout(()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()},500),this.isTextHighlightOn){clearTimeout(this._blinkTimeout);const o=e.measureText(i.substring(this._startHighlightIndex)).width;let l=this._scrollLeft+this._textWidth-o;this._highlightedText=i.substring(this._startHighlightIndex,this._endHighlightIndex);let c=e.measureText(i.substring(this._startHighlightIndex,this._endHighlightIndex)).width;l=this._rowDefinitions.length?null:this._rowDefinitions[e]}getColumnDefinition(e){return e<0||e>=this._columnDefinitions.length?null:this._columnDefinitions[e]}addRowDefinition(e,t=!1){return this._rowDefinitions.push(new mr(e,t?mr.UNITMODE_PIXEL:mr.UNITMODE_PERCENTAGE)),this._rowDefinitionObservers.push(this._rowDefinitions[this.rowCount-1].onChangedObservable.add(()=>this._markAsDirty())),this._markAsDirty(),this}addColumnDefinition(e,t=!1){return this._columnDefinitions.push(new mr(e,t?mr.UNITMODE_PIXEL:mr.UNITMODE_PERCENTAGE)),this._columnDefinitionObservers.push(this._columnDefinitions[this.columnCount-1].onChangedObservable.add(()=>this._markAsDirty())),this._markAsDirty(),this}setRowDefinition(e,t,i=!1){if(e<0||e>=this._rowDefinitions.length)return this;const s=this._rowDefinitions[e];return s&&s.isPixel===i&&s.value===t?this:(this._rowDefinitions[e].onChangedObservable.remove(this._rowDefinitionObservers[e]),this._rowDefinitions[e]=new mr(t,i?mr.UNITMODE_PIXEL:mr.UNITMODE_PERCENTAGE),this._rowDefinitionObservers[e]=this._rowDefinitions[e].onChangedObservable.add(()=>this._markAsDirty()),this._markAsDirty(),this)}setColumnDefinition(e,t,i=!1){if(e<0||e>=this._columnDefinitions.length)return this;const s=this._columnDefinitions[e];return s&&s.isPixel===i&&s.value===t?this:(this._columnDefinitions[e].onChangedObservable.remove(this._columnDefinitionObservers[e]),this._columnDefinitions[e]=new mr(t,i?mr.UNITMODE_PIXEL:mr.UNITMODE_PERCENTAGE),this._columnDefinitionObservers[e]=this._columnDefinitions[e].onChangedObservable.add(()=>this._markAsDirty()),this._markAsDirty(),this)}getChildrenAt(e,t){const i=this._cells[`${e}:${t}`];return i?i.children:null}getChildCellInfo(e){return e._tag}_removeCell(e,t){if(!!e){super.removeControl(e);for(const i of e.children){const s=this._childControls.indexOf(i);s!==-1&&this._childControls.splice(s,1)}delete this._cells[t]}}_offsetCell(e,t){if(!!this._cells[t]){this._cells[e]=this._cells[t];for(const i of this._cells[e].children)i._tag=e;delete this._cells[t]}}removeColumnDefinition(e){if(e<0||e>=this._columnDefinitions.length)return this;for(let t=0;t=this._rowDefinitions.length)return this;for(let t=0;t{for(const o in this._cells){if(!Object.prototype.hasOwnProperty.call(this._cells,o))continue;const l=o.split(":"),c=parseInt(l[0]),h=parseInt(l[1]),u=this._cells[o];u.leftInPixels=i[h],u.topInPixels=s[c],u.widthInPixels=r[h],u.heightInPixels=n[c],u._left.ignoreAdaptiveScaling=!0,u._top.ignoreAdaptiveScaling=!0,u._width.ignoreAdaptiveScaling=!0,u._height.ignoreAdaptiveScaling=!0}}),super._additionalProcessing(e,t)}_flagDescendantsAsMatrixDirty(){for(const e in this._cells){if(!Object.prototype.hasOwnProperty.call(this._cells,e))continue;this._cells[e]._markMatrixAsDirty()}}_renderHighlightSpecific(e){super._renderHighlightSpecific(e),this._getGridDefinitions((t,i,s,r)=>{for(let n=0;n{e.tags.push(t._tag)})}_parseFromContent(e,t){super._parseFromContent(e,t);const i=[];this.children.forEach(s=>{i.push(s)}),this.removeRowDefinition(0),this.removeColumnDefinition(0);for(let s=0;s=1-Xf._Epsilon&&(this._value.r=1),this._value.g>=1-Xf._Epsilon&&(this._value.g=1),this._value.b>=1-Xf._Epsilon&&(this._value.b=1),this.onValueChangedObservable.notifyObservers(this._value))}get width(){return this._width.toString(this._host)}set width(e){this._width.toString(this._host)!==e&&this._width.fromString(e)&&(this._width.getValue(this._host)===0&&(e="1px",this._width.fromString(e)),this._height.fromString(e),this._markAsDirty())}get height(){return this._height.toString(this._host)}set height(e){this._height.toString(this._host)!==e&&this._height.fromString(e)&&(this._height.getValue(this._host)===0&&(e="1px",this._height.fromString(e)),this._width.fromString(e),this._markAsDirty())}get size(){return this.width}set size(e){this.width=e}constructor(e){super(e),this.name=e,this._value=Ie.Red(),this._tmpColor=new Ie,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._squareLeft=0,this._squareTop=0,this._squareSize=0,this._h=360,this._s=1,this._v=1,this._lastPointerDownId=-1,this.onValueChangedObservable=new Se,this._pointerIsDown=!1,this.value=new Ie(.88,.1,.1),this.size="200px",this.isPointerBlocker=!0}_getTypeName(){return"ColorPicker"}_preMeasure(e){e.widthc||_S?y=b:y=(b-M)*(e-E)/(S-E)+M,v=(f-h)/(e-h),v1-y?o[C+3]=255*(1-(v-(1-y))/y):o[C+3]=255}return r.putImageData(n,0,0),s}_draw(e){e.save(),this._applyStates(e);const t=Math.min(this._currentMeasure.width,this._currentMeasure.height)*.5,i=t*.2,s=this._currentMeasure.left,r=this._currentMeasure.top;(!this._colorWheelCanvas||this._colorWheelCanvas.width!=t*2)&&(this._colorWheelCanvas=this._createColorWheelCanvas(t,i)),this._updateSquareProps(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY,e.fillRect(this._squareLeft,this._squareTop,this._squareSize,this._squareSize)),e.drawImage(this._colorWheelCanvas,s,r),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._drawGradientSquare(this._h,this._squareLeft,this._squareTop,this._squareSize,this._squareSize,e);let n=this._squareLeft+this._squareSize*this._s,o=this._squareTop+this._squareSize*(1-this._v);this._drawCircle(n,o,t*.04,e);const l=t-i*.5;n=s+t+Math.cos((this._h-180)*Math.PI/180)*l,o=r+t+Math.sin((this._h-180)*Math.PI/180)*l,this._drawCircle(n,o,i*.35,e),e.restore()}_updateValueFromPointer(e,t){if(this._pointerStartedOnWheel){const i=Math.min(this._currentMeasure.width,this._currentMeasure.height)*.5,s=i+this._currentMeasure.left,r=i+this._currentMeasure.top;this._h=Math.atan2(t-r,e-s)*180/Math.PI+180}else this._pointerStartedOnSquare&&(this._updateSquareProps(),this._s=(e-this._squareLeft)/this._squareSize,this._v=1-(t-this._squareTop)/this._squareSize,this._s=Math.min(this._s,1),this._s=Math.max(this._s,Xf._Epsilon),this._v=Math.min(this._v,1),this._v=Math.max(this._v,Xf._Epsilon));Ie.HSVtoRGBToRef(this._h,this._s,this._v,this._tmpColor),this.value=this._tmpColor}_isPointOnSquare(e,t){this._updateSquareProps();const i=this._squareLeft,s=this._squareTop,r=this._squareSize;return e>=i&&e<=i+r&&t>=s&&t<=s+r}_isPointOnWheel(e,t){const i=Math.min(this._currentMeasure.width,this._currentMeasure.height)*.5,s=i+this._currentMeasure.left,r=i+this._currentMeasure.top,n=i*.2,o=i-n,l=i*i,c=o*o,h=e-s,u=t-r,p=h*h+u*u;return p<=l&&p>=c}_onPointerDown(e,t,i,s,r){if(!super._onPointerDown(e,t,i,s,r))return!1;if(this.isReadOnly)return!0;this._pointerIsDown=!0,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const n=this._transformedPosition.x,o=this._transformedPosition.y;return this._isPointOnSquare(n,o)?this._pointerStartedOnSquare=!0:this._isPointOnWheel(n,o)&&(this._pointerStartedOnWheel=!0),this._updateValueFromPointer(n,o),this._host._capturingControl[i]=this,this._lastPointerDownId=i,!0}_onPointerMove(e,t,i,s){if(i==this._lastPointerDownId){if(!this.isReadOnly){this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const r=this._transformedPosition.x,n=this._transformedPosition.y;this._pointerIsDown&&this._updateValueFromPointer(r,n)}super._onPointerMove(e,t,i,s)}}_onPointerUp(e,t,i,s,r,n){this._pointerIsDown=!1,delete this._host._capturingControl[i],super._onPointerUp(e,t,i,s,r,n)}_onCanvasBlur(){this._forcePointerUp(),super._onCanvasBlur()}static ShowPickerDialogAsync(e,t){return new Promise(i=>{t.pickerWidth=t.pickerWidth||"640px",t.pickerHeight=t.pickerHeight||"400px",t.headerHeight=t.headerHeight||"35px",t.lastColor=t.lastColor||"#000000",t.swatchLimit=t.swatchLimit||20,t.numSwatchesPerLine=t.numSwatchesPerLine||10;const s=t.swatchLimit/t.numSwatchesPerLine,r=parseFloat(t.pickerWidth)/t.numSwatchesPerLine,n=Math.floor(r*.25),o=n*(t.numSwatchesPerLine+1),l=Math.floor((parseFloat(t.pickerWidth)-o)/t.numSwatchesPerLine),c=l*s+n*(s+1),h=(parseInt(t.pickerHeight)+c+Math.floor(l*.25)).toString()+"px",u="#c0c0c0",p="#535353",m="#414141",_="515151",f="#555555",d="#454545",C="#404040",v=Ie.FromHexString("#dddddd"),y=v.r+v.g+v.b,M="#aaaaaa",b="#ffffff";let E,S;const I=["R","G","B"],D="#454545",R="#f0f0f0";let L,w,N=!1,V,W,G;const ie=new N2;if(ie.name="Dialog Container",ie.width=t.pickerWidth,t.savedColors){ie.height=h;const St=parseInt(t.pickerHeight)/parseInt(h);ie.addRowDefinition(St,!1),ie.addRowDefinition(1-St,!1)}else ie.height=t.pickerHeight,ie.addRowDefinition(1,!1);if(e.addControl(ie),t.savedColors){w=new N2,w.name="Swatch Drawer",w.verticalAlignment=zt.VERTICAL_ALIGNMENT_TOP,w.background=p,w.width=t.pickerWidth;const St=t.savedColors.length/t.numSwatchesPerLine;let Gi;St==0?Gi=0:Gi=St+1,w.height=(l*St+Gi*n).toString()+"px",w.top=Math.floor(l*.25).toString()+"px";for(let Ai=0;Ai{},H.pointerUpAnimation=()=>{H.background=j.background},H.pointerEnterAnimation=()=>{H.color=j.background,H.background="red"},H.pointerOutAnimation=()=>{H.color=J.toHexString(),H.background=j.background},H.onPointerClickObservable.add(()=>{Qi(mt.background)}),Z.addControl(H,0,0);const te=new N2;te.name="Dialogue Body",te.background=p;const re=[.4375,.5625];te.addRowDefinition(1,!1),te.addColumnDefinition(re[0],!1),te.addColumnDefinition(re[1],!1),Z.addControl(te,1,0);const ee=new N2;ee.name="Picker Grid",ee.addRowDefinition(.85,!1),ee.addRowDefinition(.15,!1),te.addControl(ee,0,0);const oe=new Xf;oe.name="GUI Color Picker",t.pickerHeight{G=oe.name,W="",Tt(!1)}),oe.onValueChangedObservable.add(function(St){G==oe.name&&Ni(St,oe.name)}),ee.addControl(oe,0,0);const ae=new N2;ae.name="Dialogue Right Half",ae.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT;const fe=[.514,.486];ae.addRowDefinition(fe[0],!1),ae.addRowDefinition(fe[1],!1),te.addControl(ae,1,1);const de=new N2;de.name="Swatches and Buttons";const me=[.417,.583];de.addRowDefinition(1,!1),de.addColumnDefinition(me[0],!1),de.addColumnDefinition(me[1],!1),ae.addControl(de,0,0);const Fe=new N2;Fe.name="New and Current Swatches";const je=[.04,.16,.64,.16];Fe.addRowDefinition(je[0],!1),Fe.addRowDefinition(je[1],!1),Fe.addRowDefinition(je[2],!1),Fe.addRowDefinition(je[3],!1),de.addControl(Fe,0,0);const nt=new N2;nt.name="Active Swatches",nt.width=.67,nt.addRowDefinition(.5,!1),nt.addRowDefinition(.5,!1),Fe.addControl(nt,2,0);const we=Math.floor(parseInt(t.pickerWidth)*re[1]*me[0]*.11),Ke=Math.floor(parseInt(t.pickerHeight)*K[1]*fe[0]*je[1]*.5);let ft;t.pickerWidth>t.pickerHeight?ft=Ke:ft=we;const yt=new Ka;yt.text="new",yt.name="New Color Label",yt.color=u,yt.fontSize=ft,Fe.addControl(yt,1,0);const Ze=new Uu;Ze.name="New Color Swatch",Ze.background=t.lastColor,Ze.thickness=0,nt.addControl(Ze,0,0);const mt=Bb.CreateSimpleButton("currentSwatch","");mt.background=t.lastColor,mt.thickness=0,mt.onPointerClickObservable.add(()=>{const St=Ie.FromHexString(mt.background);Ni(St,mt.name),Tt(!1)}),mt.pointerDownAnimation=()=>{},mt.pointerUpAnimation=()=>{},mt.pointerEnterAnimation=()=>{},mt.pointerOutAnimation=()=>{},nt.addControl(mt,1,0);const Je=new Uu;Je.name="Swatch Outline",Je.width=.67,Je.thickness=2,Je.color=C,Je.isHitTestVisible=!1,Fe.addControl(Je,2,0);const Yt=new Ka;Yt.name="Current Color Label",Yt.text="current",Yt.color=u,Yt.fontSize=ft,Fe.addControl(Yt,3,0);const Vt=new N2;Vt.name="Button Grid",Vt.height=.8;const Ot=1/3;Vt.addRowDefinition(Ot,!1),Vt.addRowDefinition(Ot,!1),Vt.addRowDefinition(Ot,!1),de.addControl(Vt,0,1);const et=Math.floor(parseInt(t.pickerWidth)*re[1]*me[1]*.67).toString()+"px",Xe=Math.floor(parseInt(t.pickerHeight)*K[1]*fe[0]*(parseFloat(Vt.height.toString())/100)*Ot*.7).toString()+"px";parseFloat(et)>parseFloat(Xe)?E=Math.floor(parseFloat(Xe)*.45):E=Math.floor(parseFloat(et)*.11);const ct=Bb.CreateSimpleButton("butOK","OK");ct.width=et,ct.height=Xe,ct.verticalAlignment=zt.VERTICAL_ALIGNMENT_CENTER,ct.thickness=2,ct.color=u,ct.fontSize=E,ct.background=p,ct.onPointerEnterObservable.add(()=>{ct.background=m}),ct.onPointerOutObservable.add(()=>{ct.background=p}),ct.pointerDownAnimation=()=>{ct.background=_},ct.pointerUpAnimation=()=>{ct.background=m},ct.onPointerClickObservable.add(()=>{Tt(!1),Qi(Ze.background)}),Vt.addControl(ct,0,0);const wt=Bb.CreateSimpleButton("butCancel","Cancel");wt.width=et,wt.height=Xe,wt.verticalAlignment=zt.VERTICAL_ALIGNMENT_CENTER,wt.thickness=2,wt.color=u,wt.fontSize=E,wt.background=p,wt.onPointerEnterObservable.add(()=>{wt.background=m}),wt.onPointerOutObservable.add(()=>{wt.background=p}),wt.pointerDownAnimation=()=>{wt.background=_},wt.pointerUpAnimation=()=>{wt.background=m},wt.onPointerClickObservable.add(()=>{Tt(!1),Qi(mt.background)}),Vt.addControl(wt,1,0),t.savedColors&&(V=Bb.CreateSimpleButton("butSave","Save"),V.width=et,V.height=Xe,V.verticalAlignment=zt.VERTICAL_ALIGNMENT_CENTER,V.thickness=2,V.fontSize=E,t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&(t.savedColors.length==0&&Di(!0),t.savedColors.length0&&Di(!0),Vt.addControl(V,2,0));const Ut=new N2;Ut.name="Dialog Lower Right",Ut.addRowDefinition(.02,!1),Ut.addRowDefinition(.63,!1),Ut.addRowDefinition(.21,!1),Ut.addRowDefinition(.14,!1),ae.addControl(Ut,1,0);const hi=Ie.FromHexString(t.lastColor),Ri=new N2;Ri.name="RGB Values",Ri.width=.82,Ri.verticalAlignment=zt.VERTICAL_ALIGNMENT_CENTER,Ri.addRowDefinition(1/3,!1),Ri.addRowDefinition(1/3,!1),Ri.addRowDefinition(1/3,!1),Ri.addColumnDefinition(.1,!1),Ri.addColumnDefinition(.2,!1),Ri.addColumnDefinition(.7,!1),Ut.addControl(Ri,1,0);for(let St=0;St{G=Bi.name,W=Bi.text,Tt(!1)}),Bi.onBlurObservable.add(()=>{Bi.text==""&&(Bi.text="0"),Ts(Bi,"r"),G==Bi.name&&(G="")}),Bi.onTextChangedObservable.add(()=>{G==Bi.name&&Ts(Bi,"r")}),Ri.addControl(Bi,0,1);const Yi=new Jl;Yi.width=.83,Yi.height=.72,Yi.name="gIntField",Yi.fontSize=E,Yi.text=(hi.g*255).toString(),Yi.color=R,Yi.background=D,Yi.onFocusObservable.add(()=>{G=Yi.name,W=Yi.text,Tt(!1)}),Yi.onBlurObservable.add(()=>{Yi.text==""&&(Yi.text="0"),Ts(Yi,"g"),G==Yi.name&&(G="")}),Yi.onTextChangedObservable.add(()=>{G==Yi.name&&Ts(Yi,"g")}),Ri.addControl(Yi,1,1);const Vi=new Jl;Vi.width=.83,Vi.height=.72,Vi.name="bIntField",Vi.fontSize=E,Vi.text=(hi.b*255).toString(),Vi.color=R,Vi.background=D,Vi.onFocusObservable.add(()=>{G=Vi.name,W=Vi.text,Tt(!1)}),Vi.onBlurObservable.add(()=>{Vi.text==""&&(Vi.text="0"),Ts(Vi,"b"),G==Vi.name&&(G="")}),Vi.onTextChangedObservable.add(()=>{G==Vi.name&&Ts(Vi,"b")}),Ri.addControl(Vi,2,1);const Ji=new Jl;Ji.width=.95,Ji.height=.72,Ji.name="rDecField",Ji.fontSize=E,Ji.text=hi.r.toString(),Ji.color=R,Ji.background=D,Ji.onFocusObservable.add(()=>{G=Ji.name,W=Ji.text,Tt(!1)}),Ji.onBlurObservable.add(()=>{(parseFloat(Ji.text)==0||Ji.text=="")&&(Ji.text="0",Dt(Ji,"r")),G==Ji.name&&(G="")}),Ji.onTextChangedObservable.add(()=>{G==Ji.name&&Dt(Ji,"r")}),Ri.addControl(Ji,0,2);const st=new Jl;st.width=.95,st.height=.72,st.name="gDecField",st.fontSize=E,st.text=hi.g.toString(),st.color=R,st.background=D,st.onFocusObservable.add(()=>{G=st.name,W=st.text,Tt(!1)}),st.onBlurObservable.add(()=>{(parseFloat(st.text)==0||st.text=="")&&(st.text="0",Dt(st,"g")),G==st.name&&(G="")}),st.onTextChangedObservable.add(()=>{G==st.name&&Dt(st,"g")}),Ri.addControl(st,1,2);const Ht=new Jl;Ht.width=.95,Ht.height=.72,Ht.name="bDecField",Ht.fontSize=E,Ht.text=hi.b.toString(),Ht.color=R,Ht.background=D,Ht.onFocusObservable.add(()=>{G=Ht.name,W=Ht.text,Tt(!1)}),Ht.onBlurObservable.add(()=>{(parseFloat(Ht.text)==0||Ht.text=="")&&(Ht.text="0",Dt(Ht,"b")),G==Ht.name&&(G="")}),Ht.onTextChangedObservable.add(()=>{G==Ht.name&&Dt(Ht,"b")}),Ri.addControl(Ht,2,2);const kt=new N2;kt.name="Hex Value",kt.width=.82,kt.addRowDefinition(1,!1),kt.addColumnDefinition(.1,!1),kt.addColumnDefinition(.9,!1),Ut.addControl(kt,2,0);const si=new Ka;si.text="#",si.color=u,si.fontSize=E,kt.addControl(si,0,0);const Qt=new Jl;Qt.width=.96,Qt.height=.72,Qt.name="hexField",Qt.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_CENTER,Qt.fontSize=E;const Ci=t.lastColor.split("#");Qt.text=Ci[1],Qt.color=R,Qt.background=D,Qt.onFocusObservable.add(()=>{G=Qt.name,W=Qt.text,Tt(!1)}),Qt.onBlurObservable.add(()=>{if(Qt.text.length==3){const St=Qt.text.split("");Qt.text=St[0]+St[0]+St[1]+St[1]+St[2]+St[2]}Qt.text==""&&(Qt.text="000000",Ni(Ie.FromHexString(Qt.text),"b")),G==Qt.name&&(G="")}),Qt.onTextChangedObservable.add(()=>{let St=Qt.text;const Gi=/[^0-9A-F]/i.test(St);if((Qt.text.length>6||Gi)&&G==Qt.name)Qt.text=W;else{if(Qt.text.length<6){const Ai=6-Qt.text.length;for(let fr=0;fr0&&$i("",V);function Ni(St,Gi){G=Gi;const Ai=St.toHexString();if(Ze.background=Ai,Bi.name!=G&&(Bi.text=Math.floor(St.r*255).toString()),Yi.name!=G&&(Yi.text=Math.floor(St.g*255).toString()),Vi.name!=G&&(Vi.text=Math.floor(St.b*255).toString()),Ji.name!=G&&(Ji.text=St.r.toString()),st.name!=G&&(st.text=St.g.toString()),Ht.name!=G&&(Ht.text=St.b.toString()),Qt.name!=G){const fr=Ai.split("#");Qt.text=fr[1]}oe.name!=G&&(oe.value=St)}function Ts(St,Gi){let Ai=St.text;if(/[^0-9]/g.test(Ai)){St.text=W;return}else Ai!=""&&(Math.floor(parseInt(Ai))<0?Ai="0":Math.floor(parseInt(Ai))>255?Ai="255":isNaN(parseInt(Ai))&&(Ai="0")),G==St.name&&(W=Ai);if(Ai!=""){Ai=parseInt(Ai).toString(),St.text=Ai;const or=Ie.FromHexString(Ze.background);G==St.name&&(Gi=="r"?Ni(new Ie(parseInt(Ai)/255,or.g,or.b),St.name):Gi=="g"?Ni(new Ie(or.r,parseInt(Ai)/255,or.b),St.name):Ni(new Ie(or.r,or.g,parseInt(Ai)/255),St.name))}}function Dt(St,Gi){let Ai=St.text;if(/[^0-9.]/g.test(Ai)){St.text=W;return}else Ai!=""&&Ai!="."&&parseFloat(Ai)!=0&&(parseFloat(Ai)<0?Ai="0.0":parseFloat(Ai)>1?Ai="1.0":isNaN(parseFloat(Ai))&&(Ai="0.0")),G==St.name&&(W=Ai);Ai!=""&&Ai!="."&&parseFloat(Ai)!=0?(Ai=parseFloat(Ai).toString(),St.text=Ai):Ai="0.0";const or=Ie.FromHexString(Ze.background);G==St.name&&(Gi=="r"?Ni(new Ie(parseFloat(Ai),or.g,or.b),St.name):Gi=="g"?Ni(new Ie(or.r,parseFloat(Ai),or.b),St.name):Ni(new Ie(or.r,or.g,parseFloat(Ai)),St.name))}function xt(St){t.savedColors&&t.savedColors.splice(St,1),t.savedColors&&t.savedColors.length==0&&(Di(!1),N=!1)}function Wt(){if(t.savedColors&&t.savedColors[L]){let St;N?St="b":St="";const Gi=Bb.CreateSimpleButton("Swatch_"+L,St);Gi.fontFamily="coreglyphs";const Ai=Ie.FromHexString(t.savedColors[L]);Ai.r+Ai.g+Ai.b>y?Gi.color=M:Gi.color=b,Gi.fontSize=Math.floor(l*.7),Gi.textBlock.verticalAlignment=zt.VERTICAL_ALIGNMENT_CENTER,Gi.height=Gi.width=l.toString()+"px",Gi.background=t.savedColors[L],Gi.thickness=2;const or=L;return Gi.pointerDownAnimation=()=>{Gi.thickness=4},Gi.pointerUpAnimation=()=>{Gi.thickness=3},Gi.pointerEnterAnimation=()=>{Gi.thickness=3},Gi.pointerOutAnimation=()=>{Gi.thickness=2},Gi.onPointerClickObservable.add(()=>{N?(xt(or),$i("",V)):t.savedColors&&Ni(Ie.FromHexString(t.savedColors[or]),Gi.name)}),Gi}else return null}function Tt(St){St!==void 0&&(N=St);let Gi;if(N){for(let Ai=0;Aien*t.numSwatchesPerLine?rn=t.numSwatchesPerLine:rn=t.savedColors.length-(en-1)*t.numSwatchesPerLine;const sn=Math.min(Math.max(rn,0),t.numSwatchesPerLine);for(let pt=0,bi=1;ptt.numSwatchesPerLine)continue;const Zi=Wt();if(Zi!=null)w.addControl(Zi,or,bi),bi+=2,L++;else continue}}t.savedColors.length>=t.swatchLimit?is(Gi,!0):is(Gi,!1)}}function Di(St){St?(S=Bb.CreateSimpleButton("butEdit","Edit"),S.width=et,S.height=Xe,S.left=Math.floor(parseInt(et)*.1).toString()+"px",S.top=(parseFloat(S.left)*-1).toString()+"px",S.verticalAlignment=zt.VERTICAL_ALIGNMENT_BOTTOM,S.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,S.thickness=2,S.color=u,S.fontSize=E,S.background=p,S.onPointerEnterObservable.add(()=>{S.background=m}),S.onPointerOutObservable.add(()=>{S.background=p}),S.pointerDownAnimation=()=>{S.background=_},S.pointerUpAnimation=()=>{S.background=m},S.onPointerClickObservable.add(()=>{N?N=!1:N=!0,Tt()}),ee.addControl(S,1,0)):ee.removeControl(S)}function is(St,Gi){Gi?(St.color=f,St.background=d):(St.color=u,St.background=p)}function Qi(St){t.savedColors&&t.savedColors.length>0?i({savedColors:t.savedColors,pickedColor:St}):i({pickedColor:St}),e.removeControl(ie)}})}}Xf._Epsilon=1e-6;z([X()],Xf.prototype,"value",null);z([X()],Xf.prototype,"width",null);z([X()],Xf.prototype,"height",null);z([X()],Xf.prototype,"size",null);$e("BABYLON.GUI.ColorPicker",Xf);class Ute extends Z1{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thickness=1}_getTypeName(){return"Ellipse"}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),zt.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),(this._backgroundGradient||this._background)&&(e.fillStyle=this._getBackgroundColor(e),e.fill()),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._thickness&&(this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.stroke()),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_clipForChildren(e){zt.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2,this._currentMeasure.height/2,e),e.clip()}_renderHighlightSpecific(e){zt.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._highlightLineWidth/2,this._currentMeasure.height/2-this._highlightLineWidth/2,e),e.stroke()}}z([X()],Ute.prototype,"thickness",null);$e("BABYLON.GUI.Ellipse",Ute);class u1e extends Bb{constructor(e){super(e),this.name=e,this.focusedColor=null,this._isFocused=!1,this._unfocusedColor=null,this.onFocusObservable=new Se,this.onBlurObservable=new Se,this.onKeyboardEventProcessedObservable=new Se,this._unfocusedColor=this.color}onBlur(){this._isFocused&&(this._isFocused=!1,this.focusedColor&&this._unfocusedColor!=null&&(this.color=this._unfocusedColor),this.onBlurObservable.notifyObservers(this))}onFocus(){this._isFocused=!0,this.focusedColor&&(this._unfocusedColor=this.color,this.color=this.focusedColor),this.onFocusObservable.notifyObservers(this)}keepsFocusWith(){return null}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}processKeyboard(e){this.onKeyboardEventProcessedObservable.notifyObservers(e,-1,this)}_onPointerDown(e,t,i,s,r){return this.isReadOnly||this.focus(),super._onPointerDown(e,t,i,s,r)}displose(){super.dispose(),this.onBlurObservable.clear(),this.onFocusObservable.clear(),this.onKeyboardEventProcessedObservable.clear()}}$e("BABYLON.GUI.FocusableButton",u1e);class wP extends Jl{get outlineWidth(){return this._outlineWidth}set outlineWidth(e){this._outlineWidth!==e&&(this._outlineWidth=e,this._markAsDirty())}get outlineColor(){return this._outlineColor}set outlineColor(e){this._outlineColor!==e&&(this._outlineColor=e,this._markAsDirty())}get autoStretchHeight(){return this._autoStretchHeight}set autoStretchHeight(e){this._autoStretchHeight!==e&&(this._autoStretchHeight=e,this._markAsDirty())}set height(e){this.fixedRatioMasterIsWidth=!1,this._height.toString(this._host)!==e&&(this._height.fromString(e)&&this._markAsDirty(),this._autoStretchHeight=!1)}get maxHeight(){return this._maxHeight.toString(this._host)}get maxHeightInPixels(){return this._maxHeight.getValueInPixel(this._host,this._cachedParentMeasure.height)}set maxHeight(e){this._maxHeight.toString(this._host)!==e&&this._maxHeight.fromString(e)&&this._markAsDirty()}constructor(e,t=""){super(e),this.name=e,this._textHorizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,this._textVerticalAlignment=zt.VERTICAL_ALIGNMENT_TOP,this._lineSpacing=new mr(0),this._outlineWidth=0,this._outlineColor="white",this._maxHeight=new mr(1,mr.UNITMODE_PERCENTAGE,!1),this.onLinesReadyObservable=new Se,this.text=t,this.isPointerBlocker=!0,this.onLinesReadyObservable.add(()=>this._updateCursorPosition()),this._highlightCursorInfo={initialStartIndex:-1,initialRelativeStartIndex:-1,initialLineIndex:-1},this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeEndIndex:0,relativeStartIndex:0,currentLineIndex:0}}_getTypeName(){return"InputTextArea"}processKeyboard(e){this.alternativeProcessKey(e.code,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e)}alternativeProcessKey(e,t,i){if(!(i&&(i.ctrlKey||i.metaKey)&&(e==="KeyC"||e==="KeyV"||e==="KeyX"))){switch(e){case"KeyA":if(i&&(i.ctrlKey||i.metaKey)){this._selectAllText(),i.preventDefault();return}break;case"Period":i&&i.shiftKey&&i.preventDefault();break;case"Backspace":!this._isTextHighlightOn&&this._cursorInfo.globalStartIndex>0&&(this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--),this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,i&&i.preventDefault(),this._blinkIsEven=!1,this._isTextHighlightOn=!1,this._textHasChanged();break;case"Delete":!this._isTextHighlightOn&&this._cursorInfo.globalEndIndexthis._highlightCursorInfo.initialStartIndex?this._cursorInfo.globalEndIndex--:this._cursorInfo.globalStartIndex--:(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--,this._isTextHighlightOn=!0),this._blinkIsEven=!0,i.preventDefault();return}this._isTextHighlightOn?this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex:i&&(i.ctrlKey||i.metaKey)?(this._cursorInfo.globalStartIndex-=this._cursorInfo.relativeStartIndex,i.preventDefault()):this._cursorInfo.globalStartIndex>0&&this._cursorInfo.globalStartIndex--,this._blinkIsEven=!1,this._isTextHighlightOn=!1;return;case"ArrowRight":if(this._markAsDirty(),i&&i.shiftKey){if(i.ctrlKey||i.metaKey){const s=this._lines[this._cursorInfo.currentLineIndex].text.length-this._cursorInfo.relativeEndIndex-1;this._cursorInfo.globalEndIndex+=s,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex}this._isTextHighlightOn?this._cursorInfo.globalStartIndexu&&p>0&&n--,this._isTextHighlightOn?this._cursorInfo.currentLineIndex<=this._highlightCursorInfo.initialLineIndex?(this._cursorInfo.globalStartIndex=n,this._cursorInfo.globalEndIndex=this._highlightCursorInfo.initialStartIndex,this._cursorInfo.relativeEndIndex=this._highlightCursorInfo.initialRelativeStartIndex):this._cursorInfo.globalEndIndex=n:this._cursorInfo.globalStartIndex=n}this._markAsDirty();return;case"ArrowDown":if(this._blinkIsEven=!1,i&&(i.shiftKey?(this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex),this._isTextHighlightOn=!0,this._blinkIsEven=!0):this._isTextHighlightOn=!1,i.preventDefault()),this._cursorInfo.currentLineIndex===this._lines.length-1)this._cursorInfo.globalStartIndex=this.text.length;else{const s=this._lines[this._cursorInfo.currentLineIndex],r=this._lines[this._cursorInfo.currentLineIndex+1];let n=0,o=0;!this._isTextHighlightOn||this._cursorInfo.currentLineIndexu&&p>0&&n--,this._isTextHighlightOn?this._cursorInfo.currentLineIndexthis._cursorInfo.globalEndIndex&&(this._cursorInfo.globalEndIndex+=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex=this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex-=this._cursorInfo.globalStartIndex)):(this._cursorInfo.globalEndIndex=n,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex):this._cursorInfo.globalStartIndex=n}this._markAsDirty();return}t?.length===1&&(i?.preventDefault(),this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&(this._isTextHighlightOn=!1,this._blinkIsEven=!1,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t),this._cursorInfo.globalStartIndex+=t.length,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()))}}_parseLineWordWrap(e="",t,i){const s=[],r=e.split(" ");let n=0;for(let o=0;o0?e+" "+r[o]:r[0],h=i.measureText(l).width;if(h>t){o>0&&(n=i.measureText(e).width,s.push({text:e,width:n,lineEnding:" "})),e=r[o];let u="";e.split("").map(p=>{i.measureText(u+p).width>t&&(s.push({text:u,width:i.measureText(u).width,lineEnding:""}),u=""),u+=p}),e=u,n=i.measureText(e).width}else n=h,e=l}return s.push({text:e,width:n,lineEnding:" "}),s}_breakLines(e,t){const i=[],s=this.text.split(` +`);if(this.clipContent)for(const r of s)i.push(...this._parseLineWordWrap(r,e,t));else for(const r of s)i.push(this._parseLine(r,t));return i[i.length-1].lineEnding=` +`,i}_parseLine(e="",t){return{text:e,width:t.measureText(e).width,lineEnding:" "}}_preMeasure(e,t){(!this._fontOffset||this._wasDirty)&&(this._fontOffset=zt._GetFontOffset(t.font));let i=this._beforeRenderText(this._textWrapper).text;!this._isFocused&&!this.text&&this._placeholderText&&(i=this._placeholderText,this._placeholderColor&&(t.fillStyle=this._placeholderColor)),this._textWidth=t.measureText(i).width;const s=this._margin.getValueInPixel(this._host,e.width)*2;if(this._autoStretchWidth){const n=i.split(` +`).reduce((l,c)=>{const h=t.measureText(c).width,u=t.measureText(l).width;return h>u?c:l},""),o=t.measureText(n).width;this.width=Math.min(this._maxWidth.getValueInPixel(this._host,e.width),o+s)+"px",this.autoStretchWidth=!0}if(this._availableWidth=this._width.getValueInPixel(this._host,e.width)-s,this._lines=this._breakLines(this._availableWidth,t),this._contextForBreakLines=t,this._autoStretchHeight){const n=this._lines.length*this._fontOffset.height+this._margin.getValueInPixel(this._host,e.height)*2;this.height=Math.min(this._maxHeight.getValueInPixel(this._host,e.height),n)+"px",this._autoStretchHeight=!0}if(this._availableHeight=this._height.getValueInPixel(this._host,e.height)-s,this._isFocused){this._cursorInfo.currentLineIndex=0;let r=this._lines[this._cursorInfo.currentLineIndex].text.length+this._lines[this._cursorInfo.currentLineIndex].lineEnding.length,n=0;for(;n+r<=this._cursorInfo.globalStartIndex;)n+=r,this._cursorInfo.currentLineIndexthis._availableWidth){const e=this._clipTextLeft-this._lines[this._cursorInfo.currentLineIndex].width+this._availableWidth;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=this._clipTextLeft;if(this._isFocused&&!this._autoStretchHeight){const e=(this._cursorInfo.currentLineIndex+1)*this._fontOffset.height,t=this._clipTextTop-e;this._scrollTop||(this._scrollTop=t)}else this._scrollTop=this._clipTextTop}_additionalProcessing(){this.highlightedText="",this.onLinesReadyObservable.notifyObservers(this)}_drawText(e,t,i,s){const r=this._currentMeasure.width;let n=this._scrollLeft;switch(this._textHorizontalAlignment){case zt.HORIZONTAL_ALIGNMENT_LEFT:n+=0;break;case zt.HORIZONTAL_ALIGNMENT_RIGHT:n+=r-t;break;case zt.HORIZONTAL_ALIGNMENT_CENTER:n+=(r-t)/2;break}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(s.shadowColor=this.shadowColor,s.shadowBlur=this.shadowBlur,s.shadowOffsetX=this.shadowOffsetX,s.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&s.strokeText(e,this._currentMeasure.left+n,i),s.fillText(e,n,i)}_onCopyText(e){this._isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(!!this._highlightedText){try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._textHasChanged()}}_onPasteText(e){let t="";e.clipboardData&&e.clipboardData.types.indexOf("text/plain")!==-1?t=e.clipboardData.getData("text/plain"):t=this._host.clipboardData,this._isTextHighlightOn=!1,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t);const i=t.length-(this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex);this._cursorInfo.globalStartIndex+=i,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()}_draw(e){var t,i;this._computeScroll(),this._scrollLeft=(t=this._scrollLeft)!==null&&t!==void 0?t:0,this._scrollTop=(i=this._scrollTop)!==null&&i!==void 0?i:0,e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this.color&&(e.fillStyle=this.color);const s=this._currentMeasure.height,r=this._currentMeasure.width;let n=0;switch(this._textVerticalAlignment){case zt.VERTICAL_ALIGNMENT_TOP:n=this._fontOffset.ascent;break;case zt.VERTICAL_ALIGNMENT_BOTTOM:n=s-this._fontOffset.height*(this._lines.length-1)-this._fontOffset.descent;break;case zt.VERTICAL_ALIGNMENT_CENTER:n=this._fontOffset.ascent+(s-this._fontOffset.height*this._lines.length)/2;break}e.save(),e.beginPath(),e.fillStyle=this.fontStyle,e.rect(this._clipTextLeft,this._clipTextTop,this._availableWidth+2,this._availableHeight+2),e.clip(),n+=this._scrollTop;for(let o=0;othis._clipTextLeft+this._availableWidth&&(this._scrollLeft+=this._clipTextLeft+this._availableWidth-o,o=this._clipTextLeft+this._availableWidth,this._markAsDirty());let l=this._scrollTop+this._cursorInfo.currentLineIndex*this._fontOffset.height;lthis._clipTextTop+this._availableHeight&&(this._scrollTop+=this._clipTextTop+this._availableHeight-l-this._fontOffset.height,l=this._clipTextTop+this._availableHeight-this._fontOffset.height,this._markAsDirty()),this._isTextHighlightOn||e.fillRect(o,l,2,this._fontOffset.height)}if(this._resetBlinking(),this._isTextHighlightOn){clearTimeout(this._blinkTimeout),this._highlightedText=this.text.substring(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),e.globalAlpha=this._highligherOpacity,e.fillStyle=this._textHighlightColor;const o=Math.min(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex),l=Math.max(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex);let c=this._scrollTop+o*this._fontOffset.height;for(let h=o;h<=l;h++){const u=this._lines[h];let p=this._scrollLeft;switch(this._textHorizontalAlignment){case zt.HORIZONTAL_ALIGNMENT_LEFT:p+=0;break;case zt.HORIZONTAL_ALIGNMENT_RIGHT:p+=r-u.width;break;case zt.HORIZONTAL_ALIGNMENT_CENTER:p+=(r-u.width)/2;break}const m=h===o?this._cursorInfo.relativeStartIndex:0,_=h===l?this._cursorInfo.relativeEndIndex:u.text.length,f=e.measureText(u.text.substr(0,m)).width,d=u.text.substring(m,_),C=e.measureText(d).width;e.fillRect(p+f,c,C,this._fontOffset.height),c+=this._fontOffset.height}this._cursorInfo.globalEndIndex===this._cursorInfo.globalStartIndex&&this._resetBlinking()}}e.restore(),this._thickness&&(this._isFocused?this.focusedColor&&(e.strokeStyle=this.focusedColor):this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness))}_resetBlinking(){clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout(()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()},500)}_applyStates(e){super._applyStates(e),this.outlineWidth&&(e.lineWidth=this.outlineWidth,e.strokeStyle=this.outlineColor)}_onPointerDown(e,t,i,s,r){return super._onPointerDown(e,t,i,s,r)?(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn=!1,this._highlightedText="",this._isPointerDown=!0,this._host._capturingControl[i]=this,this._host.focusedControl===this?(clearTimeout(this._blinkTimeout),this._markAsDirty(),!0):this._isEnabled?(this._host.focusedControl=this,!0):!1):!1}_onPointerMove(e,t,i,s){s.event.movementX===0&&s.event.movementY===0||(this._host.focusedControl===this&&this._isPointerDown&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._isTextHighlightOn=!0),this._markAsDirty()),super._onPointerMove(e,t,i,s))}_updateCursorPosition(){var e;if(!!this._isFocused)if(this._clickedCoordinateX&&this._clickedCoordinateY){this._isTextHighlightOn||(this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeStartIndex:0,relativeEndIndex:0,currentLineIndex:0});let t=0,i=0;const s=this._clickedCoordinateY-this._scrollTop,r=Math.floor(s/this._fontOffset.height);this._cursorInfo.currentLineIndex=Math.min(Math.max(r,0),this._lines.length-1);let n=0;const o=this._clickedCoordinateX-((e=this._scrollLeft)!==null&&e!==void 0?e:0);let l=0;for(let c=0;ci;)i++,l=Math.abs(o-n),n=this._contextForBreakLines.measureText(this._lines[this._cursorInfo.currentLineIndex].text.substr(0,i)).width;Math.abs(o-n)>l&&i>0&&i--,t+=i,this._isTextHighlightOn?t=this._highlightCursorInfo.initialStartIndex){for(;i+t<=this._cursorInfo.globalEndIndex;)i+=t,this._cursorInfo.currentLineIndex0&&this._textWrapper.isWord(this._cursorInfo.globalStartIndex-1)?--this._cursorInfo.globalStartIndex:0,i=this._cursorInfo.globalEndIndexthis._markAsDirty())),this._connectedControl=e,this._markAsDirty())}get x1(){return this._x1.toString(this._host)}set x1(e){this._x1.toString(this._host)!==e&&this._x1.fromString(e)&&this._markAsDirty()}get y1(){return this._y1.toString(this._host)}set y1(e){this._y1.toString(this._host)!==e&&this._y1.fromString(e)&&this._markAsDirty()}get x2(){return this._x2.toString(this._host)}set x2(e){this._x2.toString(this._host)!==e&&this._x2.fromString(e)&&this._markAsDirty()}get y2(){return this._y2.toString(this._host)}set y2(e){this._y2.toString(this._host)!==e&&this._y2.fromString(e)&&this._markAsDirty()}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}get _effectiveX2(){return(this._connectedControl?this._connectedControl.centerX:0)+this._x2.getValue(this._host)}get _effectiveY2(){return(this._connectedControl?this._connectedControl.centerY:0)+this._y2.getValue(this._host)}constructor(e){super(e),this.name=e,this._lineWidth=1,this._x1=new mr(0),this._y1=new mr(0),this._x2=new mr(0),this._y2=new mr(0),this._dash=new Array,this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=zt.VERTICAL_ALIGNMENT_TOP}_getTypeName(){return"Line"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this._getColor(e),e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath(),e.moveTo(this._cachedParentMeasure.left+this._x1.getValue(this._host),this._cachedParentMeasure.top+this._y1.getValue(this._host)),e.lineTo(this._cachedParentMeasure.left+this._effectiveX2,this._cachedParentMeasure.top+this._effectiveY2),e.stroke(),e.restore()}_measure(){this._currentMeasure.width=Math.abs(this._x1.getValue(this._host)-this._effectiveX2)+this._lineWidth,this._currentMeasure.height=Math.abs(this._y1.getValue(this._host)-this._effectiveY2)+this._lineWidth}_computeAlignment(e){this._currentMeasure.left=e.left+Math.min(this._x1.getValue(this._host),this._effectiveX2)-this._lineWidth/2,this._currentMeasure.top=e.top+Math.min(this._y1.getValue(this._host),this._effectiveY2)-this._lineWidth/2}moveToVector3(e,t,i=!1){if(!this._host||this.parent!==this._host._rootContainer){Be.Error("Cannot move a control to a vector3 if the control is not at root level");return}const s=this._host._getGlobalViewport(),r=O.Project(e,ge.IdentityReadOnly,t.getTransformMatrix(),s);if(this._moveToProjectedPosition(r,i),r.z<0||r.z>1){this.notRenderable=!0;return}this.notRenderable=!1}_moveToProjectedPosition(e,t=!1){const i=e.x+this._linkOffsetX.getValue(this._host)+"px",s=e.y+this._linkOffsetY.getValue(this._host)+"px";t?(this.x2=i,this.y2=s,this._x2.ignoreAdaptiveScaling=!0,this._y2.ignoreAdaptiveScaling=!0):(this.x1=i,this.y1=s,this._x1.ignoreAdaptiveScaling=!0,this._y1.ignoreAdaptiveScaling=!0)}}z([X()],rR.prototype,"dash",null);z([X()],rR.prototype,"x1",null);z([X()],rR.prototype,"y1",null);z([X()],rR.prototype,"x2",null);z([X()],rR.prototype,"y2",null);z([X()],rR.prototype,"lineWidth",null);$e("BABYLON.GUI.Line",rR);class pJ{constructor(e){this._multiLine=e,this._x=new mr(0),this._y=new mr(0),this._point=new O(0,0,0)}get x(){return this._x.toString(this._multiLine._host)}set x(e){this._x.toString(this._multiLine._host)!==e&&this._x.fromString(e)&&this._multiLine._markAsDirty()}get y(){return this._y.toString(this._multiLine._host)}set y(e){this._y.toString(this._multiLine._host)!==e&&this._y.fromString(e)&&this._multiLine._markAsDirty()}get control(){return this._control}set control(e){this._control!==e&&(this._control&&this._controlObserver&&(this._control.onDirtyObservable.remove(this._controlObserver),this._controlObserver=null),this._control=e,this._control&&(this._controlObserver=this._control.onDirtyObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh&&this._meshObserver&&this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver),this._mesh=e,this._mesh&&(this._meshObserver=this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}resetLinks(){this.control=null,this.mesh=null}translate(){return this._point=this._translatePoint(),this._point}_translatePoint(){if(this._mesh!=null)return this._multiLine._host.getProjectedPositionWithZ(this._mesh.getBoundingInfo().boundingSphere.center,this._mesh.getWorldMatrix());if(this._control!=null)return new O(this._control.centerX,this._control.centerY,1-Ls);{const e=this._multiLine._host,t=this._x.getValueInPixel(e,Number(e._canvas.width)),i=this._y.getValueInPixel(e,Number(e._canvas.height));return new O(t,i,1-Ls)}}dispose(){this.resetLinks()}}class kte extends zt{constructor(e){super(e),this.name=e,this._lineWidth=1,this.onPointUpdate=()=>{this._markAsDirty()},this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=zt.VERTICAL_ALIGNMENT_TOP,this._dash=[],this._points=[]}get dash(){return this._dash}set dash(e){this._dash!==e&&(this._dash=e,this._markAsDirty())}getAt(e){return this._points[e]||(this._points[e]=new pJ(this)),this._points[e]}add(...e){return e.map(t=>this.push(t))}push(e){const t=this.getAt(this._points.length);return e==null||(e instanceof Ir?t.mesh=e:e instanceof zt?t.control=e:e.x!=null&&e.y!=null&&(t.x=e.x,t.y=e.y)),t}remove(e){let t;if(e instanceof pJ){if(t=this._points.indexOf(e),t===-1)return}else t=e;const i=this._points[t];!i||(i.dispose(),this._points.splice(t,1))}reset(){for(;this._points.length>0;)this.remove(this._points.length-1)}resetLinks(){this._points.forEach(e=>{e?.resetLinks()})}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}_getTypeName(){return"MultiLine"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this.color,e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath();let t=!0,i;this._points.forEach(s=>{!s||(t?(e.moveTo(s._point.x,s._point.y),t=!1):s._point.z<1&&i.z<1?e.lineTo(s._point.x,s._point.y):e.moveTo(s._point.x,s._point.y),i=s._point)}),e.stroke(),e.restore()}_additionalProcessing(){this._minX=null,this._minY=null,this._maxX=null,this._maxY=null,this._points.forEach(e=>{!e||(e.translate(),(this._minX==null||e._point.xthis._maxX)&&(this._maxX=e._point.x),(this._maxY==null||e._point.y>this._maxY)&&(this._maxY=e._point.y))}),this._minX==null&&(this._minX=0),this._minY==null&&(this._minY=0),this._maxX==null&&(this._maxX=0),this._maxY==null&&(this._maxY=0)}_measure(){this._minX==null||this._maxX==null||this._minY==null||this._maxY==null||(this._currentMeasure.width=Math.abs(this._maxX-this._minX)+this._lineWidth,this._currentMeasure.height=Math.abs(this._maxY-this._minY)+this._lineWidth)}_computeAlignment(){this._minX==null||this._minY==null||(this._currentMeasure.left=this._minX-this._lineWidth/2,this._currentMeasure.top=this._minY-this._lineWidth/2)}dispose(){this.reset(),super.dispose()}}z([X()],kte.prototype,"dash",null);$e("BABYLON.GUI.MultiLine",kte);class uT extends zt{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get checkSizeRatio(){return this._checkSizeRatio}set checkSizeRatio(e){e=Math.max(Math.min(1,e),0),this._checkSizeRatio!==e&&(this._checkSizeRatio=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get isChecked(){return this._isChecked}set isChecked(e){this._isChecked!==e&&(this._isChecked=e,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(e),this._isChecked&&this._host&&this._host.executeOnAllControls(t=>{if(t===this||t.group===void 0)return;const i=t;i.group===this.group&&(i.isChecked=!1)}))}constructor(e){super(e),this.name=e,this._isChecked=!1,this._background="black",this._checkSizeRatio=.8,this._thickness=1,this.group="",this.onIsCheckedChangedObservable=new Se,this.isPointerBlocker=!0}_getTypeName(){return"RadioButton"}_draw(e){e.save(),this._applyStates(e);const t=this._currentMeasure.width-this._thickness,i=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),zt.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fill(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.strokeStyle=this.color,e.lineWidth=this._thickness,e.stroke(),this._isChecked){e.fillStyle=this._isEnabled?this.color:this._disabledColor;const s=t*this._checkSizeRatio,r=i*this._checkSizeRatio;zt.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,s/2-this._thickness/2,r/2-this._thickness/2,e),e.fill()}e.restore()}_onPointerDown(e,t,i,s,r){return super._onPointerDown(e,t,i,s,r)?(this.isReadOnly||this.isChecked||(this.isChecked=!0),!0):!1}static AddRadioButtonWithHeader(e,t,i,s){const r=new Z2;r.isVertical=!1,r.height="30px";const n=new uT;n.width="20px",n.height="20px",n.isChecked=i,n.color="green",n.group=t,n.onIsCheckedChangedObservable.add(l=>s(n,l)),r.addControl(n);const o=new Ka;return o.text=e,o.width="180px",o.paddingLeft="5px",o.textHorizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,o.color="white",r.addControl(o),r}}z([X()],uT.prototype,"thickness",null);z([X()],uT.prototype,"group",void 0);z([X()],uT.prototype,"checkSizeRatio",null);z([X()],uT.prototype,"background",null);z([X()],uT.prototype,"isChecked",null);$e("BABYLON.GUI.RadioButton",uT);class I_ extends zt{get displayThumb(){return this._displayThumb}set displayThumb(e){this._displayThumb!==e&&(this._displayThumb=e,this._markAsDirty())}get step(){return this._step}set step(e){this._step!==e&&(this._step=e,this._markAsDirty())}get barOffset(){return this._barOffset.toString(this._host)}get barOffsetInPixels(){return this._barOffset.getValueInPixel(this._host,this._cachedParentMeasure.width)}set barOffset(e){this._barOffset.toString(this._host)!==e&&this._barOffset.fromString(e)&&this._markAsDirty()}get thumbWidth(){return this._thumbWidth.toString(this._host)}get thumbWidthInPixels(){return this._thumbWidth.getValueInPixel(this._host,this._cachedParentMeasure.width)}set thumbWidth(e){this._thumbWidth.toString(this._host)!==e&&this._thumbWidth.fromString(e)&&this._markAsDirty()}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get value(){return this._value}set value(e){e=Math.max(Math.min(e,this._maximum),this._minimum),this._value!==e&&(this._value=e,this._markAsDirty(),this.onValueChangedObservable.notifyObservers(this._value))}get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get isThumbClamped(){return this._isThumbClamped}set isThumbClamped(e){this._isThumbClamped!==e&&(this._isThumbClamped=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbWidth=new mr(20,mr.UNITMODE_PIXEL,!1),this._minimum=0,this._maximum=100,this._value=50,this._isVertical=!1,this._barOffset=new mr(5,mr.UNITMODE_PIXEL,!1),this._isThumbClamped=!1,this._displayThumb=!0,this._step=0,this._lastPointerDownId=-1,this._effectiveBarOffset=0,this.onValueChangedObservable=new Se,this._pointerIsDown=!1,this.isPointerBlocker=!0}_getTypeName(){return"BaseSlider"}_getThumbPosition(){return this.isVertical?(this.maximum-this.value)/(this.maximum-this.minimum)*this._backgroundBoxLength:(this.value-this.minimum)/(this.maximum-this.minimum)*this._backgroundBoxLength}_getThumbThickness(e){let t=0;switch(e){case"circle":this._thumbWidth.isPixel?t=Math.max(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):t=this._backgroundBoxThickness*this._thumbWidth.getValue(this._host);break;case"rectangle":this._thumbWidth.isPixel?t=Math.min(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):t=this._backgroundBoxThickness*this._thumbWidth.getValue(this._host)}return t}_prepareRenderingData(e){if(this._effectiveBarOffset=0,this._renderLeft=this._currentMeasure.left,this._renderTop=this._currentMeasure.top,this._renderWidth=this._currentMeasure.width,this._renderHeight=this._currentMeasure.height,this._backgroundBoxLength=Math.max(this._currentMeasure.width,this._currentMeasure.height),this._backgroundBoxThickness=Math.min(this._currentMeasure.width,this._currentMeasure.height),this._effectiveThumbThickness=this._getThumbThickness(e),this.displayThumb&&(this._backgroundBoxLength-=this._effectiveThumbThickness),this.isVertical&&this._currentMeasure.height=this._selectors.length))return this._selectors[e]}removeSelector(e){e<0||e>=this._selectors.length||(this._groupPanel.removeControl(this._selectors[e]),this._selectors.splice(e,1))}}class Hte extends LQ{addCheckbox(e,t=s=>{},i=!1){i=i||!1;const s=new BI;s.width="20px",s.height="20px",s.color="#364249",s.background="#CCCCCC",s.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,s.onIsCheckedChangedObservable.add(function(n){t(n)});const r=zt.AddHeader(s,e,"200px",{isHorizontal:!0,controlFirst:!0});r.height="30px",r.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,r.left="4px",this.groupPanel.addControl(r),this.selectors.push(r),s.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(s.color=this.groupPanel.parent.parent.buttonColor,s.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class f1e extends LQ{constructor(){super(...arguments),this._selectNb=0}addRadio(e,t=s=>{},i=!1){const s=this._selectNb++,r=new uT;r.name=e,r.width="20px",r.height="20px",r.color="#364249",r.background="#CCCCCC",r.group=this.name,r.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,r.onIsCheckedChangedObservable.add(function(o){o&&t(s)});const n=zt.AddHeader(r,e,"200px",{isHorizontal:!0,controlFirst:!0});n.height="30px",n.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,n.left="4px",this.groupPanel.addControl(n),this.selectors.push(n),r.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(r.color=this.groupPanel.parent.parent.buttonColor,r.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class FN extends LQ{addSlider(e,t=l=>{},i="Units",s=0,r=0,n=0,o=l=>l|0){const l=new nR;l.name=i,l.value=n,l.minimum=s,l.maximum=r,l.width=.9,l.height="20px",l.color="#364249",l.background="#CCCCCC",l.borderColor="black",l.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,l.left="4px",l.paddingBottom="4px",l.onValueChangedObservable.add(function(h){l.parent.children[0].text=l.parent.children[0].name+": "+o(h)+" "+l.name,t(h)});const c=zt.AddHeader(l,e+": "+o(n)+" "+i,"30px",{isHorizontal:!1,controlFirst:!1});c.height="60px",c.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,c.left="4px",c.children[0].name=e,this.groupPanel.addControl(c),this.selectors.push(c),this.groupPanel.parent&&this.groupPanel.parent.parent&&(l.color=this.groupPanel.parent.parent.buttonColor,l.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[0].name=t,this.selectors[e].children[0].text=t+": "+this.selectors[e].children[1].value+" "+this.selectors[e].children[1].name}_setSelectorLabelColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[1].background=t}}class jte extends Uu{constructor(e,t=[]){if(super(e),this.name=e,this.groups=t,this._buttonColor="#364249",this._buttonBackground="#CCCCCC",this._headerColor="black",this._barColor="white",this._barHeight="2px",this._spacerHeight="20px",this._bars=new Array,this._groups=t,this.thickness=2,this._panel=new Z2,this._panel.verticalAlignment=zt.VERTICAL_ALIGNMENT_TOP,this._panel.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,this._panel.top=5,this._panel.left=5,this._panel.width=.95,t.length>0){for(let i=0;i0&&this._addSpacer(),this._panel.addControl(e.groupPanel),this._groups.push(e),e.groupPanel.children[0].color=this._headerColor;for(let t=0;t=this._groups.length)return;const t=this._groups[e];this._panel.removeControl(t.groupPanel),this._groups.splice(e,1),e=this._groups.length)return;const i=this._groups[t];i.groupPanel.children[0].text=e}relabel(e,t,i){if(t<0||t>=this._groups.length)return;const s=this._groups[t];i<0||i>=s.selectors.length||s._setSelectorLabel(i,e)}removeFromGroupSelector(e,t){if(e<0||e>=this._groups.length)return;const i=this._groups[e];t<0||t>=i.selectors.length||i.removeSelector(t)}addToGroupCheckbox(e,t,i=()=>{},s=!1){if(e<0||e>=this._groups.length)return;this._groups[e].addCheckbox(t,i,s)}addToGroupRadio(e,t,i=()=>{},s=!1){if(e<0||e>=this._groups.length)return;this._groups[e].addRadio(t,i,s)}addToGroupSlider(e,t,i=()=>{},s="Units",r=0,n=0,o=0,l=c=>c|0){if(e<0||e>=this._groups.length)return;this._groups[e].addSlider(t,i,s,r,n,o,l)}}class HTe extends Z1{get freezeControls(){return this._freezeControls}set freezeControls(e){if(this._freezeControls===e)return;e||this._restoreMeasures(),this._freezeControls=!1;const t=this.host.getSize(),i=t.width,s=t.height,r=this.host.getContext(),n=new ru(0,0,i,s);this.host._numLayoutCalls=0,this.host._rootContainer._layout(n,r),e&&(this._updateMeasures(),this._useBuckets()&&this._makeBuckets()),this._freezeControls=e,this.host.markAsDirty()}get bucketWidth(){return this._bucketWidth}get bucketHeight(){return this._bucketHeight}setBucketSizes(e,t){this._bucketWidth=e,this._bucketHeight=t,this._useBuckets()?this._freezeControls&&this._makeBuckets():this._buckets={}}_useBuckets(){return this._bucketWidth>0&&this._bucketHeight>0}_makeBuckets(){this._buckets={},this._bucketLen=Math.ceil(this.widthInPixels/this._bucketWidth),this._dispatchInBuckets(this._children),this._oldLeft=null,this._oldTop=null}_dispatchInBuckets(e){for(let t=0;t0&&this._dispatchInBuckets(i._children)}}_updateMeasures(){const e=this.leftInPixels|0,t=this.topInPixels|0;this._measureForChildren.left-=e,this._measureForChildren.top-=t,this._currentMeasure.left-=e,this._currentMeasure.top-=t,this._customData.origLeftForChildren=this._measureForChildren.left,this._customData.origTopForChildren=this._measureForChildren.top,this._customData.origLeft=this._currentMeasure.left,this._customData.origTop=this._currentMeasure.top,this._updateChildrenMeasures(this._children,e,t)}_updateChildrenMeasures(e,t,i){for(let s=0;s0&&this._updateChildrenMeasures(r._children,t,i)}}_restoreMeasures(){const e=this.leftInPixels|0,t=this.topInPixels|0;this._measureForChildren.left=this._customData.origLeftForChildren+e,this._measureForChildren.top=this._customData.origTopForChildren+t,this._currentMeasure.left=this._customData.origLeft+e,this._currentMeasure.top=this._customData.origTop+t}constructor(e){super(e),this._freezeControls=!1,this._bucketWidth=0,this._bucketHeight=0,this._buckets={}}_getTypeName(){return"ScrollViewerWindow"}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._parentMeasure=e,this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this._measureForChildren.width=e.width,this._measureForChildren.height=e.height}_layout(e,t){return this._freezeControls?(this.invalidateRect(),!1):super._layout(e,t)}_scrollChildren(e,t,i){for(let s=0;s0&&this._scrollChildren(r._children,t,i)}}_scrollChildrenWithBuckets(e,t,i,s){const r=Math.max(0,Math.floor(-e/this._bucketWidth)),n=Math.floor((-e+this._parentMeasure.width-1)/this._bucketWidth),o=Math.floor((-t+this._parentMeasure.height-1)/this._bucketHeight);let l=Math.max(0,Math.floor(-t/this._bucketHeight));for(;l<=o;){for(let c=r;c<=n;++c){const h=l*this._bucketLen+c,u=this._buckets[h];if(u)for(let p=0;pthis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let s=0;this.isVertical?s=-((t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness)):s=(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*s*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,s,r){return this._first=!0,super._onPointerDown(e,t,i,s,r)}serialize(e){super.serialize(e),this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient))}_parseFromContent(e,t){if(super._parseFromContent(e,t),e.backgroundGradient){const i=Be.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this.backgroundGradient=new i,this.backgroundGradient.parse(e.backgroundGradient)}}}z([X()],iD.prototype,"borderColor",null);z([X()],iD.prototype,"background",null);z([X()],iD.prototype,"invertScrollDirection",null);$e("BABYLON.GUI.Scrollbar",iD);class oG extends I_{get invertScrollDirection(){return this._invertScrollDirection}set invertScrollDirection(e){this._invertScrollDirection=e}get backgroundImage(){return this._backgroundBaseImage}set backgroundImage(e){this._backgroundBaseImage!==e&&(this._backgroundBaseImage=e,this.isVertical&&this.num90RotationInVerticalMode!==0?e.isLoaded?(this._backgroundImage=e._rotate90(this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce(()=>{const t=e._rotate90(this.num90RotationInVerticalMode,!0);this._backgroundImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce(()=>{this._markAsDirty()}),this._markAsDirty()}):(this._backgroundImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce(()=>{this._markAsDirty()}),this._markAsDirty()))}get thumbImage(){return this._thumbBaseImage}set thumbImage(e){this._thumbBaseImage!==e&&(this._thumbBaseImage=e,this.isVertical&&this.num90RotationInVerticalMode!==0?e.isLoaded?(this._thumbImage=e._rotate90(-this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce(()=>{const t=e._rotate90(-this.num90RotationInVerticalMode,!0);this._thumbImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce(()=>{this._markAsDirty()}),this._markAsDirty()}):(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce(()=>{this._markAsDirty()}),this._markAsDirty()))}get thumbLength(){return this._thumbLength}set thumbLength(e){this._thumbLength!==e&&(this._thumbLength=e,this._markAsDirty())}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){this._thumbLength!==e&&(this._thumbHeight=e,this._markAsDirty())}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){this._barImageHeight!==e&&(this._barImageHeight=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._tempMeasure=new ru(0,0,0,0),this._invertScrollDirection=!1,this.num90RotationInVerticalMode=1}_getTypeName(){return"ImageScrollBar"}_getThumbThickness(){let e=0;return this._thumbWidth.isPixel?e=this._thumbWidth.getValue(this._host):e=this._backgroundBoxThickness*this._thumbWidth.getValue(this._host),e}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,s=this._renderTop,r=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,s,r,n),this.isVertical?(this._tempMeasure.copyFromFloats(i+r*(1-this._barImageHeight)*.5,this._currentMeasure.top,r*this._barImageHeight,n),this._tempMeasure.height+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)):(this._tempMeasure.copyFromFloats(this._currentMeasure.left,s+n*(1-this._barImageHeight)*.5,r,n*this._barImageHeight),this._tempMeasure.width+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)),this._backgroundImage._draw(e)),this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset+this._currentMeasure.width*(1-this._thumbHeight)*.5,this._currentMeasure.top+t,this._currentMeasure.width*this._thumbHeight,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top+this._currentMeasure.height*(1-this._thumbHeight)*.5,this._effectiveThumbThickness,this._currentMeasure.height*this._thumbHeight),this._thumbImage&&(this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}_updateValueFromPointer(e,t){this.rotation!=0&&(this._invertTransformMatrix.transformCoordinates(e,t,this._transformedPosition),e=this._transformedPosition.x,t=this._transformedPosition.y);const i=this._invertScrollDirection?-1:1;this._first&&(this._first=!1,this._originX=e,this._originY=t,(ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let s=0;this.isVertical?s=-((t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness)):s=(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*s*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,s,r){return this._first=!0,super._onPointerDown(e,t,i,s,r)}}z([X()],oG.prototype,"num90RotationInVerticalMode",void 0);z([X()],oG.prototype,"invertScrollDirection",null);class vD extends Uu{get horizontalBar(){return this._horizontalBar}get verticalBar(){return this._verticalBar}addControl(e){return e?(this._window.addControl(e),this):this}removeControl(e){return this._window.removeControl(e),this}get children(){return this._window.children}_flagDescendantsAsMatrixDirty(){for(const e of this._children)e._markMatrixAsDirty()}get freezeControls(){return this._window.freezeControls}set freezeControls(e){this._window.freezeControls=e}get bucketWidth(){return this._window.bucketWidth}get bucketHeight(){return this._window.bucketHeight}setBucketSizes(e,t){this._window.setBucketSizes(e,t)}get forceHorizontalBar(){return this._forceHorizontalBar}set forceHorizontalBar(e){this._grid.setRowDefinition(1,e?this._barSize:0,!0),this._horizontalBar.isVisible=e,this._forceHorizontalBar=e}get forceVerticalBar(){return this._forceVerticalBar}set forceVerticalBar(e){this._grid.setColumnDefinition(1,e?this._barSize:0,!0),this._verticalBar.isVisible=e,this._forceVerticalBar=e}constructor(e,t){super(e),this._barSize=20,this._pointerIsOver=!1,this._wheelPrecision=.05,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._horizontalBarImageHeight=1,this._verticalBarImageHeight=1,this._oldWindowContentsWidth=0,this._oldWindowContentsHeight=0,this._forceHorizontalBar=!1,this._forceVerticalBar=!1,this._useImageBar=t||!1,this.onDirtyObservable.add(()=>{this._horizontalBarSpace.color=this.color,this._verticalBarSpace.color=this.color,this._dragSpace.color=this.color}),this.onPointerEnterObservable.add(()=>{this._pointerIsOver=!0}),this.onPointerOutObservable.add(()=>{this._pointerIsOver=!1}),this._grid=new N2,this._useImageBar?(this._horizontalBar=new oG,this._verticalBar=new oG):(this._horizontalBar=new iD,this._verticalBar=new iD),this._window=new HTe("scrollViewer_window"),this._window.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,this._window.verticalAlignment=zt.VERTICAL_ALIGNMENT_TOP,this._grid.addColumnDefinition(1),this._grid.addColumnDefinition(0,!0),this._grid.addRowDefinition(1),this._grid.addRowDefinition(0,!0),super.addControl(this._grid),this._grid.addControl(this._window,0,0),this._verticalBarSpace=new Uu,this._verticalBarSpace.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,this._verticalBarSpace.verticalAlignment=zt.VERTICAL_ALIGNMENT_TOP,this._verticalBarSpace.thickness=1,this._grid.addControl(this._verticalBarSpace,0,1),this._addBar(this._verticalBar,this._verticalBarSpace,!0,Math.PI),this._horizontalBarSpace=new Uu,this._horizontalBarSpace.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,this._horizontalBarSpace.verticalAlignment=zt.VERTICAL_ALIGNMENT_TOP,this._horizontalBarSpace.thickness=1,this._grid.addControl(this._horizontalBarSpace,1,0),this._addBar(this._horizontalBar,this._horizontalBarSpace,!1,0),this._dragSpace=new Uu,this._dragSpace.thickness=1,this._grid.addControl(this._dragSpace,1,1),this._useImageBar||(this.barColor="grey",this.barBackground="transparent")}resetWindow(){this._window.width="100%",this._window.height="100%"}_getTypeName(){return"ScrollViewer"}_buildClientSizes(){const e=this.host.idealRatio;this._window.parentClientWidth=this._currentMeasure.width-(this._verticalBar.isVisible||this.forceVerticalBar?this._barSize*e:0)-2*this.thickness,this._window.parentClientHeight=this._currentMeasure.height-(this._horizontalBar.isVisible||this.forceHorizontalBar?this._barSize*e:0)-2*this.thickness,this._clientWidth=this._window.parentClientWidth,this._clientHeight=this._window.parentClientHeight}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._buildClientSizes()}_postMeasure(){super._postMeasure(),this._updateScroller(),this._setWindowPosition(!1)}get wheelPrecision(){return this._wheelPrecision}set wheelPrecision(e){this._wheelPrecision!==e&&(e<0&&(e=0),e>1&&(e=1),this._wheelPrecision=e)}get scrollBackground(){return this._horizontalBarSpace.background}set scrollBackground(e){this._horizontalBarSpace.background!==e&&(this._horizontalBarSpace.background=e,this._verticalBarSpace.background=e)}get barColor(){return this._barColor}set barColor(e){this._barColor!==e&&(this._barColor=e,this._horizontalBar.color=e,this._verticalBar.color=e)}get thumbImage(){return this._barImage}set thumbImage(e){if(this._barImage===e)return;this._barImage=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbImage=e,i.thumbImage=e}get horizontalThumbImage(){return this._horizontalBarImage}set horizontalThumbImage(e){if(this._horizontalBarImage===e)return;this._horizontalBarImage=e;const t=this._horizontalBar;t.thumbImage=e}get verticalThumbImage(){return this._verticalBarImage}set verticalThumbImage(e){if(this._verticalBarImage===e)return;this._verticalBarImage=e;const t=this._verticalBar;t.thumbImage=e}get barSize(){return this._barSize}set barSize(e){this._barSize!==e&&(this._barSize=e,this._markAsDirty(),this._horizontalBar.isVisible&&this._grid.setRowDefinition(1,this._barSize,!0),this._verticalBar.isVisible&&this._grid.setColumnDefinition(1,this._barSize,!0))}get thumbLength(){return this._thumbLength}set thumbLength(e){if(this._thumbLength===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbLength=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbLength=e,i.thumbLength=e,this._markAsDirty()}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){if(this._thumbHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbHeight=e,i.thumbHeight=e,this._markAsDirty()}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){if(this._barImageHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._barImageHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.barImageHeight=e,i.barImageHeight=e,this._markAsDirty()}get horizontalBarImageHeight(){return this._horizontalBarImageHeight}set horizontalBarImageHeight(e){if(this._horizontalBarImageHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._horizontalBarImageHeight=e;const t=this._horizontalBar;t.barImageHeight=e,this._markAsDirty()}get verticalBarImageHeight(){return this._verticalBarImageHeight}set verticalBarImageHeight(e){if(this._verticalBarImageHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._verticalBarImageHeight=e;const t=this._verticalBar;t.barImageHeight=e,this._markAsDirty()}get barBackground(){return this._barBackground}set barBackground(e){if(this._barBackground===e)return;this._barBackground=e;const t=this._horizontalBar,i=this._verticalBar;t.background=e,i.background=e,this._dragSpace.background=e}get barImage(){return this._barBackgroundImage}set barImage(e){this._barBackgroundImage=e;const t=this._horizontalBar,i=this._verticalBar;t.backgroundImage=e,i.backgroundImage=e}get horizontalBarImage(){return this._horizontalBarBackgroundImage}set horizontalBarImage(e){this._horizontalBarBackgroundImage=e;const t=this._horizontalBar;t.backgroundImage=e}get verticalBarImage(){return this._verticalBarBackgroundImage}set verticalBarImage(e){this._verticalBarBackgroundImage=e;const t=this._verticalBar;t.backgroundImage=e}_setWindowPosition(e=!0){const t=this.host.idealRatio,i=this._window._currentMeasure.width,s=this._window._currentMeasure.height;if(!e&&this._oldWindowContentsWidth===i&&this._oldWindowContentsHeight===s)return;this._oldWindowContentsWidth=i,this._oldWindowContentsHeight=s;const r=this._clientWidth-i,n=this._clientHeight-s,o=this._horizontalBar.value/t*r+"px",l=this._verticalBar.value/t*n+"px";o!==this._window.left&&(this._window.left=o,this.freezeControls||(this._rebuildLayout=!0)),l!==this._window.top&&(this._window.top=l,this.freezeControls||(this._rebuildLayout=!0))}_updateScroller(){const e=this._window._currentMeasure.width,t=this._window._currentMeasure.height;this._horizontalBar.isVisible&&e<=this._clientWidth&&!this.forceHorizontalBar?(this._grid.setRowDefinition(1,0,!0),this._horizontalBar.isVisible=!1,this._horizontalBar.value=0,this._rebuildLayout=!0):!this._horizontalBar.isVisible&&(e>this._clientWidth||this.forceHorizontalBar)&&(this._grid.setRowDefinition(1,this._barSize,!0),this._horizontalBar.isVisible=!0,this._rebuildLayout=!0),this._verticalBar.isVisible&&t<=this._clientHeight&&!this.forceVerticalBar?(this._grid.setColumnDefinition(1,0,!0),this._verticalBar.isVisible=!1,this._verticalBar.value=0,this._rebuildLayout=!0):!this._verticalBar.isVisible&&(t>this._clientHeight||this.forceVerticalBar)&&(this._grid.setColumnDefinition(1,this._barSize,!0),this._verticalBar.isVisible=!0,this._rebuildLayout=!0),this._buildClientSizes();const i=this.host.idealRatio;this._horizontalBar.thumbWidth=this._thumbLength*.9*(this._clientWidth/i)+"px",this._verticalBar.thumbWidth=this._thumbLength*.9*(this._clientHeight/i)+"px"}_link(e){super._link(e),this._attachWheel()}_addBar(e,t,i,s){e.paddingLeft=0,e.width="100%",e.height="100%",e.barOffset=0,e.value=0,e.maximum=1,e.horizontalAlignment=zt.HORIZONTAL_ALIGNMENT_CENTER,e.verticalAlignment=zt.VERTICAL_ALIGNMENT_CENTER,e.isVertical=i,e.rotation=s,e.isVisible=!1,t.addControl(e),e.onValueChangedObservable.add(()=>{this._setWindowPosition()})}_attachWheel(){!this._host||this._onWheelObserver||(this._onWheelObserver=this.onWheelObservable.add(e=>{!this._pointerIsOver||this.isReadOnly||(this._verticalBar.isVisible==!0&&(e.y<0&&this._verticalBar.value>0?this._verticalBar.value-=this._wheelPrecision:e.y>0&&this._verticalBar.value0&&this._horizontalBar.value>0&&(this._horizontalBar.value-=this._wheelPrecision)))}))}_renderHighlightSpecific(e){!this.isHighlighted||(super._renderHighlightSpecific(e),this._grid._renderHighlightSpecific(e),e.restore())}dispose(){this.onWheelObservable.remove(this._onWheelObserver),this._onWheelObserver=null,super.dispose()}}z([X()],vD.prototype,"wheelPrecision",null);z([X()],vD.prototype,"scrollBackground",null);z([X()],vD.prototype,"barColor",null);z([X()],vD.prototype,"barSize",null);z([X()],vD.prototype,"barBackground",null);$e("BABYLON.GUI.ScrollViewer",vD);class p1e extends Uu{get group(){return this._group}set group(e){this._group!==e&&(this._group=e)}get isActive(){return this._isActive}set isActive(e){var t,i;this._isActive!==e&&(this._isActive=e,this._isActive?(t=this.toActiveAnimation)===null||t===void 0||t.call(this):(i=this.toInactiveAnimation)===null||i===void 0||i.call(this),this._markAsDirty(),this.onIsActiveChangedObservable.notifyObservers(e),this._isActive&&this._host&&this._group&&this._host.executeOnAllControls(s=>{if(s.typeName==="ToggleButton"){if(s===this)return;const r=s;r.group===this.group&&(r.isActive=!1)}}))}constructor(e,t){super(e),this.name=e,this.onIsActiveChangedObservable=new Se,this.delegatePickingToChildren=!1,this._isActive=!1,this.group=t??"",this.thickness=0,this.isPointerBlocker=!0;let i=null;this.toActiveAnimation=()=>{this.thickness=1},this.toInactiveAnimation=()=>{this.thickness=0},this.pointerEnterActiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutActiveAnimation=()=>{i!==null&&(this.alpha=i)},this.pointerDownActiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpActiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05},this.pointerEnterInactiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutInactiveAnimation=()=>{i!==null&&(this.alpha=i)},this.pointerDownInactiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpInactiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"ToggleButton"}_processPicking(e,t,i,s,r,n,o,l){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable||!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let c=!1;for(let h=this._children.length-1;h>=0;h--){const u=this._children[h];if(u.isEnabled&&u.isHitTestVisible&&u.isVisible&&!u.notRenderable&&u.contains(e,t)){c=!0;break}}if(!c)return!1}return this._processObservables(s,e,t,i,r,n,o,l),!0}_onPointerEnter(e,t){return super._onPointerEnter(e,t)?(this.isReadOnly||(this._isActive?this.pointerEnterActiveAnimation&&this.pointerEnterActiveAnimation():this.pointerEnterInactiveAnimation&&this.pointerEnterInactiveAnimation()),!0):!1}_onPointerOut(e,t,i=!1){this.isReadOnly||(this._isActive?this.pointerOutActiveAnimation&&this.pointerOutActiveAnimation():this.pointerOutInactiveAnimation&&this.pointerOutInactiveAnimation()),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return super._onPointerDown(e,t,i,s,r)?(this.isReadOnly||(this._isActive?this.pointerDownActiveAnimation&&this.pointerDownActiveAnimation():this.pointerDownInactiveAnimation&&this.pointerDownInactiveAnimation()),!0):!1}_onPointerUp(e,t,i,s,r,n){this.isReadOnly||(this._isActive?this.pointerUpActiveAnimation&&this.pointerUpActiveAnimation():this.pointerUpInactiveAnimation&&this.pointerUpInactiveAnimation()),super._onPointerUp(e,t,i,s,r,n)}}$e("BABYLON.GUI.ToggleButton",p1e);class jTe{}class RQ extends Z2{constructor(){super(...arguments),this.onKeyPressObservable=new Se,this.defaultButtonWidth="40px",this.defaultButtonHeight="40px",this.defaultButtonPaddingLeft="2px",this.defaultButtonPaddingRight="2px",this.defaultButtonPaddingTop="2px",this.defaultButtonPaddingBottom="2px",this.defaultButtonColor="#DDD",this.defaultButtonBackground="#070707",this.shiftButtonColor="#7799FF",this.selectedShiftThickness=1,this.shiftState=0,this._currentlyConnectedInputText=null,this._connectedInputTexts=[],this._onKeyPressObserver=null}_getTypeName(){return"VirtualKeyboard"}_createKey(e,t){const i=Bb.CreateSimpleButton(e,e);return i.width=t&&t.width?t.width:this.defaultButtonWidth,i.height=t&&t.height?t.height:this.defaultButtonHeight,i.color=t&&t.color?t.color:this.defaultButtonColor,i.background=t&&t.background?t.background:this.defaultButtonBackground,i.paddingLeft=t&&t.paddingLeft?t.paddingLeft:this.defaultButtonPaddingLeft,i.paddingRight=t&&t.paddingRight?t.paddingRight:this.defaultButtonPaddingRight,i.paddingTop=t&&t.paddingTop?t.paddingTop:this.defaultButtonPaddingTop,i.paddingBottom=t&&t.paddingBottom?t.paddingBottom:this.defaultButtonPaddingBottom,i.thickness=0,i.isFocusInvisible=!0,i.shadowColor=this.shadowColor,i.shadowBlur=this.shadowBlur,i.shadowOffsetX=this.shadowOffsetX,i.shadowOffsetY=this.shadowOffsetY,i.onPointerUpObservable.add(()=>{this.onKeyPressObservable.notifyObservers(e)}),i}addKeysRow(e,t){const i=new Z2;i.isVertical=!1,i.isFocusInvisible=!0;let s=null;for(let r=0;rs.heightInPixels)&&(s=o),i.addControl(o)}i.height=s?s.height:this.defaultButtonHeight,this.addControl(i)}applyShiftState(e){if(!!this.children)for(let t=0;t1?this.selectedShiftThickness:0),o.text=e>0?o.text.toUpperCase():o.text.toLowerCase()}}}get connectedInputText(){return this._currentlyConnectedInputText}connect(e){if(this._connectedInputTexts.some(r=>r.input===e))return;this._onKeyPressObserver===null&&(this._onKeyPressObserver=this.onKeyPressObservable.add(r=>{if(!!this._currentlyConnectedInputText){switch(this._currentlyConnectedInputText._host.focusedControl=this._currentlyConnectedInputText,r){case"\u21E7":this.shiftState++,this.shiftState>2&&(this.shiftState=0),this.applyShiftState(this.shiftState);return;case"\u2190":this._currentlyConnectedInputText instanceof wP?this._currentlyConnectedInputText.alternativeProcessKey("Backspace"):this._currentlyConnectedInputText.processKey(8);return;case"\u21B5":this._currentlyConnectedInputText instanceof wP?this._currentlyConnectedInputText.alternativeProcessKey("Enter"):this._currentlyConnectedInputText.processKey(13);return}this._currentlyConnectedInputText instanceof wP?this._currentlyConnectedInputText.alternativeProcessKey("",this.shiftState?r.toUpperCase():r):this._currentlyConnectedInputText.processKey(-1,this.shiftState?r.toUpperCase():r),this.shiftState===1&&(this.shiftState=0,this.applyShiftState(this.shiftState))}})),this.isVisible=!1,this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this;const i=e.onFocusObservable.add(()=>{this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this,this.isVisible=!0}),s=e.onBlurObservable.add(()=>{e._connectedVirtualKeyboard=null,this._currentlyConnectedInputText=null,this.isVisible=!1});this._connectedInputTexts.push({input:e,onBlurObserver:s,onFocusObserver:i})}disconnect(e){if(e){const t=this._connectedInputTexts.filter(i=>i.input===e);t.length===1&&(this._removeConnectedInputObservables(t[0]),this._connectedInputTexts=this._connectedInputTexts.filter(i=>i.input!==e),this._currentlyConnectedInputText===e&&(this._currentlyConnectedInputText=null))}else this._connectedInputTexts.forEach(t=>{this._removeConnectedInputObservables(t)}),this._connectedInputTexts.length=0;this._connectedInputTexts.length===0&&(this._currentlyConnectedInputText=null,this.onKeyPressObservable.remove(this._onKeyPressObserver),this._onKeyPressObserver=null)}_removeConnectedInputObservables(e){e.input._connectedVirtualKeyboard=null,e.input.onFocusObservable.remove(e.onFocusObserver),e.input.onBlurObservable.remove(e.onBlurObserver)}dispose(){super.dispose(),this.disconnect()}static CreateDefaultLayout(e){const t=new RQ(e);return t.addKeysRow(["1","2","3","4","5","6","7","8","9","0","\u2190"]),t.addKeysRow(["q","w","e","r","t","y","u","i","o","p"]),t.addKeysRow(["a","s","d","f","g","h","j","k","l",";","'","\u21B5"]),t.addKeysRow(["\u21E7","z","x","c","v","b","n","m",",",".","/"]),t.addKeysRow([" "],[{width:"200px"}]),t}_parseFromContent(e,t){super._parseFromContent(e,t);for(const i of this.children)if(i.getClassName()==="StackPanel"){const s=i;for(const r of s.children)r.getClassName()==="Button"&&r.name&&r.onPointerUpObservable.add(()=>{this.onKeyPressObservable.notifyObservers(r.name)})}}}$e("BABYLON.GUI.VirtualKeyboard",RQ);class gC extends zt{get displayMinorLines(){return this._displayMinorLines}set displayMinorLines(e){this._displayMinorLines!==e&&(this._displayMinorLines=e,this._markAsDirty())}get displayMajorLines(){return this._displayMajorLines}set displayMajorLines(e){this._displayMajorLines!==e&&(this._displayMajorLines=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth=e,this._markAsDirty()}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight=e,this._markAsDirty()}get minorLineTickness(){return this._minorLineTickness}set minorLineTickness(e){this._minorLineTickness=e,this._markAsDirty()}get minorLineColor(){return this._minorLineColor}set minorLineColor(e){this._minorLineColor=e,this._markAsDirty()}get majorLineTickness(){return this._majorLineTickness}set majorLineTickness(e){this._majorLineTickness=e,this._markAsDirty()}get majorLineColor(){return this._majorLineColor}set majorLineColor(e){this._majorLineColor=e,this._markAsDirty()}get majorLineFrequency(){return this._majorLineFrequency}set majorLineFrequency(e){this._majorLineFrequency=e,this._markAsDirty()}constructor(e){super(e),this.name=e,this._cellWidth=20,this._cellHeight=20,this._minorLineTickness=1,this._minorLineColor="DarkGray",this._majorLineTickness=2,this._majorLineColor="White",this._majorLineFrequency=5,this._background="Black",this._displayMajorLines=!0,this._displayMinorLines=!0}_draw(e){if(e.save(),this._applyStates(e),this._isEnabled){this._background&&(e.fillStyle=this._background,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height));const t=this._currentMeasure.width/this._cellWidth,i=this._currentMeasure.height/this._cellHeight,s=this._currentMeasure.left+this._currentMeasure.width/2,r=this._currentMeasure.top+this._currentMeasure.height/2;if(this._displayMinorLines){e.strokeStyle=this._minorLineColor,e.lineWidth=this._minorLineTickness;for(let n=-t/2+1;nthis._markAsDirty()),this._markAsDirty())}get valueBarImage(){return this._valueBarImage}set valueBarImage(e){this._valueBarImage!==e&&(this._valueBarImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce(()=>this._markAsDirty()),this._markAsDirty())}get thumbImage(){return this._thumbImage}set thumbImage(e){this._thumbImage!==e&&(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce(()=>this._markAsDirty()),this._markAsDirty())}constructor(e){super(e),this.name=e,this._tempMeasure=new ru(0,0,0,0)}_getTypeName(){return"ImageBasedSlider"}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,s=this._renderTop,r=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,s,r,n),this.isThumbClamped&&this.displayThumb&&(this.isVertical?this._tempMeasure.height+=this._effectiveThumbThickness:this._tempMeasure.width+=this._effectiveThumbThickness),this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure),this._backgroundImage._draw(e)),this._valueBarImage&&(this.isVertical?this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,s+t,r,n-t+this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(i,s+t,r,n-t):this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,s,t+this._effectiveThumbThickness/2,n):this._tempMeasure.copyFromFloats(i,s,t,n),this._valueBarImage._currentMeasure.copyFrom(this._tempMeasure),this._valueBarImage._draw(e)),this.displayThumb&&(this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset,this._currentMeasure.top+t,this._currentMeasure.width,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top,this._effectiveThumbThickness,this._currentMeasure.height),this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}serialize(e){super.serialize(e);const t={},i={},s={};this.backgroundImage.serialize(t),this.thumbImage.serialize(i),this.valueBarImage.serialize(s),e.backgroundImage=t,e.thumbImage=i,e.valueBarImage=s}_parseFromContent(e,t){super._parseFromContent(e,t),this.backgroundImage=wr.Parse(e.backgroundImage,t),this.thumbImage=wr.Parse(e.thumbImage,t),this.valueBarImage=wr.Parse(e.valueBarImage,t)}}z([X()],Gte.prototype,"displayThumb",null);$e("BABYLON.GUI.ImageBasedSlider",Gte);const GTe="Statics";zt.AddHeader=function(a,e,t,i){const s=new Z2("panel"),r=i?i.isHorizontal:!0,n=i?i.controlFirst:!0;s.isVertical=!r;const o=new Ka("header");return o.text=e,o.textHorizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,r?o.width=t:o.height=t,n?(s.addControl(a),s.addControl(o),o.paddingLeft="5px"):(s.addControl(o),s.addControl(a),o.paddingRight="5px"),o.shadowBlur=a.shadowBlur,o.shadowColor=a.shadowColor,o.shadowOffsetX=a.shadowOffsetX,o.shadowOffsetY=a.shadowOffsetY,s};class Wte{constructor(){this._colorStops=[],this._gradientDirty=!0}_addColorStopsToCanvasGradient(){for(const e of this._colorStops)this._canvasGradient.addColorStop(e.offset,e.color)}getCanvasGradient(e){return(this._gradientDirty||this._context!==e)&&(this._context=e,this._canvasGradient=this._createCanvasGradient(e),this._addColorStopsToCanvasGradient(),this._gradientDirty=!1),this._canvasGradient}addColorStop(e,t){this._colorStops.push({offset:e,color:t}),this._gradientDirty=!0}removeColorStop(e){this._colorStops=this._colorStops.filter(t=>t.offset!==e),this._gradientDirty=!0}clearColorStops(){this._colorStops=[],this._gradientDirty=!0}get colorStops(){return this._colorStops}getClassName(){return"BaseGradient"}serialize(e){e.colorStops=this._colorStops,e.className=this.getClassName()}parse(e){this._colorStops=e.colorStops}}class m1e extends Wte{constructor(e,t,i,s){super(),this._x0=e??0,this._y0=t??0,this._x1=i??0,this._y1=s??0}_createCanvasGradient(e){return e.createLinearGradient(this._x0,this._y0,this._x1,this._y1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}getClassName(){return"LinearGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.x1=this._x1,e.y1=this._y1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._x1=e.x1,this._y1=e.y1}}$e("BABYLON.GUI.LinearGradient",m1e);class _1e extends Wte{constructor(e,t,i,s,r,n){super(),this._x0=e??0,this._y0=t??0,this._r0=i??0,this._x1=s??0,this._y1=r??0,this._r1=n??0}_createCanvasGradient(e){return e.createRadialGradient(this._x0,this._y0,this._r0,this._x1,this._y1,this._r1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}get r0(){return this._r0}get r1(){return this._r1}getClassName(){return"RadialGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.r0=this._r0,e.x1=this._x1,e.y1=this._y1,e.r1=this._r1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._r0=e.r0,this._x1=e.x1,this._y1=e.y1,this._r1=e.r1}}$e("BABYLON.GUI.RadialGradient",_1e);class g1e{constructor(e){this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new mr(18,mr.UNITMODE_PIXEL,!1),this.onChangedObservable=new Se,this._host=e}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&this.onChangedObservable.notifyObservers(this)}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.onChangedObservable.notifyObservers(this))}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.onChangedObservable.notifyObservers(this))}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.onChangedObservable.notifyObservers(this))}dispose(){this.onChangedObservable.clear()}}class Sh extends ep{get numLayoutCalls(){return this._numLayoutCalls}get numRenderCalls(){return this._numRenderCalls}get renderScale(){return this._renderScale}set renderScale(e){e!==this._renderScale&&(this._renderScale=e,this._onResize())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this.markAsDirty())}get idealWidth(){return this._idealWidth}set idealWidth(e){this._idealWidth!==e&&(this._idealWidth=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get idealHeight(){return this._idealHeight}set idealHeight(e){this._idealHeight!==e&&(this._idealHeight=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get useSmallestIdeal(){return this._useSmallestIdeal}set useSmallestIdeal(e){this._useSmallestIdeal!==e&&(this._useSmallestIdeal=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get renderAtIdealSize(){return this._renderAtIdealSize}set renderAtIdealSize(e){this._renderAtIdealSize!==e&&(this._renderAtIdealSize=e,this._onResize())}get idealRatio(){let e=0,t=0;return this._idealWidth&&(e=this.getSize().width/this._idealWidth),this._idealHeight&&(t=this.getSize().height/this._idealHeight),this._useSmallestIdeal&&this._idealWidth&&this._idealHeight?window.innerWidtht.typeName===e)}getControlByName(e){return this._getControlByKey("name",e)}_getControlByKey(e,t){return this._rootContainer.getDescendants().find(i=>i[e]===t)||null}get focusedControl(){return this._focusedControl}set focusedControl(e){this._focusedControl!=e&&(this._focusedControl&&this._focusedControl.onBlur(),e&&e.onFocus(),this._focusedControl=e)}get isForeground(){return this.layer?!this.layer.isBackground:!0}set isForeground(e){!this.layer||this.layer.isBackground!==!e&&(this.layer.isBackground=!e)}get clipboardData(){return this._clipboardData}set clipboardData(e){this._clipboardData=e}constructor(e,t=0,i=0,s,r=!1,n=Te.NEAREST_SAMPLINGMODE,o=!0){super(e,{width:t,height:i},s,r,n,it.TEXTUREFORMAT_RGBA,o),this.onGuiReadyObservable=new Se,this._isDirty=!1,this._rootContainer=new Z1("root"),this._lastControlOver={},this._lastControlDown={},this._capturingControl={},this._linkedControls=new Array,this._isFullscreen=!1,this._fullscreenViewport=new hu(0,0,1,1),this._idealWidth=0,this._idealHeight=0,this._useSmallestIdeal=!1,this._renderAtIdealSize=!1,this._blockNextFocusCheck=!1,this._renderScale=1,this._cursorChanged=!1,this._defaultMousePointerId=0,this._rootChildrenHaveChanged=!1,this._capturedPointerIds=new Set,this._numLayoutCalls=0,this._numRenderCalls=0,this._clipboardData="",this.onClipboardObservable=new Se,this.onControlPickedObservable=new Se,this.onBeginLayoutObservable=new Se,this.onEndLayoutObservable=new Se,this.onBeginRenderObservable=new Se,this.onEndRenderObservable=new Se,this.premulAlpha=!1,this.applyYInversionOnUpdate=!0,this.checkPointerEveryFrame=!1,this._useInvalidateRectOptimization=!0,this._invalidatedRectangle=null,this._clearMeasure=new ru(0,0,0,0),this._onClipboardCopy=l=>{const c=l,h=new zY(lv.COPY,c);this.onClipboardObservable.notifyObservers(h),c.preventDefault()},this._onClipboardCut=l=>{const c=l,h=new zY(lv.CUT,c);this.onClipboardObservable.notifyObservers(h),c.preventDefault()},this._onClipboardPaste=l=>{const c=l,h=new zY(lv.PASTE,c);this.onClipboardObservable.notifyObservers(h),c.preventDefault()},this.parseContent=this.parseSerializedObject,s=this.getScene(),!(!s||!this._texture)&&(this.applyYInversionOnUpdate=o,this._rootElement=s.getEngine().getInputElement(),this._renderObserver=s.onBeforeCameraRenderObservable.add(l=>this._checkUpdate(l)),this._controlAddedObserver=this._rootContainer.onControlAddedObservable.add(l=>{l&&(this._rootChildrenHaveChanged=!0)}),this._controlRemovedObserver=this._rootContainer.onControlRemovedObservable.add(l=>{l&&(this._rootChildrenHaveChanged=!0)}),this._preKeyboardObserver=s.onPreKeyboardObservable.add(l=>{!this._focusedControl||(l.type===i7.KEYDOWN&&this._focusedControl.processKeyboard(l.event),l.skipOnPointerObservable=!0)}),this._rootContainer._link(this),this.hasAlpha=!0,(!t||!i)&&(this._resizeObserver=s.getEngine().onResizeObservable.add(()=>this._onResize()),this._onResize()),this._texture.isReady=!0)}getClassName(){return"AdvancedDynamicTexture"}executeOnAllControls(e,t){t||(t=this._rootContainer),e(t);for(const i of t.children){if(i.children){this.executeOnAllControls(e,i);continue}e(i)}}get useInvalidateRectOptimization(){return this._useInvalidateRectOptimization}set useInvalidateRectOptimization(e){this._useInvalidateRectOptimization=e}invalidateRect(e,t,i,s){if(!!this._useInvalidateRectOptimization)if(!this._invalidatedRectangle)this._invalidatedRectangle=new ru(e,t,i-e+1,s-t+1);else{const r=Math.ceil(Math.max(this._invalidatedRectangle.left+this._invalidatedRectangle.width-1,i)),n=Math.ceil(Math.max(this._invalidatedRectangle.top+this._invalidatedRectangle.height-1,s));this._invalidatedRectangle.left=Math.floor(Math.min(this._invalidatedRectangle.left,e)),this._invalidatedRectangle.top=Math.floor(Math.min(this._invalidatedRectangle.top,t)),this._invalidatedRectangle.width=r-this._invalidatedRectangle.left+1,this._invalidatedRectangle.height=n-this._invalidatedRectangle.top+1}}markAsDirty(){this._isDirty=!0}createStyle(){return new g1e(this)}addControl(e){return this._rootContainer.addControl(e),this}removeControl(e){return this._rootContainer.removeControl(e),this}moveToNonOverlappedPosition(e,t=1,i=1){let s;if(Array.isArray(e))s=e;else{const r=this.getDescendants(!0);s=e===void 0?r.filter(n=>n.overlapGroup!==void 0):r.filter(n=>n.overlapGroup===e)}s.forEach(r=>{var n;let o=lt.Zero();const l=new lt(r.centerX,r.centerY);s.forEach(c=>{if(r!==c&&Sh._Overlaps(r,c)){const h=l.subtract(new lt(c.centerX,c.centerY)),u=h.length();u>0&&(o=o.add(h.normalize().scale(i/u)))}}),o.length()>0&&(o=o.normalize().scale(t*((n=r.overlapDeltaMultiplier)!==null&&n!==void 0?n:1)),r.linkOffsetXInPixels+=o.x,r.linkOffsetYInPixels+=o.y)})}dispose(){const e=this.getScene();!e||(this._rootElement=null,e.onBeforeCameraRenderObservable.remove(this._renderObserver),this._resizeObserver&&e.getEngine().onResizeObservable.remove(this._resizeObserver),this._prePointerObserver&&e.onPrePointerObservable.remove(this._prePointerObserver),this._sceneRenderObserver&&e.onBeforeRenderObservable.remove(this._sceneRenderObserver),this._pointerObserver&&e.onPointerObservable.remove(this._pointerObserver),this._preKeyboardObserver&&e.onPreKeyboardObservable.remove(this._preKeyboardObserver),this._canvasPointerOutObserver&&e.getEngine().onCanvasPointerOutObservable.remove(this._canvasPointerOutObserver),this._canvasBlurObserver&&e.getEngine().onCanvasBlurObservable.remove(this._canvasBlurObserver),this._controlAddedObserver&&this._rootContainer.onControlAddedObservable.remove(this._controlAddedObserver),this._controlRemovedObserver&&this._rootContainer.onControlRemovedObservable.remove(this._controlRemovedObserver),this._layerToDispose&&(this._layerToDispose.texture=null,this._layerToDispose.dispose(),this._layerToDispose=null),this._rootContainer.dispose(),this.onClipboardObservable.clear(),this.onControlPickedObservable.clear(),this.onBeginRenderObservable.clear(),this.onEndRenderObservable.clear(),this.onBeginLayoutObservable.clear(),this.onEndLayoutObservable.clear(),this.onGuiReadyObservable.clear(),super.dispose())}_onResize(){const e=this.getScene();if(!e)return;const t=e.getEngine(),i=this.getSize();let s=t.getRenderWidth()*this._renderScale,r=t.getRenderHeight()*this._renderScale;this._renderAtIdealSize&&(this._idealWidth?(r=r*this._idealWidth/s,s=this._idealWidth):this._idealHeight&&(s=s*this._idealHeight/r,r=this._idealHeight)),(i.width!==s||i.height!==r)&&(this.scaleTo(s,r),this.markAsDirty(),(this._idealWidth||this._idealHeight)&&this._rootContainer._markAllAsDirty()),this.invalidateRect(0,0,i.width-1,i.height-1)}_getGlobalViewport(){const e=this.getSize(),t=this._fullscreenViewport.toGlobal(e.width,e.height),i=Math.round(t.width*(1/this.rootContainer.scaleX)),s=Math.round(t.height*(1/this.rootContainer.scaleY));return t.x+=(t.width-i)/2,t.y+=(t.height-s)/2,t.width=i,t.height=s,t}getProjectedPosition(e,t){const i=this.getProjectedPositionWithZ(e,t);return new lt(i.x,i.y)}getProjectedPositionWithZ(e,t){const i=this.getScene();if(!i)return O.Zero();const s=this._getGlobalViewport(),r=O.Project(e,t,i.getTransformMatrix(),s);return new O(r.x,r.y,r.z)}_checkUpdate(e,t){if(!(this._layerToDispose&&(e.layerMask&this._layerToDispose.layerMask)===0)){if(this._isFullscreen&&this._linkedControls.length){const i=this.getScene();if(!i)return;const s=this._getGlobalViewport();for(const r of this._linkedControls){if(!r.isVisible)continue;const n=r._linkedMesh;if(!n||n.isDisposed()){Be.SetImmediate(()=>{r.linkWithMesh(null)});continue}const o=n.getBoundingInfo?n.getBoundingInfo().boundingSphere.center:O.ZeroReadOnly,l=O.Project(o,n.getWorldMatrix(),i.getTransformMatrix(),s);if(l.z<0||l.z>1){r.notRenderable=!0;continue}r.notRenderable=!1,this.useInvalidateRectOptimization&&r.invalidateRect(),r._moveToProjectedPosition(l)}}!this._isDirty&&!this._rootContainer.isDirty||(this._isDirty=!1,this._render(t),t||this.update(this.applyYInversionOnUpdate,this.premulAlpha,Sh.AllowGPUOptimizations))}}_render(e){var t;const i=this.getSize(),s=i.width,r=i.height,n=this.getContext();if(n.font="18px Arial",n.strokeStyle="white",this.onGuiReadyObservable.hasObservers()&&this._checkGuiIsReady(),this._rootChildrenHaveChanged){const l=(t=this.getScene())===null||t===void 0?void 0:t.activeCamera;l&&(this._rootChildrenHaveChanged=!1,this._checkUpdate(l,!0))}this.onBeginLayoutObservable.notifyObservers(this);const o=new ru(0,0,s,r);this._numLayoutCalls=0,this._rootContainer._layout(o,n),this.onEndLayoutObservable.notifyObservers(this),this._isDirty=!1,!e&&(this._invalidatedRectangle?this._clearMeasure.copyFrom(this._invalidatedRectangle):this._clearMeasure.copyFromFloats(0,0,s,r),n.clearRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),this._background&&(n.save(),n.fillStyle=this._background,n.fillRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),n.restore()),this.onBeginRenderObservable.notifyObservers(this),this._numRenderCalls=0,this._rootContainer._render(n,this._invalidatedRectangle),this.onEndRenderObservable.notifyObservers(this),this._invalidatedRectangle=null)}_changeCursor(e){this._rootElement&&(this._rootElement.style.cursor=e,this._cursorChanged=!0)}_registerLastControlDown(e,t){this._lastControlDown[t]=e,this.onControlPickedObservable.notifyObservers(e)}_doPicking(e,t,i,s,r,n,o,l){const c=this.getScene();if(!c)return;const h=c.getEngine(),u=this.getSize();if(this._isFullscreen){const p=c.cameraToUseForPointers||c.activeCamera;if(!p)return;const m=p.viewport;e=e*(u.width/(h.getRenderWidth()*m.width)),t=t*(u.height/(h.getRenderHeight()*m.height))}if(this._capturingControl[r]){this._capturingControl[r].isPointerBlocker&&(this._shouldBlockPointer=!0),this._capturingControl[r]._processObservables(s,e,t,i,r,n);return}this._cursorChanged=!1,this._rootContainer._processPicking(e,t,i,s,r,n,o,l)||(c.doNotHandleCursors||this._changeCursor(""),s===mi.POINTERMOVE&&this._lastControlOver[r]&&(this._lastControlOver[r]._onPointerOut(this._lastControlOver[r],i),delete this._lastControlOver[r])),!this._cursorChanged&&!c.doNotHandleCursors&&this._changeCursor(""),this._manageFocus()}_cleanControlAfterRemovalFromList(e,t){for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;e[i]===t&&delete e[i]}}_cleanControlAfterRemoval(e){this._cleanControlAfterRemovalFromList(this._lastControlDown,e),this._cleanControlAfterRemovalFromList(this._lastControlOver,e)}pick(e,t,i=null){this._isFullscreen&&this._scene&&this._translateToPicking(this._scene,new hu(0,0,0,0),i,e,t)}_translateToPicking(e,t,i,s=e.pointerX,r=e.pointerY){const n=e.cameraToUseForPointers||e.activeCamera,o=e.getEngine(),l=e.cameraToUseForPointers;if(!n)t.x=0,t.y=0,t.width=o.getRenderWidth(),t.height=o.getRenderHeight();else if(n.rigCameras.length){const u=new hu(0,0,1,1);n.rigCameras.forEach(p=>{p.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),u);const m=s/o.getHardwareScalingLevel()-u.x,_=r/o.getHardwareScalingLevel()-(o.getRenderHeight()-u.y-u.height);m<0||_<0||s>u.width||r>u.height||(e.cameraToUseForPointers=p,t.x=u.x,t.y=u.y,t.width=u.width,t.height=u.height)})}else n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),t);const c=s/o.getHardwareScalingLevel()-t.x,h=r/o.getHardwareScalingLevel()-(o.getRenderHeight()-t.y-t.height);if(this._shouldBlockPointer=!1,i){const u=i.event.pointerId||this._defaultMousePointerId;this._doPicking(c,h,i,i.type,u,i.event.button,i.event.deltaX,i.event.deltaY),(this._shouldBlockPointer||this._capturingControl[u])&&(i.skipOnPointerObservable=!0)}else this._doPicking(c,h,null,mi.POINTERMOVE,this._defaultMousePointerId,0);e.cameraToUseForPointers=l}attach(){const e=this.getScene();if(!e)return;const t=new hu(0,0,0,0);this._prePointerObserver=e.onPrePointerObservable.add(i=>{if(!(e.isPointerCaptured(i.event.pointerId)&&i.type===mi.POINTERUP&&!this._capturedPointerIds.has(i.event.pointerId))&&!(i.type!==mi.POINTERMOVE&&i.type!==mi.POINTERUP&&i.type!==mi.POINTERDOWN&&i.type!==mi.POINTERWHEEL)){if(i.type===mi.POINTERMOVE){if(e.isPointerCaptured(i.event.pointerId))return;i.event.pointerId&&(this._defaultMousePointerId=i.event.pointerId)}this._translateToPicking(e,t,i)}}),this._attachPickingToSceneRender(e,()=>this._translateToPicking(e,t,null),!1),this._attachToOnPointerOut(e),this._attachToOnBlur(e)}registerClipboardEvents(){self.addEventListener("copy",this._onClipboardCopy,!1),self.addEventListener("cut",this._onClipboardCut,!1),self.addEventListener("paste",this._onClipboardPaste,!1)}unRegisterClipboardEvents(){self.removeEventListener("copy",this._onClipboardCopy),self.removeEventListener("cut",this._onClipboardCut),self.removeEventListener("paste",this._onClipboardPaste)}_transformUvs(e){const t=this.getTextureMatrix();let i;if(t.isIdentityAs3x2())i=e;else{const s=ue.Matrix[0];t.getRowToRef(0,ue.Vector4[0]),t.getRowToRef(1,ue.Vector4[1]),t.getRowToRef(2,ue.Vector4[2]);const r=ue.Vector4[0],n=ue.Vector4[1],o=ue.Vector4[2];s.setRowFromFloats(0,r.x,r.y,0,0),s.setRowFromFloats(1,n.x,n.y,0,0),s.setRowFromFloats(2,0,0,1,0),s.setRowFromFloats(3,o.x,o.y,0,1),i=ue.Vector2[0],lt.TransformToRef(e,s,i)}if((this.wrapU===Te.WRAP_ADDRESSMODE||this.wrapU===Te.MIRROR_ADDRESSMODE)&&i.x>1){let s=i.x-Math.trunc(i.x);this.wrapU===Te.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2===1&&(s=1-s),i.x=s}if((this.wrapV===Te.WRAP_ADDRESSMODE||this.wrapV===Te.MIRROR_ADDRESSMODE)&&i.y>1){let s=i.y-Math.trunc(i.y);this.wrapV===Te.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2===1&&(s=1-s),i.y=s}return i}attachToMesh(e,t=!0){const i=this.getScene();!i||(this._pointerObserver&&i.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=i.onPointerObservable.add(s=>{if(s.type!==mi.POINTERMOVE&&s.type!==mi.POINTERUP&&s.type!==mi.POINTERDOWN&&s.type!==mi.POINTERWHEEL)return;s.type===mi.POINTERMOVE&&s.event.pointerId&&(this._defaultMousePointerId=s.event.pointerId);const r=s.event.pointerId||this._defaultMousePointerId;if(s.pickInfo&&s.pickInfo.hit&&s.pickInfo.pickedMesh===e){let n=s.pickInfo.getTextureCoordinates();if(n){n=this._transformUvs(n);const o=this.getSize();this._doPicking(n.x*o.width,(this.applyYInversionOnUpdate?1-n.y:n.y)*o.height,s,s.type,r,s.event.button,s.event.deltaX,s.event.deltaY)}}else if(s.type===mi.POINTERUP){if(this._lastControlDown[r]&&this._lastControlDown[r]._forcePointerUp(r),delete this._lastControlDown[r],this.focusedControl){const n=this.focusedControl.keepsFocusWith();let o=!0;if(n)for(const l of n){if(this===l._host)continue;const c=l._host;if(c._lastControlOver[r]&&c._lastControlOver[r].isAscendant(l)){o=!1;break}}o&&(this.focusedControl=null)}}else s.type===mi.POINTERMOVE&&(this._lastControlOver[r]&&this._lastControlOver[r]._onPointerOut(this._lastControlOver[r],s,!0),delete this._lastControlOver[r])}),e.enablePointerMoveEvents=t,this._attachPickingToSceneRender(i,()=>{const s=this._defaultMousePointerId,r=i?.pick(i.pointerX,i.pointerY);if(r&&r.hit&&r.pickedMesh===e){let n=r.getTextureCoordinates();if(n){n=this._transformUvs(n);const o=this.getSize();this._doPicking(n.x*o.width,(this.applyYInversionOnUpdate?1-n.y:n.y)*o.height,null,mi.POINTERMOVE,s,0)}}else this._lastControlOver[s]&&this._lastControlOver[s]._onPointerOut(this._lastControlOver[s],null,!0),delete this._lastControlOver[s]},!0),this._attachToOnPointerOut(i),this._attachToOnBlur(i))}moveFocusToControl(e){this.focusedControl=e,this._lastPickedControl=e,this._blockNextFocusCheck=!0}_manageFocus(){if(this._blockNextFocusCheck){this._blockNextFocusCheck=!1,this._lastPickedControl=this._focusedControl;return}if(this._focusedControl&&this._focusedControl!==this._lastPickedControl){if(this._lastPickedControl.isFocusInvisible)return;this.focusedControl=null}}_attachPickingToSceneRender(e,t,i){this._sceneRenderObserver=e.onBeforeRenderObservable.add(()=>{!this.checkPointerEveryFrame||(this._linkedControls.length>0||i)&&t()})}_attachToOnPointerOut(e){this._canvasPointerOutObserver=e.getEngine().onCanvasPointerOutObservable.add(t=>{this._lastControlOver[t.pointerId]&&this._lastControlOver[t.pointerId]._onPointerOut(this._lastControlOver[t.pointerId],null),delete this._lastControlOver[t.pointerId],this._lastControlDown[t.pointerId]&&this._lastControlDown[t.pointerId]!==this._capturingControl[t.pointerId]&&(this._lastControlDown[t.pointerId]._forcePointerUp(t.pointerId),delete this._lastControlDown[t.pointerId])})}_attachToOnBlur(e){this._canvasBlurObserver=e.getEngine().onCanvasBlurObservable.add(()=>{Object.entries(this._lastControlDown).forEach(([,t])=>{t._onCanvasBlur()}),this.focusedControl=null,this._lastControlDown={}})}serializeContent(){const e=this.getSize(),t={root:{},width:e.width,height:e.height};return this._rootContainer.serialize(t.root),t}parseSerializedObject(e,t){if(this._rootContainer=zt.Parse(e.root,this),t){const i=e.width,s=e.height;typeof i=="number"&&typeof s=="number"&&i>=0&&s>=0?this.scaleTo(i,s):this.scaleTo(1920,1080)}}clone(e){const t=this.getScene();if(!t)return this;const i=this.getSize(),s=this.serializeContent(),r=new Sh(e??"Clone of "+this.name,i.width,i.height,t,!this.noMipmap,this.samplingMode);return r.parseSerializedObject(s),r}static async ParseFromSnippetAsync(e,t,i){const s=i??Sh.CreateFullscreenUI("ADT from snippet");if(e==="_BLANK")return s;const r=await Sh._LoadURLContentAsync(Sh.SnippetUrl+"/"+e.replace(/#/g,"/"),!0);return s.parseSerializedObject(r,t),s}parseFromSnippetAsync(e,t){return Sh.ParseFromSnippetAsync(e,t,this)}static async ParseFromFileAsync(e,t,i){const s=i??Sh.CreateFullscreenUI("ADT from URL"),r=await Sh._LoadURLContentAsync(e);return s.parseSerializedObject(r,t),s}parseFromURLAsync(e,t){return Sh.ParseFromFileAsync(e,t,this)}static _LoadURLContentAsync(e,t=!1){return e===""?Promise.reject("No URL provided"):new Promise((i,s)=>{const r=new wl;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){let n;if(t){const l=JSON.parse(JSON.parse(r.responseText).jsonPayload);n=l.encodedGui?new TextDecoder("utf-8").decode(NG(l.encodedGui)):l.gui}else n=r.responseText;const o=JSON.parse(n);i(o)}else s("Unable to load")}),r.open("GET",e),r.send()})}static _Overlaps(e,t){return!(e.centerX>t.centerX+t.widthInPixels||e.centerX+e.widthInPixelst.centerY+t.heightInPixels)}static CreateForMesh(e,t=1024,i=1024,s=!0,r=!1,n,o=this._CreateMaterial){const l=WL(),c=new Sh(`AdvancedDynamicTexture for ${e.name} [${l}]`,t,i,e.getScene(),!0,Te.TRILINEAR_SAMPLINGMODE,n);return o(e,l,c,r),c.attachToMesh(e,s),c}static _CreateMaterial(e,t,i,s){const r=Bo("BABYLON.StandardMaterial");if(!r)throw"StandardMaterial needs to be imported before as it contains a side-effect required by your code.";const n=new r(`AdvancedDynamicTextureMaterial for ${e.name} [${t}]`,e.getScene());n.backFaceCulling=!1,n.diffuseColor=Ie.Black(),n.specularColor=Ie.Black(),s?(n.diffuseTexture=i,n.emissiveTexture=i,i.hasAlpha=!0):(n.emissiveTexture=i,n.opacityTexture=i),e.material=n}static CreateForMeshTexture(e,t=1024,i=1024,s=!0,r){const n=new Sh(e.name+" AdvancedDynamicTexture",t,i,e.getScene(),!0,Te.TRILINEAR_SAMPLINGMODE,r);return n.attachToMesh(e,s),n}static CreateFullscreenUI(e,t=!0,i=null,s=Te.BILINEAR_SAMPLINGMODE,r=!1){const n=new Sh(e,0,0,i,!1,s),o=n.getScene(),l=new _he(e+"_layer",null,o,!t);if(l.texture=n,n._layerToDispose=l,n._isFullscreen=!0,r&&o){const c=1/o.getEngine().getHardwareScalingLevel();n._rootContainer.scaleX=c,n._rootContainer.scaleY=c}return n.attach(),n}scale(e){super.scale(e),this.markAsDirty()}scaleTo(e,t){super.scaleTo(e,t),this.markAsDirty()}_checkGuiIsReady(){this.guiIsReady()&&(this.onGuiReadyObservable.notifyObservers(this),this.onGuiReadyObservable.clear())}guiIsReady(){return this._rootContainer.isReady()}}Sh.SnippetUrl=it.SnippetUrl;Sh.AllowGPUOptimizations=!0;class WTe{get renderTimeCounter(){return this._renderTime}get layoutTimeCounter(){return this._layoutTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeginRenderObserver=this.texture.onBeginRenderObservable.add(()=>{this._renderTime.beginMonitoring()}),this._onEndRenderObserver=this.texture.onEndRenderObservable.add(()=>{this._renderTime.endMonitoring(!0)})):(this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null))}get captureLayoutTime(){return this._captureLayoutTime}set captureLayoutTime(e){e!==this._captureLayoutTime&&(this._captureLayoutTime=e,e?(this._onBeginLayoutObserver=this.texture.onBeginLayoutObservable.add(()=>{this._layoutTime.beginMonitoring()}),this._onEndLayoutObserver=this.texture.onEndLayoutObservable.add(()=>{this._layoutTime.endMonitoring(!0)})):(this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null))}constructor(e){this.texture=e,this._captureRenderTime=!1,this._renderTime=new Tc,this._captureLayoutTime=!1,this._layoutTime=new Tc,this._onBeginRenderObserver=null,this._onEndRenderObserver=null,this._onBeginLayoutObserver=null,this._onEndLayoutObserver=null}dispose(){this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null,this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null,this.texture=null}}const yre="XmlLoader Exception : XML file is malformed or corrupted.";class YTe{constructor(e=null){this._nodes={},this._nodeTypes={element:1,attribute:2,text:3},this._isLoaded=!1,this._objectAttributes={textHorizontalAlignment:1,textVerticalAlignment:2,horizontalAlignment:3,verticalAlignment:4,stretch:5},e&&(this._parentClass=e)}_getChainElement(e){let t=window;this._parentClass&&(t=this._parentClass);let i=e;i=i.split(".");for(let s=0;s0&&p>m)throw"XmlLoader Exception : In the Grid element, the number of columns is defined in the first row, do not add more columns in the subsequent rows.";if(u==0){if(!n[f].attributes.getNamedItem("width"))throw"XmlLoader Exception : Width must be defined for all the grid columns in the first row";s=Number(n[f].attributes.getNamedItem("width").nodeValue),c=n[f].attributes.getNamedItem("isPixel")?JSON.parse(n[f].attributes.getNamedItem("isPixel").nodeValue):!1,t.addColumnDefinition(s,c)}l=n[f].children;for(let d=0;d{if(r.readyState===4&&r.status===200){if(!r.responseXML)if(s){s(yre);return}else throw yre;const n=r.responseXML.documentElement;this._parseXml(n.firstChild,t),this._isLoaded=!0,i&&i()}},r.onerror=function(){s&&s("an error occurred during loading the layout")},r.open("GET",e,!0),r.send()}async loadLayoutAsync(e,t){return new Promise((i,s)=>{this.loadLayout(e,t,i,s)})}}class QY extends O{constructor(e,t=0){super(e.x,e.y,e.z),this.buttonIndex=t}}class UW{get position(){return this._node?this._node.position:O.Zero()}set position(e){!this._node||(this._node.position=e)}get scaling(){return this._node?this._node.scaling:new O(1,1,1)}set scaling(e){!this._node||(this._isScaledByManager=!1,this._node.scaling=e)}get behaviors(){return this._behaviors}addBehavior(e){if(this._behaviors.indexOf(e)!==-1)return this;e.init();const i=this._host.scene;return i.isLoading?i.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)}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}get isVisible(){return this._isVisible}set isVisible(e){if(this._isVisible===e)return;this._isVisible=e;const t=this.mesh;t&&t.setEnabled(e)}constructor(e){this.name=e,this._downCount=0,this._enterCount=-1,this._downPointerIds={},this._isVisible=!0,this._isScaledByManager=!1,this.onPointerMoveObservable=new Se,this.onPointerOutObservable=new Se,this.onPointerDownObservable=new Se,this.onPointerUpObservable=new Se,this.onPointerClickObservable=new Se,this.onPointerEnterObservable=new Se,this._behaviors=new Array}get typeName(){return this._getTypeName()}getClassName(){return this._getTypeName()}_getTypeName(){return"Control3D"}get node(){return this._node}get mesh(){return this._node instanceof Ir?this._node:null}linkToTransformNode(e){return this._node&&(this._node.parent=e),this}_prepareNode(e){if(!this._node){if(this._node=this._createNode(e),!this.node)return;this._injectGUI3DReservedDataStore(this.node).control=this;const t=this.mesh;t&&(t.isPickable=!0,this._affectMaterial(t))}}_injectGUI3DReservedDataStore(e){var t,i;return e.reservedDataStore=(t=e.reservedDataStore)!==null&&t!==void 0?t:{},e.reservedDataStore.GUI3D=(i=e.reservedDataStore.GUI3D)!==null&&i!==void 0?i:{},e.reservedDataStore.GUI3D}_createNode(e){return null}_affectMaterial(e){e.material=null}_isTouchButton3D(e){return e._generatePointerEventType!==void 0}_onPointerMove(e,t){this.onPointerMoveObservable.notifyObservers(t,-1,e,this)}_onPointerEnter(e){return this._enterCount===-1&&(this._enterCount=0),this._enterCount++,this._enterCount>1?!1:(this.onPointerEnterObservable.notifyObservers(this,-1,e,this),this.pointerEnterAnimation&&this.pointerEnterAnimation(),!0)}_onPointerOut(e){this._enterCount--,!(this._enterCount>0)&&(this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,e,this),this.pointerOutAnimation&&this.pointerOutAnimation())}_onPointerDown(e,t,i,s){return this._downCount++,this._downPointerIds[i]=this._downPointerIds[i]+1||1,this._downCount!==1?!1:(this.onPointerDownObservable.notifyObservers(new QY(t,s),-1,e,this),this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_onPointerUp(e,t,i,s,r){if(this._downCount--,this._downPointerIds[i]--,this._downPointerIds[i]<=0&&delete this._downPointerIds[i],this._downCount<0){this._downCount=0;return}this._downCount==0&&(r&&(this._enterCount>0||this._enterCount===-1)&&this.onPointerClickObservable.notifyObservers(new QY(t,s),-1,e,this),this.onPointerUpObservable.notifyObservers(new QY(t,s),-1,e,this),this.pointerUpAnimation&&this.pointerUpAnimation())}forcePointerUp(e=null){if(e!==null)this._onPointerUp(this,O.Zero(),e,0,!0);else{for(const t in this._downPointerIds)this._onPointerUp(this,O.Zero(),+t,0,!0);this._downCount>0&&(this._downCount=1,this._onPointerUp(this,O.Zero(),0,0,!0))}}_processObservables(e,t,i,s,r){if(this._isTouchButton3D(this)&&i&&(e=this._generatePointerEventType(e,i,this._downCount)),e===mi.POINTERMOVE){this._onPointerMove(this,t);const n=this._host._lastControlOver[s];return n&&n!==this&&n._onPointerOut(this),n!==this&&this._onPointerEnter(this),this._host._lastControlOver[s]=this,!0}return e===mi.POINTERDOWN?(this._onPointerDown(this,t,s,r),this._host._lastControlDown[s]=this,this._host._lastPickedControl=this,!0):e===mi.POINTERUP||e===mi.POINTERDOUBLETAP?(this._host._lastControlDown[s]&&this._host._lastControlDown[s]._onPointerUp(this,t,s,r,!0),delete this._host._lastControlDown[s],!0):!1}_disposeNode(){this._node&&(this._node.dispose(),this._node=null)}dispose(){this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._disposeNode();for(const e of this._behaviors)e.detach()}}class v1e extends UW{constructor(){super(...arguments),this._contentResolution=512,this._contentScaleRatio=2}get content(){return this._content}set content(e){this._content=e,!(!e||!this._host||!this._host.utilityLayer)&&(this._facadeTexture?this._facadeTexture.rootContainer.clearControls():(this._facadeTexture=new Sh("Facade",this._contentResolution,this._contentResolution,this._host.utilityLayer.utilityLayerScene,!0,Te.TRILINEAR_SAMPLINGMODE),this._setFacadeTextureScaling(),this._facadeTexture.premulAlpha=!0),this._facadeTexture.addControl(e),this._applyFacade(this._facadeTexture))}_setFacadeTextureScaling(){var e;this._facadeTexture&&(this._facadeTexture.rootContainer.scaleX=this._contentScaleRatio,this._facadeTexture.rootContainer.scaleY=(e=this._contentScaleRatioY)!==null&&e!==void 0?e:this._contentScaleRatio)}get contentResolution(){return this._contentResolution}set contentResolution(e){this._contentResolution!==e&&(this._contentResolution=e,this._resetContent())}_disposeFacadeTexture(){this._facadeTexture&&(this._facadeTexture.dispose(),this._facadeTexture=null)}_resetContent(){this._disposeFacadeTexture(),this.content=this._content}_applyFacade(e){}}class C1e extends v1e{constructor(e){super(e)}_getTypeName(){return"AbstractButton3D"}_createNode(e){return new Ki("button"+this.name,e)}}class PQ extends C1e{constructor(e,t){super(e),this._options={width:1,height:1,depth:.08,...t},this.pointerEnterAnimation=()=>{!this.mesh||(this._currentMaterial.emissiveColor=Ie.Red())},this.pointerOutAnimation=()=>{this._currentMaterial.emissiveColor=Ie.Black()},this.pointerDownAnimation=()=>{!this.mesh||this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{!this.mesh||this.mesh.scaling.scaleInPlace(1/.95)}}_applyFacade(e){this._currentMaterial.emissiveTexture=e}_getTypeName(){return"Button3D"}_createNode(e){const t=new Array(6);for(let s=0;s<6;s++)t[s]=new Ui(0,0,0,0);e.useRightHandedSystem?t[0].copyFromFloats(1,0,0,1):t[1].copyFromFloats(0,0,1,1);const i=pl(this.name+"_rootMesh",{width:this._options.width,height:this._options.height,depth:this._options.depth,faceUV:t,wrap:!0},e);return this._contentScaleRatioY=this._contentScaleRatio*this._options.width/this._options.height,this._setFacadeTextureScaling(),i}_affectMaterial(e){const t=new jt(this.name+"Material",e.getScene());t.specularColor=Ie.Black(),e.material=t,this._currentMaterial=t,this._resetContent()}dispose(){super.dispose(),this._disposeFacadeTexture(),this._currentMaterial&&this._currentMaterial.dispose()}}class Rc extends UW{get children(){return this._children}get blockLayout(){return this._blockLayout}set blockLayout(e){this._blockLayout!==e&&(this._blockLayout=e,this._blockLayout||this._arrangeChildren())}constructor(e){super(e),this._blockLayout=!1,this._children=new Array}updateLayout(){return this._arrangeChildren(),this}containsControl(e){return this._children.indexOf(e)!==-1}addControl(e){return this._children.indexOf(e)!==-1?this:(e.parent=this,e._host=this._host,this._children.push(e),this._host.utilityLayer&&(e._prepareNode(this._host.utilityLayer.utilityLayerScene),e.node&&(e.node.parent=this.node),this.blockLayout||this._arrangeChildren()),this)}_arrangeChildren(){}_createNode(e){return new Ki("ContainerNode",e)}removeControl(e){const t=this._children.indexOf(e);return t!==-1&&(this._children.splice(t,1),e.parent=null,e._disposeNode()),this}_getTypeName(){return"Container3D"}dispose(){for(const e of this._children)e.dispose();this._children.length=0,super.dispose()}}Rc.UNSET_ORIENTATION=0;Rc.FACEORIGIN_ORIENTATION=1;Rc.FACEORIGINREVERSED_ORIENTATION=2;Rc.FACEFORWARD_ORIENTATION=3;Rc.FACEFORWARDREVERSED_ORIENTATION=4;class FF extends Rc{get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._orientation=e,Be.SetImmediate(()=>{this._arrangeChildren()}))}get columns(){return this._columns}set columns(e){this._columns!==e&&(this._columns=e,this._rowThenColum=!0,Be.SetImmediate(()=>{this._arrangeChildren()}))}get rows(){return this._rows}set rows(e){this._rows!==e&&(this._rows=e,this._rowThenColum=!1,Be.SetImmediate(()=>{this._arrangeChildren()}))}constructor(e){super(e),this._columns=10,this._rows=0,this._rowThenColum=!0,this._orientation=Rc.FACEORIGIN_ORIENTATION,this.margin=0}_arrangeChildren(){this._cellWidth=0,this._cellHeight=0;let e=0,t=0,i=0;const s=ge.Invert(this.node.computeWorldMatrix(!0));for(const c of this._children){if(!c.mesh)continue;i++,c.mesh.computeWorldMatrix(!0);const h=c.mesh.getHierarchyBoundingVectors(),u=ue.Vector3[0],p=ue.Vector3[1];h.max.subtractToRef(h.min,p),p.scaleInPlace(.5),O.TransformNormalToRef(p,s,u),this._cellWidth=Math.max(this._cellWidth,u.x*2),this._cellHeight=Math.max(this._cellHeight,u.y*2)}this._cellWidth+=this.margin*2,this._cellHeight+=this.margin*2,this._rowThenColum?(t=this._columns,e=Math.ceil(i/this._columns)):(e=this._rows,t=Math.ceil(i/this._rows));const r=t*.5*this._cellWidth,n=e*.5*this._cellHeight,o=[];let l=0;if(this._rowThenColum)for(let c=0;ci));h++);else for(let c=0;ci));h++);l=0;for(const c of this._children)!c.mesh||(this._mapGridNode(c,o[l]),l++);this._finalProcessing()}_finalProcessing(){}}class XTe extends FF{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,Be.SetImmediate(()=>{this._arrangeChildren()}))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const s=this._cylindricalMapping(t);switch(e.position=s,this.orientation){case Rc.FACEORIGIN_ORIENTATION:i.lookAt(new O(2*s.x,s.y,2*s.z));break;case Rc.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new O(-s.x,s.y,-s.z));break;case Rc.FACEFORWARD_ORIENTATION:break;case Rc.FACEFORWARDREVERSED_ORIENTATION:i.rotate(Fo.Y,Math.PI,sr.LOCAL);break}}_cylindricalMapping(e){const t=new O(0,e.y,this._radius),i=e.x/this._radius;return ge.RotationYawPitchRollToRef(i,0,0,ue.Matrix[0]),O.TransformNormal(t,ue.Matrix[0])}}const KTe="fluentVertexShader",QTe=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 world;uniform mat4 viewProjection;varying vec2 vUV; +#ifdef BORDER +varying vec2 scaleInfo;uniform float borderWidth;uniform vec3 scaleFactor; +#endif +#ifdef HOVERLIGHT +varying vec3 worldPosition; +#endif +void main(void) {vUV=uv; +#ifdef BORDER +vec3 scale=scaleFactor;float minScale=min(min(scale.x,scale.y),scale.z);float maxScale=max(max(scale.x,scale.y),scale.z);float minOverMiddleScale=minScale/(scale.x+scale.y+scale.z-minScale-maxScale);float areaYZ=scale.y*scale.z;float areaXZ=scale.x*scale.z;float areaXY=scale.x*scale.y;float scaledBorderWidth=borderWidth; +if (abs(normal.x)==1.0) +{scale.x=scale.y;scale.y=scale.z;if (areaYZ>areaXZ && areaYZ>areaXY) +{scaledBorderWidth*=minOverMiddleScale;}} +else if (abs(normal.y)==1.0) +{scale.x=scale.z;if (areaXZ>areaXY && areaXZ>areaYZ) +{scaledBorderWidth*=minOverMiddleScale;}} +else +{if (areaXY>areaYZ && areaXY>areaXZ) +{scaledBorderWidth*=minOverMiddleScale;}} +float scaleRatio=min(scale.x,scale.y)/max(scale.x,scale.y);if (scale.x>scale.y) +{scaleInfo.x=1.0-(scaledBorderWidth*scaleRatio);scaleInfo.y=1.0-scaledBorderWidth;} +else +{scaleInfo.x=1.0-scaledBorderWidth;scaleInfo.y=1.0-(scaledBorderWidth*scaleRatio);} +#endif +vec4 worldPos=world*vec4(position,1.0); +#ifdef HOVERLIGHT +worldPosition=worldPos.xyz; +#endif +gl_Position=viewProjection*worldPos;} +`;Ue.ShadersStore[KTe]=QTe;const ZTe="fluentPixelShader",qTe=`precision highp float;varying vec2 vUV;uniform vec4 albedoColor; +#ifdef INNERGLOW +uniform vec4 innerGlowColor; +#endif +#ifdef BORDER +varying vec2 scaleInfo;uniform float edgeSmoothingValue;uniform float borderMinValue; +#endif +#ifdef HOVERLIGHT +varying vec3 worldPosition;uniform vec3 hoverPosition;uniform vec4 hoverColor;uniform float hoverRadius; +#endif +#ifdef TEXTURE +uniform sampler2D albedoSampler;uniform mat4 textureMatrix;vec2 finalUV; +#endif +void main(void) {vec3 albedo=albedoColor.rgb;float alpha=albedoColor.a; +#ifdef TEXTURE +finalUV=vec2(textureMatrix*vec4(vUV,1.0,0.0));albedo=texture2D(albedoSampler,finalUV).rgb; +#endif +#ifdef HOVERLIGHT +float pointToHover=(1.0-clamp(length(hoverPosition-worldPosition)/hoverRadius,0.,1.))*hoverColor.a;albedo=clamp(albedo+hoverColor.rgb*pointToHover,0.,1.); +#else +float pointToHover=1.0; +#endif +#ifdef BORDER +float borderPower=10.0;float inverseBorderPower=1.0/borderPower;vec3 borderColor=albedo*borderPower;vec2 distanceToEdge;distanceToEdge.x=abs(vUV.x-0.5)*2.0;distanceToEdge.y=abs(vUV.y-0.5)*2.0;float borderValue=max(smoothstep(scaleInfo.x-edgeSmoothingValue,scaleInfo.x+edgeSmoothingValue,distanceToEdge.x), +smoothstep(scaleInfo.y-edgeSmoothingValue,scaleInfo.y+edgeSmoothingValue,distanceToEdge.y));borderColor=borderColor*borderValue*max(borderMinValue*inverseBorderPower,pointToHover); +albedo+=borderColor;alpha=max(alpha,borderValue); +#endif +#ifdef INNERGLOW +vec2 uvGlow=(vUV-vec2(0.5,0.5))*(innerGlowColor.a*2.0);uvGlow=uvGlow*uvGlow;uvGlow=uvGlow*uvGlow;albedo+=mix(vec3(0.0,0.0,0.0),innerGlowColor.rgb,uvGlow.x+uvGlow.y); +#endif +gl_FragColor=vec4(albedo,alpha);}`;Ue.ShadersStore[ZTe]=qTe;class A1e extends ta{constructor(){super(),this.INNERGLOW=!1,this.BORDER=!1,this.HOVERLIGHT=!1,this.TEXTURE=!1,this.rebuild()}}class pu extends Bl{constructor(e,t){super(e,t),this.innerGlowColorIntensity=.5,this.innerGlowColor=new Ie(1,1,1),this.albedoColor=new Ie(.3,.35,.4),this.renderBorders=!1,this.borderWidth=.5,this.edgeSmoothingValue=.02,this.borderMinValue=.1,this.renderHoverLight=!1,this.hoverRadius=.01,this.hoverColor=new Zt(.3,.3,.3,1),this.hoverPosition=O.Zero()}needAlphaBlending(){return this.alpha!==1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new A1e);const i=this.getScene(),s=t.materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&s._renderId===i.getRenderId())return!0;if(s._areTexturesDirty)if(s.INNERGLOW=this.innerGlowColorIntensity>0,s.BORDER=this.renderBorders,s.HOVERLIGHT=this.renderHoverLight,this._albedoTexture)if(this._albedoTexture.isReadyOrNotBlocking())s.TEXTURE=!0;else return!1;else s.TEXTURE=!1;const r=i.getEngine();if(s.isDirty){s.markAsProcessed(),i.resetCachedMaterial();const n=[se.PositionKind];n.push(se.NormalKind),n.push(se.UVKind);const o="fluent",l=["world","viewProjection","innerGlowColor","albedoColor","borderWidth","edgeSmoothingValue","scaleFactor","borderMinValue","hoverColor","hoverPosition","hoverRadius","textureMatrix"],c=["albedoSampler"],h=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:l,uniformBuffersNames:h,samplers:c,defines:s,maxSimultaneousLights:4});const u=s.toString();t.setEffect(i.getEngine().createEffect(o,{attributes:n,uniformsNames:l,uniformBuffersNames:h,samplers:c,defines:u,fallbacks:null,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),s,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(s._renderId=i.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!!n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._mustRebind(s,n)&&(this._activeEffect.setColor4("albedoColor",this.albedoColor,this.alpha),r.INNERGLOW&&this._activeEffect.setColor4("innerGlowColor",this.innerGlowColor,this.innerGlowColorIntensity),r.BORDER&&(this._activeEffect.setFloat("borderWidth",this.borderWidth),this._activeEffect.setFloat("edgeSmoothingValue",this.edgeSmoothingValue),this._activeEffect.setFloat("borderMinValue",this.borderMinValue),t.getBoundingInfo().boundingBox.extendSize.multiplyToRef(t.scaling,ue.Vector3[0]),this._activeEffect.setVector3("scaleFactor",ue.Vector3[0])),r.HOVERLIGHT&&(this._activeEffect.setDirectColor4("hoverColor",this.hoverColor),this._activeEffect.setFloat("hoverRadius",this.hoverRadius),this._activeEffect.setVector3("hoverPosition",this.hoverPosition)),r.TEXTURE&&this._albedoTexture)){this._activeEffect.setTexture("albedoSampler",this._albedoTexture);const o=this._albedoTexture.getTextureMatrix();this._activeEffect.setMatrix("textureMatrix",o)}this._afterBind(t,this._activeEffect)}}getActiveTextures(){return super.getActiveTextures()}hasTexture(e){return!!super.hasTexture(e)}dispose(e){super.dispose(e)}clone(e){return Kt.Clone(()=>new pu(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GUI.FluentMaterial",e}getClassName(){return"FluentMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new pu(e.name,t),e,t,i)}}z([X(),_t("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"innerGlowColorIntensity",void 0);z([Br()],pu.prototype,"innerGlowColor",void 0);z([Br()],pu.prototype,"albedoColor",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"renderBorders",void 0);z([X()],pu.prototype,"borderWidth",void 0);z([X()],pu.prototype,"edgeSmoothingValue",void 0);z([X()],pu.prototype,"borderMinValue",void 0);z([X(),_t("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"renderHoverLight",void 0);z([X()],pu.prototype,"hoverRadius",void 0);z([bF()],pu.prototype,"hoverColor",void 0);z([bo()],pu.prototype,"hoverPosition",void 0);z([xs("albedoTexture")],pu.prototype,"_albedoTexture",void 0);z([_t("_markAllSubMeshesAsTexturesAndMiscDirty")],pu.prototype,"albedoTexture",void 0);$e("BABYLON.GUI.FluentMaterial",pu);class NL extends FF{get backPlateMargin(){return this._backPlateMargin}set backPlateMargin(e){this._backPlateMargin=e,this._children.length>=1&&(this.children.forEach(t=>{this._updateCurrentMinMax(t.position)}),this._updateMargins())}_createNode(e){const t=new Oe(`menu_${this.name}`,e);return this._backPlate=pl("backPlate"+this.name,{size:1},e),this._backPlate.parent=t,t}_affectMaterial(e){this._backPlateMaterial=new pu(this.name+"backPlateMaterial",e.getScene()),this._backPlateMaterial.albedoColor=new Ie(.08,.15,.55),this._backPlateMaterial.renderBorders=!0,this._backPlateMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add(t=>{t?(this._backPlateMaterial.hoverPosition=t,this._backPlateMaterial.hoverColor.a=1):this._backPlateMaterial.hoverColor.a=0}),this._backPlate.material=this._backPlateMaterial}_mapGridNode(e,t){!e.mesh||(e.position=t.clone(),this._updateCurrentMinMax(t))}_finalProcessing(){this._updateMargins()}_updateCurrentMinMax(e){this._currentMin||(this._currentMin=e.clone(),this._currentMax=e.clone()),this._currentMin.minimizeInPlace(e),this._currentMax.maximizeInPlace(e)}_updateMargins(){if(this._children.length>0){this._currentMin.addInPlaceFromFloats(-this._cellWidth/2,-this._cellHeight/2,0),this._currentMax.addInPlaceFromFloats(this._cellWidth/2,this._cellHeight/2,0);const e=this._currentMax.subtract(this._currentMin);this._backPlate.scaling.x=e.x+this._cellWidth*this.backPlateMargin,this._backPlate.scaling.y=e.y+this._cellHeight*this.backPlateMargin,this._backPlate.scaling.z=.001;for(let t=0;t0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}} +void Pick_Radius_B144( +float Radius, +float Radius_Top_Left, +float Radius_Top_Right, +float Radius_Bottom_Left, +float Radius_Bottom_Right, +vec3 Position, +out float Result) +{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;} +void main() +{vec3 Nrm_World_Q128;Nrm_World_Q128=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q131;vec3 Tangent_World_N_Q131;float Tangent_Length_Q131;Tangent_World_Q131=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q131=length(Tangent_World_Q131);Tangent_World_N_Q131=Tangent_World_Q131/Tangent_Length_Q131;vec3 Binormal_World_Q132;vec3 Binormal_World_N_Q132;float Binormal_Length_Q132;Object_To_World_Dir_B132(vec3(0,1,0),Binormal_World_Q132,Binormal_World_N_Q132,Binormal_Length_Q132);float Anisotropy_Q133=Tangent_Length_Q131/Binormal_Length_Q132;vec3 Result_Q177;Result_Q177=mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(_Use_Global_Left_Index_));vec3 Result_Q178;Result_Q178=mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(_Use_Global_Right_Index_));float Result_Q144;Pick_Radius_B144(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q144);vec3 Dir_Q140;PickDir_B140(_Angle_,Tangent_World_N_Q131,Binormal_World_N_Q132,Dir_Q140);float Radius_Q147;float Line_Width_Q147;RelativeOrAbsoluteDetail_B147(Result_Q144,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q132,Radius_Q147,Line_Width_Q147);vec4 Out_Color_Q145=vec4(Radius_Q147,Line_Width_Q147,0,1);vec3 New_P_Q129;vec2 New_UV_Q129;float Radial_Gradient_Q129;vec3 Radial_Dir_Q129;Move_Verts_B129(Anisotropy_Q133,position,Radius_Q147,New_P_Q129,New_UV_Q129,Radial_Gradient_Q129,Radial_Dir_Q129);vec3 Pos_World_Q115;Object_To_World_Pos_B115(New_P_Q129,Pos_World_Q115);vec4 Blob_Info_Q180; +#if BLOB_ENABLE +Blob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q177,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q180); +#else +Blob_Info_Q180=vec4(0,0,0,0); +#endif +vec4 Blob_Info_Q181; +#if BLOB_ENABLE_2 +Blob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q178,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q181); +#else +Blob_Info_Q181=vec4(0,0,0,0); +#endif +float Gradient1_Q130;float Gradient2_Q130; +#if SMOOTH_EDGES +Edge_AA_Vertex_B130(Pos_World_Q115,position,normal,cameraPosition,Radial_Gradient_Q129,Radial_Dir_Q129,tangent,Gradient1_Q130,Gradient2_Q130); +#else +Gradient1_Q130=1.0;Gradient2_Q130=1.0; +#endif +vec2 Rect_UV_Q139;vec4 Rect_Parms_Q139;vec2 Scale_XY_Q139;vec2 Line_UV_Q139;Round_Rect_Vertex_B139(New_UV_Q129,Radius_Q147,0.0,Anisotropy_Q133,Gradient1_Q130,Gradient2_Q130,Rect_UV_Q139,Rect_Parms_Q139,Scale_XY_Q139,Line_UV_Q139);vec3 Line_Vertex_Q135;Line_Vertex_B135(Scale_XY_Q139,Line_UV_Q139,0.0,_Rate_,_Highlight_Transform_,Line_Vertex_Q135);vec3 Position=Pos_World_Q115;vec3 Normal=Dir_Q140;vec2 UV=Rect_UV_Q139;vec3 Tangent=Line_Vertex_Q135;vec3 Binormal=Nrm_World_Q128;vec4 Color=Out_Color_Q145;vec4 Extra1=Rect_Parms_Q139;vec4 Extra2=Blob_Info_Q180;vec4 Extra3=Blob_Info_Q181;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}`;Ue.ShadersStore[tSe]=iSe;class sSe extends ta{constructor(){super(),this.BLOB_ENABLE=!0,this.BLOB_ENABLE_2=!0,this.SMOOTH_EDGES=!0,this.IRIDESCENT_MAP_ENABLE=!0,this._needNormals=!0,this.rebuild()}}class Qa extends Bl{constructor(e,t){super(e,t),this.radius=.03,this.lineWidth=.01,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new Zt(.0392157,.0666667,.207843,1),this.lineColor=new Zt(.14902,.133333,.384314,1),this.blobIntensity=.98,this.blobFarSize=.04,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.blobNearSize=.22,this.blobPulse=0,this.blobFade=0,this.blobNearSize2=.22,this.blobPulse2=0,this.blobFade2=0,this._rate=.135,this.highlightColor=new Zt(.98,.98,.98,1),this.highlightWidth=.25,this._highlightTransform=new Ui(1,1,0,0),this._highlight=1,this.iridescenceIntensity=0,this.iridescenceEdgeIntensity=1,this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.globalLeftIndexTipPosition=O.Zero(),this._globalLeftIndexTipPosition4=Ui.Zero(),this.globalRightIndexTipPosition=O.Zero(),this._globalRightIndexTipPosition4=Ui.Zero(),this.alphaMode=it.ALPHA_DISABLE,this.backFaceCulling=!1,this._blobTexture=new Te(Qa.BLOB_TEXTURE_URL,this.getScene(),!0,!1,Te.NEAREST_SAMPLINGMODE),this._iridescentMap=new Te(Qa.IM_TEXTURE_URL,this.getScene(),!0,!1,Te.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new sSe);const i=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(ze.PrepareDefinesForAttributes(e,i,!1,!1),i.isDirty){i.markAsProcessed(),s.resetCachedMaterial();const n=new Fl;i.FOG&&n.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(i,n),i.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[se.PositionKind];i.NORMAL&&o.push(se.NormalKind),i.UV1&&o.push(se.UVKind),i.UV2&&o.push(se.UV2Kind),i.VERTEXCOLOR&&o.push(se.ColorKind),i.TANGENT&&o.push(se.TangentKind),ze.PrepareAttributesForInstances(o,i);const l="fluentBackplate",c=i.toString(),h=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Angle_","_Fade_Out_","_Reflected_","_Frequency_","_Vertical_Offset_","_Iridescent_Map_","_Use_Global_Left_Index_","_Use_Global_Right_Index_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position"],u=["_Blob_Texture_","_Iridescent_Map_"],p=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:i,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:c,fallbacks:n,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),i,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(i._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)}bindForSubMesh(e,t,i){var s,r;if(!i.materialDefines)return;const o=i.effect;!o||(this._activeEffect=o,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",(r=(s=this.getScene().activeCamera)===null||s===void 0?void 0:s.position)!==null&&r!==void 0?r:O.ZeroReadOnly),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",1),this._activeEffect.setFloat("_Radius_Top_Right_",1),this._activeEffect.setFloat("_Radius_Bottom_Left_",1),this._activeEffect.setFloat("_Radius_Bottom_Right_",1),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMap),this._activeEffect.setFloat("_Use_Global_Left_Index_",1),this._activeEffect.setFloat("_Use_Global_Right_Index_",1),this._globalLeftIndexTipPosition4.set(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this._globalLeftIndexTipPosition4),this._globalRightIndexTipPosition4.set(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this._globalRightIndexTipPosition4),this._afterBind(t,this._activeEffect))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._blobTexture.dispose(),this._iridescentMap.dispose()}clone(e){return Kt.Clone(()=>new Qa(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentBackplateMaterial",e}getClassName(){return"FluentBackplateMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new Qa(e.name,t),e,t,i)}}Qa.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-blob.png";Qa.IM_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-iridescence.png";z([X()],Qa.prototype,"radius",void 0);z([X()],Qa.prototype,"lineWidth",void 0);z([X()],Qa.prototype,"absoluteSizes",void 0);z([X()],Qa.prototype,"baseColor",void 0);z([X()],Qa.prototype,"lineColor",void 0);z([X()],Qa.prototype,"blobIntensity",void 0);z([X()],Qa.prototype,"blobFarSize",void 0);z([X()],Qa.prototype,"blobNearDistance",void 0);z([X()],Qa.prototype,"blobFarDistance",void 0);z([X()],Qa.prototype,"blobFadeLength",void 0);z([X()],Qa.prototype,"blobNearSize",void 0);z([X()],Qa.prototype,"blobPulse",void 0);z([X()],Qa.prototype,"blobFade",void 0);z([X()],Qa.prototype,"blobNearSize2",void 0);z([X()],Qa.prototype,"blobPulse2",void 0);z([X()],Qa.prototype,"blobFade2",void 0);z([X()],Qa.prototype,"highlightColor",void 0);z([X()],Qa.prototype,"highlightWidth",void 0);z([X()],Qa.prototype,"iridescenceIntensity",void 0);z([X()],Qa.prototype,"iridescenceEdgeIntensity",void 0);z([X()],Qa.prototype,"fadeOut",void 0);z([bo()],Qa.prototype,"globalLeftIndexTipPosition",void 0);z([bo()],Qa.prototype,"globalRightIndexTipPosition",void 0);$e("BABYLON.GUI.FluentBackplateMaterial",Qa);class sF extends UW{set renderingGroupId(e){this._model.renderingGroupId=e}get renderingGroupId(){return this._model.renderingGroupId}get material(){return this._material}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=t}_getTypeName(){return"HolographicBackplate"}_createNode(e){var t;const i=pl(((t=this.name)!==null&&t!==void 0?t:"HolographicBackplate")+"_CollisionMesh",{width:1,height:1,depth:1},e);return i.isPickable=!0,i.visibility=0,As.ImportMeshAsync(void 0,sF.MODEL_BASE_URL,sF.MODEL_FILENAME,e).then(s=>{const r=s.meshes[1];r.name=`${this.name}_frontPlate`,r.isPickable=!1,r.parent=i,this._material&&(r.material=this._material),this._model=r}),i}_createMaterial(e){this._material=new Qa(this.name+" Material",e.getScene())}_affectMaterial(e){this._shareMaterials?this._host._touchSharedMaterials.fluentBackplateMaterial?this._material=this._host._touchSharedMaterials.fluentBackplateMaterial:(this._createMaterial(e),this._host._touchSharedMaterials.fluentBackplateMaterial=this._material):this._createMaterial(e)}dispose(){super.dispose(),this.shareMaterials||this._material.dispose(),this._model.dispose()}}sF.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/";sF.MODEL_FILENAME="mrtk-fluent-backplate.glb";class rSe extends PQ{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}set tooltipText(e){if(!e){this._disposeTooltip();return}if(!this._tooltipFade){const t=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Jd("",{size:1},this._backPlate._scene);const i=Jd("",{size:1,sideOrientation:Oe.DOUBLESIDE},this._backPlate._scene),s=new jt("",this._backPlate._scene);s.diffuseColor=Ie.FromHexString("#212121"),i.material=s,i.isPickable=!1,this._tooltipMesh.addChild(i),i.position=O.Forward(t).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=O.Up().scale(.7).add(O.Forward(t).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=Sh.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new Ka,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new yK,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add(()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)}),this._tooltipOutObserver=this.onPointerOutObservable.add(()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)})}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{!this.mesh||this._frontPlate.setEnabled(!0)},this.pointerOutAnimation=()=>{!this.mesh||this._frontPlate.setEnabled(!1)}}_getTypeName(){return"HolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new Z2;if(e.isVertical=!0,Zb()&&!!document.createElement&&this._imageUrl){const t=new wr;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new Ka;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this._frontPlate&&(this.content=e)}_createNode(e){return this._backPlate=pl(this.name+"BackMesh",{width:1,height:1,depth:.08},e),this._frontPlate=pl(this.name+"FrontMesh",{width:1,height:1,depth:.08},e),this._frontPlate.parent=this._backPlate,this._frontPlate.position=O.Forward(e.useRightHandedSystem).scale(-.08),this._frontPlate.isPickable=!1,this._frontPlate.setEnabled(!1),this._textPlate=super._createNode(e),this._textPlate.parent=this._backPlate,this._textPlate.position=O.Forward(e.useRightHandedSystem).scale(-.08),this._textPlate.isPickable=!1,this._backPlate}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e}_createBackMaterial(e){this._backMaterial=new pu(this.name+"Back Material",e.getScene()),this._backMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add(t=>{t?(this._backMaterial.hoverPosition=t,this._backMaterial.hoverColor.a=1):this._backMaterial.hoverColor.a=0})}_createFrontMaterial(e){this._frontMaterial=new pu(this.name+"Front Material",e.getScene()),this._frontMaterial.innerGlowColorIntensity=0,this._frontMaterial.alpha=.5,this._frontMaterial.renderBorders=!0}_createPlateMaterial(e){this._plateMaterial=new jt(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ie.Black()}_affectMaterial(e){this._shareMaterials?(this._host._sharedMaterials.backFluentMaterial?this._backMaterial=this._host._sharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._sharedMaterials.backFluentMaterial=this._backMaterial),this._host._sharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._sharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._sharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._frontPlate.material=this._frontMaterial,this._textPlate.material=this._plateMaterial,this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}const nSe="fluentButtonPixelShader",aSe=`uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform bool _Relative_Width_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool Enable_Fade;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool _Use_Blob_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Holo_Edge_Fragment_B35( +vec4 Edges, +float Edge_Width, +out float NotEdge) +{vec2 c=vec2(min(Edges.r,Edges.g),min(Edges.b,Edges.a));vec2 df=fwidth(c)*Edge_Width;vec2 g=clamp(c/df,0.0,1.0);NotEdge=g.x*g.y;} +void Blob_Fragment_B39( +vec2 UV, +vec3 Blob_Info, +sampler2D Blob_Texture, +out vec4 Blob_Color) +{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));} +vec2 FilterStep(vec2 Edge,vec2 X) +{vec2 dX=max(fwidth(X),vec2(0.00001,0.00001));return clamp( (X+dX-max(Edge,X-dX))/(dX*2.0),0.0,1.0);} +void Wireframe_Fragment_B59( +vec3 Widths, +vec2 UV, +float Proximity, +vec4 Edge_Color, +out vec4 Wireframe) +{vec2 c=min(UV,vec2(1.0,1.0)-UV);vec2 g=FilterStep(Widths.xy*0.5,c); +Wireframe=(1.0-min(g.x,g.y))*Proximity*Edge_Color;} +void Proximity_B53( +vec3 Proximity_Center, +vec3 Proximity_Center_2, +float Proximity_Max_Intensity, +float Proximity_Near_Radius, +vec3 Position, +vec3 Show_Selection, +vec4 Extra1, +float Dist_To_Face, +float Intensity, +out float Proximity) +{vec2 delta1=Extra1.xy;vec2 delta2=Extra1.zw;float d2=sqrt(min(dot(delta1,delta1),dot(delta2,delta2))+Dist_To_Face*Dist_To_Face);Proximity=Intensity*Proximity_Max_Intensity*(1.0-clamp(d2/Proximity_Near_Radius,0.0,1.0))*(1.0-Show_Selection.x)+Show_Selection.x;} +void To_XYZ_B46( +vec3 Vec3, +out float X, +out float Y, +out float Z) +{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;} +void main() +{float NotEdge_Q35; +#if ENABLE_FADE +Holo_Edge_Fragment_B35(vColor,_Fade_Width_,NotEdge_Q35); +#else +NotEdge_Q35=1.0; +#endif +vec4 Blob_Color_Q39;float k=dot(vUV,vUV);vec2 blobTextureCoord=vec2(vec2(sqrt(k),vTangent.x).x,1.0-vec2(sqrt(k),vTangent.x).y);vec4 blobColor=mix(vec4(1.0,1.0,1.0,1.0)*step(1.0-vTangent.x,clamp(sqrt(k)+0.1,0.0,1.0)),texture(_Blob_Texture_,blobTextureCoord),float(_Use_Blob_Texture_));Blob_Color_Q39=vTangent.y*blobColor*(1.0-clamp(k,0.0,1.0));float Is_Quad_Q24;Is_Quad_Q24=vNormal.z;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));float X_Q46;float Y_Q46;float Z_Q46;To_XYZ_B46(vBinormal,X_Q46,Y_Q46,Z_Q46);float Proximity_Q53;Proximity_B53(Blob_Position_Q41,Blob_Position_Q42,_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vPosition,vBinormal,vExtra1,Y_Q46,Z_Q46,Proximity_Q53);vec4 Wireframe_Q59;Wireframe_Fragment_B59(vNormal,vUV,Proximity_Q53,_Edge_Color_,Wireframe_Q59);vec4 Wire_Or_Blob_Q23=mix(Wireframe_Q59,Blob_Color_Q39,Is_Quad_Q24);vec4 Result_Q22;Result_Q22=mix(Wire_Or_Blob_Q23,vec4(0.3,0.3,0.3,0.3),float(_Show_Frame_));vec4 Final_Color_Q37=NotEdge_Q35*Result_Q22;vec4 Out_Color=Final_Color_Q37;float Clip_Threshold=0.0;bool To_sRGB=false;gl_FragColor=Out_Color;}`;Ue.ShadersStore[nSe]=aSe;const oSe="fluentButtonVertexShader",lSe=`uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool _Enable_Fade_;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;void Blob_Vertex_B47( +vec3 Position, +vec3 Normal, +vec3 Tangent, +vec3 Bitangent, +vec3 Blob_Position, +float Intensity, +float Blob_Near_Size, +float Blob_Far_Size, +float Blob_Near_Distance, +float Blob_Far_Distance, +vec4 Vx_Color, +vec2 UV, +vec3 Face_Center, +vec2 Face_Size, +vec2 In_UV, +float Blob_Fade_Length, +float Selection_Fade, +float Selection_Fade_Size, +float Inner_Fade, +vec3 Active_Face_Center, +float Blob_Pulse, +float Blob_Fade, +float Blob_Enabled, +out vec3 Out_Position, +out vec2 Out_UV, +out vec3 Blob_Info) +{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal);Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; +vec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);} +vec2 ProjectProximity( +vec3 blobPosition, +vec3 position, +vec3 center, +vec3 dir, +vec3 xdir, +vec3 ydir, +out float vdistance +) +{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;} +void Proximity_Vertex_B66( +vec3 Blob_Position, +vec3 Blob_Position_2, +vec3 Active_Face_Center, +vec3 Active_Face_Dir, +vec3 Position, +float Proximity_Far_Distance, +float Relative_Scale, +float Proximity_Anisotropy, +vec3 Up, +out vec4 Extra1, +out float Distance_To_Face, +out float Intensity) +{vec3 Active_Face_Dir_X=normalize(cross(Active_Face_Dir,Up));vec3 Active_Face_Dir_Y=cross(Active_Face_Dir,Active_Face_Dir_X);float distz1,distz2;Extra1.xy=ProjectProximity(Blob_Position,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz1)/Relative_Scale;Extra1.zw=ProjectProximity(Blob_Position_2,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz2)/Relative_Scale;Distance_To_Face=dot(Active_Face_Dir,Position-Active_Face_Center);Intensity=1.0-clamp(min(distz1,distz2)/Proximity_Far_Distance,0.0,1.0);} +void Holo_Edge_Vertex_B44( +vec3 Incident, +vec3 Normal, +vec2 UV, +vec3 Tangent, +vec3 Bitangent, +bool Smooth_Active_Face, +float Active, +out vec4 Holo_Edges) +{float NdotI=dot(Incident,Normal);vec2 flip=(UV-vec2(0.5,0.5));float udot=dot(Incident,Tangent)*flip.x*NdotI;float uval=1.0-float(udot>0.0);float vdot=-dot(Incident,Bitangent)*flip.y*NdotI;float vval=1.0-float(vdot>0.0);float Smooth_And_Active=step(1.0,float(Smooth_Active_Face && Active>0.0));uval=mix(uval,max(1.0,uval),Smooth_And_Active); +vval=mix(vval,max(1.0,vval),Smooth_And_Active);Holo_Edges=vec4(1.0,1.0,1.0,1.0)-vec4(uval*UV.x,uval*(1.0-UV.x),vval*UV.y,vval*(1.0-UV.y));} +void Object_To_World_Pos_B13( +vec3 Pos_Object, +out vec3 Pos_World) +{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;} +void Choose_Blob_B38( +vec4 Vx_Color, +vec3 Position1, +vec3 Position2, +bool Blob_Enable_1, +bool Blob_Enable_2, +float Near_Size_1, +float Near_Size_2, +float Blob_Inner_Fade_1, +float Blob_Inner_Fade_2, +float Blob_Pulse_1, +float Blob_Pulse_2, +float Blob_Fade_1, +float Blob_Fade_2, +out vec3 Position, +out float Near_Size, +out float Inner_Fade, +out float Blob_Enable, +out float Fade, +out float Pulse) +{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=float(Blob_Enable_1);float b2=float(Blob_Enable_2);Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;} +void Wireframe_Vertex_B51( +vec3 Position, +vec3 Normal, +vec3 Tangent, +vec3 Bitangent, +float Edge_Width, +vec2 Face_Size, +out vec3 Wire_Vx_Pos, +out vec2 UV, +out vec2 Widths) +{Widths.xy=Edge_Width/Face_Size;float x=dot(Position,Tangent);float y=dot(Position,Bitangent);float dx=0.5-abs(x);float newx=(0.5-dx*Widths.x*2.0)*sign(x);float dy=0.5-abs(y);float newy=(0.5-dy*Widths.y*2.0)*sign(y);Wire_Vx_Pos=Normal*0.5+newx*Tangent+newy*Bitangent;UV.x=dot(Wire_Vx_Pos,Tangent)+0.5;UV.y=dot(Wire_Vx_Pos,Bitangent)+0.5;} +vec2 ramp2(vec2 start,vec2 end,vec2 x) +{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));} +float computeSelection( +vec3 blobPosition, +vec3 normal, +vec3 tangent, +vec3 bitangent, +vec3 faceCenter, +vec2 faceSize, +float selectionFuzz, +float farDistance, +float fadeLength +) +{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;} +void Selection_Vertex_B48( +vec3 Blob_Position, +vec3 Blob_Position_2, +vec3 Face_Center, +vec2 Face_Size, +vec3 Normal, +vec3 Tangent, +vec3 Bitangent, +float Selection_Fuzz, +float Selected, +float Far_Distance, +float Fade_Length, +vec3 Active_Face_Dir, +out float Show_Selection) +{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float Active=max(0.0,dot(Active_Face_Dir,Normal));Show_Selection=mix(max(select1,select2),1.0,Selected)*Active;} +void Proximity_Visibility_B54( +float Selection, +vec3 Proximity_Center, +vec3 Proximity_Center_2, +float Input_Width, +float Proximity_Far_Distance, +float Proximity_Radius, +vec3 Active_Face_Center, +vec3 Active_Face_Dir, +out float Width) +{vec3 boxEdges=(world*vec4(vec3(0.5,0.5,0.5),0.0)).xyz;float boxMaxSize=length(boxEdges);float d1=dot(Proximity_Center-Active_Face_Center,Active_Face_Dir);vec3 blob1=Proximity_Center-d1*Active_Face_Dir;float d2=dot(Proximity_Center_2-Active_Face_Center,Active_Face_Dir);vec3 blob2=Proximity_Center_2-d2*Active_Face_Dir;vec3 delta1=blob1-Active_Face_Center;vec3 delta2=blob2-Active_Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=Input_Width*(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));} +void Object_To_World_Dir_B67( +vec3 Dir_Object, +out vec3 Dir_World) +{Dir_World=(world*vec4(Dir_Object,0.0)).xyz;} +void main() +{vec3 Active_Face_Center_Q49;Active_Face_Center_Q49=(world*vec4(_Active_Face_Dir_*0.5,1.0)).xyz;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));vec3 Active_Face_Dir_Q64=normalize((world*vec4(_Active_Face_Dir_,0.0)).xyz);float Relative_Scale_Q57; +#if RELATIVE_WIDTH +Relative_Scale_Q57=length((world*vec4(vec3(0,1,0),0.0)).xyz); +#else +Relative_Scale_Q57=1.0; +#endif +vec3 Tangent_World_Q30;Tangent_World_Q30=(world*vec4(tangent,0.0)).xyz;vec3 Binormal_World_Q31;Binormal_World_Q31=(world*vec4((cross(normal,tangent)),0.0)).xyz;vec3 Normal_World_Q60;Normal_World_Q60=(world*vec4(normal,0.0)).xyz;vec3 Result_Q18=0.5*normal;vec3 Dir_World_Q67;Object_To_World_Dir_B67(_Active_Face_Up_,Dir_World_Q67);float Product_Q56=_Edge_Width_*Relative_Scale_Q57;vec3 Normal_World_N_Q29=normalize(Normal_World_Q60);vec3 Tangent_World_N_Q28=normalize(Tangent_World_Q30);vec3 Binormal_World_N_Q32=normalize(Binormal_World_Q31);vec3 Position_Q38;float Near_Size_Q38;float Inner_Fade_Q38;float Blob_Enable_Q38;float Fade_Q38;float Pulse_Q38;Choose_Blob_B38(color,Blob_Position_Q41,Blob_Position_Q42,_Blob_Enable_,_Blob_Enable_2_,_Blob_Near_Size_,_Blob_Near_Size_2_,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q38,Near_Size_Q38,Inner_Fade_Q38,Blob_Enable_Q38,Fade_Q38,Pulse_Q38);vec3 Face_Center_Q33;Face_Center_Q33=(world*vec4(Result_Q18,1.0)).xyz;vec2 Face_Size_Q50=vec2(length(Tangent_World_Q30),length(Binormal_World_Q31));float Show_Selection_Q48;Selection_Vertex_B48(Blob_Position_Q41,Blob_Position_Q42,Face_Center_Q33,Face_Size_Q50,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,Active_Face_Dir_Q64,Show_Selection_Q48);vec3 Normalized_Q72=normalize(Dir_World_Q67);float Active_Q34=max(0.0,dot(Active_Face_Dir_Q64,Normal_World_N_Q29));float Width_Q54;Proximity_Visibility_B54(Show_Selection_Q48,Blob_Position_Q41,Blob_Position_Q42,Product_Q56,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Active_Face_Center_Q49,Active_Face_Dir_Q64,Width_Q54);vec3 Wire_Vx_Pos_Q51;vec2 UV_Q51;vec2 Widths_Q51;Wireframe_Vertex_B51(position,normal,tangent,(cross(normal,tangent)),Width_Q54,Face_Size_Q50,Wire_Vx_Pos_Q51,UV_Q51,Widths_Q51);vec3 Vec3_Q27=vec3(Widths_Q51.x,Widths_Q51.y,color.r);vec3 Pos_World_Q13;Object_To_World_Pos_B13(Wire_Vx_Pos_Q51,Pos_World_Q13);vec3 Incident_Q36=normalize(Pos_World_Q13-cameraPosition);vec3 Out_Position_Q47;vec2 Out_UV_Q47;vec3 Blob_Info_Q47;Blob_Vertex_B47(Pos_World_Q13,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,Position_Q38,_Blob_Intensity_,Near_Size_Q38,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q33,Face_Size_Q50,UV_Q51,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q38,Active_Face_Center_Q49,Pulse_Q38,Fade_Q38,Blob_Enable_Q38,Out_Position_Q47,Out_UV_Q47,Blob_Info_Q47);vec4 Extra1_Q66;float Distance_To_Face_Q66;float Intensity_Q66;Proximity_Vertex_B66(Blob_Position_Q41,Blob_Position_Q42,Active_Face_Center_Q49,Active_Face_Dir_Q64,Pos_World_Q13,_Proximity_Far_Distance_,Relative_Scale_Q57,_Proximity_Anisotropy_,Normalized_Q72,Extra1_Q66,Distance_To_Face_Q66,Intensity_Q66);vec4 Holo_Edges_Q44;Holo_Edge_Vertex_B44(Incident_Q36,Normal_World_N_Q29,uv,Tangent_World_Q30,Binormal_World_Q31,_Smooth_Active_Face_,Active_Q34,Holo_Edges_Q44);vec3 Vec3_Q19=vec3(Show_Selection_Q48,Distance_To_Face_Q66,Intensity_Q66);vec3 Position=Out_Position_Q47;vec2 UV=Out_UV_Q47;vec3 Tangent=Blob_Info_Q47;vec3 Binormal=Vec3_Q19;vec3 Normal=Vec3_Q27;vec4 Extra1=Extra1_Q66;vec4 Color=Holo_Edges_Q44;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;}`;Ue.ShadersStore[oSe]=lSe;class cSe extends ta{constructor(){super(),this.RELATIVE_WIDTH=!0,this.ENABLE_FADE=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class In extends Bl{constructor(e,t){super(e,t),this.edgeWidth=.04,this.edgeColor=new Zt(.592157,.592157,.592157,1),this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=1.5,this.proximityAnisotropy=1,this.selectionFuzz=.5,this.selected=0,this.selectionFade=0,this.selectionFadeSize=.3,this.selectedDistance=.08,this.selectedFadeLength=.08,this.blobIntensity=.5,this.blobFarSize=.05,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.leftBlobEnable=!0,this.leftBlobNearSize=.025,this.leftBlobPulse=0,this.leftBlobFade=1,this.leftBlobInnerFade=.01,this.rightBlobEnable=!0,this.rightBlobNearSize=.025,this.rightBlobPulse=0,this.rightBlobFade=1,this.rightBlobInnerFade=.01,this.activeFaceDir=new O(0,0,-1),this.activeFaceUp=new O(0,1,0),this.enableFade=!0,this.fadeWidth=1.5,this.smoothActiveFace=!0,this.showFrame=!1,this.useBlobTexture=!0,this.globalLeftIndexTipPosition=O.Zero(),this.globalRightIndexTipPosition=O.Zero(),this.alphaMode=it.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new Te(In.BLOB_TEXTURE_URL,this.getScene(),!0,!1,Te.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new cSe);const i=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(ze.PrepareDefinesForAttributes(e,i,!0,!1),i.isDirty){i.markAsProcessed(),s.resetCachedMaterial();const n=new Fl;i.FOG&&n.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(i,n),i.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[se.PositionKind];i.NORMAL&&o.push(se.NormalKind),i.UV1&&o.push(se.UVKind),i.UV2&&o.push(se.UV2Kind),i.VERTEXCOLOR&&o.push(se.ColorKind),i.TANGENT&&o.push(se.TangentKind),ze.PrepareAttributesForInstances(o,i);const l="fluentButton",c=i.toString(),h=["world","viewProjection","cameraPosition","_Edge_Width_","_Edge_Color_","_Relative_Width_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Active_Face_Dir_","_Active_Face_Up_","_Enable_Fade_","_Fade_Width_","_Smooth_Active_Face_","_Show_Frame_","_Use_Blob_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],u=["_Blob_Texture_"],p=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:i,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:c,fallbacks:n,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),i,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(i._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setColor4("_Edge_Color_",new Ie(this.edgeColor.r,this.edgeColor.g,this.edgeColor.b),this.edgeColor.a),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Blob_Enable_",this.leftBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.leftBlobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.leftBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.leftBlobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.leftBlobFade),this._activeEffect.setFloat("_Blob_Enable_2_",this.rightBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.rightBlobNearSize),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.rightBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_2_",this.rightBlobPulse),this._activeEffect.setFloat("_Blob_Fade_2_",this.rightBlobFade),this._activeEffect.setVector3("_Active_Face_Dir_",this.activeFaceDir),this._activeEffect.setVector3("_Active_Face_Up_",this.activeFaceUp),this._activeEffect.setFloat("_Fade_Width_",this.fadeWidth),this._activeEffect.setFloat("_Smooth_Active_Face_",this.smoothActiveFace?1:0),this._activeEffect.setFloat("_Show_Frame_",this.showFrame?1:0),this._activeEffect.setFloat("_Use_Blob_Texture_",this.useBlobTexture?1:0),this._activeEffect.setFloat("Use_Global_Left_Index",1),this._activeEffect.setFloat("Use_Global_Right_Index",1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",new Ui(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1)),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",new Ui(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1)),this._afterBind(t,this._activeEffect))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return Kt.Clone(()=>new In(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentButtonMaterial",e}getClassName(){return"FluentButtonMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new In(e.name,t),e,t,i)}}In.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-button-blob.png";z([X()],In.prototype,"edgeWidth",void 0);z([bF()],In.prototype,"edgeColor",void 0);z([X()],In.prototype,"proximityMaxIntensity",void 0);z([X()],In.prototype,"proximityFarDistance",void 0);z([X()],In.prototype,"proximityNearRadius",void 0);z([X()],In.prototype,"proximityAnisotropy",void 0);z([X()],In.prototype,"selectionFuzz",void 0);z([X()],In.prototype,"selected",void 0);z([X()],In.prototype,"selectionFade",void 0);z([X()],In.prototype,"selectionFadeSize",void 0);z([X()],In.prototype,"selectedDistance",void 0);z([X()],In.prototype,"selectedFadeLength",void 0);z([X()],In.prototype,"blobIntensity",void 0);z([X()],In.prototype,"blobFarSize",void 0);z([X()],In.prototype,"blobNearDistance",void 0);z([X()],In.prototype,"blobFarDistance",void 0);z([X()],In.prototype,"blobFadeLength",void 0);z([X()],In.prototype,"leftBlobEnable",void 0);z([X()],In.prototype,"leftBlobNearSize",void 0);z([X()],In.prototype,"leftBlobPulse",void 0);z([X()],In.prototype,"leftBlobFade",void 0);z([X()],In.prototype,"leftBlobInnerFade",void 0);z([X()],In.prototype,"rightBlobEnable",void 0);z([X()],In.prototype,"rightBlobNearSize",void 0);z([X()],In.prototype,"rightBlobPulse",void 0);z([X()],In.prototype,"rightBlobFade",void 0);z([X()],In.prototype,"rightBlobInnerFade",void 0);z([bo()],In.prototype,"activeFaceDir",void 0);z([bo()],In.prototype,"activeFaceUp",void 0);z([X()],In.prototype,"enableFade",void 0);z([X()],In.prototype,"fadeWidth",void 0);z([X()],In.prototype,"smoothActiveFace",void 0);z([X()],In.prototype,"showFrame",void 0);z([X()],In.prototype,"useBlobTexture",void 0);z([bo()],In.prototype,"globalLeftIndexTipPosition",void 0);z([bo()],In.prototype,"globalRightIndexTipPosition",void 0);$e("BABYLON.GUI.FluentButtonMaterial",In);class DQ extends PQ{constructor(e,t){super(e),this._isNearPressed=!1,this._interactionSurfaceHeight=0,this._isToggleButton=!1,this._toggleState=!1,this._toggleButtonCallback=()=>{this._onToggle(!this._toggleState)},this.onToggleObservable=new Se,this.collidableFrontDirection=O.Zero(),t&&(this.collisionMesh=t)}get isActiveNearInteraction(){return this._isNearPressed}set collidableFrontDirection(e){if(this._collidableFrontDirection=e.normalize(),this._collisionMesh){const t=ue.Matrix[0];t.copyFrom(this._collisionMesh.getWorldMatrix()),t.invert(),O.TransformNormalToRef(this._collidableFrontDirection,t,this._collidableFrontDirection),this._collidableFrontDirection.normalize()}}get collidableFrontDirection(){if(this._collisionMesh){const e=ue.Vector3[0];return O.TransformNormalToRef(this._collidableFrontDirection,this._collisionMesh.getWorldMatrix(),e),e.normalize()}return this._collidableFrontDirection}set collisionMesh(e){var t;this._collisionMesh&&(this._collisionMesh.isNearPickable=!1,!((t=this._collisionMesh.reservedDataStore)===null||t===void 0)&&t.GUI3D&&(this._collisionMesh.reservedDataStore.GUI3D={}),this._collisionMesh.getChildMeshes().forEach(i=>{var s;i.isNearPickable=!1,!((s=i.reservedDataStore)===null||s===void 0)&&s.GUI3D&&(i.reservedDataStore.GUI3D={})})),this._collisionMesh=e,this._injectGUI3DReservedDataStore(this._collisionMesh).control=this,this._collisionMesh.isNearPickable=!0,this._collisionMesh.getChildMeshes().forEach(i=>{this._injectGUI3DReservedDataStore(i).control=this,i.isNearPickable=!0}),this.collidableFrontDirection=e.forward}set isToggleButton(e){e!==this._isToggleButton&&(this._isToggleButton=e,e?this.onPointerUpObservable.add(this._toggleButtonCallback):(this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this._toggleState&&this._onToggle(!1)))}get isToggleButton(){return this._isToggleButton}set isToggled(e){this._isToggleButton&&this._toggleState!==e&&this._onToggle(e)}get isToggled(){return this._toggleState}_onToggle(e){this._toggleState=e,this.onToggleObservable.notifyObservers(e)}_isInteractionInFrontOfButton(e){return this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition())>0}getPressDepth(e){if(!this._isNearPressed)return 0;const t=this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition());return this._interactionSurfaceHeight-t}_getInteractionHeight(e,t){const i=this.collidableFrontDirection;if(i.length()===0)return O.Distance(e,t);const s=O.Dot(t,i);return O.Dot(e,i)-s}_generatePointerEventType(e,t,i){if(e===mi.POINTERDOWN||e===mi.POINTERMOVE)if(this._isInteractionInFrontOfButton(t))this._isNearPressed=!0,this._interactionSurfaceHeight=this._getInteractionHeight(t,this._collisionMesh.getAbsolutePosition());else return mi.POINTERMOVE;if(e===mi.POINTERUP){if(i==0)return mi.POINTERMOVE;this._isNearPressed=!1}return e}_getTypeName(){return"TouchButton3D"}_createNode(e){return super._createNode(e)}dispose(){super.dispose(),this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this.onToggleObservable.clear(),this._collisionMesh&&this._collisionMesh.dispose()}}class II extends DQ{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(!e){this._disposeTooltip();return}if(!this._tooltipFade){const t=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Jd("",{size:1},this._backPlate._scene);const i=Jd("",{size:1,sideOrientation:Oe.DOUBLESIDE},this._backPlate._scene),s=new jt("",this._backPlate._scene);s.diffuseColor=Ie.FromHexString("#212121"),i.material=s,i.isPickable=!1,this._tooltipMesh.addChild(i),i.position=O.Forward(t).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=O.Up().scale(.7).add(O.Forward(t).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=Sh.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new Ka,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new yK,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add(()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)}),this._tooltipOutObserver=this.onPointerOutObservable.add(()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)})}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&!!this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._isBackplateVisible=!0,this._frontPlateDepth=.5,this._backPlateDepth=.04,this._backplateColor=new Ie(.08,.15,.55),this._backplateToggledColor=new Ie(.25,.4,.95),this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontMaterial.leftBlobEnable=!0,this._frontMaterial.rightBlobEnable=!0},this.pointerOutAnimation=()=>{this._frontMaterial.leftBlobEnable=!1,this._frontMaterial.rightBlobEnable=!1},this.pointerDownAnimation=()=>{this._frontPlate&&!this.isActiveNearInteraction&&(this._frontPlate.scaling.z=this._frontPlateDepth*.2,this._frontPlate.position=O.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-.2*this._frontPlateDepth)/2),this._textPlate.position=O.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+.2*this._frontPlateDepth)/2))},this.pointerUpAnimation=()=>{this._frontPlate&&(this._frontPlate.scaling.z=this._frontPlateDepth,this._frontPlate.position=O.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-this._frontPlateDepth)/2),this._textPlate.position=O.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+this._frontPlateDepth)/2))},this.onPointerMoveObservable.add(i=>{if(this._frontPlate&&this.isActiveNearInteraction){const s=O.Zero();if(this._backPlate.getWorldMatrix().decompose(s,void 0,void 0)){let r=this._getInteractionHeight(i,this._backPlate.getAbsolutePosition())/s.z;r=Bt.Clamp(r-this._backPlateDepth/2,.2*this._frontPlateDepth,this._frontPlateDepth),this._frontPlate.scaling.z=r,this._frontPlate.position=O.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-r)/2),this._textPlate.position=O.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+r)/2)}}}),this._pointerHoverObserver=this.onPointerMoveObservable.add(i=>{this._frontMaterial.globalLeftIndexTipPosition=i})}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new Z2;if(e.isVertical=!0,Zb()&&!!document.createElement&&this._imageUrl){const t=new wr;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new Ka;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this.content=e}_createNode(e){var t;this.name=(t=this.name)!==null&&t!==void 0?t:"TouchHolographicButton";const i=pl(`${this.name}_collisionMesh`,{width:1,height:1,depth:this._frontPlateDepth},e);i.isPickable=!0,i.isNearPickable=!0,i.visibility=0,i.position=O.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),As.ImportMeshAsync(void 0,II.MODEL_BASE_URL,II.MODEL_FILENAME,e).then(r=>{const n=pl("${this.name}_alphaMesh",{width:1,height:1,depth:1},e);n.isPickable=!1,n.material=new jt("${this.name}_alphaMesh_material",e),n.material.alpha=.15;const o=r.meshes[1];o.name=`${this.name}_frontPlate`,o.isPickable=!1,o.scaling.z=this._frontPlateDepth,n.parent=o,o.parent=i,this._frontMaterial&&(o.material=this._frontMaterial),this._frontPlate=o}),this._backPlate=pl(`${this.name}_backPlate`,{width:1,height:1,depth:this._backPlateDepth},e),this._backPlate.position=O.Forward(e.useRightHandedSystem).scale(this._backPlateDepth/2),this._backPlate.isPickable=!1,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.position=O.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),this._backPlate.addChild(i),this._backPlate.addChild(this._textPlate);const s=new Ki("{this.name}_root",e);return this._backPlate.setParent(s),this.collisionMesh=i,this.collidableFrontDirection=this._backPlate.forward.negate(),s}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=new Ie(.4,.4,.4)}_createBackMaterial(e){this._backMaterial=new pu(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.albedoColor=this._backplateColor,this._backMaterial.renderBorders=!0,this._backMaterial.renderHoverLight=!1}_createFrontMaterial(e){this._frontMaterial=new In(this.name+"Front Material",e.getScene())}_createPlateMaterial(e){this._plateMaterial=new jt(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ie.Black()}_onToggle(e){this._backMaterial&&(e?this._backMaterial.albedoColor=this._backplateToggledColor:this._backMaterial.albedoColor=this._backplateColor),super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.backFluentMaterial?this._backMaterial=this._host._touchSharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.backFluentMaterial=this._backMaterial),this._host._touchSharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._touchSharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerMoveObservable.remove(this._pointerHoverObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}II.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/";II.MODEL_FILENAME="mrtk-fluent-button.glb";class x1e{constructor(){this.followBehaviorEnabled=!1,this.sixDofDragBehaviorEnabled=!0,this.surfaceMagnetismBehaviorEnabled=!0,this._followBehavior=new kle,this._sixDofDragBehavior=new Z$,this._surfaceMagnetismBehavior=new Ule}get name(){return"Default"}get followBehavior(){return this._followBehavior}get sixDofDragBehavior(){return this._sixDofDragBehavior}get surfaceMagnetismBehavior(){return this._surfaceMagnetismBehavior}init(){}attach(e,t,i){this._scene=e.getScene(),this.attachedNode=e,this._addObservables(),this._followBehavior.attach(e),this._sixDofDragBehavior.attach(e),this._sixDofDragBehavior.draggableMeshes=t||null,this._sixDofDragBehavior.faceCameraOnDragStart=!0,this._surfaceMagnetismBehavior.attach(e,this._scene),i&&(this._surfaceMagnetismBehavior.meshes=i),this._surfaceMagnetismBehavior.enabled=!1}detach(){this.attachedNode=null,this._removeObservables(),this._followBehavior.detach(),this._sixDofDragBehavior.detach(),this._surfaceMagnetismBehavior.detach()}_addObservables(){this._onBeforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{this._followBehavior._enabled=!this._sixDofDragBehavior.isMoving&&this.followBehaviorEnabled}),this._onDragObserver=this._sixDofDragBehavior.onDragObservable.add(e=>{this._sixDofDragBehavior.disableMovement=this._surfaceMagnetismBehavior.findAndUpdateTarget(e.pickInfo)})}_removeObservables(){this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._sixDofDragBehavior.onDragObservable.remove(this._onDragObserver)}}const hSe="handleVertexShader",uSe="precision highp float;attribute vec3 position;uniform vec3 positionOffset;uniform mat4 worldViewProjection;uniform float scale;void main(void) {vec4 vPos=vec4((vec3(position)+positionOffset)*scale,1.0);gl_Position=worldViewProjection*vPos;}";Ue.ShadersStore[hSe]=uSe;const dSe="handlePixelShader",fSe="uniform vec3 color;void main(void) {gl_FragColor=vec4(color,1.0);}";Ue.ShadersStore[dSe]=fSe;class b1e extends oh{get hover(){return this._hover}set hover(e){this._hover=e,this._updateInterpolationTarget()}get drag(){return this._drag}set drag(e){this._drag=e,this._updateInterpolationTarget()}constructor(e,t){super(e,t,"handle",{attributes:["position"],uniforms:["worldViewProjection","color","scale","positionOffset"],needAlphaBlending:!1,needAlphaTesting:!1}),this._hover=!1,this._drag=!1,this._color=new Ie,this._scale=1,this._lastTick=-1,this.animationLength=100,this.hoverColor=new Ie(0,.467,.84),this.baseColor=new Ie(1,1,1),this.hoverScale=.75,this.baseScale=.35,this.dragScale=.55,this._positionOffset=O.Zero(),this._updateInterpolationTarget(),this._lastTick=Date.now(),this._onBeforeRender=this.getScene().onBeforeRenderObservable.add(()=>{const i=Date.now(),s=i-this._lastTick,r=this._targetScale-this._scale,n=hn.Color3[0].copyFrom(this._targetColor).subtractToRef(this._color,hn.Color3[0]);this._scale=this._scale+r*s/this.animationLength,n.scaleToRef(s/this.animationLength,n),this._color.addToRef(n,this._color),this.setColor3("color",this._color),this.setFloat("scale",this._scale),this.setVector3("positionOffset",this._positionOffset),this._lastTick=i})}_updateInterpolationTarget(){this.drag?(this._targetColor=this.hoverColor,this._targetScale=this.dragScale):this.hover?(this._targetColor=this.hoverColor,this._targetScale=this.hoverScale):(this._targetColor=this.baseColor,this._targetScale=this.baseScale)}dispose(){super.dispose(),this.getScene().onBeforeRenderObservable.remove(this._onBeforeRender)}}var yM;(function(a){a[a.IDLE=0]="IDLE",a[a.HOVER=1]="HOVER",a[a.DRAG=2]="DRAG"})(yM||(yM={}));class Yte{get state(){return this._state}get gizmo(){return this._gizmo}set hover(e){e?this._state|=yM.HOVER:this._state&=~yM.HOVER,this._updateMaterial()}set drag(e){e?this._state|=yM.DRAG:this._state&=~yM.DRAG,this._updateMaterial()}constructor(e,t){this._state=yM.IDLE,this._materials=[],this._scene=t,this._gizmo=e,this.node=this.createNode(),this.node.reservedDataStore={handle:this}}_createMaterial(e){const t=new b1e("handle",this._scene);return e&&(t._positionOffset=e),t}_updateMaterial(){const e=this._state;for(const t of this._materials)t.hover=!1,t.drag=!1;if(e&yM.DRAG)for(const t of this._materials)t.drag=!0;else if(e&yM.HOVER)for(const t of this._materials)t.hover=!0}setDragBehavior(e,t,i){const s=new Fb;this._dragBehavior=s,this._dragStartObserver=s.onDragStartObservable.add(e),this._draggingObserver=s.onDragObservable.add(t),this._dragEndObserver=s.onDragEndObservable.add(i),this._dragBehavior.attach(this.node)}dispose(){this._dragBehavior.onDragStartObservable.remove(this._dragStartObserver),this._dragBehavior.onDragObservable.remove(this._draggingObserver),this._dragBehavior.onDragEndObservable.remove(this._dragEndObserver),this._dragBehavior.detach();for(const e of this._materials)e.dispose();this.node.dispose()}}class E1e extends Yte{createNode(){const e=pl("sideVert",{width:1,height:10,depth:.1},this._scene),t=new Ki("side",this._scene);e.parent=t;const i=this._createMaterial();return e.material=i,e.isNearGrabbable=!0,this._materials.push(i),t}}class y1e extends Yte{createNode(){const e=pl("angleHor",{width:3,height:1,depth:.1},this._scene),t=pl("angleVert",{width:1,height:3,depth:.1},this._scene),i=new Ki("angle",this._scene);return e.parent=i,t.parent=i,e.material=this._createMaterial(new O(1,0,0)),t.material=this._createMaterial(new O(0,1,0)),t.isNearGrabbable=!0,e.isNearGrabbable=!0,this._materials.push(e.material),this._materials.push(t.material),i}}class M1e extends ua{set attachedSlate(e){e?(this.attachedMesh=e.mesh,this.updateBoundingBox(),this._pickedPointObserver=e._host.onPickingObservable.add(t=>{if(this._handleHovered&&(!t||t.parent!==this._handleHovered.node)&&(this._handleHovered.hover=!1,this._handleHovered=null),t&&t.parent&&t.parent.reservedDataStore&&t.parent.reservedDataStore.handle){const i=t.parent.reservedDataStore.handle;i.gizmo===this&&(this._handleHovered=i,this._handleHovered.hover=!0)}})):this._attachedSlate&&this._attachedSlate._host.onPickingObservable.remove(this._pickedPointObserver),this._attachedSlate=e}get attachedSlate(){return this._attachedSlate}constructor(e){super(e),this._boundingDimensions=new O(0,0,0),this._renderObserver=null,this._tmpQuaternion=new ke,this._tmpVector=new O(0,0,0),this._corners=[],this._sides=[],this._boundingBoxGizmo={min:new O,max:new O},this._margin=.35,this._handleSize=.075,this._attachedSlate=null,this._existingSlateScale=new O,this.fixedScreenSize=!1,this.fixedScreenSizeDistanceFactor=10,this._createNode(),this.updateScale=!1,this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add(()=>{this.attachedMesh&&!this._existingSlateScale.equals(this.attachedMesh.scaling)&&this.updateBoundingBox()})}_createNode(){this._handlesParent=new Ki("handlesParent",this.gizmoLayer.utilityLayerScene),this._handlesParent.rotationQuaternion=ke.Identity();const e=[{dimensions:new O(-1,-1,0),origin:new O(1,0,0)},{dimensions:new O(1,-1,0),origin:new O(0,0,0)},{dimensions:new O(1,1,0),origin:new O(0,1,0)},{dimensions:new O(-1,1,0),origin:new O(1,1,0)}];for(let t=0;t<4;t++){const i=new y1e(this,this.gizmoLayer.utilityLayerScene);this._corners.push(i),i.node.rotation.z=Math.PI/2*t,i.node.parent=this._handlesParent,this._assignDragBehaviorCorners(i,(s,r,n,o)=>this._moveHandle(s,r,n,o,!0),e[t])}for(let t=0;t<4;t++){const i=new E1e(this,this.gizmoLayer.utilityLayerScene);this._sides.push(i),i.node.rotation.z=Math.PI/2*t,i.node.parent=this._handlesParent,this._assignDragBehaviorSides(i,t%2===0?new O(0,1,0):new O(1,0,0))}this._handlesParent.parent=this._rootMesh}_keepAspectRatio(e,t,i=!1){const s=ue.Vector3[0];s.copyFromFloats(t,1,0).normalize(),i&&(s.y*=-1);const r=O.Dot(e,s);e.copyFrom(s).scaleInPlace(r)}_clampDimensions(e,t,i,s=!1){const r=ue.Vector3[0];r.copyFrom(e).multiplyInPlace(i);const n=ue.Vector3[1];if(n.copyFromFloats(Math.max(this._attachedSlate.minDimensions.x,r.x+t.x),Math.max(this._attachedSlate.minDimensions.y,r.y+t.y),0),s){const o=t.x/t.y;n.x=Math.max(n.x,n.y*o),n.y=Math.max(n.y,n.x/o)}r.copyFrom(n).subtractInPlace(t),e.x=Math.sign(e.x)*Math.abs(r.x),e.y=Math.sign(e.y)*Math.abs(r.y)}_moveHandle(e,t,i,s,r){if(!this._attachedSlate)return;if(r){const l=t.x/t.y;this._keepAspectRatio(i,l,s.dimensions.x*s.dimensions.y<0)}this._clampDimensions(i,t,s.dimensions,r);const n=ue.Vector3[0],o=ue.Vector3[1];n.copyFrom(i).multiplyInPlace(s.origin),o.copyFrom(i).multiplyInPlace(s.dimensions),this._attachedSlate.origin.copyFrom(e).addInPlace(n),this._attachedSlate.dimensions.set(t.x+o.x,t.y+o.y)}_assignDragBehaviorCorners(e,t,i){const s=new O,r=new O,n=new O,o=new ge,l=new O,c=(m,_,f,d)=>{m.subtractToRef(f,ue.Vector3[0]);const C=O.Dot(ue.Vector3[0],_);ue.Vector3[1].copyFrom(_).scaleInPlace(C),ue.Vector3[0].subtractInPlace(ue.Vector3[1]),ue.Vector3[0].addToRef(f,d)},h=m=>{this.attachedSlate&&this.attachedMesh&&(s.set(this.attachedSlate.dimensions.x,this.attachedSlate.dimensions.y,Ls),r.copyFrom(this.attachedSlate.origin),n.copyFrom(m.position),o.copyFrom(this.attachedMesh.computeWorldMatrix(!0)),o.invert(),this.attachedSlate._followButton.isToggled=!1,O.TransformNormalToRef(O.Forward(),this.attachedMesh.getWorldMatrix(),l),l.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))},u=m=>{this.attachedSlate&&this.attachedMesh&&(c(m.position,l,n,this._tmpVector),this._tmpVector.subtractInPlace(n),O.TransformNormalToRef(this._tmpVector,o,this._tmpVector),t(r,s,this._tmpVector,i),this.attachedSlate._positionElements(),this.updateBoundingBox())},p=()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))};e.setDragBehavior(h,u,p)}_assignDragBehaviorSides(e,t){const i=new ke,s=new O,r=new O,n=new O,o=new O,l=u=>{this.attachedSlate&&this.attachedMesh&&(i.copyFrom(this.attachedMesh.rotationQuaternion),s.copyFrom(u.position),n.copyFrom(this.attachedMesh.getAbsolutePivotPoint()),r.copyFrom(s).subtractInPlace(n).normalize(),this.attachedSlate._followButton.isToggled=!1,O.TransformNormalToRef(t,this.attachedMesh.getWorldMatrix(),o),o.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))},c=u=>{if(this.attachedSlate&&this.attachedMesh){this._tmpVector.copyFrom(u.position),this._tmpVector.subtractInPlace(n),this._tmpVector.normalize();const p=-O.GetAngleBetweenVectorsOnPlane(this._tmpVector,r,o);ke.RotationAxisToRef(t,p,this._tmpQuaternion),i.multiplyToRef(this._tmpQuaternion,this.attachedMesh.rotationQuaternion)}},h=()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))};e.setDragBehavior(l,c,h)}_attachedNodeChanged(e){e&&this.updateBoundingBox()}updateBoundingBox(){if(this.attachedMesh){yn._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=ke.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),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();t.max.subtractToRef(t.min,this._boundingDimensions),this._boundingBoxGizmo.min=t.min,this._boundingBoxGizmo.max=t.max,this._updateHandlesPosition(),this._updateHandlesScaling(),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),yn._RestorePivotPoint(this.attachedMesh),this.attachedMesh.setParent(e),this.attachedMesh.computeWorldMatrix(!0),this._existingSlateScale.copyFrom(this.attachedMesh.scaling)}}_updateHandlesPosition(){const e=this._boundingBoxGizmo.min.clone(),t=this._boundingBoxGizmo.max.clone(),i=this._corners[0].node.scaling.length();e.x-=this._margin*i,e.y-=this._margin*i,t.x+=this._margin*i,t.y+=this._margin*i;const s=e.add(t).scaleInPlace(.5);this._corners[0].node.position.copyFromFloats(e.x,e.y,0),this._corners[1].node.position.copyFromFloats(t.x,e.y,0),this._corners[2].node.position.copyFromFloats(t.x,t.y,0),this._corners[3].node.position.copyFromFloats(e.x,t.y,0),this._sides[0].node.position.copyFromFloats(e.x,s.y,0),this._sides[1].node.position.copyFromFloats(s.x,e.y,0),this._sides[2].node.position.copyFromFloats(t.x,s.y,0),this._sides[3].node.position.copyFromFloats(s.x,t.y,0)}_updateHandlesScaling(){if(this._attachedSlate&&this._attachedSlate.mesh){const e=this._attachedSlate.mesh.scaling.x*this._attachedSlate.dimensions.x,t=this._attachedSlate.mesh.scaling.y*this._attachedSlate.dimensions.y,i=Math.min(e,t)*this._handleSize;for(let s=0;si?t=this.minDimensions.x/e.x:t=this.minDimensions.y/e.y}this._dimensions.copyFrom(e).scaleInPlace(t),this._updatePivot(),this._positionElements()}get titleBarHeight(){return this._titleBarHeight}set titleBarHeight(e){this._titleBarHeight=e}set renderingGroupId(e){this._titleBar.renderingGroupId=e,this._titleBarTitle.renderingGroupId=e,this._contentPlate.renderingGroupId=e,this._backPlate.renderingGroupId=e}get renderingGroupId(){return this._titleBar.renderingGroupId}set title(e){this._titleText=e,this._titleTextComponent&&(this._titleTextComponent.text=e)}get title(){return this._titleText}constructor(e){super(e),this.titleBarMargin=.005,this.origin=new O(0,0,0),this._dimensions=new lt(21.875,12.5),this._titleBarHeight=.625,this._titleText="",this._contentScaleRatio=1,this.minDimensions=new lt(15.625,6.25),this.defaultDimensions=this._dimensions.clone(),this._followButton=new II("followButton"+this.name),this._followButton.isToggleButton=!0,this._closeButton=new II("closeButton"+this.name),this._contentViewport=new hu(0,0,1,1),this._contentDragBehavior=new uc({dragPlaneNormal:new O(0,0,-1)})}_applyFacade(e){this._contentMaterial.albedoTexture=e,this._resetContentPositionAndZoom(),this._applyContentViewport(),e.attachToMesh(this._contentPlate,!0)}_addControl(e){e._host=this._host,this._host.utilityLayer&&e._prepareNode(this._host.utilityLayer.utilityLayerScene)}_getTypeName(){return"HolographicSlate"}_positionElements(){const e=this._followButton,t=this._closeButton,i=this._titleBar,s=this._titleBarTitle,r=this._contentPlate,n=this._backPlate;if(e&&t&&i){t.scaling.setAll(this.titleBarHeight),e.scaling.setAll(this.titleBarHeight),t.position.copyFromFloats(this.dimensions.x-this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin),e.position.copyFromFloats(this.dimensions.x-3*this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin);const o=this.dimensions.y-this.titleBarHeight-this.titleBarMargin,l=r.getScene().useRightHandedSystem;i.scaling.set(this.dimensions.x,this.titleBarHeight,Ls),s.scaling.set(this.dimensions.x-2*this.titleBarHeight,this.titleBarHeight,Ls),r.scaling.copyFromFloats(this.dimensions.x,o,Ls),n.scaling.copyFromFloats(this.dimensions.x,o,Ls),i.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight/2),0).addInPlace(this.origin),s.position.copyFromFloats(this.dimensions.x/2-this.titleBarHeight,-(this.titleBarHeight/2),l?Ls:-Ls).addInPlace(this.origin),r.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),0).addInPlace(this.origin),n.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),l?-Ls:Ls).addInPlace(this.origin),this._titleTextComponent.host.scaleTo(d_._DEFAULT_TEXT_RESOLUTION_Y*s.scaling.x/s.scaling.y,d_._DEFAULT_TEXT_RESOLUTION_Y);const c=this.dimensions.x/o;this._contentViewport.width=this._contentScaleRatio,this._contentViewport.height=this._contentScaleRatio/c,this._applyContentViewport(),this._gizmo&&this._gizmo.updateBoundingBox()}}_applyContentViewport(){var e;if(((e=this._contentPlate)===null||e===void 0?void 0:e.material)&&this._contentPlate.material.albedoTexture){const t=this._contentPlate.material.albedoTexture;t.uScale=this._contentScaleRatio,t.vScale=this._contentScaleRatio/this._contentViewport.width*this._contentViewport.height,t.uOffset=this._contentViewport.x,t.vOffset=this._contentViewport.y}}_resetContentPositionAndZoom(){this._contentViewport.x=0,this._contentViewport.y=1-this._contentViewport.height/this._contentViewport.width,this._contentScaleRatio=1}_updatePivot(){if(!this.mesh)return;const e=new O(this.dimensions.x*.5,-this.dimensions.y*.5,Ls);e.addInPlace(this.origin),e.z=0;const t=new O(0,0,0);O.TransformCoordinatesToRef(t,this.mesh.computeWorldMatrix(!0),t),this.mesh.setPivotPoint(e);const i=new O(0,0,0);O.TransformCoordinatesToRef(i,this.mesh.computeWorldMatrix(!0),i),this.mesh.position.addInPlace(t).subtractInPlace(i)}_createNode(e){const t=new Oe("slate_"+this.name,e);this._titleBar=pl("titleBar_"+this.name,{size:1},e),this._titleBarTitle=Jd("titleText_"+this.name,{size:1},e),this._titleBarTitle.parent=t,this._titleBarTitle.isPickable=!1;const i=Sh.CreateForMesh(this._titleBarTitle);if(this._titleTextComponent=new Ka("titleText_"+this.name,this._titleText),this._titleTextComponent.textWrapping=FM.Ellipsis,this._titleTextComponent.textHorizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,this._titleTextComponent.color="white",this._titleTextComponent.fontSize=d_._DEFAULT_TEXT_RESOLUTION_Y/2,this._titleTextComponent.paddingLeft=d_._DEFAULT_TEXT_RESOLUTION_Y/4,i.addControl(this._titleTextComponent),e.useRightHandedSystem){const n=new Ui(0,0,1,1);this._contentPlate=Jd("contentPlate_"+this.name,{size:1,sideOrientation:Jt.BACKSIDE,frontUVs:n},e),this._backPlate=Jd("backPlate_"+this.name,{size:1,sideOrientation:Jt.FRONTSIDE},e)}else{const n=new Ui(0,0,1,1);this._contentPlate=Jd("contentPlate_"+this.name,{size:1,sideOrientation:Jt.FRONTSIDE,frontUVs:n},e),this._backPlate=Jd("backPlate_"+this.name,{size:1,sideOrientation:Jt.BACKSIDE},e)}this._titleBar.parent=t,this._titleBar.isNearGrabbable=!0,this._contentPlate.parent=t,this._backPlate.parent=t,this._attachContentPlateBehavior(),this._addControl(this._followButton),this._addControl(this._closeButton);const s=this._followButton,r=this._closeButton;return s.node.parent=t,r.node.parent=t,this._positionElements(),this._followButton.imageUrl=d_.ASSETS_BASE_URL+d_.FOLLOW_ICON_FILENAME,this._closeButton.imageUrl=d_.ASSETS_BASE_URL+d_.CLOSE_ICON_FILENAME,this._followButton.isBackplateVisible=!1,this._closeButton.isBackplateVisible=!1,this._followButton.onToggleObservable.add(n=>{this._defaultBehavior.followBehaviorEnabled=n,this._defaultBehavior.followBehaviorEnabled&&this._defaultBehavior.followBehavior.recenter()}),this._closeButton.onPointerClickObservable.add(()=>{this.dispose()}),t.rotationQuaternion=ke.Identity(),t.isVisible=!1,t}_attachContentPlateBehavior(){this._contentDragBehavior.attach(this._contentPlate),this._contentDragBehavior.moveAttached=!1,this._contentDragBehavior.useObjectOrientationForDragging=!0,this._contentDragBehavior.updateDragPlane=!1;const e=new O,t=new O,i=new O,s=new O,r=new lt;let n,o;this._contentDragBehavior.onDragStartObservable.add(c=>{!this.node||(n=this._contentViewport.clone(),o=this.node.computeWorldMatrix(!0),e.copyFrom(c.dragPlanePoint),t.set(this.dimensions.x,this.dimensions.y,Ls),t.y-=this.titleBarHeight+this.titleBarMargin,O.TransformNormalToRef(t,o,t),i.copyFromFloats(0,1,0),O.TransformNormalToRef(i,o,i),s.copyFromFloats(1,0,0),O.TransformNormalToRef(s,o,s),i.normalize(),i.scaleInPlace(1/O.Dot(i,t)),s.normalize(),s.scaleInPlace(1/O.Dot(s,t)))});const l=new O;this._contentDragBehavior.onDragObservable.add(c=>{l.copyFrom(c.dragPlanePoint),l.subtractInPlace(e),r.copyFromFloats(O.Dot(l,s),O.Dot(l,i)),this._contentViewport.x=Bt.Clamp(n.x-l.x,0,1-this._contentViewport.width*this._contentScaleRatio),this._contentViewport.y=Bt.Clamp(n.y-l.y,0,1-this._contentViewport.height*this._contentScaleRatio),this._applyContentViewport()})}_affectMaterial(e){this._titleBarMaterial=new Qa(`${this.name} plateMaterial`,e.getScene()),this._contentMaterial=new pu(`${this.name} contentMaterial`,e.getScene()),this._contentMaterial.renderBorders=!0,this._backMaterial=new Qa(`${this.name} backPlate`,e.getScene()),this._backMaterial.lineWidth=Ls,this._backMaterial.radius=.005,this._backMaterial.backFaceCulling=!0,this._titleBar.material=this._titleBarMaterial,this._contentPlate.material=this._contentMaterial,this._backPlate.material=this._backMaterial,this._resetContent(),this._applyContentViewport()}_prepareNode(e){super._prepareNode(e),this._gizmo=new M1e(this._host.utilityLayer),this._gizmo.attachedSlate=this,this._defaultBehavior=new x1e,this._defaultBehavior.attach(this.node,[this._titleBar]),this._defaultBehavior.sixDofDragBehavior.onDragStartObservable.add(()=>{this._followButton.isToggled=!1}),this._positionChangedObserver=this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.add(()=>{this._gizmo.updateBoundingBox()}),this._updatePivot(),this.resetDefaultAspectAndPose(!1)}resetDefaultAspectAndPose(e=!0){if(!this._host||!this._host.utilityLayer||!this.node)return;const t=this._host.utilityLayer.utilityLayerScene,i=t.activeCamera;if(i){const s=i.getWorldMatrix(),r=O.TransformNormal(O.Backward(t.useRightHandedSystem),s);this.origin.setAll(0),this._gizmo.updateBoundingBox();const n=this.node.getAbsolutePivotPoint();this.node.position.copyFrom(i.position).subtractInPlace(r).subtractInPlace(n),this.node.rotationQuaternion=ke.FromLookDirectionLH(r,new O(0,1,0)),e&&(this.dimensions=this.defaultDimensions)}}dispose(){super.dispose(),this._titleBarMaterial.dispose(),this._contentMaterial.dispose(),this._titleBar.dispose(),this._titleBarTitle.dispose(),this._contentPlate.dispose(),this._backPlate.dispose(),this._followButton.dispose(),this._closeButton.dispose(),this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.remove(this._positionChangedObserver),this._defaultBehavior.detach(),this._gizmo.dispose(),this._contentDragBehavior.detach()}}d_.ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/";d_.CLOSE_ICON_FILENAME="IconClose.png";d_.FOLLOW_ICON_FILENAME="IconFollowMe.png";d_._DEFAULT_TEXT_RESOLUTION_Y=102.4;class pSe extends PQ{constructor(e,t){super(t),this._currentMesh=e,this.pointerEnterAnimation=()=>{!this.mesh||this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{!this.mesh||this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{!this.mesh||this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{!this.mesh||this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"MeshButton3D"}_createNode(e){return this._currentMesh.getChildMeshes().forEach(t=>{this._injectGUI3DReservedDataStore(t).control=this}),this._currentMesh}_affectMaterial(e){}}class rF extends NL{get defaultBehavior(){return this._defaultBehavior}get isPinned(){return this._isPinned}set isPinned(e){if(this._pinButton.isToggled!==e){this._pinButton.isToggled=e;return}this._isPinned=e,e?this._defaultBehavior.followBehaviorEnabled=!1:this._defaultBehavior.followBehaviorEnabled=!0}_createPinButton(e){const t=new II("pin"+this.name,!1);return t.imageUrl=rF._ASSETS_BASE_URL+rF._PIN_ICON_FILENAME,t.parent=this,t._host=this._host,t.isToggleButton=!0,t.onToggleObservable.add(i=>{this.isPinned=i}),this._host.utilityLayer&&(t._prepareNode(this._host.utilityLayer.utilityLayerScene),t.scaling.scaleInPlace(NL.MENU_BUTTON_SCALE),t.node&&(t.node.parent=e)),t}_createNode(e){const t=super._createNode(e);return this._pinButton=this._createPinButton(t),this.isPinned=!1,this._defaultBehavior.attach(t,[this._backPlate]),this._defaultBehavior.followBehavior.ignoreCameraPitchAndRoll=!0,this._defaultBehavior.followBehavior.pitchOffset=-15,this._defaultBehavior.followBehavior.minimumDistance=.3,this._defaultBehavior.followBehavior.defaultDistance=.4,this._defaultBehavior.followBehavior.maximumDistance=.6,this._backPlate.isNearGrabbable=!0,t.isVisible=!1,t}_finalProcessing(){super._finalProcessing(),this._pinButton.position.copyFromFloats((this._backPlate.scaling.x+NL.MENU_BUTTON_SCALE)/2,this._backPlate.scaling.y/2,0)}constructor(e){super(e),this._isPinned=!1,this._defaultBehavior=new x1e,this._dragObserver=this._defaultBehavior.sixDofDragBehavior.onDragObservable.add(()=>{this.isPinned=!0}),this.backPlateMargin=1}dispose(){super.dispose(),this._defaultBehavior.sixDofDragBehavior.onDragObservable.remove(this._dragObserver),this._defaultBehavior.detach()}}rF._ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/";rF._PIN_ICON_FILENAME="IconPin.png";class mSe extends FF{_mapGridNode(e,t){const i=e.mesh;if(!i)return;e.position=t.clone();const s=ue.Vector3[0];switch(s.copyFrom(t),this.orientation){case Rc.FACEORIGIN_ORIENTATION:case Rc.FACEFORWARD_ORIENTATION:s.addInPlace(new O(0,0,1)),i.lookAt(s);break;case Rc.FACEFORWARDREVERSED_ORIENTATION:case Rc.FACEORIGINREVERSED_ORIENTATION:s.addInPlace(new O(0,0,-1)),i.lookAt(s);break}}}class _Se extends FF{constructor(){super(...arguments),this._iteration=100}get iteration(){return this._iteration}set iteration(e){this._iteration!==e&&(this._iteration=e,Be.SetImmediate(()=>{this._arrangeChildren()}))}_mapGridNode(e,t){const i=e.mesh,s=this._scatterMapping(t);if(!!i){switch(this.orientation){case Rc.FACEORIGIN_ORIENTATION:case Rc.FACEFORWARD_ORIENTATION:i.lookAt(new O(0,0,1));break;case Rc.FACEFORWARDREVERSED_ORIENTATION:case Rc.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new O(0,0,-1));break}e.position=s}}_scatterMapping(e){return e.x=(1-Math.random()*2)*this._cellWidth,e.y=(1-Math.random()*2)*this._cellHeight,e}_finalProcessing(){const e=[];for(const t of this._children)!t.mesh||e.push(t.mesh);for(let t=0;t{const c=o.position.lengthSquared(),h=l.position.lengthSquared();return ch?-1:0});const i=Math.pow(this.margin,2),s=Math.max(this._cellWidth,this._cellHeight),r=ue.Vector2[0],n=ue.Vector3[0];for(let o=0;o0.0) {C=mix(H,S,k);} else {C=mix(H,G,k); } +return C;} +void Sky_Environment_B50( +vec3 Normal, +vec3 Reflected, +vec4 Sky_Color, +vec4 Horizon_Color, +vec4 Ground_Color, +float Horizon_Power, +out vec4 Reflected_Color, +out vec4 Indirect_Color) +{Reflected_Color=SampleEnv_Bid50(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);} +void Min_Segment_Distance_B65( +vec3 P0, +vec3 P1, +vec3 Q0, +vec3 Q1, +out vec3 NearP, +out vec3 NearQ, +out float Distance) +{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}} +if (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}} +sc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);} +void To_XYZ_B74( +vec3 Vec3, +out float X, +out float Y, +out float Z) +{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;} +void Finger_Positions_B64( +vec3 Left_Index_Pos, +vec3 Right_Index_Pos, +vec3 Left_Index_Middle_Pos, +vec3 Right_Index_Middle_Pos, +out vec3 Left_Index, +out vec3 Right_Index, +out vec3 Left_Index_Middle, +out vec3 Right_Index_Middle) +{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);} +void VaryHSV_B108( +vec3 HSV_In, +float Hue_Shift, +float Saturation_Shift, +float Value_Shift, +out vec3 HSV_Out) +{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));} +void Remap_Range_B114( +float In_Min, +float In_Max, +float Out_Min, +float Out_Max, +float In, +out float Out) +{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));} +void To_HSV_B75( +vec4 Color, +out float Hue, +out float Saturation, +out float Value, +out float Alpha, +out vec3 HSV) +{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;} +void Conditional_Float_B36( +bool Which, +float If_True, +float If_False, +out float Result) +{Result=Which ? If_True : If_False;} +void Greater_Than_B37( +float Left, +float Right, +out bool Not_Greater_Than, +out bool Greater_Than) +{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;} +void Remap_Range_B105( +float In_Min, +float In_Max, +float Out_Min, +float Out_Max, +float In, +out float Out) +{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));} +void main() +{vec2 XY_Q85;XY_Q85=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q27;vec3 Tangent_World_N_Q27;float Tangent_Length_Q27;Tangent_World_Q27=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q27=length(Tangent_World_Q27);Tangent_World_N_Q27=Tangent_World_Q27/Tangent_Length_Q27;vec3 Normal_World_Q60;vec3 Normal_World_N_Q60;float Normal_Length_Q60;Object_To_World_Dir_B60(vec3(0,0,1),Normal_World_Q60,Normal_World_N_Q60,Normal_Length_Q60);float X_Q78;float Y_Q78;float Z_Q78;To_XYZ_B78(position,X_Q78,Y_Q78,Z_Q78);vec3 Nrm_World_Q26;Nrm_World_Q26=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q28;vec3 Binormal_World_N_Q28;float Binormal_Length_Q28;Object_To_World_Dir_B28(vec3(0,1,0),Binormal_World_Q28,Binormal_World_N_Q28,Binormal_Length_Q28);float Anisotropy_Q29=Tangent_Length_Q27/Binormal_Length_Q28;float Result_Q69;Pick_Radius_B69(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q69);float Anisotropy_Q53=Binormal_Length_Q28/Normal_Length_Q60;bool Not_Greater_Than_Q37;bool Greater_Than_Q37;Greater_Than_B37(Z_Q78,0.0,Not_Greater_Than_Q37,Greater_Than_Q37);vec4 Linear_Q101;Linear_Q101.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q101.a=_Left_Color_.a;vec4 Linear_Q102;Linear_Q102.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q102.a=_Right_Color_.a;vec3 Difference_Q61=vec3(0,0,0)-Normal_World_N_Q60;vec4 Out_Color_Q34=vec4(X_Q78,Y_Q78,Z_Q78,1);float Result_Q36;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_,_Bevel_Front_,Result_Q36);float Result_Q94;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q94);vec3 New_P_Q130;vec2 New_UV_Q130;float Radial_Gradient_Q130;vec3 Radial_Dir_Q130;vec3 New_Normal_Q130;Move_Verts_B130(Anisotropy_Q29,position,Result_Q69,Result_Q36,normal,Anisotropy_Q53,Result_Q94,New_P_Q130,New_UV_Q130,Radial_Gradient_Q130,Radial_Dir_Q130,New_Normal_Q130);float X_Q98;float Y_Q98;X_Q98=New_UV_Q130.x;Y_Q98=New_UV_Q130.y;vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q130,Pos_World_Q12);vec3 Nrm_World_Q32;Object_To_World_Normal_B32(New_Normal_Q130,Nrm_World_Q32);vec4 Blob_Info_Q23; +#if BLOB_ENABLE +Blob_Vertex_B23(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q23); +#else +Blob_Info_Q23=vec4(0,0,0,0); +#endif +vec4 Blob_Info_Q24; +#if BLOB_ENABLE_2 +Blob_Vertex_B24(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q24); +#else +Blob_Info_Q24=vec4(0,0,0,0); +#endif +float Out_Q105;Remap_Range_B105(0.0,1.0,0.0,1.0,X_Q98,Out_Q105);float X_Q86;float Y_Q86;float Z_Q86;To_XYZ_B78(Nrm_World_Q32,X_Q86,Y_Q86,Z_Q86);vec4 Color_At_T_Q97=mix(Linear_Q101,Linear_Q102,Out_Q105);float Minus_F_Q87=-Z_Q86;float R_Q99;float G_Q99;float B_Q99;float A_Q99;R_Q99=Color_At_T_Q97.r; G_Q99=Color_At_T_Q97.g; B_Q99=Color_At_T_Q97.b; A_Q99=Color_At_T_Q97.a;float ClampF_Q88=clamp(0.0,Minus_F_Q87,1.0);float Result_Q93;Conditional_Float_B93(_Decal_Front_Only_,ClampF_Q88,1.0,Result_Q93);vec4 Vec4_Q89=vec4(Result_Q93,Radial_Gradient_Q130,G_Q99,B_Q99);vec3 Position=Pos_World_Q12;vec3 Normal=Nrm_World_Q32;vec2 UV=XY_Q85;vec3 Tangent=Tangent_World_N_Q27;vec3 Binormal=Difference_Q61;vec4 Color=Out_Color_Q34;vec4 Extra1=Vec4_Q89;vec4 Extra2=Blob_Info_Q23;vec4 Extra3=Blob_Info_Q24;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}`;Ue.ShadersStore[CSe]=ASe;class xSe extends ta{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class nr extends Bl{constructor(e,t){super(e,t),this.radius=.6,this.bevelFront=.6,this.bevelFrontStretch=.077,this.bevelBack=0,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=1.102,this.sunTheta=.76,this.sunPhi=.526,this.indirectDiffuse=.658,this.albedo=new Zt(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=0,this.leftGradientColor=new Zt(.0117647,.505882,.996078,1),this.rightGradientColor=new Zt(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.13,this.skyColor=new Zt(.0117647,.964706,.996078,1),this.horizonColor=new Zt(.0117647,.333333,.996078,1),this.groundColor=new Zt(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new O(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new O(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new Te("",this.getScene()),this.leftIndexPosition=new O(0,0,1),this.rightIndexPosition=new O(-1,-1,-1),this.leftIndexMiddlePosition=new O(0,0,0),this.rightIndexMiddlePosition=new O(0,0,0),this.decalScaleXY=new lt(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new Ui(.5,0,-.55,1),this.globaRightIndexTipPosition=new Ui(0,0,0,1),this.globalLeftThumbTipPosition=new Ui(.5,0,-.55,1),this.globalRightThumbTipPosition=new Ui(0,0,0,1),this.globalLeftIndexMiddlePosition=new Ui(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new Ui(0,0,0,1),this.alphaMode=it.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new Te(nr.BLUE_GRADIENT_TEXTURE_URL,this.getScene(),!0,!1,Te.NEAREST_SAMPLINGMODE),this._decalTexture=new Te("",this.getScene()),this._reflectionMapTexture=new Te("",this.getScene()),this._indirectEnvTexture=new Te("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new xSe);const i=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(ze.PrepareDefinesForAttributes(e,i,!1,!1),i.isDirty){i.markAsProcessed(),s.resetCachedMaterial();const n=new Fl;i.FOG&&n.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(i,n),i.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[se.PositionKind];i.NORMAL&&o.push(se.NormalKind),i.UV1&&o.push(se.UVKind),i.UV2&&o.push(se.UV2Kind),i.VERTEXCOLOR&&o.push(se.ColorKind),i.TANGENT&&o.push(se.TangentKind),ze.PrepareAttributesForInstances(o,i);const l="mrdlSliderBar",c=i.toString(),h=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],u=["_Rim_Texture_","_Iridescence_Texture_"],p=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:i,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:c,fallbacks:n,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),i,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(i._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;!r||(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return Kt.Clone(()=>new nr(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderBarMaterial",e}getClassName(){return"MRDLSliderBarMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new nr(e.name,t),e,t,i)}}nr.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png";z([X()],nr.prototype,"radius",void 0);z([X()],nr.prototype,"bevelFront",void 0);z([X()],nr.prototype,"bevelFrontStretch",void 0);z([X()],nr.prototype,"bevelBack",void 0);z([X()],nr.prototype,"bevelBackStretch",void 0);z([X()],nr.prototype,"radiusTopLeft",void 0);z([X()],nr.prototype,"radiusTopRight",void 0);z([X()],nr.prototype,"radiusBottomLeft",void 0);z([X()],nr.prototype,"radiusBottomRight",void 0);z([X()],nr.prototype,"bulgeEnabled",void 0);z([X()],nr.prototype,"bulgeHeight",void 0);z([X()],nr.prototype,"bulgeRadius",void 0);z([X()],nr.prototype,"sunIntensity",void 0);z([X()],nr.prototype,"sunTheta",void 0);z([X()],nr.prototype,"sunPhi",void 0);z([X()],nr.prototype,"indirectDiffuse",void 0);z([X()],nr.prototype,"albedo",void 0);z([X()],nr.prototype,"specular",void 0);z([X()],nr.prototype,"shininess",void 0);z([X()],nr.prototype,"sharpness",void 0);z([X()],nr.prototype,"subsurface",void 0);z([X()],nr.prototype,"leftGradientColor",void 0);z([X()],nr.prototype,"rightGradientColor",void 0);z([X()],nr.prototype,"reflection",void 0);z([X()],nr.prototype,"frontReflect",void 0);z([X()],nr.prototype,"edgeReflect",void 0);z([X()],nr.prototype,"power",void 0);z([X()],nr.prototype,"skyColor",void 0);z([X()],nr.prototype,"horizonColor",void 0);z([X()],nr.prototype,"groundColor",void 0);z([X()],nr.prototype,"horizonPower",void 0);z([X()],nr.prototype,"width",void 0);z([X()],nr.prototype,"fuzz",void 0);z([X()],nr.prototype,"minFuzz",void 0);z([X()],nr.prototype,"clipFade",void 0);z([X()],nr.prototype,"hueShift",void 0);z([X()],nr.prototype,"saturationShift",void 0);z([X()],nr.prototype,"valueShift",void 0);z([X()],nr.prototype,"blobPosition",void 0);z([X()],nr.prototype,"blobIntensity",void 0);z([X()],nr.prototype,"blobNearSize",void 0);z([X()],nr.prototype,"blobFarSize",void 0);z([X()],nr.prototype,"blobNearDistance",void 0);z([X()],nr.prototype,"blobFarDistance",void 0);z([X()],nr.prototype,"blobFadeLength",void 0);z([X()],nr.prototype,"blobPulse",void 0);z([X()],nr.prototype,"blobFade",void 0);z([X()],nr.prototype,"blobPosition2",void 0);z([X()],nr.prototype,"blobNearSize2",void 0);z([X()],nr.prototype,"blobPulse2",void 0);z([X()],nr.prototype,"blobFade2",void 0);z([X()],nr.prototype,"blobTexture",void 0);z([X()],nr.prototype,"leftIndexPosition",void 0);z([X()],nr.prototype,"rightIndexPosition",void 0);z([X()],nr.prototype,"leftIndexMiddlePosition",void 0);z([X()],nr.prototype,"rightIndexMiddlePosition",void 0);z([X()],nr.prototype,"decalScaleXY",void 0);z([X()],nr.prototype,"decalFrontOnly",void 0);z([X()],nr.prototype,"rimIntensity",void 0);z([X()],nr.prototype,"rimHueShift",void 0);z([X()],nr.prototype,"rimSaturationShift",void 0);z([X()],nr.prototype,"rimValueShift",void 0);z([X()],nr.prototype,"iridescenceIntensity",void 0);$e("BABYLON.GUI.MRDLSliderBarMaterial",nr);const bSe="mrdlSliderThumbPixelShader",ESe=`uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Bevel_Front_;uniform float _Bevel_Front_Stretch_;uniform float _Bevel_Back_;uniform float _Bevel_Back_Stretch_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform bool _Bulge_Enabled_;uniform float _Bulge_Height_;uniform float _Bulge_Radius_;uniform float _Sun_Intensity_;uniform float _Sun_Theta_;uniform float _Sun_Phi_;uniform float _Indirect_Diffuse_;uniform vec4 _Albedo_;uniform float _Specular_;uniform float _Shininess_;uniform float _Sharpness_;uniform float _Subsurface_;uniform vec4 _Left_Color_;uniform vec4 _Right_Color_;uniform float _Reflection_;uniform float _Front_Reflect_;uniform float _Edge_Reflect_;uniform float _Power_;uniform vec4 _Sky_Color_;uniform vec4 _Horizon_Color_;uniform vec4 _Ground_Color_;uniform float _Horizon_Power_;uniform sampler2D _Reflection_Map_;uniform sampler2D _Indirect_Environment_;uniform float _Width_;uniform float _Fuzz_;uniform float _Min_Fuzz_;uniform float _Clip_Fade_;uniform float _Hue_Shift_;uniform float _Saturation_Shift_;uniform float _Value_Shift_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Left_Index_Pos_;uniform vec3 _Right_Index_Pos_;uniform vec3 _Left_Index_Middle_Pos_;uniform vec3 _Right_Index_Middle_Pos_;uniform sampler2D _Decal_;uniform vec2 _Decal_Scale_XY_;uniform bool _Decal_Front_Only_;uniform float _Rim_Intensity_;uniform sampler2D _Rim_Texture_;uniform float _Rim_Hue_Shift_;uniform float _Rim_Saturation_Shift_;uniform float _Rim_Value_Shift_;uniform float _Iridescence_Intensity_;uniform sampler2D _Iridescence_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform vec4 Global_Left_Index_Middle_Position;uniform vec4 Global_Right_Index_Middle_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Blob_Fragment_B180( +sampler2D Blob_Texture, +vec4 Blob_Info1, +vec4 Blob_Info2, +out vec4 Blob_Color) +{float k1=dot(Blob_Info1.xy,Blob_Info1.xy);float k2=dot(Blob_Info2.xy,Blob_Info2.xy);vec3 closer=k10.0) {C=mix(H,S,k);} else {C=mix(H,G,k); } +return C;} +void Sky_Environment_B200( +vec3 Normal, +vec3 Reflected, +vec4 Sky_Color, +vec4 Horizon_Color, +vec4 Ground_Color, +float Horizon_Power, +out vec4 Reflected_Color, +out vec4 Indirect_Color) +{Reflected_Color=SampleEnv_Bid200(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);} +void Min_Segment_Distance_B215( +vec3 P0, +vec3 P1, +vec3 Q0, +vec3 Q1, +out vec3 NearP, +out vec3 NearQ, +out float Distance) +{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}} +if (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}} +sc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);} +void To_XYZ_B224( +vec3 Vec3, +out float X, +out float Y, +out float Z) +{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;} +void Finger_Positions_B214( +vec3 Left_Index_Pos, +vec3 Right_Index_Pos, +vec3 Left_Index_Middle_Pos, +vec3 Right_Index_Middle_Pos, +out vec3 Left_Index, +out vec3 Right_Index, +out vec3 Left_Index_Middle, +out vec3 Right_Index_Middle) +{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);} +void VaryHSV_B258( +vec3 HSV_In, +float Hue_Shift, +float Saturation_Shift, +float Value_Shift, +out vec3 HSV_Out) +{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));} +void Remap_Range_B264( +float In_Min, +float In_Max, +float Out_Min, +float Out_Max, +float In, +out float Out) +{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));} +void To_HSV_B225( +vec4 Color, +out float Hue, +out float Saturation, +out float Value, +out float Alpha, +out vec3 HSV) +{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;} +void Conditional_Float_B186( +bool Which, +float If_True, +float If_False, +out float Result) +{Result=Which ? If_True : If_False;} +void Greater_Than_B187( +float Left, +float Right, +out bool Not_Greater_Than, +out bool Greater_Than) +{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;} +void Remap_Range_B255( +float In_Min, +float In_Max, +float Out_Min, +float Out_Max, +float In, +out float Out) +{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));} +void main() +{vec2 XY_Q235;XY_Q235=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q177;vec3 Tangent_World_N_Q177;float Tangent_Length_Q177;Tangent_World_Q177=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q177=length(Tangent_World_Q177);Tangent_World_N_Q177=Tangent_World_Q177/Tangent_Length_Q177;vec3 Normal_World_Q210;vec3 Normal_World_N_Q210;float Normal_Length_Q210;Object_To_World_Dir_B210(vec3(0,0,1),Normal_World_Q210,Normal_World_N_Q210,Normal_Length_Q210);float X_Q228;float Y_Q228;float Z_Q228;To_XYZ_B228(position,X_Q228,Y_Q228,Z_Q228);vec3 Nrm_World_Q176;Nrm_World_Q176=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q178;vec3 Binormal_World_N_Q178;float Binormal_Length_Q178;Object_To_World_Dir_B178(vec3(0,1,0),Binormal_World_Q178,Binormal_World_N_Q178,Binormal_Length_Q178);float Anisotropy_Q179=Tangent_Length_Q177/Binormal_Length_Q178;float Result_Q219;Pick_Radius_B219(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q219);float Anisotropy_Q203=Binormal_Length_Q178/Normal_Length_Q210;bool Not_Greater_Than_Q187;bool Greater_Than_Q187;Greater_Than_B187(Z_Q228,0.0,Not_Greater_Than_Q187,Greater_Than_Q187);vec4 Linear_Q251;Linear_Q251.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q251.a=_Left_Color_.a;vec4 Linear_Q252;Linear_Q252.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q252.a=_Right_Color_.a;vec3 Difference_Q211=vec3(0,0,0)-Normal_World_N_Q210;vec4 Out_Color_Q184=vec4(X_Q228,Y_Q228,Z_Q228,1);float Result_Q186;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_,_Bevel_Front_,Result_Q186);float Result_Q244;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q244);vec3 New_P_Q280;vec2 New_UV_Q280;float Radial_Gradient_Q280;vec3 Radial_Dir_Q280;vec3 New_Normal_Q280;Move_Verts_B280(Anisotropy_Q179,position,Result_Q219,Result_Q186,normal,Anisotropy_Q203,Result_Q244,New_P_Q280,New_UV_Q280,Radial_Gradient_Q280,Radial_Dir_Q280,New_Normal_Q280);float X_Q248;float Y_Q248;X_Q248=New_UV_Q280.x;Y_Q248=New_UV_Q280.y;vec3 Pos_World_Q162;Object_To_World_Pos_B162(New_P_Q280,Pos_World_Q162);vec3 Nrm_World_Q182;Object_To_World_Normal_B182(New_Normal_Q280,Nrm_World_Q182);vec4 Blob_Info_Q173; +#if BLOB_ENABLE +Blob_Vertex_B173(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q173); +#else +Blob_Info_Q173=vec4(0,0,0,0); +#endif +vec4 Blob_Info_Q174; +#if BLOB_ENABLE_2 +Blob_Vertex_B174(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q174); +#else +Blob_Info_Q174=vec4(0,0,0,0); +#endif +float Out_Q255;Remap_Range_B255(0.0,1.0,0.0,1.0,X_Q248,Out_Q255);float X_Q236;float Y_Q236;float Z_Q236;To_XYZ_B228(Nrm_World_Q182,X_Q236,Y_Q236,Z_Q236);vec4 Color_At_T_Q247=mix(Linear_Q251,Linear_Q252,Out_Q255);float Minus_F_Q237=-Z_Q236;float R_Q249;float G_Q249;float B_Q249;float A_Q249;R_Q249=Color_At_T_Q247.r; G_Q249=Color_At_T_Q247.g; B_Q249=Color_At_T_Q247.b; A_Q249=Color_At_T_Q247.a;float ClampF_Q238=clamp(0.0,Minus_F_Q237,1.0);float Result_Q243;Conditional_Float_B243(_Decal_Front_Only_,ClampF_Q238,1.0,Result_Q243);vec4 Vec4_Q239=vec4(Result_Q243,Radial_Gradient_Q280,G_Q249,B_Q249);vec3 Position=Pos_World_Q162;vec3 Normal=Nrm_World_Q182;vec2 UV=XY_Q235;vec3 Tangent=Tangent_World_N_Q177;vec3 Binormal=Difference_Q211;vec4 Color=Out_Color_Q184;vec4 Extra1=Vec4_Q239;vec4 Extra2=Blob_Info_Q173;vec4 Extra3=Blob_Info_Q174;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}`;Ue.ShadersStore[ySe]=MSe;class TSe extends ta{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class ar extends Bl{constructor(e,t){super(e,t),this.radius=.157,this.bevelFront=.065,this.bevelFrontStretch=.077,this.bevelBack=.031,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=2,this.sunTheta=.937,this.sunPhi=.555,this.indirectDiffuse=1,this.albedo=new Zt(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=.31,this.leftGradientColor=new Zt(.0117647,.505882,.996078,1),this.rightGradientColor=new Zt(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.1,this.skyColor=new Zt(.0117647,.960784,.996078,1),this.horizonColor=new Zt(.0117647,.333333,.996078,1),this.groundColor=new Zt(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new O(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new O(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new Te("",this.getScene()),this.leftIndexPosition=new O(0,0,1),this.rightIndexPosition=new O(-1,-1,-1),this.leftIndexMiddlePosition=new O(0,0,0),this.rightIndexMiddlePosition=new O(0,0,0),this.decalScaleXY=new lt(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new Ui(.5,0,-.55,1),this.globaRightIndexTipPosition=new Ui(0,0,0,1),this.globalLeftThumbTipPosition=new Ui(.5,0,-.55,1),this.globalRightThumbTipPosition=new Ui(0,0,0,1),this.globalLeftIndexMiddlePosition=new Ui(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new Ui(0,0,0,1),this.alphaMode=it.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new Te(ar.BLUE_GRADIENT_TEXTURE_URL,t,!0,!1,Te.NEAREST_SAMPLINGMODE),this._decalTexture=new Te("",this.getScene()),this._reflectionMapTexture=new Te("",this.getScene()),this._indirectEnvTexture=new Te("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new TSe);const i=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(ze.PrepareDefinesForAttributes(e,i,!1,!1),i.isDirty){i.markAsProcessed(),s.resetCachedMaterial();const n=new Fl;i.FOG&&n.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(i,n),i.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[se.PositionKind];i.NORMAL&&o.push(se.NormalKind),i.UV1&&o.push(se.UVKind),i.UV2&&o.push(se.UV2Kind),i.VERTEXCOLOR&&o.push(se.ColorKind),i.TANGENT&&o.push(se.TangentKind),ze.PrepareAttributesForInstances(o,i);const l="mrdlSliderThumb",c=i.toString(),h=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],u=["_Rim_Texture_","_Iridescence_Texture_"],p=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:i,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:c,fallbacks:n,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),i)}return!t.effect||!t.effect.isReady()?!1:(i._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;!r||(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return Kt.Clone(()=>new ar(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderThumbMaterial",e}getClassName(){return"MRDLSliderThumbMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new ar(e.name,t),e,t,i)}}ar.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png";z([X()],ar.prototype,"radius",void 0);z([X()],ar.prototype,"bevelFront",void 0);z([X()],ar.prototype,"bevelFrontStretch",void 0);z([X()],ar.prototype,"bevelBack",void 0);z([X()],ar.prototype,"bevelBackStretch",void 0);z([X()],ar.prototype,"radiusTopLeft",void 0);z([X()],ar.prototype,"radiusTopRight",void 0);z([X()],ar.prototype,"radiusBottomLeft",void 0);z([X()],ar.prototype,"radiusBottomRight",void 0);z([X()],ar.prototype,"bulgeEnabled",void 0);z([X()],ar.prototype,"bulgeHeight",void 0);z([X()],ar.prototype,"bulgeRadius",void 0);z([X()],ar.prototype,"sunIntensity",void 0);z([X()],ar.prototype,"sunTheta",void 0);z([X()],ar.prototype,"sunPhi",void 0);z([X()],ar.prototype,"indirectDiffuse",void 0);z([X()],ar.prototype,"albedo",void 0);z([X()],ar.prototype,"specular",void 0);z([X()],ar.prototype,"shininess",void 0);z([X()],ar.prototype,"sharpness",void 0);z([X()],ar.prototype,"subsurface",void 0);z([X()],ar.prototype,"leftGradientColor",void 0);z([X()],ar.prototype,"rightGradientColor",void 0);z([X()],ar.prototype,"reflection",void 0);z([X()],ar.prototype,"frontReflect",void 0);z([X()],ar.prototype,"edgeReflect",void 0);z([X()],ar.prototype,"power",void 0);z([X()],ar.prototype,"skyColor",void 0);z([X()],ar.prototype,"horizonColor",void 0);z([X()],ar.prototype,"groundColor",void 0);z([X()],ar.prototype,"horizonPower",void 0);z([X()],ar.prototype,"width",void 0);z([X()],ar.prototype,"fuzz",void 0);z([X()],ar.prototype,"minFuzz",void 0);z([X()],ar.prototype,"clipFade",void 0);z([X()],ar.prototype,"hueShift",void 0);z([X()],ar.prototype,"saturationShift",void 0);z([X()],ar.prototype,"valueShift",void 0);z([X()],ar.prototype,"blobPosition",void 0);z([X()],ar.prototype,"blobIntensity",void 0);z([X()],ar.prototype,"blobNearSize",void 0);z([X()],ar.prototype,"blobFarSize",void 0);z([X()],ar.prototype,"blobNearDistance",void 0);z([X()],ar.prototype,"blobFarDistance",void 0);z([X()],ar.prototype,"blobFadeLength",void 0);z([X()],ar.prototype,"blobPulse",void 0);z([X()],ar.prototype,"blobFade",void 0);z([X()],ar.prototype,"blobPosition2",void 0);z([X()],ar.prototype,"blobNearSize2",void 0);z([X()],ar.prototype,"blobPulse2",void 0);z([X()],ar.prototype,"blobFade2",void 0);z([X()],ar.prototype,"blobTexture",void 0);z([X()],ar.prototype,"leftIndexPosition",void 0);z([X()],ar.prototype,"rightIndexPosition",void 0);z([X()],ar.prototype,"leftIndexMiddlePosition",void 0);z([X()],ar.prototype,"rightIndexMiddlePosition",void 0);z([X()],ar.prototype,"decalScaleXY",void 0);z([X()],ar.prototype,"decalFrontOnly",void 0);z([X()],ar.prototype,"rimIntensity",void 0);z([X()],ar.prototype,"rimHueShift",void 0);z([X()],ar.prototype,"rimSaturationShift",void 0);z([X()],ar.prototype,"rimValueShift",void 0);z([X()],ar.prototype,"iridescenceIntensity",void 0);$e("BABYLON.GUI.MRDLSliderThumbMaterial",ar);const SSe="mrdlBackplatePixelShader",ISe=`uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;void FastLinearTosRGB_B353( +vec4 Linear, +out vec4 sRGB) +{sRGB.rgb=sqrt(clamp(Linear.rgb,0.0,1.0));sRGB.a=Linear.a;} +void Round_Rect_Fragment_B332( +float Radius, +float Line_Width, +vec4 Line_Color, +float Filter_Width, +vec2 UV, +float Line_Visibility, +vec4 Rect_Parms, +vec4 Fill_Color, +out vec4 Color) +{float d=length(max(abs(UV)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);float g=min(Rect_Parms.z,Rect_Parms.w);float dgrad=max(fwidth(g)*Filter_Width,0.00001);float Inside_Rect=clamp(g/dgrad,0.0,1.0);float inner=clamp((d+dx*0.5-max(Radius-Line_Width,d-dx*0.5))/dx,0.0,1.0);Color=clamp(mix(Fill_Color,Line_Color,inner),0.0,1.0)*Inside_Rect;} +void Iridescence_B343( +vec3 Position, +vec3 Normal, +vec2 UV, +vec3 Axis, +vec3 Eye, +vec4 Tint, +sampler2D Texture, +bool Reflected, +float Frequency, +float Vertical_Offset, +out vec4 Color) +{vec3 i=normalize(Position-Eye);vec3 r=reflect(i,Normal);float idota=dot(i,Axis);float idotr=dot(i,r);float x=Reflected ? idotr : idota;vec2 xy;xy.x=fract((x*Frequency+1.0)*0.5+UV.y*Vertical_Offset);xy.y=0.5;Color=texture(Texture,xy);Color.rgb*=Tint.rgb;} +void Scale_RGB_B346( +vec4 Color, +float Scalar, +out vec4 Result) +{Result=vec4(Scalar,Scalar,Scalar,1)*Color;} +void Scale_RGB_B344( +float Scalar, +vec4 Color, +out vec4 Result) +{Result=vec4(Scalar,Scalar,Scalar,1)*Color;} +void Line_Fragment_B362( +vec4 Base_Color, +vec4 Highlight_Color, +float Highlight_Width, +vec3 Line_Vertex, +float Highlight, +out vec4 Line_Color) +{float k2=1.0-clamp(abs(Line_Vertex.y/Highlight_Width),0.0,1.0);Line_Color=mix(Base_Color,Highlight_Color,Highlight*k2);} +void Edge_B356( +vec4 RectParms, +float Radius, +float Line_Width, +vec2 UV, +float Edge_Width, +float Edge_Power, +out float Result) +{float d=length(max(abs(UV)-RectParms.xy,0.0));float edge=1.0-clamp((1.0-d/(Radius-Line_Width))/Edge_Width,0.0,1.0);Result=pow(edge,Edge_Power);} +void Gradient_B355( +vec4 Gradient_Color, +vec4 Top_Left, +vec4 Top_Right, +vec4 Bottom_Left, +vec4 Bottom_Right, +vec2 UV, +out vec4 Result) +{vec3 top=Top_Left.rgb+(Top_Right.rgb-Top_Left.rgb)*UV.x;vec3 bottom=Bottom_Left.rgb+(Bottom_Right.rgb-Bottom_Left.rgb)*UV.x;Result.rgb=Gradient_Color.rgb*(bottom+(top-bottom)*UV.y);Result.a=1.0;} +void main() +{float X_Q338;float Y_Q338;float Z_Q338;float W_Q338;X_Q338=vExtra2.x;Y_Q338=vExtra2.y;Z_Q338=vExtra2.z;W_Q338=vExtra2.w;vec4 Color_Q343; +#if IRIDESCENCE_ENABLE +Iridescence_B343(vPosition,vNormal,vUV,vBinormal,cameraPosition,_Iridescence_Tint_,_Iridescent_Map_,_Reflected_,_Frequency_,_Vertical_Offset_,Color_Q343); +#else +Color_Q343=vec4(0,0,0,0); +#endif +vec4 Result_Q344;Scale_RGB_B344(_Iridescence_Intensity_,Color_Q343,Result_Q344);vec4 Line_Color_Q362;Line_Fragment_B362(_Line_Color_,_Highlight_Color_,_Highlight_Width_,vTangent,_Highlight_,Line_Color_Q362);float Result_Q356; +#if EDGE_ONLY +Edge_B356(vExtra1,Z_Q338,W_Q338,vUV,_Edge_Width_,_Edge_Power_,Result_Q356); +#else +Result_Q356=1.0; +#endif +vec2 Vec2_Q339=vec2(X_Q338,Y_Q338);vec4 Result_Q355;Gradient_B355(_Gradient_Color_,_Top_Left_,_Top_Right_,_Bottom_Left_,_Bottom_Right_,Vec2_Q339,Result_Q355);vec4 Linear_Q348;Linear_Q348.rgb=clamp(Result_Q355.rgb*Result_Q355.rgb,0.0,1.0);Linear_Q348.a=Result_Q355.a;vec4 Result_Q346;Scale_RGB_B346(Linear_Q348,Result_Q356,Result_Q346);vec4 Sum_Q345=Result_Q346+Result_Q344;vec4 Color_At_T_Q347=mix(Line_Color_Q362,Result_Q346,_Line_Gradient_Blend_);vec4 Base_And_Iridescent_Q350;Base_And_Iridescent_Q350=_Base_Color_+vec4(Sum_Q345.rgb,0.0);vec4 Sum_Q349=Color_At_T_Q347+_Iridescence_Edge_Intensity_*Color_Q343;vec4 Result_Q351=Sum_Q349; Result_Q351.a=1.0;vec4 Color_Q332;Round_Rect_Fragment_B332(Z_Q338,W_Q338,Result_Q351,_Filter_Width_,vUV,1.0,vExtra1,Base_And_Iridescent_Q350,Color_Q332);vec4 Result_Q354=_Fade_Out_*Color_Q332;vec4 sRGB_Q353;FastLinearTosRGB_B353(Result_Q354,sRGB_Q353);vec4 Out_Color=sRGB_Q353;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}`;Ue.ShadersStore[SSe]=ISe;const LSe="mrdlBackplateVertexShader",RSe=`uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec3 tangent;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;void Object_To_World_Pos_B314( +vec3 Pos_Object, +out vec3 Pos_World) +{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;} +void Round_Rect_Vertex_B357( +vec2 UV, +float Radius, +float Margin, +float Anisotropy, +float Gradient1, +float Gradient2, +vec3 Normal, +vec4 Color_Scale_Translate, +out vec2 Rect_UV, +out vec4 Rect_Parms, +out vec2 Scale_XY, +out vec2 Line_UV, +out vec2 Color_UV_Info) +{Scale_XY=vec2(Anisotropy,1.0);Line_UV=(UV-vec2(0.5,0.5));Rect_UV=Line_UV*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius)-vec2(Margin,Margin);Rect_Parms.z=Gradient1; +Rect_Parms.w=Gradient2;Color_UV_Info=(Line_UV+vec2(0.5,0.5))*Color_Scale_Translate.xy+Color_Scale_Translate.zw;} +void Line_Vertex_B333( +vec2 Scale_XY, +vec2 UV, +float Time, +float Rate, +vec4 Highlight_Transform, +out vec3 Line_Vertex) +{float angle2=(Rate*Time)*2.0*3.1416;float sinAngle2=sin(angle2);float cosAngle2=cos(angle2);vec2 xformUV=UV*Highlight_Transform.xy+Highlight_Transform.zw;Line_Vertex.x=0.0;Line_Vertex.y=cosAngle2*xformUV.x-sinAngle2*xformUV.y;Line_Vertex.z=0.0; } +void PickDir_B334( +float Degrees, +vec3 DirX, +vec3 DirY, +out vec3 Dir) +{float a=Degrees*3.14159/180.0;Dir=cos(a)*DirX+sin(a)*DirY;} +void Move_Verts_B327( +float Anisotropy, +vec3 P, +float Radius, +out vec3 New_P, +out vec2 New_UV, +out float Radial_Gradient, +out vec3 Radial_Dir) +{vec2 UV=P.xy*2.0+0.5;vec2 center=clamp(UV,0.0,1.0);vec2 delta=UV-center;vec2 r2=2.0*vec2(Radius/Anisotropy,Radius);New_UV=center+r2*(UV-2.0*center+0.5);New_P=vec3(New_UV-0.5,P.z);Radial_Gradient=1.0-length(delta)*2.0;Radial_Dir=vec3(delta*r2,0.0);} +void Pick_Radius_B336( +float Radius, +float Radius_Top_Left, +float Radius_Top_Right, +float Radius_Bottom_Left, +float Radius_Bottom_Right, +vec3 Position, +out float Result) +{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;} +void Edge_AA_Vertex_B328( +vec3 Position_World, +vec3 Position_Object, +vec3 Normal_Object, +vec3 Eye, +float Radial_Gradient, +vec3 Radial_Dir, +vec3 Tangent, +out float Gradient1, +out float Gradient2) +{vec3 I=(Eye-Position_World);vec3 T=(vec4(Tangent,0.0)).xyz;float g=(dot(T,I)<0.0) ? 0.0 : 1.0;if (Normal_Object.z==0.0) { +Gradient1=Position_Object.z>0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}} +void Object_To_World_Dir_B330( +vec3 Dir_Object, +out vec3 Binormal_World, +out vec3 Binormal_World_N, +out float Binormal_Length) +{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;Binormal_Length=length(Binormal_World);Binormal_World_N=Binormal_World/Binormal_Length;} +void RelativeOrAbsoluteDetail_B341( +float Nominal_Radius, +float Nominal_LineWidth, +bool Absolute_Measurements, +float Height, +out float Radius, +out float Line_Width) +{float scale=Absolute_Measurements ? 1.0/Height : 1.0;Radius=Nominal_Radius*scale;Line_Width=Nominal_LineWidth*scale;} +void main() +{vec3 Nrm_World_Q326;Nrm_World_Q326=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q329;vec3 Tangent_World_N_Q329;float Tangent_Length_Q329;Tangent_World_Q329=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q329=length(Tangent_World_Q329);Tangent_World_N_Q329=Tangent_World_Q329/Tangent_Length_Q329;vec3 Binormal_World_Q330;vec3 Binormal_World_N_Q330;float Binormal_Length_Q330;Object_To_World_Dir_B330(vec3(0,1,0),Binormal_World_Q330,Binormal_World_N_Q330,Binormal_Length_Q330);float Radius_Q341;float Line_Width_Q341;RelativeOrAbsoluteDetail_B341(_Radius_,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q330,Radius_Q341,Line_Width_Q341);vec3 Dir_Q334;PickDir_B334(_Angle_,Tangent_World_N_Q329,Binormal_World_N_Q330,Dir_Q334);float Result_Q336;Pick_Radius_B336(Radius_Q341,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q336);float Anisotropy_Q331=Tangent_Length_Q329/Binormal_Length_Q330;vec4 Out_Color_Q337=vec4(Result_Q336,Line_Width_Q341,0,1);vec3 New_P_Q327;vec2 New_UV_Q327;float Radial_Gradient_Q327;vec3 Radial_Dir_Q327;Move_Verts_B327(Anisotropy_Q331,position,Result_Q336,New_P_Q327,New_UV_Q327,Radial_Gradient_Q327,Radial_Dir_Q327);vec3 Pos_World_Q314;Object_To_World_Pos_B314(New_P_Q327,Pos_World_Q314);float Gradient1_Q328;float Gradient2_Q328; +#if SMOOTH_EDGES +Edge_AA_Vertex_B328(Pos_World_Q314,position,normal,cameraPosition,Radial_Gradient_Q327,Radial_Dir_Q327,tangent,Gradient1_Q328,Gradient2_Q328); +#else +Gradient1_Q328=1.0;Gradient2_Q328=1.0; +#endif +vec2 Rect_UV_Q357;vec4 Rect_Parms_Q357;vec2 Scale_XY_Q357;vec2 Line_UV_Q357;vec2 Color_UV_Info_Q357;Round_Rect_Vertex_B357(New_UV_Q327,Result_Q336,0.0,Anisotropy_Q331,Gradient1_Q328,Gradient2_Q328,normal,vec4(1,1,0,0),Rect_UV_Q357,Rect_Parms_Q357,Scale_XY_Q357,Line_UV_Q357,Color_UV_Info_Q357);vec3 Line_Vertex_Q333;Line_Vertex_B333(Scale_XY_Q357,Line_UV_Q357,(20.0),_Rate_,_Highlight_Transform_,Line_Vertex_Q333);float X_Q359;float Y_Q359;X_Q359=Color_UV_Info_Q357.x;Y_Q359=Color_UV_Info_Q357.y;vec4 Vec4_Q358=vec4(X_Q359,Y_Q359,Result_Q336,Line_Width_Q341);vec3 Position=Pos_World_Q314;vec3 Normal=Nrm_World_Q326;vec2 UV=Rect_UV_Q357;vec3 Tangent=Line_Vertex_Q333;vec3 Binormal=Dir_Q334;vec4 Color=Out_Color_Q337;vec4 Extra1=Rect_Parms_Q357;vec4 Extra2=Vec4_Q358;vec4 Extra3=vec4(0,0,0,0);gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vExtra1=Extra1;vExtra2=Extra2;}`;Ue.ShadersStore[LSe]=RSe;class PSe extends ta{constructor(){super(),this.IRIDESCENCE_ENABLE=!0,this.SMOOTH_EDGES=!0,this._needNormals=!0,this.rebuild()}}class Vo extends Bl{constructor(e,t){super(e,t),this.radius=.3,this.lineWidth=.003,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new Zt(0,0,0,1),this.lineColor=new Zt(.2,.262745,.4,1),this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this._rate=0,this.highlightColor=new Zt(.239216,.435294,.827451,1),this.highlightWidth=0,this._highlightTransform=new Ui(1,1,0,0),this._highlight=1,this.iridescenceIntensity=.45,this.iridescenceEdgeIntensity=1,this.iridescenceTint=new Zt(1,1,1,1),this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.gradientColor=new Zt(.74902,.74902,.74902,1),this.topLeftGradientColor=new Zt(.00784314,.294118,.580392,1),this.topRightGradientColor=new Zt(.305882,0,1,1),this.bottomLeftGradientColor=new Zt(.133333,.258824,.992157,1),this.bottomRightGradientColor=new Zt(.176471,.176471,.619608,1),this.edgeWidth=.5,this.edgePower=1,this.edgeLineGradientBlend=.5,this.alphaMode=it.ALPHA_DISABLE,this.backFaceCulling=!1,this._iridescentMapTexture=new Te(Vo.IRIDESCENT_MAP_TEXTURE_URL,this.getScene(),!0,!1,Te.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new PSe);const i=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(ze.PrepareDefinesForAttributes(e,i,!1,!1),i.isDirty){i.markAsProcessed(),s.resetCachedMaterial();const n=new Fl;i.FOG&&n.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(i,n),i.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[se.PositionKind];i.NORMAL&&o.push(se.NormalKind),i.UV1&&o.push(se.UVKind),i.UV2&&o.push(se.UV2Kind),i.VERTEXCOLOR&&o.push(se.ColorKind),i.TANGENT&&o.push(se.TangentKind),ze.PrepareAttributesForInstances(o,i);const l="mrdlBackplate",c=i.toString(),h=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Iridescence_Tint_","_Iridescent_Map_","_Angle_","_Reflected_","_Frequency_","_Vertical_Offset_","_Gradient_Color_","_Top_Left_","_Top_Right_","_Bottom_Left_","_Bottom_Right_","_Edge_Width_","_Edge_Power_","_Line_Gradient_Blend_","_Fade_Out_"],u=["_Iridescent_Map_"],p=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:i,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:c,fallbacks:n,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),i)}return!t.effect||!t.effect.isReady()?!1:(i._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;!r||(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setDirectColor4("_Iridescence_Tint_",this.iridescenceTint),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMapTexture),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setDirectColor4("_Gradient_Color_",this.gradientColor),this._activeEffect.setDirectColor4("_Top_Left_",this.topLeftGradientColor),this._activeEffect.setDirectColor4("_Top_Right_",this.topRightGradientColor),this._activeEffect.setDirectColor4("_Bottom_Left_",this.bottomLeftGradientColor),this._activeEffect.setDirectColor4("_Bottom_Right_",this.bottomRightGradientColor),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setFloat("_Edge_Power_",this.edgePower),this._activeEffect.setFloat("_Line_Gradient_Blend_",this.edgeLineGradientBlend),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._afterBind(t,this._activeEffect))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return Kt.Clone(()=>new Vo(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLBackplateMaterial",e}getClassName(){return"MRDLBackplateMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new Vo(e.name,t),e,t,i)}}Vo.IRIDESCENT_MAP_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-backplate-iridescence.png";z([X()],Vo.prototype,"radius",void 0);z([X()],Vo.prototype,"lineWidth",void 0);z([X()],Vo.prototype,"absoluteSizes",void 0);z([X()],Vo.prototype,"baseColor",void 0);z([X()],Vo.prototype,"lineColor",void 0);z([X()],Vo.prototype,"radiusTopLeft",void 0);z([X()],Vo.prototype,"radiusTopRight",void 0);z([X()],Vo.prototype,"radiusBottomLeft",void 0);z([X()],Vo.prototype,"radiusBottomRight",void 0);z([X()],Vo.prototype,"highlightColor",void 0);z([X()],Vo.prototype,"highlightWidth",void 0);z([X()],Vo.prototype,"iridescenceIntensity",void 0);z([X()],Vo.prototype,"iridescenceEdgeIntensity",void 0);z([X()],Vo.prototype,"iridescenceTint",void 0);z([X()],Vo.prototype,"fadeOut",void 0);z([X()],Vo.prototype,"gradientColor",void 0);z([X()],Vo.prototype,"topLeftGradientColor",void 0);z([X()],Vo.prototype,"topRightGradientColor",void 0);z([X()],Vo.prototype,"bottomLeftGradientColor",void 0);z([X()],Vo.prototype,"bottomRightGradientColor",void 0);z([X()],Vo.prototype,"edgeWidth",void 0);z([X()],Vo.prototype,"edgePower",void 0);z([X()],Vo.prototype,"edgeLineGradientBlend",void 0);$e("BABYLON.GUI.MRDLBackplateMaterial",Vo);const Mre=0,DSe=100,OSe=50,Tre=0,NZ=1,wSe=.2;class nF extends UW{constructor(e,t){super(e),this.onValueChangedObservable=new Se,this._sliderBackplateVisible=t||!1,this._minimum=Mre,this._maximum=DSe,this._step=Tre,this._value=OSe}get mesh(){return this.node?this._sliderThumb:null}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=Math.max(e,Mre),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=Math.max(e,this._minimum),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get step(){return this._step}set step(e){this._step!==e&&(this._step=Math.max(Math.min(e,this._maximum-this._minimum),Tre))}get value(){return this._value}set value(e){this._value!==e&&(this._value=Math.max(Math.min(e,this._maximum),this._minimum),this._sliderThumb&&(this._sliderThumb.position.x=this._convertToPosition(this.value)),this.onValueChangedObservable.notifyObservers(this._value))}get start(){return this.node?this._sliderBar.position.x-this._sliderBar.scaling.x/2:-NZ/2}get end(){return this.node?this._sliderBar.position.x+this._sliderBar.scaling.x/2:NZ/2}get sliderBarMaterial(){return this._sliderBarMaterial}get sliderThumbMaterial(){return this._sliderThumbMaterial}get sliderBackplateMaterial(){return this._sliderBackplateMaterial}set isVisible(e){var t;this._isVisible!==e&&(this._isVisible=e,(t=this.node)===null||t===void 0||t.setEnabled(e))}_createNode(e){const t=pl(`${this.name}_sliderbackplate`,{width:1,height:1,depth:1},e);return t.isPickable=!1,t.visibility=0,t.scaling=new O(1,.5,.8),As.ImportMeshAsync(void 0,nF.MODEL_BASE_URL,nF.MODEL_FILENAME,e).then(i=>{i.meshes.forEach(o=>{o.isPickable=!1});const s=i.meshes[1],r=i.meshes[1].clone(`${this.name}_sliderbar`,t),n=i.meshes[1].clone(`${this.name}_sliderthumb`,t);s.visibility=0,this._sliderBackplateVisible&&(s.visibility=1,s.name=`${this.name}_sliderbackplate`,s.scaling.x=1,s.scaling.z=.2,s.parent=t,this._sliderBackplateMaterial&&(s.material=this._sliderBackplateMaterial),this._sliderBackplate=s),r&&(r.parent=t,r.position.z=-.1,r.scaling=new O(NZ-wSe,.04,.3),this._sliderBarMaterial&&(r.material=this._sliderBarMaterial),this._sliderBar=r),n&&(n.parent=t,n.isPickable=!0,n.position.z=-.115,n.scaling=new O(.025,.3,.6),n.position.x=this._convertToPosition(this.value),n.addBehavior(this._createBehavior()),this._sliderThumbMaterial&&(n.material=this._sliderThumbMaterial),this._sliderThumb=n),this._injectGUI3DReservedDataStore(t).control=this,t.getChildMeshes().forEach(o=>{this._injectGUI3DReservedDataStore(o).control=this})}),this._affectMaterial(t),t}_affectMaterial(e){var t,i,s;this._sliderBackplateMaterial=(t=this._sliderBackplateMaterial)!==null&&t!==void 0?t:new Vo(`${this.name}_sliderbackplate_material`,e.getScene()),this._sliderBarMaterial=(i=this._sliderBarMaterial)!==null&&i!==void 0?i:new nr(`${this.name}_sliderbar_material`,e.getScene()),this._sliderThumbMaterial=(s=this._sliderThumbMaterial)!==null&&s!==void 0?s:new ar(`${this.name}_sliderthumb_material`,e.getScene())}_createBehavior(){const e=new uc({dragAxis:O.Right()});return e.moveAttached=!1,e.onDragStartObservable.add(()=>{this._draggedPosition=this._sliderThumb.position.x}),e.onDragObservable.add(t=>{this._draggedPosition+=t.dragDistance/this.scaling.x,this.value=this._convertToValue(this._draggedPosition)}),e}_convertToPosition(e){const t=(e-this.minimum)/(this.maximum-this.minimum)*(this.end-this.start)+this.start;return Math.min(Math.max(t,this.start),this.end)}_convertToValue(e){let t=(e-this.start)/(this.end-this.start)*(this.maximum-this.minimum);return t=this.step?Math.round(t/this.step)*this.step:t,Math.max(Math.min(this.minimum+t,this._maximum),this._minimum)}dispose(){var e,t,i,s,r,n;super.dispose(),(e=this._sliderBar)===null||e===void 0||e.dispose(),(t=this._sliderThumb)===null||t===void 0||t.dispose(),(i=this._sliderBarMaterial)===null||i===void 0||i.dispose(),(s=this._sliderThumbMaterial)===null||s===void 0||s.dispose(),(r=this._sliderBackplate)===null||r===void 0||r.dispose(),(n=this._sliderBackplateMaterial)===null||n===void 0||n.dispose()}}nF.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/";nF.MODEL_FILENAME="mrtk-fluent-backplate.glb";class NSe extends FF{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,Be.SetImmediate(()=>{this._arrangeChildren()}))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const s=this._sphericalMapping(t);switch(e.position=s,this.orientation){case Rc.FACEORIGIN_ORIENTATION:i.lookAt(new O(2*s.x,2*s.y,2*s.z));break;case Rc.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new O(-s.x,-s.y,-s.z));break;case Rc.FACEFORWARD_ORIENTATION:break;case Rc.FACEFORWARDREVERSED_ORIENTATION:i.rotate(Fo.Y,Math.PI,sr.LOCAL);break}}_sphericalMapping(e){const t=new O(0,0,this._radius),i=e.y/this._radius,s=-(e.x/this._radius);return ge.RotationYawPitchRollToRef(s,i,0,ue.Matrix[0]),O.TransformNormal(t,ue.Matrix[0])}}class BSe extends Rc{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,Be.SetImmediate(()=>{this._arrangeChildren()}))}constructor(e=!1){super(),this._isVertical=!1,this.margin=.1,this._isVertical=e}_arrangeChildren(){let e=0,t=0,i=0;const s=[],r=ge.Invert(this.node.computeWorldMatrix(!0));for(const l of this._children){if(!l.mesh)continue;i++,l.mesh.computeWorldMatrix(!0),l.mesh.getWorldMatrix().multiplyToRef(r,ue.Matrix[0]);const c=l.mesh.getBoundingInfo().boundingBox,h=O.TransformNormal(c.extendSize,ue.Matrix[0]);s.push(h),this._isVertical?t+=h.y:e+=h.x}this._isVertical?t+=(i-1)*this.margin/2:e+=(i-1)*this.margin/2;let n;this._isVertical?n=-t:n=-e;let o=0;for(const l of this._children){if(!l.mesh)continue;i--;const c=s[o++];this._isVertical?(l.position.y=n+c.y,l.position.x=0,n+=c.y*2):(l.position.x=n+c.x,l.position.y=0,n+=c.x*2),n+=i>0?this.margin:0}}}class FSe extends DQ{constructor(e,t){super(t,e),this._currentMesh=e,this.pointerEnterAnimation=()=>{!this.mesh||this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{!this.mesh||this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{!this.mesh||this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{!this.mesh||this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"TouchMeshButton3D"}_createNode(){return this._currentMesh.getChildMeshes().forEach(e=>{this._injectGUI3DReservedDataStore(e).control=this}),this._currentMesh}_affectMaterial(e){}}const VSe="mrdlBackglowPixelShader",zSe=`uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;float BiasFunc(float b,float v) {return pow(v,log(clamp(b,0.001,0.999))/log(0.5));} +void Fuzzy_Round_Rect_B33( +float Size_X, +float Size_Y, +float Radius_X, +float Radius_Y, +float Line_Width, +vec2 UV, +float Outer_Fuzz, +float Max_Outer_Fuzz, +out float Rect_Distance, +out float Inner_Distance) +{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius_X,Radius_Y),halfSize),vec2(0.001,0.001));float radius=min(r.x,r.y)-Max_Outer_Fuzz;vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);float d=distance(nearestp,v);Inner_Distance=clamp(1.0-(radius-d)/Line_Width,0.0,1.0);Rect_Distance=clamp(1.0-(d-radius)/Outer_Fuzz,0.0,1.0)*Inner_Distance;} +void main() +{float X_Q42;float Y_Q42;X_Q42=vNormal.x;Y_Q42=vNormal.y;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Sqrt_F_Q27=sqrt(MaxAB_Q24);float Power_Q43=pow(MaxAB_Q24,_Intensity_Fade_In_Exponent_);float Value_At_T_Q26=mix(_Outer_Fuzz_Start_,_Outer_Fuzz_End_,Sqrt_F_Q27);float Product_Q23=_Max_Intensity_*Power_Q43;float Rect_Distance_Q33;float Inner_Distance_Q33;Fuzzy_Round_Rect_B33(X_Q42,Y_Q42,_Bevel_Radius_,_Bevel_Radius_,_Line_Width_,vUV,Value_At_T_Q26,_Outer_Fuzz_Start_,Rect_Distance_Q33,Inner_Distance_Q33);float Power_Q44=pow(Inner_Distance_Q33,_Blend_Exponent_);float Result_Q45=pow(BiasFunc(_Bias_,Rect_Distance_Q33),_Falloff_);vec4 Color_At_T_Q25=mix(_Inner_Color_,_Color_,Power_Q44);float Product_Q22=Result_Q45*Product_Q23;vec4 Result_Q28=Product_Q22*Color_At_T_Q25;vec4 Out_Color=Result_Q28;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}`;Ue.ShadersStore[VSe]=zSe;const USe="mrdlBackglowVertexShader",kSe=`uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;varying vec3 vNormal;varying vec2 vUV;void main() +{vec3 Dir_World_Q41=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q40=(world*vec4((cross(normal,tangent)),0.0)).xyz;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Length_Q16=length(Dir_World_Q41);float Length_Q17=length(Dir_World_Q40);bool Greater_Than_Q37=MaxAB_Q24>0.0;vec3 Sizes_Q35;vec2 XY_Q35;Sizes_Q35=(_Absolute_Sizes_ ? vec3(Length_Q16,Length_Q17,0) : vec3(Length_Q16/Length_Q17,1,0));XY_Q35=(uv-vec2(0.5,0.5))*Sizes_Q35.xy;vec3 Result_Q38=Greater_Than_Q37 ? position : vec3(0,0,0);vec3 Pos_World_Q39=(world*vec4(Result_Q38,1.0)).xyz;vec3 Position=Pos_World_Q39;vec3 Normal=Sizes_Q35;vec2 UV=XY_Q35;vec3 Tangent=vec3(0,0,0);vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;}`;Ue.ShadersStore[USe]=kSe;class HSe extends ta{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class t2 extends Bl{constructor(e,t){super(e,t),this.bevelRadius=.16,this.lineWidth=.16,this.absoluteSizes=!1,this.tuningMotion=0,this.motion=1,this.maxIntensity=.7,this.intensityFadeInExponent=2,this.outerFuzzStart=.04,this.outerFuzzEnd=.04,this.color=new Zt(.682353,.698039,1,1),this.innerColor=new Zt(.356863,.392157,.796078,1),this.blendExponent=1.5,this.falloff=2,this.bias=.5,this.alphaMode=it.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new HSe);const i=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(ze.PrepareDefinesForAttributes(e,i,!1,!1),i.isDirty){i.markAsProcessed(),s.resetCachedMaterial();const n=new Fl;i.FOG&&n.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(i,n),i.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[se.PositionKind];i.NORMAL&&o.push(se.NormalKind),i.UV1&&o.push(se.UVKind),i.UV2&&o.push(se.UV2Kind),i.VERTEXCOLOR&&o.push(se.ColorKind),i.TANGENT&&o.push(se.TangentKind),ze.PrepareAttributesForInstances(o,i);const l="mrdlBackglow",c=i.toString(),h=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Bevel_Radius_","_Line_Width_","_Absolute_Sizes_","_Tuning_Motion_","_Motion_","_Max_Intensity_","_Intensity_Fade_In_Exponent_","_Outer_Fuzz_Start_","_Outer_Fuzz_End_","_Color_","_Inner_Color_","_Blend_Exponent_","_Falloff_","_Bias_"],u=[],p=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:i,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:c,fallbacks:n,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),i)}return!t.effect||!t.effect.isReady()?!1:(i._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setFloat("_Bevel_Radius_",this.bevelRadius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Tuning_Motion_",this.tuningMotion),this._activeEffect.setFloat("_Motion_",this.motion),this._activeEffect.setFloat("_Max_Intensity_",this.maxIntensity),this._activeEffect.setFloat("_Intensity_Fade_In_Exponent_",this.intensityFadeInExponent),this._activeEffect.setFloat("_Outer_Fuzz_Start_",this.outerFuzzStart),this._activeEffect.setFloat("_Outer_Fuzz_End_",this.outerFuzzEnd),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setDirectColor4("_Inner_Color_",this.innerColor),this._activeEffect.setFloat("_Blend_Exponent_",this.blendExponent),this._activeEffect.setFloat("_Falloff_",this.falloff),this._activeEffect.setFloat("_Bias_",this.bias),this._afterBind(t,this._activeEffect))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return Kt.Clone(()=>new t2(e,this.getScene()),this)}serialize(){const e=Kt.Serialize(this);return e.customType="BABYLON.MRDLBackglowMaterial",e}getClassName(){return"MRDLBackglowMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new t2(e.name,t),e,t,i)}}z([X()],t2.prototype,"bevelRadius",void 0);z([X()],t2.prototype,"lineWidth",void 0);z([X()],t2.prototype,"absoluteSizes",void 0);z([X()],t2.prototype,"tuningMotion",void 0);z([X()],t2.prototype,"motion",void 0);z([X()],t2.prototype,"maxIntensity",void 0);z([X()],t2.prototype,"intensityFadeInExponent",void 0);z([X()],t2.prototype,"outerFuzzStart",void 0);z([X()],t2.prototype,"outerFuzzEnd",void 0);z([X()],t2.prototype,"color",void 0);z([X()],t2.prototype,"innerColor",void 0);z([X()],t2.prototype,"blendExponent",void 0);z([X()],t2.prototype,"falloff",void 0);z([X()],t2.prototype,"bias",void 0);$e("BABYLON.GUI.MRDLBackglowMaterial",t2);const jSe="mrdlFrontplatePixelShader",GSe=`uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;void Scale_Color_B54( +vec4 Color, +float Scalar, +out vec4 Result) +{Result=Scalar*Color;} +void Scale_RGB_B50( +vec4 Color, +float Scalar, +out vec4 Result) +{Result=vec4(Scalar,Scalar,Scalar,1)*Color;} +void Proximity_Fragment_B51( +float Proximity_Max_Intensity, +float Proximity_Near_Radius, +vec4 Deltas, +float Show_Selection, +float Distance_Fade1, +float Distance_Fade2, +float Strength, +out float Proximity) +{float proximity1=(1.0-clamp(length(Deltas.xy)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade1;float proximity2=(1.0-clamp(length(Deltas.zw)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade2;Proximity=Strength*(Proximity_Max_Intensity*max(proximity1,proximity2) *(1.0-Show_Selection)+Show_Selection);} +void Blob_Fragment_B56( +vec2 UV, +vec3 Blob_Info, +sampler2D Blob_Texture, +out vec4 Blob_Color) +{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));} +void Round_Rect_Fragment_B61( +float Radius, +vec4 Line_Color, +float Filter_Width, +float Line_Visibility, +vec4 Fill_Color, +bool Smooth_Edges, +vec4 Rect_Parms, +out float Inside_Rect) +{float d=length(max(abs(Rect_Parms.zw)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);Inside_Rect=Smooth_Edges ? clamp((Radius-d)/dx,0.0,1.0) : 1.0-step(Radius,d);} +void main() +{float Is_Quad_Q53;Is_Quad_Q53=vNormal.z;vec4 Blob_Color_Q56;Blob_Fragment_B56(vUV,vTangent,_Blob_Texture_,Blob_Color_Q56);float X_Q52;float Y_Q52;float Z_Q52;float W_Q52;X_Q52=vExtra3.x;Y_Q52=vExtra3.y;Z_Q52=vExtra3.z;W_Q52=vExtra3.w;float Proximity_Q51;Proximity_Fragment_B51(_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vExtra2,X_Q52,Y_Q52,Z_Q52,1.0,Proximity_Q51);float Inside_Rect_Q61;Round_Rect_Fragment_B61(W_Q52,vec4(1,1,1,1),_Filter_Width_,1.0,vec4(0,0,0,0),_Smooth_Edges_,vExtra1,Inside_Rect_Q61);vec4 Result_Q50;Scale_RGB_B50(_Edge_Color_,Proximity_Q51,Result_Q50);vec4 Result_Q47=Inside_Rect_Q61*Blob_Color_Q56;vec4 Color_At_T_Q48=mix(Result_Q50,Result_Q47,Is_Quad_Q53);vec4 Result_Q54;Scale_Color_B54(Color_At_T_Q48,_Fade_Out_,Result_Q54);vec4 Out_Color=Result_Q54;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}`;Ue.ShadersStore[jSe]=GSe;const WSe="mrdlFrontplateVertexShader",YSe=`uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;void Blob_Vertex_B40( +vec3 Position, +vec3 Normal, +vec3 Tangent, +vec3 Bitangent, +vec3 Blob_Position, +float Intensity, +float Blob_Near_Size, +float Blob_Far_Size, +float Blob_Near_Distance, +float Blob_Far_Distance, +vec4 Vx_Color, +vec2 UV, +vec3 Face_Center, +vec2 Face_Size, +vec2 In_UV, +float Blob_Fade_Length, +float Selection_Fade, +float Selection_Fade_Size, +float Inner_Fade, +float Blob_Pulse, +float Blob_Fade, +float Blob_Enabled, +float DistanceOffset, +out vec3 Out_Position, +out vec2 Out_UV, +out vec3 Blob_Info, +out vec2 Blob_Relative_UV) +{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal)+DistanceOffset*Blob_Far_Distance;Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; +vec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);Blob_Relative_UV=blobClipped/Face_Size.y;} +void Round_Rect_Vertex_B36( +vec2 UV, +vec3 Tangent, +vec3 Binormal, +float Radius, +float Anisotropy, +vec2 Blob_Center_UV, +out vec2 Rect_UV, +out vec2 Scale_XY, +out vec4 Rect_Parms) +{Scale_XY=vec2(Anisotropy,1.0);Rect_UV=(UV-vec2(0.5,0.5))*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius);Rect_Parms.zw=Blob_Center_UV;} +vec2 ProjectProximity( +vec3 blobPosition, +vec3 position, +vec3 center, +vec3 dir, +vec3 xdir, +vec3 ydir, +out float vdistance +) +{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;} +void Proximity_Vertex_B33( +vec3 Blob_Position, +vec3 Blob_Position_2, +vec3 Face_Center, +vec3 Position, +float Proximity_Far_Distance, +float Relative_Scale, +float Proximity_Anisotropy, +vec3 Normal, +vec3 Tangent, +vec3 Binormal, +out vec4 Extra, +out float Distance_To_Face, +out float Distance_Fade1, +out float Distance_Fade2) +{float distz1,distz2;Extra.xy=ProjectProximity(Blob_Position,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz1)/Relative_Scale;Extra.zw=ProjectProximity(Blob_Position_2,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz2)/Relative_Scale;Distance_To_Face=dot(Normal,Position-Face_Center);Distance_Fade1=1.0-clamp(distz1/Proximity_Far_Distance,0.0,1.0);Distance_Fade2=1.0-clamp(distz2/Proximity_Far_Distance,0.0,1.0);} +void Object_To_World_Pos_B12( +vec3 Pos_Object, +out vec3 Pos_World) +{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;} +void Choose_Blob_B27( +vec4 Vx_Color, +vec3 Position1, +vec3 Position2, +bool Blob_Enable_1, +bool Blob_Enable_2, +float Near_Size_1, +float Near_Size_2, +float Blob_Inner_Fade_1, +float Blob_Inner_Fade_2, +float Blob_Pulse_1, +float Blob_Pulse_2, +float Blob_Fade_1, +float Blob_Fade_2, +out vec3 Position, +out float Near_Size, +out float Inner_Fade, +out float Blob_Enable, +out float Fade, +out float Pulse) +{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=Blob_Enable_1 ? 1.0 : 0.0;float b2=Blob_Enable_2 ? 1.0 : 0.0;Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;} +void Move_Verts_B32( +vec2 UV, +float Radius, +float Anisotropy, +float Line_Width, +float Visible, +out vec3 New_P, +out vec2 New_UV) +{vec2 xy=2.0*UV-vec2(0.5,0.5);vec2 center=clamp(xy,0.0,1.0);vec2 delta=2.0*(xy-center);float deltaLength=length(delta);vec2 aniso=vec2(1.0/Anisotropy,1.0);center=(center-vec2(0.5,0.5))*(1.0-2.0*Radius*aniso);New_UV=vec2((2.0-2.0*deltaLength)*Visible,0.0);float deltaRadius= (Radius-Line_Width*New_UV.x);New_P.xy=(center+deltaRadius/deltaLength *aniso*delta);New_P.z=0.0;} +void Object_To_World_Dir_B14( +vec3 Dir_Object, +out vec3 Binormal_World) +{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;} +void Proximity_Visibility_B55( +float Selection, +vec3 Proximity_Center, +vec3 Proximity_Center_2, +float Proximity_Far_Distance, +float Proximity_Radius, +vec3 Face_Center, +vec3 Normal, +vec2 Face_Size, +float Gaze, +out float Width) +{float boxMaxSize=length(Face_Size)*0.5;float d1=dot(Proximity_Center-Face_Center,Normal);vec3 blob1=Proximity_Center-d1*Normal;float d2=dot(Proximity_Center_2-Face_Center,Normal);vec3 blob2=Proximity_Center_2-d2*Normal;vec3 delta1=blob1-Face_Center;vec3 delta2=blob2-Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));Width=max(Gaze,Width);} +vec2 ramp2(vec2 start,vec2 end,vec2 x) +{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));} +float computeSelection( +vec3 blobPosition, +vec3 normal, +vec3 tangent, +vec3 bitangent, +vec3 faceCenter, +vec2 faceSize, +float selectionFuzz, +float farDistance, +float fadeLength +) +{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;} +void Selection_Vertex_B31( +vec3 Blob_Position, +vec3 Blob_Position_2, +vec3 Face_Center, +vec2 Face_Size, +vec3 Normal, +vec3 Tangent, +vec3 Bitangent, +float Selection_Fuzz, +float Selected, +float Far_Distance, +float Fade_Length, +vec3 Active_Face_Dir, +out float Show_Selection) +{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);Show_Selection=mix(max(select1,select2),1.0,Selected);} +void main() +{vec3 Vec3_Q29=vec3(vec2(0,0).x,vec2(0,0).y,color.r);vec3 Nrm_World_Q24;Nrm_World_Q24=normalize((world*vec4(normal,0.0)).xyz);vec3 Face_Center_Q30;Face_Center_Q30=(world*vec4(vec3(0,0,0),1.0)).xyz;vec3 Tangent_World_Q13;Tangent_World_Q13=(world*vec4(tangent,0.0)).xyz;vec3 Result_Q42;Result_Q42=_Use_Global_Left_Index_ ? Global_Left_Index_Tip_Position.xyz : _Blob_Position_;vec3 Result_Q43;Result_Q43=_Use_Global_Right_Index_ ? Global_Right_Index_Tip_Position.xyz : _Blob_Position_2_;float Value_At_T_Q58=mix(_Blob_Near_Size_,_Blob_Pulse_Max_Size_,_Blob_Pulse_);float Value_At_T_Q59=mix(_Blob_Near_Size_2_,_Blob_Pulse_Max_Size_,_Blob_Pulse_2_);vec3 Cross_Q70=cross(normal,tangent);float Product_Q45=_Gaze_Intensity_*_Gaze_Focus_;float Step_Q46=step(0.0001,Product_Q45);vec3 Tangent_World_N_Q15=normalize(Tangent_World_Q13);vec3 Position_Q27;float Near_Size_Q27;float Inner_Fade_Q27;float Blob_Enable_Q27;float Fade_Q27;float Pulse_Q27;Choose_Blob_B27(color,Result_Q42,Result_Q43,_Blob_Enable_,_Blob_Enable_2_,Value_At_T_Q58,Value_At_T_Q59,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q27,Near_Size_Q27,Inner_Fade_Q27,Blob_Enable_Q27,Fade_Q27,Pulse_Q27);vec3 Binormal_World_Q14;Object_To_World_Dir_B14(Cross_Q70,Binormal_World_Q14);float Anisotropy_Q21=length(Tangent_World_Q13)/length(Binormal_World_Q14);vec3 Binormal_World_N_Q16=normalize(Binormal_World_Q14);vec2 Face_Size_Q35;float ScaleY_Q35;Face_Size_Q35=vec2(length(Tangent_World_Q13),length(Binormal_World_Q14));ScaleY_Q35=Face_Size_Q35.y;float Out_Radius_Q38;float Out_Line_Width_Q38;Out_Radius_Q38=_Relative_To_Height_ ? _Radius_ : _Radius_/ScaleY_Q35;Out_Line_Width_Q38=_Relative_To_Height_ ? _Line_Width_ : _Line_Width_/ScaleY_Q35;float Show_Selection_Q31;Selection_Vertex_B31(Result_Q42,Result_Q43,Face_Center_Q30,Face_Size_Q35,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,vec3(0,0,-1),Show_Selection_Q31);float MaxAB_Q41=max(Show_Selection_Q31,Product_Q45);float Width_Q55;Proximity_Visibility_B55(Show_Selection_Q31,Result_Q42,Result_Q43,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Face_Center_Q30,Nrm_World_Q24,Face_Size_Q35,Step_Q46,Width_Q55);vec3 New_P_Q32;vec2 New_UV_Q32;Move_Verts_B32(uv,Out_Radius_Q38,Anisotropy_Q21,Out_Line_Width_Q38,Width_Q55,New_P_Q32,New_UV_Q32);vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q32,Pos_World_Q12);vec3 Out_Position_Q40;vec2 Out_UV_Q40;vec3 Blob_Info_Q40;vec2 Blob_Relative_UV_Q40;Blob_Vertex_B40(Pos_World_Q12,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Position_Q27,_Blob_Intensity_,Near_Size_Q27,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q30,Face_Size_Q35,New_UV_Q32,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q27,Pulse_Q27,Fade_Q27,Blob_Enable_Q27,0.0,Out_Position_Q40,Out_UV_Q40,Blob_Info_Q40,Blob_Relative_UV_Q40);vec2 Rect_UV_Q36;vec2 Scale_XY_Q36;vec4 Rect_Parms_Q36;Round_Rect_Vertex_B36(New_UV_Q32,Tangent_World_Q13,Binormal_World_Q14,Out_Radius_Q38,Anisotropy_Q21,Blob_Relative_UV_Q40,Rect_UV_Q36,Scale_XY_Q36,Rect_Parms_Q36);vec4 Extra_Q33;float Distance_To_Face_Q33;float Distance_Fade1_Q33;float Distance_Fade2_Q33;Proximity_Vertex_B33(Result_Q42,Result_Q43,Face_Center_Q30,Pos_World_Q12,_Proximity_Far_Distance_,1.0,_Proximity_Anisotropy_,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Extra_Q33,Distance_To_Face_Q33,Distance_Fade1_Q33,Distance_Fade2_Q33);vec4 Vec4_Q37=vec4(MaxAB_Q41,Distance_Fade1_Q33,Distance_Fade2_Q33,Out_Radius_Q38);vec3 Position=Out_Position_Q40;vec3 Normal=Vec3_Q29;vec2 UV=Out_UV_Q40;vec3 Tangent=Blob_Info_Q40;vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);vec4 Extra1=Rect_Parms_Q36;vec4 Extra2=Extra_Q33;vec4 Extra3=Vec4_Q37;gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;vTangent=Tangent;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}`;Ue.ShadersStore[WSe]=YSe;class XSe extends ta{constructor(){super(),this.SMOOTH_EDGES=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class wn extends Bl{constructor(e,t){super(e,t),this.radius=.12,this.lineWidth=.01,this.relativeToHeight=!1,this._filterWidth=1,this.edgeColor=new Zt(.53,.53,.53,1),this.blobEnable=!0,this.blobPosition=new O(100,100,100),this.blobIntensity=.5,this.blobNearSize=.032,this.blobFarSize=.048,this.blobNearDistance=.008,this.blobFarDistance=.064,this.blobFadeLength=.04,this.blobInnerFade=.01,this.blobPulse=0,this.blobFade=1,this.blobPulseMaxSize=.05,this.blobEnable2=!0,this.blobPosition2=new O(10,10.1,-.6),this.blobNearSize2=.008,this.blobInnerFade2=.1,this.blobPulse2=0,this.blobFade2=1,this.gazeIntensity=.8,this.gazeFocus=0,this.selectionFuzz=.5,this.selected=1,this.selectionFade=.2,this.selectionFadeSize=0,this.selectedDistance=.08,this.selectedFadeLength=.08,this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=.016,this.proximityAnisotropy=1,this.useGlobalLeftIndex=!0,this.useGlobalRightIndex=!0,this.fadeOut=1,this.alphaMode=it.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new Te(wn.BLOB_TEXTURE_URL,t,!0,!1,Te.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new XSe);const i=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(ze.PrepareDefinesForAttributes(e,i,!1,!1),i.isDirty){i.markAsProcessed(),s.resetCachedMaterial();const n=new Fl;i.FOG&&n.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(i,n),i.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[se.PositionKind];i.NORMAL&&o.push(se.NormalKind),i.UV1&&o.push(se.UVKind),i.UV2&&o.push(se.UV2Kind),i.VERTEXCOLOR&&o.push(se.ColorKind),i.TANGENT&&o.push(se.TangentKind),ze.PrepareAttributesForInstances(o,i);const l="mrdlFrontplate",c=i.toString(),h=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Relative_To_Height_","_Filter_Width_","_Edge_Color_","_Fade_Out_","_Smooth_Edges_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Pulse_Max_Size_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Gaze_Intensity_","_Gaze_Focus_","_Blob_Texture_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","_Use_Global_Left_Index_","_Use_Global_Right_Index_"],u=[],p=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:i,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:c,fallbacks:n,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),i)}return!t.effect||!t.effect.isReady()?!1:(i._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Relative_To_Height_",this.relativeToHeight?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Edge_Color_",this.edgeColor),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Blob_Enable_",this.blobEnable?1:0),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.blobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setFloat("_Blob_Pulse_Max_Size_",this.blobPulseMaxSize),this._activeEffect.setFloat("_Blob_Enable_2_",this.blobEnable2?1:0),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.blobInnerFade2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Gaze_Intensity_",this.gazeIntensity),this._activeEffect.setFloat("_Gaze_Focus_",this.gazeFocus),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Use_Global_Left_Index_",this.useGlobalLeftIndex?1:0),this._activeEffect.setFloat("_Use_Global_Right_Index_",this.useGlobalRightIndex?1:0),this._afterBind(t,this._activeEffect))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return Kt.Clone(()=>new wn(e,this.getScene()),this)}serialize(){const e=Kt.Serialize(this);return e.customType="BABYLON.MRDLFrontplateMaterial",e}getClassName(){return"MRDLFrontplateMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new wn(e.name,t),e,t,i)}}wn.BLOB_TEXTURE_URL="";z([X()],wn.prototype,"radius",void 0);z([X()],wn.prototype,"lineWidth",void 0);z([X()],wn.prototype,"relativeToHeight",void 0);z([X()],wn.prototype,"edgeColor",void 0);z([X()],wn.prototype,"blobEnable",void 0);z([X()],wn.prototype,"blobPosition",void 0);z([X()],wn.prototype,"blobIntensity",void 0);z([X()],wn.prototype,"blobNearSize",void 0);z([X()],wn.prototype,"blobFarSize",void 0);z([X()],wn.prototype,"blobNearDistance",void 0);z([X()],wn.prototype,"blobFarDistance",void 0);z([X()],wn.prototype,"blobFadeLength",void 0);z([X()],wn.prototype,"blobInnerFade",void 0);z([X()],wn.prototype,"blobPulse",void 0);z([X()],wn.prototype,"blobFade",void 0);z([X()],wn.prototype,"blobPulseMaxSize",void 0);z([X()],wn.prototype,"blobEnable2",void 0);z([X()],wn.prototype,"blobPosition2",void 0);z([X()],wn.prototype,"blobNearSize2",void 0);z([X()],wn.prototype,"blobInnerFade2",void 0);z([X()],wn.prototype,"blobPulse2",void 0);z([X()],wn.prototype,"blobFade2",void 0);z([X()],wn.prototype,"gazeIntensity",void 0);z([X()],wn.prototype,"gazeFocus",void 0);z([X()],wn.prototype,"selectionFuzz",void 0);z([X()],wn.prototype,"selected",void 0);z([X()],wn.prototype,"selectionFade",void 0);z([X()],wn.prototype,"selectionFadeSize",void 0);z([X()],wn.prototype,"selectedDistance",void 0);z([X()],wn.prototype,"selectedFadeLength",void 0);z([X()],wn.prototype,"proximityMaxIntensity",void 0);z([X()],wn.prototype,"proximityFarDistance",void 0);z([X()],wn.prototype,"proximityNearRadius",void 0);z([X()],wn.prototype,"proximityAnisotropy",void 0);z([X()],wn.prototype,"useGlobalLeftIndex",void 0);z([X()],wn.prototype,"useGlobalRightIndex",void 0);$e("BABYLON.GUI.MRDLFrontplateMaterial",wn);const KSe="mrdlInnerquadPixelShader",QSe=`uniform vec3 cameraPosition;varying vec2 vUV;varying vec3 vTangent;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;float FilterStep_Bid194(float edge,float x,float filterWidth) +{float dx=max(1.0E-5,fwidth(x)*filterWidth);return max((x+dx*0.5-max(edge,x-dx*0.5))/dx,0.0);} +void Round_Rect_B194( +float Size_X, +float Size_Y, +float Radius, +vec4 Rect_Color, +float Filter_Width, +vec2 UV, +float Glow_Fraction, +float Glow_Max, +float Glow_Falloff, +out vec4 Color) +{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius,Radius),halfSize),vec2(0.01,0.01));vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);vec2 delta=(v-nearestp)/max(vec2(0.01,0.01),r);float Distance=length(delta);float insideRect=1.0-FilterStep_Bid194(1.0-Glow_Fraction,Distance,Filter_Width);float glow=clamp((1.0-Distance)/Glow_Fraction,0.0,1.0);glow=pow(glow,Glow_Falloff);Color=Rect_Color*max(insideRect,glow*Glow_Max);} +void main() +{float X_Q192;float Y_Q192;float Z_Q192;X_Q192=vTangent.x;Y_Q192=vTangent.y;Z_Q192=vTangent.z;vec4 Color_Q194;Round_Rect_B194(X_Q192,1.0,Y_Q192,_Color_,_Filter_Width_,vUV,_Glow_Fraction_,_Glow_Max_,_Glow_Falloff_,Color_Q194);vec4 Out_Color=Color_Q194;float Clip_Threshold=0.0;gl_FragColor=Out_Color;} +`;Ue.ShadersStore[KSe]=QSe;const ZSe="mrdlInnerquadVertexShader",qSe=`uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;varying vec2 vUV;varying vec3 vTangent;void main() +{vec3 Pos_World_Q189;Pos_World_Q189=(world*vec4(position,1.0)).xyz;vec3 Dir_World_Q190;Dir_World_Q190=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q191;Dir_World_Q191=(world*vec4((cross(normal,tangent)),0.0)).xyz;float Length_Q180=length(Dir_World_Q190);float Length_Q181=length(Dir_World_Q191);float Quotient_Q184=Length_Q180/Length_Q181;float Quotient_Q195=_Radius_/Length_Q181;vec2 Result_Q193;Result_Q193=vec2((uv.x-0.5)*Length_Q180/Length_Q181,(uv.y-0.5));float Result_Q198=_Fixed_Radius_ ? Quotient_Q195 : _Radius_;vec3 Vec3_Q183=vec3(Quotient_Q184,Result_Q198,0);vec3 Position=Pos_World_Q189;vec3 Normal=vec3(0,0,0);vec2 UV=Result_Q193;vec3 Tangent=Vec3_Q183;vec3 Binormal=vec3(0,0,0);vec4 Color=color;gl_Position=viewProjection*vec4(Position,1);vUV=UV;vTangent=Tangent;} +`;Ue.ShadersStore[ZSe]=qSe;class JSe extends ta{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class a7 extends Bl{constructor(e,t){super(e,t),this.color=new Zt(1,1,1,.05),this.radius=.12,this.fixedRadius=!0,this._filterWidth=1,this.glowFraction=0,this.glowMax=.5,this.glowFalloff=2,this.alphaMode=it.ALPHA_COMBINE,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new JSe);const i=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(ze.PrepareDefinesForAttributes(e,i,!0,!1),i.isDirty){i.markAsProcessed(),s.resetCachedMaterial();const n=new Fl;i.FOG&&n.addFallback(1,"FOG"),ze.HandleFallbacksForShadows(i,n),i.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[se.PositionKind];i.NORMAL&&o.push(se.NormalKind),i.UV1&&o.push(se.UVKind),i.UV2&&o.push(se.UV2Kind),i.VERTEXCOLOR&&o.push(se.ColorKind),i.TANGENT&&o.push(se.TangentKind),ze.PrepareAttributesForInstances(o,i);const l="mrdlInnerquad",c=i.toString(),h=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Color_","_Radius_","_Fixed_Radius_","_Filter_Width_","_Glow_Fraction_","_Glow_Max_","_Glow_Falloff_"],u=[],p=new Array;ze.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:i,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:h,uniformBuffersNames:p,samplers:u,defines:c,fallbacks:n,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),i)}return!t.effect||!t.effect.isReady()?!1:(i._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const n=i.effect;!n||(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Fixed_Radius_",this.fixedRadius?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setFloat("_Glow_Fraction_",this.glowFraction),this._activeEffect.setFloat("_Glow_Max_",this.glowMax),this._activeEffect.setFloat("_Glow_Falloff_",this.glowFalloff),this._afterBind(t,this._activeEffect))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return Kt.Clone(()=>new a7(e,this.getScene()),this)}serialize(){const e=Kt.Serialize(this);return e.customType="BABYLON.MRDLInnerquadMaterial",e}getClassName(){return"MRDLInnerquadMaterial"}static Parse(e,t,i){return Kt.Parse(()=>new a7(e.name,t),e,t,i)}}z([X()],a7.prototype,"color",void 0);z([X()],a7.prototype,"radius",void 0);z([X()],a7.prototype,"fixedRadius",void 0);z([X()],a7.prototype,"glowFraction",void 0);z([X()],a7.prototype,"glowMax",void 0);z([X()],a7.prototype,"glowFalloff",void 0);$e("BABYLON.GUI.MRDLInnerquadMaterial",a7);class Z3 extends DQ{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._backGlow.renderingGroupId=e,this._innerQuad.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(!e){this._disposeTooltip();return}if(!this._tooltipFade){const t=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Jd("",{size:1},this._backPlate._scene),this._tooltipMesh.position=O.Down().scale(.7).add(O.Forward(t).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._frontPlateCollisionMesh,this._tooltipTexture=Sh.CreateForMesh(this._tooltipMesh);const i=new Uu;i.height=.25,i.width=.8,i.cornerRadius=25,i.color="#ffffff",i.thickness=20,i.background="#060668",this._tooltipTexture.addControl(i),this._tooltipTextBlock=new Ka,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=100,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new yK,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add(()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)}),this._tooltipOutObserver=this.onPointerOutObservable.add(()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)})}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}get tooltipText(){var e;return((e=this._tooltipTextBlock)===null||e===void 0?void 0:e.text)||null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get subtext(){return this._subtext}set subtext(e){this._subtext!==e&&(this._subtext=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get backGlowMaterial(){return this._backGlowMaterial}get innerQuadMaterial(){return this._innerQuadMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this.width=1,this.height=1,this.radius=.14,this.textSizeInPixels=18,this.imageSizeInPixels=40,this.plateMaterialColor=new Ie(.4,.4,.4),this.frontPlateDepth=.2,this.backPlateDepth=.04,this.backGlowOffset=.1,this.flatPlaneDepth=.001,this.innerQuadRadius=this.radius-.04,this.innerQuadColor=new Zt(0,0,0,0),this.innerQuadToggledColor=new Zt(.5197843,.6485234,.9607843,.6),this.innerQuadHoverColor=new Zt(1,1,1,.05),this.innerQuadToggledHoverColor=new Zt(.5197843,.6485234,.9607843,1),this._isBackplateVisible=!0,this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(1),this.isToggleButton&&this._innerQuadMaterial&&(this.isToggled?this._innerQuadMaterial.color=this.innerQuadToggledHoverColor:this._innerQuadMaterial.color=this.innerQuadHoverColor)},this.pointerOutAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(-.8),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)},this.pointerDownAnimation=()=>{},this.pointerUpAnimation=()=>{},this._pointerClickObserver=this.onPointerClickObservable.add(()=>{this._frontPlate&&this._backGlow&&!this.isActiveNearInteraction&&this._performClickAnimation(),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)}),this._pointerEnterObserver=this.onPointerEnterObservable.add(()=>{this.pointerEnterAnimation()}),this._pointerOutObserver=this.onPointerOutObservable.add(()=>{this.pointerOutAnimation()}),this._toggleObserver=this.onToggleObservable.add(i=>{i?this._innerQuadMaterial.color=this.innerQuadToggledColor:this._innerQuadMaterial.color=this.innerQuadColor})}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){let e;this._getAspectRatio()<=1?e=this._alignContentVertically():e=this._alignContentHorizontally(),this.content=e}_getAspectRatio(){return this.width/this.height}_alignContentVertically(){const e=new Z2;if(e.isVertical=!0,Zb()&&!!document.createElement&&this._imageUrl){const t=new wr;t.source=this._imageUrl,t.heightInPixels=180,t.widthInPixels=100,t.paddingTopInPixels=40,t.paddingBottomInPixels=40,e.addControl(t)}if(this._text){const t=new Ka;t.text=this._text,t.color="white",t.heightInPixels=30,t.fontSize=24,e.addControl(t)}return e}_alignContentHorizontally(){let e=240;const t=15,i=new Uu;i.widthInPixels=e,i.heightInPixels=e,i.color="transparent",i.setPaddingInPixels(t,t,t,t),e-=t*2;const s=new Z2;if(s.isVertical=!1,s.scaleY=this._getAspectRatio(),Zb()&&!!document.createElement&&this._imageUrl){const r=new Uu(`${this.name}_image`);r.widthInPixels=this.imageSizeInPixels,r.heightInPixels=this.imageSizeInPixels,r.color="transparent",e-=this.imageSizeInPixels;const n=new wr;n.source=this._imageUrl,r.addControl(n),s.addControl(r)}if(this._text){const r=new Ka(`${this.name}_text`);if(r.text=this._text,r.color="white",r.fontSize=this.textSizeInPixels,r.widthInPixels=e,this._imageUrl&&(r.textHorizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,r.paddingLeftInPixels=t),this._subtext){const n=new N2;n.addColumnDefinition(1),n.addRowDefinition(.5),n.addRowDefinition(.5),n.widthInPixels=e,n.heightInPixels=45;const o=new Ka(`${this.name}_subtext`);o.text=this._subtext,o.color="#EEEEEEAB",o.fontSize=this.textSizeInPixels*.75,o.fontWeight="600",this._imageUrl&&(o.textHorizontalAlignment=zt.HORIZONTAL_ALIGNMENT_LEFT,o.paddingLeftInPixels=t),n.addControl(r,0),n.addControl(o,1),s.addControl(n)}else s.addControl(r)}return i.addControl(s),i}_createNode(e){var t;this.name=(t=this.name)!==null&&t!==void 0?t:"TouchHolographicButton";const i=this._createBackPlate(e),s=this._createFrontPlate(e),r=this._createInnerQuad(e),n=this._createBackGlow(e);this._frontPlateCollisionMesh=s,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.scaling.x=this.width,this._textPlate.parent=s,this._backPlate=i,this._backPlate.position=O.Forward(e.useRightHandedSystem).scale(this.backPlateDepth/2),this._backPlate.isPickable=!1,this._backPlate.addChild(s),this._backPlate.addChild(r),n&&this._backPlate.addChild(n);const o=new Ki(`${this.name}_root`,e);return this._backPlate.setParent(o),this.collisionMesh=s,this.collidableFrontDirection=this._backPlate.forward.negate(),o}_createBackPlate(e){const t=pl(`${this.name}_backPlate`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=.2,As.ImportMeshAsync(void 0,Z3.MRTK_ASSET_BASE_URL,Z3.BACKPLATE_MODEL_FILENAME,e).then(i=>{const s=i.meshes[1];s.visibility=0,this._isBackplateVisible&&(s.visibility=1,s.name=`${this.name}_backPlate`,s.isPickable=!1,s.scaling.x=this.width,s.scaling.y=this.height,s.parent=t),this._backMaterial&&(s.material=this._backMaterial),this._backPlate=s}),t}_createFrontPlate(e){const t=pl(`${this.name}_frontPlate`,{width:this.width,height:this.height,depth:this.frontPlateDepth},e);return t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=O.Forward(e.useRightHandedSystem).scale((this.backPlateDepth-this.frontPlateDepth)/2),As.ImportMeshAsync(void 0,Z3.MRTK_ASSET_BASE_URL,Z3.FRONTPLATE_MODEL_FILENAME,e).then(i=>{const s=pl(`${this.name}_collisionPlate`,{width:this.width,height:this.height},e);s.isPickable=!1,s.scaling.z=this.frontPlateDepth,s.visibility=0,s.parent=t,this._collisionPlate=s;const r=i.meshes[1];r.name=`${this.name}_frontPlate`,r.isPickable=!1,r.scaling.x=this.width-this.backGlowOffset,r.scaling.y=this.height-this.backGlowOffset,r.position=O.Forward(e.useRightHandedSystem).scale(-.5),r.parent=s,this.isToggleButton&&(r.visibility=0),this._frontMaterial&&(r.material=this._frontMaterial),this._textPlate.scaling.x=1,this._textPlate.parent=r,this._frontPlate=r}),t}_createInnerQuad(e){const t=pl(`${this.name}_innerQuad`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-this.flatPlaneDepth,As.ImportMeshAsync(void 0,Z3.MRTK_ASSET_BASE_URL,Z3.INNERQUAD_MODEL_FILENAME,e).then(i=>{const s=i.meshes[1];s.name=`${this.name}_innerQuad`,s.isPickable=!1,s.scaling.x=this.width-this.backGlowOffset,s.scaling.y=this.height-this.backGlowOffset,s.parent=t,this._innerQuadMaterial&&(s.material=this._innerQuadMaterial),this._innerQuad=s}),t}_createBackGlow(e){if(this.isToggleButton)return;const t=pl(`${this.name}_backGlow`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-this.flatPlaneDepth*2,As.ImportMeshAsync(void 0,Z3.MRTK_ASSET_BASE_URL,Z3.BACKGLOW_MODEL_FILENAME,e).then(i=>{const s=i.meshes[1];s.name=`${this.name}_backGlow`,s.isPickable=!1,s.scaling.x=this.width-this.backGlowOffset,s.scaling.y=this.height-this.backGlowOffset,s.parent=t,this._backGlowMaterial&&(s.material=this._backGlowMaterial),this._backGlow=s}),t}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=this.plateMaterialColor}_performClickAnimation(){const t=new ev("Click Animation Group"),i=[{name:"backGlowMotion",mesh:this._backGlow,property:"material.motion",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[1,.0144,.0144]},{frame:40,values:[.0027713229489760476,0,0]},{frame:45,values:[.0027713229489760476]}]},{name:"_collisionPlateZSlide",mesh:this._collisionPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[O.Forward(this._collisionPlate._scene.useRightHandedSystem).scale(this.frontPlateDepth/2).z,0,0]},{frame:40,values:[0,.005403332496794331]},{frame:45,values:[0]}]},{name:"_collisionPlateZScale",mesh:this._collisionPlate,property:"scaling.z",keys:[{frame:0,values:[this.frontPlateDepth,0,0]},{frame:20,values:[this.backPlateDepth,0,0]},{frame:40,values:[this.frontPlateDepth,.0054]},{frame:45,values:[this.frontPlateDepth]}]}];for(const s of i){const r=new at(s.name,s.property,60,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CYCLE),n=[];for(const o of s.keys)n.push({frame:o.frame,value:o.values[0],inTangent:o.values[1],outTangent:o.values[2],interpolation:o.values[3]});r.setKeys(n),s.mesh&&t.addTargetedAnimation(r,s.mesh)}t.normalize(0,45),t.speedRatio=1,t.play()}_performEnterExitAnimation(e){const i=new ev("Enter Exit Animation Group"),s=[{name:"frontPlateFadeOut",mesh:this._frontPlate,property:"material.fadeOut",keys:[{frame:0,values:[0,0,.025045314830017686,0]},{frame:40,values:[1.00205599570012,.025045314830017686,0,0]}]},{name:"textPlateZSlide",mesh:this._textPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:40,values:[O.Forward(this._textPlate._scene.useRightHandedSystem).scale(-.15).z,0,0]}]}];for(const r of s){const n=new at(r.name,r.property,60,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CYCLE),o=[];for(const l of r.keys)o.push({frame:l.frame,value:l.values[0],inTangent:l.values[1],outTangent:l.values[2],interpolation:l.values[3]});n.setKeys(o),r.mesh&&i.addTargetedAnimation(n,r.mesh)}i.normalize(0,45),i.speedRatio=e,i.play()}_createBackMaterial(e){var t;this._backMaterial=(t=this._backMaterial)!==null&&t!==void 0?t:new Vo(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.absoluteSizes=!0,this._backMaterial.radius=this.radius,this._backMaterial.lineWidth=.02}_createFrontMaterial(e){var t;this._frontMaterial=(t=this._frontMaterial)!==null&&t!==void 0?t:new wn(this.name+"Front Material",e.getScene()),this.frontMaterial.radius=this.innerQuadRadius,this.frontMaterial.fadeOut=0}_createBackGlowMaterial(e){var t;const i=this.radius+.04;this._backGlowMaterial=(t=this._backGlowMaterial)!==null&&t!==void 0?t:new t2(this.name+"Back Glow Material",e.getScene()),this._backGlowMaterial.bevelRadius=i,this._backGlowMaterial.lineWidth=i,this._backGlowMaterial.motion=0}_createInnerQuadMaterial(e){var t;this._innerQuadMaterial=(t=this._innerQuadMaterial)!==null&&t!==void 0?t:new a7("inner_quad",e.getScene()),this._innerQuadMaterial.radius=this.innerQuadRadius,this.isToggleButton&&(this._innerQuadMaterial.color=this.innerQuadColor)}_createPlateMaterial(e){var t;this._plateMaterial=(t=this._plateMaterial)!==null&&t!==void 0?t:new jt(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ie.Black()}_onToggle(e){super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.mrdlBackplateMaterial?this._backMaterial=this._host._touchSharedMaterials.mrdlBackplateMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.mrdlBackplateMaterial=this._backMaterial),this._host._touchSharedMaterials.mrdlFrontplateMaterial?this._frontMaterial=this._host._touchSharedMaterials.mrdlFrontplateMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.mrdlFrontplateMaterial=this._frontMaterial),this._host._touchSharedMaterials.mrdlBackglowMaterial?this._backGlowMaterial=this._host._touchSharedMaterials.mrdlBackglowMaterial:(this._createBackGlowMaterial(e),this._host._touchSharedMaterials.mrdlBackglowMaterial=this._backGlowMaterial),this._host._touchSharedMaterials.mrdlInnerQuadMaterial?this._innerQuadMaterial=this._host._touchSharedMaterials.mrdlInnerQuadMaterial:(this._createInnerQuadMaterial(e),this._host._touchSharedMaterials.mrdlInnerQuadMaterial=this._innerQuadMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e),this._createBackGlowMaterial(e),this._createInnerQuadMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._backGlow&&(this._backGlow.material=this._backGlowMaterial),this._innerQuad&&(this._innerQuad.material=this._innerQuadMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerClickObservable.remove(this._pointerClickObserver),this.onPointerEnterObservable.remove(this._pointerEnterObserver),this.onPointerOutObservable.remove(this._pointerOutObserver),this.onToggleObservable.remove(this._toggleObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._backGlowMaterial.dispose(),this._innerQuadMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}Z3.MRTK_ASSET_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/";Z3.FRONTPLATE_MODEL_FILENAME="mrtk-fluent-frontplate.glb";Z3.BACKPLATE_MODEL_FILENAME="mrtk-fluent-backplate.glb";Z3.BACKGLOW_MODEL_FILENAME="mrtk-fluent-button.glb";Z3.INNERQUAD_MODEL_FILENAME="SlateProximity.glb";class lG{get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get controlScaling(){return this._customControlScaling}set controlScaling(e){if(this._customControlScaling!==e&&e>0){const t=e/this._customControlScaling;this._customControlScaling=e,this._rootContainer.children.forEach(i=>{i.scaling.scaleInPlace(t),e!==1&&(i._isScaledByManager=!0)})}}get useRealisticScaling(){return this.controlScaling===lG.MRTK_REALISTIC_SCALING}set useRealisticScaling(e){this.controlScaling=e?lG.MRTK_REALISTIC_SCALING:1}constructor(e){this._customControlScaling=1,this._lastControlOver={},this._lastControlDown={},this.onPickedPointChangedObservable=new Se,this.onPickingObservable=new Se,this._sharedMaterials={},this._touchSharedMaterials={},this._scene=e||Ii.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>{this._sceneDisposeObserver=null,this._utilityLayer=null,this.dispose()}),this._utilityLayer=Mn._CreateDefaultUtilityLayerFromScene(this._scene),this._utilityLayer.onlyCheckPointerDownEvents=!1,this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.mainSceneTrackerPredicate=i=>{var s,r,n;return i&&((n=(r=(s=i.reservedDataStore)===null||s===void 0?void 0:s.GUI3D)===null||r===void 0?void 0:r.control)===null||n===void 0?void 0:n._node)},this._rootContainer=new Rc("RootContainer"),this._rootContainer._host=this;const t=this._utilityLayer.utilityLayerScene;this._pointerOutObserver=this._utilityLayer.onPointerOutObservable.add(i=>{this._handlePointerOut(i,!0)}),this._pointerObserver=t.onPointerObservable.add(i=>{this._doPicking(i)}),this._utilityLayer.utilityLayerScene.autoClear=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,new gn("hemi",O.Up(),this._utilityLayer.utilityLayerScene)}_handlePointerOut(e,t){const i=this._lastControlOver[e];i&&(i._onPointerOut(i),delete this._lastControlOver[e]),t&&this._lastControlDown[e]&&(this._lastControlDown[e].forcePointerUp(),delete this._lastControlDown[e]),this.onPickedPointChangedObservable.notifyObservers(null)}_doPicking(e){var t,i,s;if(!this._utilityLayer||!this._utilityLayer.shouldRender||!this._utilityLayer.utilityLayerScene.activeCamera)return!1;const r=e.event,n=r.pointerId||0,o=r.button,l=e.pickInfo;if(l&&this.onPickingObservable.notifyObservers(l.pickedMesh),!l||!l.hit)return this._handlePointerOut(n,e.type===mi.POINTERUP),!1;l.pickedPoint&&this.onPickedPointChangedObservable.notifyObservers(l.pickedPoint);const c=(i=(t=l.pickedMesh.reservedDataStore)===null||t===void 0?void 0:t.GUI3D)===null||i===void 0?void 0:i.control;return!!c&&!c._processObservables(e.type,l.pickedPoint,((s=l.originMesh)===null||s===void 0?void 0:s.position)||null,n,o)&&e.type===mi.POINTERMOVE&&(this._lastControlOver[n]&&this._lastControlOver[n]._onPointerOut(this._lastControlOver[n]),delete this._lastControlOver[n]),e.type===mi.POINTERUP&&(this._lastControlDown[r.pointerId]&&(this._lastControlDown[r.pointerId].forcePointerUp(),delete this._lastControlDown[r.pointerId]),(r.pointerType==="touch"||r.pointerType==="xr"&&this._scene.getEngine().hostInformation.isMobile)&&this._handlePointerOut(n,!1)),!0}get rootContainer(){return this._rootContainer}containsControl(e){return this._rootContainer.containsControl(e)}addControl(e){return this._rootContainer.addControl(e),this._customControlScaling!==1&&(e.scaling.scaleInPlace(this._customControlScaling),e._isScaledByManager=!0),this}removeControl(e){return this._rootContainer.removeControl(e),e._isScaledByManager&&(e.scaling.scaleInPlace(1/this._customControlScaling),e._isScaledByManager=!1),this}dispose(){this._rootContainer.dispose();for(const t in this._sharedMaterials)!Object.prototype.hasOwnProperty.call(this._sharedMaterials,t)||this._sharedMaterials[t].dispose();this._sharedMaterials={};for(const t in this._touchSharedMaterials)!Object.prototype.hasOwnProperty.call(this._touchSharedMaterials,t)||this._touchSharedMaterials[t].dispose();this._touchSharedMaterials={},this._pointerOutObserver&&this._utilityLayer&&(this._utilityLayer.onPointerOutObservable.remove(this._pointerOutObserver),this._pointerOutObserver=null),this.onPickedPointChangedObservable.clear(),this.onPickingObservable.clear();const e=this._utilityLayer?this._utilityLayer.utilityLayerScene:null;e&&this._pointerObserver&&(e.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=null),this._scene&&this._sceneDisposeObserver&&(this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null),this._utilityLayer&&this._utilityLayer.dispose()}}lG.MRTK_REALISTIC_SCALING=.032;const $Se=Object.freeze(Object.defineProperty({__proto__:null,Button:Bb,Checkbox:BI,ColorPicker:Xf,Container:Z1,Control:zt,Ellipse:Ute,FocusableButton:u1e,Grid:N2,Image:wr,InputText:Jl,InputTextArea:wP,InputPassword:d1e,Line:rR,MultiLine:kte,RadioButton:uT,StackPanel:Z2,SelectorGroup:LQ,CheckboxGroup:Hte,RadioGroup:f1e,SliderGroup:FN,SelectionPanel:jte,ScrollViewer:vD,get TextWrapping(){return FM},TextBlock:Ka,TextWrapper:LX,ToggleButton:p1e,KeyPropertySet:jTe,VirtualKeyboard:RQ,Rectangle:Uu,DisplayGrid:gC,BaseSlider:I_,Slider:nR,ImageBasedSlider:Gte,ScrollBar:iD,ImageScrollBar:oG,name:GTe,BaseGradient:Wte,LinearGradient:m1e,RadialGradient:_1e,AdvancedDynamicTexture:Sh,AdvancedDynamicTextureInstrumentation:WTe,Vector2WithInfo:KY,Matrix2D:Wn,MathTools:IQ,Measure:ru,MultiLinePoint:pJ,Style:g1e,ValueAndUnit:mr,XmlLoader:YTe,TouchHolographicButtonV3:Z3,AbstractButton3D:C1e,Button3D:PQ,Container3D:Rc,Control3D:UW,CylinderPanel:XTe,HandMenu:JTe,HolographicBackplate:sF,HolographicButton:rSe,HolographicSlate:d_,MeshButton3D:pSe,NearMenu:rF,PlanePanel:mSe,ScatterPanel:_Se,Slider3D:nF,SpherePanel:NSe,StackPanel3D:BSe,TouchButton3D:DQ,TouchMeshButton3D:FSe,TouchHolographicButton:II,TouchHolographicMenu:NL,VolumeBasedPanel:FF,FluentMaterialDefines:A1e,FluentMaterial:pu,FluentButtonMaterial:In,FluentBackplateMaterial:Qa,HandleMaterial:b1e,MRDLSliderBarMaterial:nr,MRDLSliderThumbMaterial:ar,MRDLBackplateMaterial:Vo,SlateGizmo:M1e,get HandleState(){return yM},GizmoHandle:Yte,SideHandle:E1e,CornerHandle:y1e,GUI3DManager:lG,Vector3WithInfo:QY},Symbol.toStringTag,{value:"Module"})),T1e=UG($Se);var BZ={exports:{}},Sre;function e9e(){return Sre||(Sre=1,function(a,e){(function(i,s){a.exports=s(fJ,T1e)})(typeof self<"u"?self:QN,(t,i)=>(()=>{var s={"../../../../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":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.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,kGAAA;EACA,kBAAA;EACA,gCAAA;EACA,kBAAA;AAJZ;AAQI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,YAAA;EACA,8BAAA;EACA,wBAAA;AANR;AAQQ;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,oBAAA;EACA,WAAA;EACA,YAAA;EACA,mBAAA;EACA,uBAAA;AANZ;AASQ;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;EAEA,2GAAA;EACA,mHAAA;AARZ;AAUY;EACI,oBAAA;EACA,UAAA;EACA,YAAA;EACA,gCAAA;EACA,oCAAA;EACA,2CAAA;EACA,kBAAA;AARhB;AAaI;EACI,aAAA;EACA,WAAA;EACA,2BAAA;EACA,2BAAA;AAXR;AAaQ;EACI,oBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,kBAAA;AAXZ;AAaY;EACI,WAAA;AAXhB;AAeQ;EACI,oBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,YAAA;AAbZ;AAiBI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,YAAA;EACA,wDAAA;EACA,wBAAA;AAfR;AAkBI;EACI,WAAA;EACA,cAAA;AAhBR;AAmBI;EACI,WAAA;EACA,cAAA;AAjBR;AAoBI;EACI,WAAA;EACA,cAAA;AAlBR;AAqBI;EACI,WAAA;EACA,cAAA;AAnBR;AAqBQ;EACI,YAAA;AAnBZ;AAuBI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,8BAAA;EACA,wBAAA;AArBR;AAuBQ;EACI,oBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,YAAA;AArBZ;AAwBQ;EACI,kBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,kBAAA;AAtBZ;AAwBY;EACI,WAAA;AAtBhB;AA2BI;EACI,YAAA;EACA,eAAA;EACA,YAAA;EACA,kBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;AAzBR",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: 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);\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:""}]),f.locals={};const d=f},"../../../../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/guiEditor/dist/components/log/log.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,`#log-console { + background: #333333; + height: 120px; + box-sizing: border-box; + margin: 0; + padding: 10px; + width: 100%; + overflow: hidden; + overflow-y: auto; +} +#log-console .log { + color: white; + font-size: 14px; + font-family: "Courier New", Courier, monospace; +} +#log-console .log.error { + color: red; +}`,"",{version:3,sources:["webpack://./../../../tools/guiEditor/dist/components/log/log.scss"],names:[],mappings:"AAAA;EACI,mBAAA;EACA,aAAA;EACA,sBAAA;EACA,SAAA;EACA,aAAA;EACA,WAAA;EACA,gBAAA;EACA,gBAAA;AACJ;AACI;EACI,YAAA;EACA,eAAA;EACA,8CAAA;AACR;AACQ;EACI,UAAA;AACZ",sourcesContent:[`#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 +\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:""}]),f.locals={};const d=f},"../../../../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/guiEditor/dist/components/propertyTab/propertyTab.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,`:root { + --backgroundGrey: #aaaaaa; + --spacingHeight: 30px; + --button: #333333; + --buttonBackground: #ffffff; + --buttonDisabledBackground: #c8c8c8; + --disabledBackground: #c8c8c8; + --buttonPressed: #ffffff; + --buttonPressedBackground: #606060; + --buttonHoverBackground: #afafaf; +} + +#ge-propertyTab { + user-select: none; + color: black; + background: #e2e2e2; +} +#ge-propertyTab * { + font-family: "acumin-pro-condensed", sans-serif; + font-size: 12px; +} +#ge-propertyTab #header { + height: 32px; + font-size: 16px; + color: white; + background: white; + 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; +} +#ge-propertyTab #header #logo { + position: relative; + grid-column: 1; + width: 32px; + height: 32px; + left: 0; + display: flex; + align-self: center; + justify-self: center; + filter: invert(1); +} +#ge-propertyTab #header #title { + background: white; + color: black; + grid-column: 2; + display: grid; + align-items: center; + text-align: center; +} +#ge-propertyTab .range { + -webkit-appearance: none; + width: 100%; + height: 2px; + background: #bcbcbc; + border-radius: 5px; + outline: none; + opacity: 0.7; + -webkit-transition: 0.2s; + transition: opacity 0.2s; + padding: 0; +} +#ge-propertyTab .range:hover { + opacity: 1; +} +#ge-propertyTab .range::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 14px; + height: 14px; + border-radius: 50%; + background: #e2e2e2; + border: solid; + border-width: thin; + cursor: pointer; +} +#ge-propertyTab .range::-moz-range-thumb { + width: 14px; + height: 14px; + border-radius: 50%; + background: rgb(0, 0, 0); + cursor: pointer; +} +#ge-propertyTab input[type=color] { + -webkit-appearance: none; + border: 1px solid rgba(255, 255, 255, 0.5); + padding: 0; + width: 30px; + height: 20px; +} +#ge-propertyTab input[type=color]::-webkit-color-swatch-wrapper { + padding: 0; +} +#ge-propertyTab input[type=color]::-webkit-color-swatch { + border: none; +} +#ge-propertyTab hr { + border: 1px solid #d0cece; +} +#ge-propertyTab .icon { + width: 30px; + height: 30px; +} +#ge-propertyTab .unit { + width: 26px; + height: 26px; + color: var(--button); + background-color: var(--buttonBackground); + border: none; + margin-top: 2px; + cursor: pointer; + margin-left: 2px; + font-family: "atten-round-new", sans-serif; + font-weight: 500; + font-style: normal; + display: flex; + justify-content: center; + align-items: center; +} +#ge-propertyTab .unit:disabled { + background-color: var(--buttonDisabledBackground); + cursor: not-allowed; +} +#ge-propertyTab .unit:not(:disabled):hover { + background-color: var(--buttonHoverBackground); +} +#ge-propertyTab .unit:not(:disabled):active { + color: var(--buttonPressed); + background-color: var(--buttonPressedBackground); +} +#ge-propertyTab input, +#ge-propertyTab select { + outline-style: solid; + outline-width: 0px; + outline-color: transparent; + outline-offset: -1px; + outline-width: 1px; + transition: outline-color 0.2s; + border: transparent; + padding-left: 5px; +} +#ge-propertyTab input:focus, +#ge-propertyTab select:focus { + outline-width: 1px; + outline-color: black; +} +#ge-propertyTab .hasArrows input::-webkit-outer-spin-button, +#ge-propertyTab .hasArrows input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; +} +#ge-propertyTab .hasArrows input[type=number] { + -moz-appearance: textfield; +} +#ge-propertyTab .sliderLine { + height: var(--spacingHeight); + display: grid; + grid-template-rows: 100%; + grid-template-columns: auto 1fr 20px 1fr; + flex-grow: 1; +} +#ge-propertyTab .sliderLine .label { + grid-column: 1; + display: flex; + align-items: center; + min-width: 15px; + font-weight: 600; +} +#ge-propertyTab .sliderLine .img { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .sliderLine .slider { + grid-column: 4; + grid-row: 1; + margin-right: 5px; + display: flex; + align-items: center; + padding-left: 5px; +} +#ge-propertyTab .sliderLine .floatLine { + grid-column: 2; + padding-left: 0px; + grid-template-columns: 1fr auto; +} +#ge-propertyTab .sliderLine .floatLine .label { + grid-column: 1; + display: none; + align-items: center; + font-weight: 600; +} +#ge-propertyTab .sliderLine .floatLine .short { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .sliderLine .floatLine .short input { + width: 100%; + background-color: white; + height: 24px; +} +#ge-propertyTab .sliderLine .floatLine .short input::-webkit-outer-spin-button, +#ge-propertyTab .sliderLine .floatLine .short input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; +} +#ge-propertyTab .sliderLine .floatLine .short input[type=number] { + -webkit-appearance: textfield; + -moz-appearance: textfield; + appearance: textfield; +} +#ge-propertyTab .ge-divider { + padding-right: 18px; + padding-left: 5px; + display: grid; + grid-template-columns: auto 1fr; + padding-top: 1px; + padding-bottom: 1px; +} +#ge-propertyTab .ge-divider.double { + display: grid; + grid-template-columns: auto 1fr 5px 1fr; +} +#ge-propertyTab .ge-divider.double > .textInputLine:first-of-type, +#ge-propertyTab .ge-divider.double > .floatLine:first-of-type { + grid-column: 2; +} +#ge-propertyTab .ge-divider.double > .textInputLine:nth-of-type(2), +#ge-propertyTab .ge-divider.double > .floatLine:nth-of-type(2) { + grid-column: 4; +} +#ge-propertyTab .ge-divider.quad { + display: grid; + grid-template-columns: 1fr 5px 1fr 5px 1fr 5px 1fr; +} +#ge-propertyTab .ge-divider.quad > .textInputLine:first-of-type, +#ge-propertyTab .ge-divider.quad > .floatLine:first-of-type { + grid-column: 1; +} +#ge-propertyTab .ge-divider.quad > .textInputLine:nth-of-type(2), +#ge-propertyTab .ge-divider.quad > .floatLine:nth-of-type(2) { + grid-column: 3; +} +#ge-propertyTab .ge-divider.quad > .textInputLine:nth-of-type(3), +#ge-propertyTab .ge-divider.quad > .floatLine:nth-of-type(3) { + grid-column: 5; +} +#ge-propertyTab .ge-divider.quad > .textInputLine:nth-of-type(4), +#ge-propertyTab .ge-divider.quad > .floatLine:nth-of-type(4) { + grid-column: 7; +} +#ge-propertyTab .ge-grid-divider { + display: grid; + grid-template-columns: 150px 1fr auto; +} +#ge-propertyTab .ge-grid-divider .textLine { + grid-column: auto; +} +#ge-propertyTab .ge-grid-button-divider { + display: grid; + grid-template-columns: 60px 60px 60px 60px; +} +#ge-propertyTab .ge-grid-remove { + display: grid; + background-color: #c2c2c2; + margin-bottom: 5px; + filter: invert(1); +} +#ge-propertyTab .ge-grid-edit { + display: grid; + background-color: #878787; + margin-bottom: 5px; + filter: invert(1); +} +#ge-propertyTab .ge-grid { + display: grid; + margin-bottom: 5px; +} +#ge-propertyTab .ge-divider.double .textInputLine { + grid-template-columns: auto auto 1fr auto; +} +#ge-propertyTab .textInputLine, +#ge-propertyTab .floatLine { + user-select: none; + padding-bottom: 0px; + padding-top: 0px; + height: var(--spacingHeight); + display: grid; + grid-template-columns: auto auto 1fr; + flex-grow: 1; +} +#ge-propertyTab .textInputLine .label, +#ge-propertyTab .floatLine .label { + grid-column: 2; + display: flex; + align-items: center; + min-width: 15px; + font-weight: 600; +} +#ge-propertyTab .textInputLine .disabled, +#ge-propertyTab .floatLine .disabled { + color: var(--backgroundGrey); + background-color: var(--disabledBackground); +} +#ge-propertyTab .textInputLine img, +#ge-propertyTab .floatLine img { + width: 30px; +} +#ge-propertyTab .textInputLine .img, +#ge-propertyTab .floatLine .img { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .textInputLine .value, +#ge-propertyTab .floatLine .value { + display: flex; + align-items: center; + grid-column: 3; + background: transparent; + height: 26px; + position: relative; + background-color: white; + margin-top: 2px; + overflow-y: hidden; +} +#ge-propertyTab .textInputLine .value input, +#ge-propertyTab .floatLine .value input { + width: 100%; + height: 24px; + color: #333333; +} +#ge-propertyTab .textInputLine .value input.hasArrows, +#ge-propertyTab .floatLine .value input.hasArrows { + padding-right: 15px; +} +#ge-propertyTab .textInputLine .value .arrows, +#ge-propertyTab .floatLine .value .arrows { + display: none; + position: absolute; + right: 0; + flex-direction: column; + cursor: grab; +} +#ge-propertyTab .textInputLine .value .arrows .downArrowIcon, +#ge-propertyTab .textInputLine .value .arrows .upArrowIcon, +#ge-propertyTab .floatLine .value .arrows .downArrowIcon, +#ge-propertyTab .floatLine .value .arrows .upArrowIcon { + width: 13px; + height: 13px; +} +#ge-propertyTab .textInputLine .value:hover .arrows, #ge-propertyTab .textInputLine .value:focus .arrows, #ge-propertyTab .textInputLine .value.dragging .arrows, +#ge-propertyTab .floatLine .value:hover .arrows, +#ge-propertyTab .floatLine .value:focus .arrows, +#ge-propertyTab .floatLine .value.dragging .arrows { + display: flex; +} +#ge-propertyTab .textInputLine .value .arrows:hover, +#ge-propertyTab .floatLine .value .arrows:hover { + background-color: var(--buttonHoverBackground); +} +#ge-propertyTab .textInputLine .value.dragging .arrows, +#ge-propertyTab .floatLine .value.dragging .arrows { + background-color: var(--buttonPressedBackground); +} +#ge-propertyTab .textInputLine .value.dragging .arrows .downArrowIcon, +#ge-propertyTab .textInputLine .value.dragging .arrows .upArrowIcon, +#ge-propertyTab .floatLine .value.dragging .arrows .downArrowIcon, +#ge-propertyTab .floatLine .value.dragging .arrows .upArrowIcon { + filter: brightness(10); +} +#ge-propertyTab .textInputLine.withUnits { + grid-template-columns: auto auto 1fr auto; +} +#ge-propertyTab .textInputArea { + height: 100%; + display: grid; + grid-template-columns: 1fr 120px; +} +#ge-propertyTab .textInputArea .disabled { + color: var(--backgroundGrey); + background-color: var(--disabledBackground); +} +#ge-propertyTab .textInputArea .label { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .textInputArea .value { + display: flex; + align-items: center; + grid-column: 2; +} +#ge-propertyTab .textInputArea .value textarea { + width: calc(150% - 5px); + margin-left: -50%; + height: 40px; +} +#ge-propertyTab .paneContainer { + margin-top: 3px; + display: grid; + grid-template-rows: 100%; + grid-template-columns: 100%; +} +#ge-propertyTab .paneContainer .paneList { + border-left: 3px solid transparent; +} +#ge-propertyTab .paneContainer:hover .paneList { + border-left: 3px solid rgba(51, 122, 183, 0.8); +} +#ge-propertyTab .paneContainer:hover .paneContainer-content .header .title { + border-left: 3px solid rgb(51, 122, 183); +} +#ge-propertyTab .paneContainer .paneContainer-highlight-border { + grid-row: 1; + grid-column: 1; + opacity: 1; + border: 3px solid red; + transition: opacity 250ms; + pointer-events: none; +} +#ge-propertyTab .paneContainer .paneContainer-highlight-border.transparent { + opacity: 0; +} +#ge-propertyTab .paneContainer .paneContainer-content { + grid-row: 1; + grid-column: 1; +} +#ge-propertyTab .paneContainer .paneContainer-content .header { + display: grid; + grid-template-columns: 1fr auto; + background: #cccccc; + height: var(--spacingHeight); + padding-bottom: 0px; + padding-top: 0px; + padding-right: 5px; + cursor: pointer; +} +#ge-propertyTab .paneContainer .paneContainer-content .header .title { + border-left: 3px solid transparent; + padding-left: 5px; + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .paneContainer .paneContainer-content .header .collapse { + grid-column: 2; + display: flex; + align-items: center; + justify-items: center; + transform-origin: center; +} +#ge-propertyTab .paneContainer .paneContainer-content .header .collapse.closed { + transform: rotate(180deg); +} +#ge-propertyTab .paneContainer .paneContainer-content .paneList > div:not(:last-child) { + border-bottom: 0.5px solid rgba(255, 255, 255, 0.1); +} +#ge-propertyTab .paneContainer .paneContainer-content .fragment > div:not(:last-child) { + border-bottom: 0.5px solid rgba(255, 255, 255, 0.1); +} +#ge-propertyTab .color-picker { + height: 26px; + width: 26px; +} +#ge-propertyTab .color-picker .color-rect-background { + width: calc(100% - 2px); + height: calc(100% - 2px); + border: 1px black solid; + cursor: pointer; + background: repeating-conic-gradient(#e2e2e2 0% 25%, white 0% 50%) 50%/100% 100%; +} +#ge-propertyTab .color-picker .color-rect-background .color-rect { + height: 100%; +} +#ge-propertyTab .color-picker .color-picker-cover { + z-index: 2; + position: fixed; + top: 0px; + right: 0px; + bottom: 0px; + left: 0px; +} +#ge-propertyTab .color-picker .color-picker-float { + position: absolute; + outline: 1px solid black; +} +#ge-propertyTab .color-picker .color-picker-container { + background-color: #e2e2e2; +} +#ge-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; +} +#ge-propertyTab .gradient-step .step { + grid-row: 1; + grid-column: 1; +} +#ge-propertyTab .gradient-step .color { + grid-row: 1; + grid-column: 2; + cursor: pointer; +} +#ge-propertyTab .gradient-step .step-value { + margin-left: 5px; + grid-row: 1; + grid-column: 3; + text-align: right; + margin-right: 5px; +} +#ge-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; +} +#ge-propertyTab .gradient-step .step-slider input { + width: 90%; +} +#ge-propertyTab .gradient-step .gradient-copy { + grid-row: 1; + grid-column: 5; + display: grid; + align-content: center; + justify-content: center; +} +#ge-propertyTab .gradient-step .gradient-copy .img { + height: 20px; + width: 20px; +} +#ge-propertyTab .gradient-step .gradient-copy .img:hover { + cursor: pointer; +} +#ge-propertyTab .gradient-step .gradient-delete { + grid-row: 1; + grid-column: 6; + display: grid; + align-content: center; + justify-content: center; +} +#ge-propertyTab .gradient-step .gradient-delete .img { + height: 20px; + width: 20px; +} +#ge-propertyTab .gradient-step .gradient-delete .img:hover { + cursor: pointer; +} +#ge-propertyTab .alignment-bar { + display: flex; + justify-content: center; + padding-right: 5px; +} +#ge-propertyTab .command-button { + cursor: pointer; + width: 30px; +} +#ge-propertyTab .command-button .command-label { + display: none; +} +#ge-propertyTab .command-button .command-button-icon { + height: 100%; + width: 100%; + display: grid; + color: white; + align-content: center; + justify-content: center; +} +#ge-propertyTab .command-button:hover { + background-color: white; +} +#ge-propertyTab .command-button .active { + transform-origin: center; + background-color: white; +} +#ge-propertyTab .command-button img.active { + background-color: white; +} +#ge-propertyTab .command-button.disabled { + background-color: var(--buttonDisabledBackground); + pointer-events: none; +} +#ge-propertyTab .command-button-alt { + cursor: pointer; + width: 40px; + margin-left: 5px; + margin-right: 5px; + background-color: white; +} +#ge-propertyTab .command-button-alt .command-label { + display: none; +} +#ge-propertyTab .command-button-alt .command-button-icon { + height: 100%; + width: 100%; + display: grid; + align-content: center; + justify-content: center; +} +#ge-propertyTab .command-button-alt:hover { + background-color: #c2c2c2; + filter: invert(1); +} +#ge-propertyTab .command-button-alt-disabled { + cursor: pointer; + pointer-events: none; + width: 40px; + margin-left: 5px; + margin-right: 5px; + background-color: white; +} +#ge-propertyTab .command-button-alt-disabled .command-label { + display: none; +} +#ge-propertyTab .command-button-alt-disabled .command-button-icon { + height: 100%; + width: 100%; + display: grid; + align-content: center; + justify-content: center; +} +#ge-propertyTab .command-button-alt-disabled img { + filter: invert(1); +} +#ge-propertyTab .command-button-alt-active { + cursor: pointer; + pointer-events: none; + width: 40px; + margin-left: 5px; + margin-right: 5px; + background-color: #c2c2c2; + filter: invert(1); +} +#ge-propertyTab .command-button-alt-active .command-label { + display: none; +} +#ge-propertyTab .command-button-alt-active .command-button-icon { + height: 100%; + width: 100%; + display: grid; + align-content: center; + justify-content: center; +} +#ge-propertyTab .floatLine { + user-select: none; + height: var(--spacingHeight); + padding-bottom: 0px; + padding-top: 0px; + display: grid; + grid-template-columns: auto auto 2fr auto; + flex-grow: 1; +} +#ge-propertyTab .floatLine .label { + grid-column: 2; + display: flex; + align-items: center; + min-width: 15px; + font-weight: 600; +} +#ge-propertyTab .floatLine img { + width: 30px; +} +#ge-propertyTab .floatLine .img { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .floatLine .value { + display: flex; + align-items: center; + grid-column: 3; + background: transparent; + height: 26px; +} +#ge-propertyTab .floatLine .value input { + width: 100%; + background-color: white; + height: 24px; +} +#ge-propertyTab .floatLine .short { + grid-column: 2; + display: flex; + align-items: center; +} +#ge-propertyTab .floatLine .short input { + width: 100%; +} +#ge-propertyTab .floatLine .short input::-webkit-outer-spin-button, +#ge-propertyTab .floatLine .short input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; +} +#ge-propertyTab .floatLine .short input[type=number] { + -moz-appearance: textfield; +} +#ge-propertyTab .vector3Line { + padding-bottom: 0px; + padding-top: 0px; + display: grid; +} +#ge-propertyTab .vector3Line .firstLine { + display: grid; + grid-template-columns: 1fr auto 20px; + height: var(--spacingHeight); +} +#ge-propertyTab .vector3Line .firstLine .label { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .vector3Line .firstLine .vector { + grid-column: 2; + display: flex; + align-items: center; + text-align: right; + opacity: 0.8; +} +#ge-propertyTab .vector3Line .firstLine .expand { + grid-column: 3; + display: grid; + align-items: center; + justify-items: center; + cursor: pointer; +} +#ge-propertyTab .vector3Line .secondLine { + display: grid; + padding-right: 5px; + border-left: 1px solid rgb(51, 122, 183); +} +#ge-propertyTab .vector3Line .secondLine .no-right-margin { + margin-right: 0; +} +#ge-propertyTab .vector3Line .secondLine .numeric { + display: grid; + grid-template-columns: 1fr auto; +} +#ge-propertyTab .vector3Line .secondLine .numeric-label { + text-align: right; + grid-column: 1; + display: flex; + align-items: center; + justify-self: right; + margin-right: 10px; +} +#ge-propertyTab .vector3Line .secondLine .numeric-value { + width: 120px; + grid-column: 2; + display: flex; + align-items: center; + border: 1px solid rgb(51, 122, 183); +} +#ge-propertyTab .buttonLine { + height: var(--spacingHeight); + padding-bottom: 0px; + padding-top: 0px; + display: grid; + align-items: center; + justify-items: stretch; + padding-bottom: 5px; +} +#ge-propertyTab .buttonLine input[type=file] { + display: none; +} +#ge-propertyTab .buttonLine .file-upload { + background: var(--backgroundGrey); + border: 1px solid #424242; + margin: 5px 10px; + color: white; + padding: 4px 5px; + opacity: 0.9; + cursor: pointer; + text-align: center; + border-radius: 4px; +} +#ge-propertyTab .buttonLine .file-upload:hover { + opacity: 1; +} +#ge-propertyTab .buttonLine .file-upload:active { + transform: scale(0.98); + transform-origin: 0.5 0.5; +} +#ge-propertyTab .buttonLine button { + background: var(--backgroundGrey); + border: 1px solid #424242; + margin: 5px 10px 5px 10px; + color: white; + padding: 4px 5px; + opacity: 0.9; + border-radius: 4px; +} +#ge-propertyTab .buttonLine button:hover { + opacity: 1; +} +#ge-propertyTab .buttonLine button:active { + background: #282828; +} +#ge-propertyTab .buttonLine button:focus { + border: 1px solid #424242; + outline: 0px; +} +#ge-propertyTab .numeric { + padding-bottom: 0px; + padding-top: 0px; + height: var(--spacingHeight); + display: grid; + grid-template-columns: 1fr 120px auto; +} +#ge-propertyTab .numeric .numeric-label { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .numeric .number { + display: flex; + align-items: center; + grid-column: 2; + height: 10px; +} +#ge-propertyTab .numeric .number .input { + width: calc(100% - 5px); + height: 10px; +} +#ge-propertyTab .checkBoxLine { + padding-bottom: 0px; + padding-top: 0px; + height: var(--spacingHeight); + display: grid; + grid-template-columns: auto 1fr auto; + flex-grow: 1; +} +#ge-propertyTab .checkBoxLine .label { + grid-column: 2; + display: flex; + align-items: center; + min-width: 100px; + margin-left: 15px; + height: var(--spacingHeight); + font-weight: 600; +} +#ge-propertyTab .checkBoxLine img { + width: 30px; +} +#ge-propertyTab .checkBoxLine .img { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .checkBoxLine .hidden { + display: none; +} +#ge-propertyTab .listLine { + padding-bottom: 0px; + padding-top: 0px; + height: var(--spacingHeight); + display: grid; + grid-template-columns: auto 1fr auto; + flex-grow: 1; +} +#ge-propertyTab .listLine .label { + grid-column: 2; + display: none; + align-items: center; +} +#ge-propertyTab .listLine img { + width: 30px; +} +#ge-propertyTab .listLine .img { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .listLine .options { + grid-column: 2; + padding-left: 15px; + display: flex; + align-items: center; +} +#ge-propertyTab .listLine .options select { + width: 100%; + height: 25px; + border: transparent; +} +#ge-propertyTab .listLine .options input { + width: 100%; + height: 24px; + color: #333333; +} +#ge-propertyTab .color3Line { + padding-left: 15px; + padding-bottom: 0px; + padding-top: 0px; + display: grid; + flex-grow: 1; +} +#ge-propertyTab .color3Line .firstLine { + height: var(--spacingHeight); + display: flex; + align-items: center; +} +#ge-propertyTab .color3Line .firstLine .label { + grid-column: 2; + padding-left: 5px; + display: none; + align-items: center; + min-width: 15px; +} +#ge-propertyTab .color3Line .firstLine .img { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-propertyTab .color3Line .firstLine img { + width: 30px; + height: 30px; +} +#ge-propertyTab .color3Line .firstLine .textInputLine { + grid-column: 3; + padding-left: 2px; + flex-grow: 1; +} +#ge-propertyTab .color3Line .firstLine .color3 { + display: flex; + align-items: center; +} +#ge-propertyTab .color3Line .firstLine .color3 input { + margin-right: 5px; +} +#ge-propertyTab .color3Line .firstLine .copy { + grid-column: 4; + display: none; + align-items: center; + justify-items: center; + cursor: pointer; + color: black; +} +#ge-propertyTab .color3Line .firstLine .copy img { + height: 100%; + width: 20px; +} +#ge-propertyTab .color3Line .firstLine .expand { + grid-column: 4; + display: none; + align-items: center; + justify-items: center; + cursor: pointer; +} +#ge-propertyTab .color3Line .firstLine .expand img { + height: 100%; + width: 20px; +} +#ge-propertyTab .color3Line .secondLine { + display: grid; + padding-right: 5px; + border-left: 1px solid rgb(51, 122, 183); +} +#ge-propertyTab .color3Line .secondLine .numeric { + display: grid; + grid-template-columns: 1fr auto; +} +#ge-propertyTab .color3Line .secondLine .numeric-label { + text-align: right; + grid-column: 1; + display: flex; + align-items: center; + justify-self: right; + margin-right: 10px; +} +#ge-propertyTab .color3Line .secondLine .numeric-value { + width: 120px; + grid-column: 2; + display: flex; + align-items: center; + border: 1px solid rgb(51, 122, 183); +} +#ge-propertyTab .textLine { + padding-left: 5px; + padding-bottom: 0px; + padding-top: 0px; + padding-right: 18px; + height: auto; + display: grid; + grid-template-columns: auto auto 2fr 1fr; +} +#ge-propertyTab .textLine .label { + grid-column: 2; + padding-left: 5px; + padding-top: 4px; + display: flex; + align-items: left; + min-width: 15px; + color: #a9a9a9; + font-size: 10px; + font-family: "acumin-pro-semi-condensed", sans-serif; + font-weight: 600; +} +#ge-propertyTab .textLine img { + width: 30px; +} +#ge-propertyTab .textLine .img { + grid-column: 1; + display: flex; + align-items: center; +} +#ge-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; +} +#ge-propertyTab .textLine .value { + display: none; + grid-column: 3; + 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; +} +#ge-propertyTab .textLine .value.check { + color: green; +} +#ge-propertyTab .textLine .value.uncheck { + color: red; +}`,"",{version:3,sources:["webpack://./../../../tools/guiEditor/dist/components/propertyTab/propertyTab.scss"],names:[],mappings:"AAAA;EACI,yBAAA;EACA,qBAAA;EACA,iBAAA;EACA,2BAAA;EACA,mCAAA;EACA,6BAAA;EACA,wBAAA;EACA,kCAAA;EACA,gCAAA;AACJ;;AAEA;EACI,iBAAA;EAKA,YAAA;EACA,mBAAA;AAHJ;AAII;EACI,+CAAA;EACA,eAAA;AAFR;AAII;EACI,YAAA;EACA,eAAA;EACA,YAAA;EACA,iBAAA;EACA,WAAA;EACA,kBAAA;EACA,aAAA;EACA,+BAAA;EACA,yBAAA;EACA,sBAAA;EACA,qBAAA;EACA,iBAAA;AAFR;AAIQ;EACI,kBAAA;EACA,cAAA;EACA,WAAA;EACA,YAAA;EACA,OAAA;EACA,aAAA;EACA,kBAAA;EACA,oBAAA;EACA,iBAAA;AAFZ;AAKQ;EACI,iBAAA;EACA,YAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,kBAAA;AAHZ;AAOI;EACI,wBAAA;EACA,WAAA;EACA,WAAA;EACA,mBAAA;EACA,kBAAA;EACA,aAAA;EACA,YAAA;EACA,wBAAA;EACA,wBAAA;EACA,UAAA;AALR;AAQI;EACI,UAAA;AANR;AASI;EACI,wBAAA;EACA,gBAAA;EACA,WAAA;EACA,YAAA;EACA,kBAAA;EACA,mBAAA;EACA,aAAA;EACA,kBAAA;EACA,eAAA;AAPR;AAUI;EACI,WAAA;EACA,YAAA;EACA,kBAAA;EACA,wBAAA;EACA,eAAA;AARR;AAWI;EACI,wBAAA;EACA,0CAAA;EACA,UAAA;EACA,WAAA;EACA,YAAA;AATR;AAWI;EACI,UAAA;AATR;AAWI;EACI,YAAA;AATR;AAYI;EACI,yBAAA;AAVR;AAaI;EACI,WAAA;EACA,YAAA;AAXR;AAcI;EACI,WAAA;EACA,YAAA;EACA,oBAAA;EACA,yCAAA;EACA,YAAA;EACA,eAAA;EACA,eAAA;EACA,gBAAA;EACA,0CAAA;EACA,gBAAA;EACA,kBAAA;EACA,aAAA;EACA,uBAAA;EACA,mBAAA;AAZR;AAeI;EACI,iDAAA;EACA,mBAAA;AAbR;AAgBI;EACI,8CAAA;AAdR;AAiBI;EACI,2BAAA;EACA,gDAAA;AAfR;AAkBI;;EAEI,oBAAA;EACA,kBAAA;EACA,0BAAA;EACA,oBAAA;EACA,kBAAA;EACA,8BAAA;EACA,mBAAA;EACA,iBAAA;AAhBR;AAkBQ;;EACI,kBAAA;EACA,oBAAA;AAfZ;AAmBI;;EAEI,wBAAA;EACA,SAAA;AAjBR;AAoBI;EACI,0BAAA;AAlBR;AAqBI;EACI,4BAAA;EACA,aAAA;EACA,wBAAA;EACA,wCAAA;EACA,YAAA;AAnBR;AAqBQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;EACA,gBAAA;AAnBZ;AAsBQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AApBZ;AAuBQ;EACI,cAAA;EACA,WAAA;EACA,iBAAA;EACA,aAAA;EACA,mBAAA;EACA,iBAAA;AArBZ;AAwBQ;EACI,cAAA;EACA,iBAAA;EACA,+BAAA;AAtBZ;AAwBY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,gBAAA;AAtBhB;AAyBY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAvBhB;AAyBgB;EACI,WAAA;EACA,uBAAA;EACA,YAAA;AAvBpB;AA0BgB;;EAEI,wBAAA;EACA,SAAA;AAxBpB;AA2BgB;EACI,6BAAA;EACA,0BAAA;EACA,qBAAA;AAzBpB;AA+BI;EACI,mBAtOiB;EAuOjB,iBAAA;EACA,aAAA;EACA,+BAAA;EACA,gBAAA;EACA,mBAAA;AA7BR;AA+BI;EACI,aAAA;EACA,uCAAA;AA7BR;AAgCY;;EACI,cAAA;AA7BhB;AA+BY;;EACI,cAAA;AA5BhB;AAgCI;EACI,aAAA;EACA,kDAAA;AA9BR;AAiCY;;EACI,cAAA;AA9BhB;AAgCY;;EACI,cAAA;AA7BhB;AA+BY;;EACI,cAAA;AA5BhB;AA8BY;;EACI,cAAA;AA3BhB;AA+BI;EACI,aAAA;EACA,qCAAA;AA7BR;AA+BQ;EACI,iBAAA;AA7BZ;AAiCI;EACI,aAAA;EACA,0CAAA;AA/BR;AAkCI;EACI,aAAA;EACA,yBAAA;EACA,kBAAA;EACA,iBAAA;AAhCR;AAmCI;EACI,aAAA;EACA,yBAAA;EACA,kBAAA;EACA,iBAAA;AAjCR;AAoCI;EACI,aAAA;EACA,kBAAA;AAlCR;AAqCI;EACI,yCAAA;AAnCR;AAsCI;;EAEI,iBAAA;EACA,mBAvTkB;EAwTlB,gBAvTe;EAwTf,4BAAA;EACA,aAAA;EACA,oCAAA;EACA,YAAA;AApCR;AAqCQ;;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;EACA,gBAAA;AAlCZ;AAqCQ;;EACI,4BAAA;EACA,2CAAA;AAlCZ;AAqCQ;;EACI,WAAA;AAlCZ;AAqCQ;;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAlCZ;AAqCQ;;EACI,aAAA;EACA,mBAAA;EACA,cAAA;EACA,uBAAA;EACA,YAAA;EACA,kBAAA;EACA,uBAAA;EACA,eAAA;EACA,kBAAA;AAlCZ;AAmCY;;EACI,WAAA;EACA,YAAA;EACA,cAAA;AAhChB;AAkCY;;EACI,mBAAA;AA/BhB;AAiCY;;EACI,aAAA;EACA,kBAAA;EACA,QAAA;EACA,sBAAA;EACA,YAAA;AA9BhB;AA+BgB;;;;EAEI,WAAA;EACA,YAAA;AA3BpB;AA8BY;;;;EAGI,aAAA;AA3BhB;AA6BY;;EACI,8CAAA;AA1BhB;AA4BY;;EACI,gDAAA;AAzBhB;AA0BgB;;;;EAEI,sBAAA;AAtBpB;AA4BI;EACI,yCAAA;AA1BR;AA6BI;EACI,YAAA;EACA,aAAA;EACA,gCAAA;AA3BR;AA6BQ;EACI,4BAAA;EACA,2CAAA;AA3BZ;AA8BQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AA5BZ;AA+BQ;EACI,aAAA;EACA,mBAAA;EACA,cAAA;AA7BZ;AA+BY;EACI,uBAAA;EACA,iBAAA;EACA,YAAA;AA7BhB;AAkCI;EACI,eAAA;EACA,aAAA;EACA,wBAAA;EACA,2BAAA;AAhCR;AAkCQ;EACI,kCAAA;AAhCZ;AAoCY;EACI,8CAAA;AAlChB;AAuCoB;EACI,wCAAA;AArCxB;AA2CQ;EACI,WAAA;EACA,cAAA;EACA,UAAA;EACA,qBAAA;EACA,yBAAA;EACA,oBAAA;AAzCZ;AA2CY;EACI,UAAA;AAzChB;AA6CQ;EACI,WAAA;EACA,cAAA;AA3CZ;AA6CY;EACI,aAAA;EACA,+BAAA;EACA,mBAAA;EACA,4BAAA;EACA,mBAndU;EAodV,gBAndO;EAodP,kBAAA;EACA,eAAA;AA3ChB;AA6CgB;EACI,kCAAA;EACA,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;AA3CpB;AA8CgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,wBAAA;AA5CpB;AA8CoB;EACI,yBAAA;AA5CxB;AAiDY;EACI,mDAAA;AA/ChB;AAkDY;EACI,mDAAA;AAhDhB;AAqDI;EACI,YAAA;EACA,WAAA;AAnDR;AAqDQ;EACI,uBAAA;EACA,wBAAA;EACA,uBAAA;EACA,eAAA;EACA,gFAAA;AAnDZ;AAoDY;EACI,YAAA;AAlDhB;AAsDQ;EACI,UAAA;EACA,eAAA;EACA,QAAA;EACA,UAAA;EACA,WAAA;EACA,SAAA;AApDZ;AAuDQ;EACI,kBAAA;EACA,wBAAA;AArDZ;AAwDQ;EACI,yBAAA;AAtDZ;AA0DI;EACI,aAAA;EACA,wBAAA;EACA,oDAAA;EACA,gBAAA;EACA,iBAAA;EACA,mBAAA;AAxDR;AA0DQ;EACI,WAAA;EACA,cAAA;AAxDZ;AA2DQ;EACI,WAAA;EACA,cAAA;EACA,eAAA;AAzDZ;AA4DQ;EACI,gBAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,iBAAA;AA1DZ;AA6DQ;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,wBAAA;EACA,qBAAA;EACA,kBAAA;EACA,kBAAA;AA3DZ;AA6DY;EACI,UAAA;AA3DhB;AA+DQ;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;AA7DZ;AA+DY;EACI,YAAA;EACA,WAAA;AA7DhB;AA+DY;EACI,eAAA;AA7DhB;AAgEQ;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;AA9DZ;AA+DY;EACI,YAAA;EACA,WAAA;AA7DhB;AA+DY;EACI,eAAA;AA7DhB;AAkEI;EACI,aAAA;EACA,uBAAA;EACA,kBAAA;AAhER;AAmEI;EACI,eAAA;EACA,WAAA;AAjER;AAmEQ;EACI,aAAA;AAjEZ;AAoEQ;EACI,YAAA;EACA,WAAA;EACA,aAAA;EACA,YAAA;EACA,qBAAA;EACA,uBAAA;AAlEZ;AAqEQ;EACI,uBAAA;AAnEZ;AAsEQ;EACI,wBAAA;EACA,uBAAA;AApEZ;AAwEY;EACI,uBAAA;AAtEhB;AA0EQ;EACI,iDAAA;EACA,oBAAA;AAxEZ;AA4EI;EACI,eAAA;EACA,WAAA;EACA,gBAAA;EACA,iBAAA;EAKA,uBAAA;AA9ER;AA0EQ;EACI,aAAA;AAxEZ;AA4EQ;EACI,YAAA;EACA,WAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;AA1EZ;AA4EQ;EACI,yBAAA;EACA,iBAAA;AA1EZ;AA8EI;EACI,eAAA;EACA,oBAAA;EACA,WAAA;EACA,gBAAA;EACA,iBAAA;EAKA,uBAAA;AAhFR;AA4EQ;EACI,aAAA;AA1EZ;AA8EQ;EACI,YAAA;EACA,WAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;AA5EZ;AA+EQ;EACI,iBAAA;AA7EZ;AAiFI;EACI,eAAA;EACA,oBAAA;EACA,WAAA;EACA,gBAAA;EACA,iBAAA;EAKA,yBAAA;EACA,iBAAA;AAnFR;AA8EQ;EACI,aAAA;AA5EZ;AAiFQ;EACI,YAAA;EACA,WAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;AA/EZ;AAmFI;EACI,iBAAA;EACA,4BAAA;EACA,mBAptBkB;EAqtBlB,gBAptBe;EAqtBf,aAAA;EACA,yCAAA;EACA,YAAA;AAjFR;AAmFQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;EACA,gBAAA;AAjFZ;AAoFQ;EACI,WAAA;AAlFZ;AAqFQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAnFZ;AAsFQ;EACI,aAAA;EACA,mBAAA;EACA,cAAA;EACA,uBAAA;EACA,YAAA;AApFZ;AAqFY;EACI,WAAA;EACA,uBAAA;EACA,YAAA;AAnFhB;AAuFQ;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;AAtFZ;AAwFY;EACI,WAAA;AAtFhB;AAyFY;;EAEI,wBAAA;EACA,SAAA;AAvFhB;AA0FY;EACI,0BAAA;AAxFhB;AA6FI;EACI,mBAhxBkB;EAixBlB,gBAhxBe;EAixBf,aAAA;AA3FR;AA4FQ;EACI,aAAA;EACA,oCAAA;EACA,4BAAA;AA1FZ;AA4FY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AA1FhB;AA6FY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,iBAAA;EACA,YAAA;AA3FhB;AA8FY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AA5FhB;AAgGQ;EACI,aAAA;EACA,kBAAA;EACA,wCAAA;AA9FZ;AAgGY;EACI,eAAA;AA9FhB;AAiGY;EACI,aAAA;EACA,+BAAA;AA/FhB;AAkGY;EACI,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mBAAA;EACA,kBAAA;AAhGhB;AAmGY;EACI,YAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mCAAA;AAjGhB;AAsGI;EACI,4BAAA;EACA,mBAl1BkB;EAm1BlB,gBAl1Be;EAm1Bf,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,mBAAA;AApGR;AAqGQ;EACI,aAAA;AAnGZ;AAsGQ;EACI,iCAAA;EACA,yBAAA;EACA,gBAAA;EACA,YAAA;EACA,gBAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;EACA,kBAAA;AApGZ;AAuGQ;EACI,UAAA;AArGZ;AAwGQ;EACI,sBAAA;EACA,yBAAA;AAtGZ;AAyGQ;EACI,iCAAA;EACA,yBAAA;EACA,yBAAA;EACA,YAAA;EACA,gBAAA;EACA,YAAA;EACA,kBAAA;AAvGZ;AA0GQ;EACI,UAAA;AAxGZ;AA2GQ;EACI,mBAAA;AAzGZ;AA4GQ;EACI,yBAAA;EACA,YAAA;AA1GZ;AA8GI;EACI,mBA14BkB;EA24BlB,gBA14Be;EA24Bf,4BAAA;EACA,aAAA;EACA,qCAAA;AA5GR;AA8GQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AA5GZ;AA+GQ;EACI,aAAA;EACA,mBAAA;EACA,cAAA;EACA,YAAA;AA7GZ;AA8GY;EACI,uBAAA;EACA,YAAA;AA5GhB;AAiHI;EACI,mBAn6BkB;EAo6BlB,gBAn6Be;EAo6Bf,4BAAA;EACA,aAAA;EACA,oCAAA;EACA,YAAA;AA/GR;AAiHQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,gBAAA;EACA,iBAAA;EACA,4BAAA;EACA,gBAAA;AA/GZ;AAkHQ;EACI,WAAA;AAhHZ;AAmHQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAjHZ;AAoHQ;EACI,aAAA;AAlHZ;AAsHI;EACI,mBAp8BkB;EAq8BlB,gBAp8Be;EAq8Bf,4BAAA;EACA,aAAA;EACA,oCAAA;EACA,YAAA;AApHR;AAsHQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AApHZ;AAuHQ;EACI,WAAA;AArHZ;AAwHQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAtHZ;AAyHQ;EACI,cAAA;EACA,kBAAA;EACA,aAAA;EACA,mBAAA;AAvHZ;AAyHY;EACI,WAAA;EACA,YAAA;EACA,mBAAA;AAvHhB;AA0HY;EACI,WAAA;EACA,YAAA;EACA,cAAA;AAxHhB;AA6HI;EACI,kBAAA;EACA,mBAj/BkB;EAk/BlB,gBAj/Be;EAk/Bf,aAAA;EACA,YAAA;AA3HR;AA6HQ;EACI,4BAAA;EACA,aAAA;EACA,mBAAA;AA3HZ;AA6HY;EACI,cAAA;EACA,iBAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;AA3HhB;AA8HY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AA5HhB;AA+HY;EACI,WAAA;EACA,YAAA;AA7HhB;AAgIY;EACI,cAAA;EACA,iBAAA;EACA,YAAA;AA9HhB;AAiIY;EACI,aAAA;EACA,mBAAA;AA/HhB;AAiIgB;EACI,iBAAA;AA/HpB;AAmIY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;EACA,YAAA;AAjIhB;AAkIgB;EACI,YAAA;EACA,WAAA;AAhIpB;AAoIY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AAlIhB;AAoIgB;EACI,YAAA;EACA,WAAA;AAlIpB;AAuIQ;EACI,aAAA;EACA,kBAAA;EACA,wCAAA;AArIZ;AAuIY;EACI,aAAA;EACA,+BAAA;AArIhB;AAwIY;EACI,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mBAAA;EACA,kBAAA;AAtIhB;AAyIY;EACI,YAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mCAAA;AAvIhB;AA4II;EACI,iBAvlCgB;EAwlChB,mBAvlCkB;EAwlClB,gBAvlCe;EAwlCf,mBAvlCiB;EAwlCjB,YAAA;EACA,aAAA;EACA,wCAAA;AA1IR;AA2IQ;EACI,cAAA;EACA,iBAAA;EACA,gBAAA;EACA,aAAA;EACA,iBAAA;EACA,eAAA;EACA,cAAA;EACA,eAAA;EACA,oDAAA;EACA,gBAAA;AAzIZ;AA4IQ;EACI,WAAA;AA1IZ;AA6IQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AA3IZ;AA8IQ;EACI,cAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;EACA,eAAA;EACA,YAAA;EACA,WAAA;EACA,eAAA;EACA,gBAAA;EACA,0BAAA;EACA,eAAA;AA5IZ;AA+IQ;EACI,aAAA;EACA,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;AA7IZ;AA+IY;EACI,YAAA;AA7IhB;AAgJY;EACI,UAAA;AA9IhB",sourcesContent:[`:root {\r + --backgroundGrey: #aaaaaa;\r + --spacingHeight: 30px;\r + --button: #333333;\r + --buttonBackground: #ffffff;\r + --buttonDisabledBackground: #c8c8c8;\r + --disabledBackground: #c8c8c8;\r + --buttonPressed: #ffffff;\r + --buttonPressedBackground: #606060;\r + --buttonHoverBackground: #afafaf;\r +}\r +\r +#ge-propertyTab {\r + user-select: none;\r + $line-padding-left: 5px;\r + $line-padding-bottom: 0px;\r + $line-padding-top: 0px;\r + $line-padding-right: 18px;\r + color: black;\r + background: #e2e2e2;\r + * {\r + font-family: "acumin-pro-condensed", sans-serif;\r + font-size: 12px;\r + }\r + #header {\r + height: 32px;\r + font-size: 16px;\r + color: white;\r + background: white;\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: 32px;\r + height: 32px;\r + left: 0;\r + display: flex;\r + align-self: center;\r + justify-self: center;\r + filter: invert(1);\r + }\r +\r + #title {\r + background: white;\r + color: black;\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: 100%;\r + height: 2px;\r + background: #bcbcbc;\r + border-radius: 5px;\r + outline: none;\r + opacity: 0.7;\r + -webkit-transition: 0.2s;\r + transition: opacity 0.2s;\r + padding: 0;\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: #e2e2e2;\r + border: solid;\r + border-width: thin;\r + cursor: pointer;\r + }\r +\r + .range::-moz-range-thumb {\r + width: 14px;\r + height: 14px;\r + border-radius: 50%;\r + background: rgb(0, 0, 0);\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 + hr {\r + border: 1px solid #d0cece;\r + }\r +\r + .icon {\r + width: 30px;\r + height: 30px;\r + }\r +\r + .unit {\r + width: 26px;\r + height: 26px;\r + color: var(--button);\r + background-color: var(--buttonBackground);\r + border: none;\r + margin-top: 2px;\r + cursor: pointer;\r + margin-left: 2px;\r + font-family: "atten-round-new", sans-serif;\r + font-weight: 500;\r + font-style: normal;\r + display: flex;\r + justify-content: center;\r + align-items: center;\r + }\r +\r + .unit:disabled {\r + background-color: var(--buttonDisabledBackground);\r + cursor: not-allowed;\r + }\r +\r + .unit:not(:disabled):hover {\r + background-color: var(--buttonHoverBackground);\r + }\r +\r + .unit:not(:disabled):active {\r + color: var(--buttonPressed);\r + background-color: var(--buttonPressedBackground);\r + }\r +\r + input,\r + select {\r + outline-style: solid;\r + outline-width: 0px;\r + outline-color: transparent;\r + outline-offset: -1px;\r + outline-width: 1px;\r + transition: outline-color 0.2s;\r + border: transparent;\r + padding-left: 5px;\r +\r + &:focus {\r + outline-width: 1px;\r + outline-color: black;\r + }\r + }\r +\r + .hasArrows input::-webkit-outer-spin-button,\r + .hasArrows input::-webkit-inner-spin-button {\r + -webkit-appearance: none;\r + margin: 0;\r + }\r +\r + .hasArrows input[type="number"] {\r + -moz-appearance: textfield;\r + }\r +\r + .sliderLine {\r + height: var(--spacingHeight);\r + display: grid;\r + grid-template-rows: 100%;\r + grid-template-columns: auto 1fr 20px 1fr;\r + flex-grow: 1;\r +\r + .label {\r + grid-column: 1;\r + display: flex;\r + align-items: center;\r + min-width: 15px;\r + font-weight: 600;\r + }\r +\r + .img {\r + grid-column: 1;\r + display: flex;\r + align-items: center;\r + }\r +\r + .slider {\r + grid-column: 4;\r + grid-row: 1;\r + margin-right: 5px;\r + display: flex;\r + align-items: center;\r + padding-left: 5px;\r + }\r +\r + .floatLine {\r + grid-column: 2;\r + padding-left: 0px;\r + grid-template-columns: 1fr auto;\r +\r + .label {\r + grid-column: 1;\r + display: none;\r + align-items: center;\r + font-weight: 600;\r + }\r +\r + .short {\r + grid-column: 1;\r + display: flex;\r + align-items: center;\r +\r + input {\r + width: 100%;\r + background-color: white;\r + height: 24px;\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 + -webkit-appearance: textfield;\r + -moz-appearance: textfield;\r + appearance: textfield;\r + }\r + }\r + }\r + }\r +\r + .ge-divider {\r + padding-right: $line-padding-right;\r + padding-left: 5px;\r + display: grid;\r + grid-template-columns: auto 1fr;\r + padding-top: 1px;\r + padding-bottom: 1px;\r + }\r + .ge-divider.double {\r + display: grid;\r + grid-template-columns: auto 1fr 5px 1fr;\r + > .textInputLine,\r + > .floatLine {\r + &:first-of-type {\r + grid-column: 2;\r + }\r + &:nth-of-type(2) {\r + grid-column: 4;\r + }\r + }\r + }\r + .ge-divider.quad {\r + display: grid;\r + grid-template-columns: 1fr 5px 1fr 5px 1fr 5px 1fr;\r + > .textInputLine,\r + > .floatLine {\r + &:first-of-type {\r + grid-column: 1;\r + }\r + &:nth-of-type(2) {\r + grid-column: 3;\r + }\r + &:nth-of-type(3) {\r + grid-column: 5;\r + }\r + &:nth-of-type(4) {\r + grid-column: 7;\r + }\r + }\r + }\r + .ge-grid-divider {\r + display: grid;\r + grid-template-columns: 150px 1fr auto;\r +\r + .textLine {\r + grid-column: auto;\r + }\r + }\r +\r + .ge-grid-button-divider {\r + display: grid;\r + grid-template-columns: 60px 60px 60px 60px;\r + }\r +\r + .ge-grid-remove {\r + display: grid;\r + background-color: #c2c2c2;\r + margin-bottom: 5px;\r + filter: invert(1);\r + }\r +\r + .ge-grid-edit {\r + display: grid;\r + background-color: #878787;\r + margin-bottom: 5px;\r + filter: invert(1);\r + }\r +\r + .ge-grid {\r + display: grid;\r + margin-bottom: 5px;\r + }\r +\r + .ge-divider.double .textInputLine {\r + grid-template-columns: auto auto 1fr auto;\r + }\r +\r + .textInputLine,\r + .floatLine {\r + user-select: none;\r + padding-bottom: $line-padding-bottom;\r + padding-top: $line-padding-top;\r + height: var(--spacingHeight);\r + display: grid;\r + grid-template-columns: auto auto 1fr;\r + flex-grow: 1;\r + .label {\r + grid-column: 2;\r + display: flex;\r + align-items: center;\r + min-width: 15px;\r + font-weight: 600;\r + }\r +\r + .disabled {\r + color: var(--backgroundGrey);\r + background-color: var(--disabledBackground);\r + }\r +\r + img {\r + width: 30px;\r + }\r +\r + .img {\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: 3;\r + background: transparent;\r + height: 26px;\r + position: relative;\r + background-color: white;\r + margin-top: 2px;\r + overflow-y: hidden;\r + input {\r + width: 100%;\r + height: 24px;\r + color: #333333;\r + }\r + input.hasArrows {\r + padding-right: 15px;\r + }\r + .arrows {\r + display: none;\r + position: absolute;\r + right: 0;\r + flex-direction: column;\r + cursor: grab;\r + .downArrowIcon,\r + .upArrowIcon {\r + width: 13px;\r + height: 13px;\r + }\r + }\r + &:hover .arrows,\r + &:focus .arrows,\r + &.dragging .arrows {\r + display: flex;\r + }\r + .arrows:hover {\r + background-color: var(--buttonHoverBackground);\r + }\r + &.dragging .arrows {\r + background-color: var(--buttonPressedBackground);\r + .downArrowIcon,\r + .upArrowIcon {\r + filter: brightness(10);\r + }\r + }\r + }\r + }\r +\r + .textInputLine.withUnits {\r + grid-template-columns: auto auto 1fr auto;\r + }\r +\r + .textInputArea {\r + height: 100%;\r + display: grid;\r + grid-template-columns: 1fr 120px;\r +\r + .disabled {\r + color: var(--backgroundGrey);\r + background-color: var(--disabledBackground);\r + }\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 + textarea {\r + width: calc(150% - 5px);\r + margin-left: -50%;\r + height: 40px;\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 + .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: #cccccc;\r + height: var(--spacingHeight);\r + padding-bottom: $line-padding-bottom;\r + padding-top: $line-padding-top;\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: 26px;\r + width: 26px;\r +\r + .color-rect-background {\r + width: calc(100% - 2px);\r + height: calc(100% - 2px);\r + border: 1px black solid;\r + cursor: pointer;\r + background: repeating-conic-gradient(#e2e2e2 0% 25%, white 0% 50%) 50% / 100% 100%;\r + .color-rect {\r + height: 100%;\r + }\r + }\r +\r + .color-picker-cover {\r + z-index: 2;\r + position: fixed;\r + top: 0px;\r + right: 0px;\r + bottom: 0px;\r + left: 0px;\r + }\r +\r + .color-picker-float {\r + position: absolute;\r + outline: 1px solid black;\r + }\r +\r + .color-picker-container {\r + background-color: #e2e2e2;\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 + .alignment-bar {\r + display: flex;\r + justify-content: center;\r + padding-right: 5px;\r + }\r +\r + .command-button {\r + cursor: pointer;\r + width: 30px;\r +\r + .command-label {\r + display: none;\r + }\r +\r + .command-button-icon {\r + height: 100%;\r + width: 100%;\r + display: grid;\r + color: white;\r + align-content: center;\r + justify-content: center;\r + }\r +\r + &:hover {\r + background-color: white;\r + }\r +\r + .active {\r + transform-origin: center;\r + background-color: white;\r + }\r +\r + img {\r + &.active {\r + background-color: white;\r + }\r + }\r +\r + &.disabled {\r + background-color: var(--buttonDisabledBackground);\r + pointer-events: none;\r + }\r + }\r +\r + .command-button-alt {\r + cursor: pointer;\r + width: 40px;\r + margin-left: 5px;\r + margin-right: 5px;\r + .command-label {\r + display: none;\r + }\r +\r + background-color: white;\r + .command-button-icon {\r + height: 100%;\r + width: 100%;\r + display: grid;\r + align-content: center;\r + justify-content: center;\r + }\r + &:hover {\r + background-color: #c2c2c2;\r + filter: invert(1);\r + }\r + }\r +\r + .command-button-alt-disabled {\r + cursor: pointer;\r + pointer-events: none;\r + width: 40px;\r + margin-left: 5px;\r + margin-right: 5px;\r + .command-label {\r + display: none;\r + }\r +\r + background-color: white;\r + .command-button-icon {\r + height: 100%;\r + width: 100%;\r + display: grid;\r + align-content: center;\r + justify-content: center;\r + }\r +\r + img {\r + filter: invert(1);\r + }\r + }\r +\r + .command-button-alt-active {\r + cursor: pointer;\r + pointer-events: none;\r + width: 40px;\r + margin-left: 5px;\r + margin-right: 5px;\r + .command-label {\r + display: none;\r + }\r +\r + background-color: #c2c2c2;\r + filter: invert(1);\r + .command-button-icon {\r + height: 100%;\r + width: 100%;\r + display: grid;\r + align-content: center;\r + justify-content: center;\r + }\r + }\r +\r + .floatLine {\r + user-select: none;\r + height: var(--spacingHeight);\r + padding-bottom: $line-padding-bottom;\r + padding-top: $line-padding-top;\r + display: grid;\r + grid-template-columns: auto auto 2fr auto;\r + flex-grow: 1;\r +\r + .label {\r + grid-column: 2;\r + display: flex;\r + align-items: center;\r + min-width: 15px;\r + font-weight: 600;\r + }\r +\r + img {\r + width: 30px;\r + }\r +\r + .img {\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: 3;\r + background: transparent;\r + height: 26px;\r + input {\r + width: 100%;\r + background-color: white;\r + height: 24px;\r + }\r + }\r +\r + .short {\r + grid-column: 2;\r +\r + display: flex;\r + align-items: center;\r +\r + input {\r + width: 100%;\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-bottom: $line-padding-bottom;\r + padding-top: $line-padding-top;\r + display: grid;\r + .firstLine {\r + display: grid;\r + grid-template-columns: 1fr auto 20px;\r + height: var(--spacingHeight);\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: var(--spacingHeight);\r + padding-bottom: $line-padding-bottom;\r + padding-top: $line-padding-top;\r + display: grid;\r + align-items: center;\r + justify-items: stretch;\r + padding-bottom: 5px;\r + input[type="file"] {\r + display: none;\r + }\r +\r + .file-upload {\r + background: var(--backgroundGrey);\r + border: 1px solid #424242;\r + margin: 5px 10px;\r + color: white;\r + padding: 4px 5px;\r + opacity: 0.9;\r + cursor: pointer;\r + text-align: center;\r + border-radius: 4px;\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: var(--backgroundGrey);\r + border: 1px solid #424242;\r + margin: 5px 10px 5px 10px;\r + color: white;\r + padding: 4px 5px;\r + opacity: 0.9;\r + border-radius: 4px;\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 #424242;\r + outline: 0px;\r + }\r + }\r +\r + .numeric {\r + padding-bottom: $line-padding-bottom;\r + padding-top: $line-padding-top;\r + height: var(--spacingHeight);\r + display: grid;\r + grid-template-columns: 1fr 120px auto;\r +\r + .numeric-label {\r + grid-column: 1;\r + display: flex;\r + align-items: center;\r + }\r +\r + .number {\r + display: flex;\r + align-items: center;\r + grid-column: 2;\r + height: 10px;\r + .input {\r + width: calc(100% - 5px);\r + height: 10px;\r + }\r + }\r + }\r +\r + .checkBoxLine {\r + padding-bottom: $line-padding-bottom;\r + padding-top: $line-padding-top;\r + height: var(--spacingHeight);\r + display: grid;\r + grid-template-columns: auto 1fr auto;\r + flex-grow: 1;\r +\r + .label {\r + grid-column: 2;\r + display: flex;\r + align-items: center;\r + min-width: 100px;\r + margin-left: 15px;\r + height: var(--spacingHeight);\r + font-weight: 600;\r + }\r +\r + img {\r + width: 30px;\r + }\r +\r + .img {\r + grid-column: 1;\r + display: flex;\r + align-items: center;\r + }\r +\r + .hidden {\r + display: none;\r + }\r + }\r +\r + .listLine {\r + padding-bottom: $line-padding-bottom;\r + padding-top: $line-padding-top;\r + height: var(--spacingHeight);\r + display: grid;\r + grid-template-columns: auto 1fr auto;\r + flex-grow: 1;\r +\r + .label {\r + grid-column: 2;\r + display: none;\r + align-items: center;\r + }\r +\r + img {\r + width: 30px;\r + }\r +\r + .img {\r + grid-column: 1;\r + display: flex;\r + align-items: center;\r + }\r +\r + .options {\r + grid-column: 2;\r + padding-left: 15px;\r + display: flex;\r + align-items: center;\r +\r + select {\r + width: 100%;\r + height: 25px;\r + border: transparent;\r + }\r +\r + input {\r + width: 100%;\r + height: 24px;\r + color: #333333;\r + }\r + }\r + }\r +\r + .color3Line {\r + padding-left: 15px;\r + padding-bottom: $line-padding-bottom;\r + padding-top: $line-padding-top;\r + display: grid;\r + flex-grow: 1;\r +\r + .firstLine {\r + height: var(--spacingHeight);\r + display: flex;\r + align-items: center;\r +\r + .label {\r + grid-column: 2;\r + padding-left: 5px;\r + display: none;\r + align-items: center;\r + min-width: 15px;\r + }\r +\r + .img {\r + grid-column: 1;\r + display: flex;\r + align-items: center;\r + }\r +\r + img {\r + width: 30px;\r + height: 30px;\r + }\r +\r + .textInputLine {\r + grid-column: 3;\r + padding-left: 2px;\r + flex-grow: 1;\r + }\r +\r + .color3 {\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: none;\r + align-items: center;\r + justify-items: center;\r + cursor: pointer;\r + color: black;\r + img {\r + height: 100%;\r + width: 20px;\r + }\r + }\r +\r + .expand {\r + grid-column: 4;\r + display: none;\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 + padding-bottom: $line-padding-bottom;\r + padding-top: $line-padding-top;\r + padding-right: $line-padding-right;\r + height: auto;\r + display: grid;\r + grid-template-columns: auto auto 2fr 1fr;\r + .label {\r + grid-column: 2;\r + padding-left: 5px;\r + padding-top: 4px;\r + display: flex;\r + align-items: left;\r + min-width: 15px;\r + color: #a9a9a9;\r + font-size: 10px;\r + font-family: "acumin-pro-semi-condensed", sans-serif;\r + font-weight: 600;\r + }\r +\r + img {\r + width: 30px;\r + }\r +\r + .img {\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 + display: none;\r + grid-column: 3;\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 +`],sourceRoot:""}]),f.locals={};const d=f},"../../../../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/guiEditor/dist/components/sceneExplorer/sceneExplorer.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,`#ge-scene-explorer-host { + position: absolute; + left: 0px; + top: 0px; + bottom: 0px; +} +#ge-scene-explorer-host * { + font-family: "acumin-pro-condensed"; +} +#ge-scene-explorer-host:focus { + outline: none; +} + +#ge-__resizable_base__ { + display: none; +} + +.ge-context-menu { + background: #e2e2e2; +} +.ge-context-menu .react-contextmenu-item { + padding: 10px; + cursor: pointer; +} +.ge-context-menu .react-contextmenu-item:hover { + background: #e2e2e2; +} + +.ge-eact-contextmenu.context-menu.react-contextmenu--visible { + z-index: 99; + transform: scale(1); +} + +#ge-sceneExplorer { + background: #e2e2e2; + height: 100%; + margin: 0; + padding: 0; + display: grid; + grid-template-rows: auto 1fr; + font: 16px "acumin-pro-condensed"; +} +#ge-sceneExplorer:focus { + outline: none; +} +#ge-sceneExplorer #header { + height: 30px; + font-size: 16px; + color: black; + background: #e2e2e2; + grid-row: 1; + text-align: center; + display: grid; + grid-template-columns: 30px 1fr 50px; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} +#ge-sceneExplorer #header #logo { + position: relative; + grid-column: 1; + width: 24px; + height: 24px; + left: 0; + display: flex; + align-self: center; + justify-self: center; +} +#ge-sceneExplorer #header #title { + grid-column: 2; + display: grid; + align-items: center; + text-align: center; +} +#ge-sceneExplorer #header #commands { + grid-column: 3; + display: grid; + align-items: center; + grid-template-columns: 1fr 1fr; +} +#ge-sceneExplorer #header #commands .expand { + grid-column: 1; + display: grid; + align-items: center; + justify-items: center; + cursor: pointer; +} +#ge-sceneExplorer #header #commands .close { + grid-column: 2; + display: grid; + align-items: center; + justify-items: center; + cursor: pointer; +} +#ge-sceneExplorer #tree { + grid-row: 2; + overflow-x: hidden; + overflow-y: auto; +} +#ge-sceneExplorer .filter { + display: flex; + align-items: stretch; +} +#ge-sceneExplorer .filter input { + width: 100%; + margin: 10px 40px 5px 40px; + 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: black; +} +#ge-sceneExplorer .filter input::placeholder { + color: lightgray; +} +#ge-sceneExplorer .filter input:focus { + box-shadow: none; + outline: none; + background-position: 0 0; +} +#ge-sceneExplorer .groupContainer { + margin-left: 0px; + color: black; + margin-top: 0px; + margin-bottom: 0px; + height: 24px; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + align-self: center; + display: grid; + align-items: center; +} +#ge-sceneExplorer .groupContainer:hover { + background: #bbbbbb; +} +#ge-sceneExplorer .groupContainer .expandableHeader { + display: grid; + grid-template-columns: 1fr 20px; +} +#ge-sceneExplorer .groupContainer .expandableHeader .text { + grid-column: 1; + display: grid; + grid-template-columns: 20px 1fr; +} +#ge-sceneExplorer .groupContainer .expandableHeader .text .arrow { + grid-column: 1; + margin-left: 0px; + color: black; + cursor: pointer; + display: inline-block; + margin-right: 6px; + opacity: 0.5; +} +#ge-sceneExplorer .groupContainer .expandableHeader .text .text-value { + grid-column: 2; + display: flex; + align-items: center; +} +#ge-sceneExplorer .groupContainer .expandableHeader .expandAll { + opacity: 0.5; + grid-column: 2; + margin-right: 10px; +} +#ge-sceneExplorer .icon { + display: grid; + align-items: center; + justify-items: center; + cursor: pointer; +} +#ge-sceneExplorer .addComponent { + display: none; +} +#ge-sceneExplorer .makeChild { + grid-column: 3; +} +#ge-sceneExplorer .itemContainer { + margin-left: 0px; + color: black; + margin-top: 0px; + margin-bottom: 0px; + height: 32px; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + display: grid; + grid-template-columns: 20px 1fr; + border: 2px solid transparent; +} +#ge-sceneExplorer .itemContainer.hover { + border: 2px solid #527089; + cursor: pointer; +} +#ge-sceneExplorer .itemContainer.seAbove { + border-top: 2px solid #527089; + cursor: pointer; +} +#ge-sceneExplorer .itemContainer.seBelow { + border-bottom: 2px solid #527089; + cursor: pointer; +} +#ge-sceneExplorer .itemContainer.selected { + background: #bfbebe; + color: black; +} +#ge-sceneExplorer .itemContainer.dragged { + background: transparent; + color: black; +} +#ge-sceneExplorer .itemContainer.parent { + background: #ffffff; + color: black; +} +#ge-sceneExplorer .itemContainer .isNotActive { + opacity: 0.3; +} +#ge-sceneExplorer .itemContainer .arrow { + grid-column: 1; + color: black; + opacity: 0.6; +} +#ge-sceneExplorer .itemContainer .popup { + width: 200px; + visibility: hidden; + background-color: #bbbbbb; + color: #fff; + border: 1px solid rgba(255, 255, 255, 0.5); + position: absolute; + z-index: 1; + margin-left: -180px; + box-sizing: border-box; +} +#ge-sceneExplorer .itemContainer .popup.show { + visibility: visible; +} +#ge-sceneExplorer .itemContainer .popup:focus { + outline: none; +} +#ge-sceneExplorer .itemContainer .popup .popupMenu { + padding: 6px 5px 5px 10px; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + height: 18px; +} +#ge-sceneExplorer .itemContainer .popup .popupMenu:hover { + background: white; + color: #333333; +} +#ge-sceneExplorer .itemContainer .sceneNode { + grid-column: 2; + margin-left: -10px; + display: grid; + grid-template-columns: 1fr 20px 20px 20px 20px 10px 20px 20px auto 5px; + align-items: center; + cursor: pointer; +} +#ge-sceneExplorer .itemContainer .sceneNode .sceneTitle { + grid-column: 1; + margin-right: 5px; + display: flex; + align-items: center; + height: 24px; +} +#ge-sceneExplorer .itemContainer .sceneNode .translation { + grid-column: 2; + opacity: 0.6; +} +#ge-sceneExplorer .itemContainer .sceneNode .translation.selected { + opacity: 1; +} +#ge-sceneExplorer .itemContainer .sceneNode .rotation { + grid-column: 3; + opacity: 0.6; +} +#ge-sceneExplorer .itemContainer .sceneNode .rotation.selected { + opacity: 1; +} +#ge-sceneExplorer .itemContainer .sceneNode .scaling { + grid-column: 4; + opacity: 0.6; +} +#ge-sceneExplorer .itemContainer .sceneNode .scaling.selected { + opacity: 1; +} +#ge-sceneExplorer .itemContainer .sceneNode .bounding { + grid-column: 5; + opacity: 0.6; +} +#ge-sceneExplorer .itemContainer .sceneNode .bounding.selected { + opacity: 1; +} +#ge-sceneExplorer .itemContainer .sceneNode .separator { + grid-column: 6; + margin-left: 5px; + width: 5px; + display: flex; + align-items: center; + height: 18px; + border-left: solid 1px rgb(51, 122, 183); +} +#ge-sceneExplorer .itemContainer .sceneNode .pickingMode { + grid-column: 7; + opacity: 0.6; +} +#ge-sceneExplorer .itemContainer .sceneNode .pickingMode.selected { + opacity: 1; +} +#ge-sceneExplorer .itemContainer .sceneNode .refresh { + grid-column: 8; +} +#ge-sceneExplorer .itemContainer .sceneNode .extensions { + width: 20px; + grid-column: 9; +} +#ge-sceneExplorer .itemContainer .adtextureTools { + grid-column: 2; + display: grid; + grid-template-columns: 1fr 20px auto 5px; + align-items: center; +} +#ge-sceneExplorer .itemContainer .adtextureTools .pickingMode { + grid-column: 2; + opacity: 0.6; +} +#ge-sceneExplorer .itemContainer .adtextureTools .pickingMode.selected { + opacity: 1; +} +#ge-sceneExplorer .itemContainer .adtextureTools .extensions { + width: 20px; + grid-column: 3; +} +#ge-sceneExplorer .itemContainer .controlTools { + grid-column: 2; + display: grid; + align-items: center; + grid-template-columns: auto 1fr auto auto auto; +} +#ge-sceneExplorer .itemContainer .controlTools .controlType { + grid-column: 1; +} +#ge-sceneExplorer .itemContainer .controlTools .controlType img { + width: 32px; + height: 32px; + filter: invert(100%); +} +#ge-sceneExplorer .itemContainer .controlTools .highlight { + grid-column: 3; +} +#ge-sceneExplorer .itemContainer .controlTools .visibility { + grid-column: 4; +} +#ge-sceneExplorer .itemContainer .controlTools .extensions { + width: 20px; + grid-column: 5; +} +#ge-sceneExplorer .itemContainer .title { + background: transparent; + white-space: nowrap; + overflow: hidden; + min-width: 0; + margin-right: 5px; + align-items: center; + height: 24px; + cursor: pointer; +} +#ge-sceneExplorer .itemContainer .title .titleText { + font-family: "acumin-pro-condensed", sans-serif; + font-size: 16px; + border: unset; + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; + outline: none; +}`,"",{version:3,sources:["webpack://./../../../tools/guiEditor/dist/components/sceneExplorer/sceneExplorer.scss"],names:[],mappings:"AAAA;EACI,kBAAA;EACA,SAAA;EACA,QAAA;EACA,WAAA;AACJ;AAAI;EACI,mCAAA;AAER;AAAI;EACI,aAAA;AAER;;AAEA;EACI,aAAA;AACJ;;AAEA;EACI,mBAAA;AACJ;AACI;EACI,aAAA;EACA,eAAA;AACR;AACQ;EACI,mBAAA;AACZ;;AAIA;EACI,WAAA;EACA,mBAAA;AADJ;;AAIA;EACI,mBAAA;EACA,YAAA;EACA,SAAA;EACA,UAAA;EACA,aAAA;EACA,4BAAA;EACA,iCAAA;AADJ;AAGI;EACI,aAAA;AADR;AAII;EACI,YAAA;EACA,eAAA;EACA,YAAA;EACA,mBAAA;EACA,WAAA;EACA,kBAAA;EACA,aAAA;EACA,oCAAA;EACA,yBAAA;EACA,sBAAA;EACA,qBAAA;EACA,iBAAA;AAFR;AAIQ;EACI,kBAAA;EACA,cAAA;EACA,WAAA;EACA,YAAA;EACA,OAAA;EACA,aAAA;EACA,kBAAA;EACA,oBAAA;AAFZ;AAKQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,kBAAA;AAHZ;AAMQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,8BAAA;AAJZ;AAMY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AAJhB;AAOY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AALhB;AAUI;EACI,WAAA;EAEA,kBAAA;EACA,gBAAA;AATR;AAYI;EACI,aAAA;EACA,oBAAA;AAVR;AAYQ;EACI,WAAA;EACA,0BAAA;EACA,cAAA;EACA,YAAA;EACA,UAAA;EACA,0CAAA;EACA,wFAAA;EACA,8BAAA;EACA,4BAAA;EACA,4BAAA;EACA,YAAA;AAVZ;AAaQ;EACI,gBAAA;AAXZ;AAcQ;EACI,gBAAA;EACA,aAAA;EACA,wBAAA;AAZZ;AAgBI;EACI,gBAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;EACA,YAAA;EAEA,yBAAA;EACA,sBAAA;EACA,qBAAA;EACA,iBAAA;EAEA,kBAAA;EACA,aAAA;EACA,mBAAA;AAhBR;AAkBQ;EACI,mBAAA;AAhBZ;AAmBQ;EACI,aAAA;EACA,+BAAA;AAjBZ;AAmBY;EACI,cAAA;EACA,aAAA;EACA,+BAAA;AAjBhB;AAmBgB;EACI,cAAA;EACA,gBAAA;EACA,YAAA;EACA,eAAA;EACA,qBAAA;EACA,iBAAA;EACA,YAAA;AAjBpB;AAoBgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAlBpB;AAsBY;EACI,YAAA;EACA,cAAA;EACA,kBAAA;AApBhB;AAyBI;EACI,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AAvBR;AA0BI;EACI,aAAA;AAxBR;AA2BI;EACI,cAAA;AAzBR;AA4BI;EACI,gBAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;EACA,YAAA;EACA,yBAAA;EACA,sBAAA;EACA,qBAAA;EACA,iBAAA;EACA,aAAA;EACA,+BAAA;EACA,6BAAA;AA1BR;AA2BQ;EACI,yBAAA;EACA,eAAA;AAzBZ;AA4BQ;EACI,6BAAA;EACA,eAAA;AA1BZ;AA4BQ;EACI,gCAAA;EACA,eAAA;AA1BZ;AA6BQ;EACI,mBAAA;EACA,YAAA;AA3BZ;AA8BQ;EACI,uBAAA;EACA,YAAA;AA5BZ;AA+BQ;EACI,mBAAA;EACA,YAAA;AA7BZ;AAgCQ;EACI,YAAA;AA9BZ;AAgCQ;EACI,cAAA;EACA,YAAA;EACA,YAAA;AA9BZ;AAiCQ;EACI,YAAA;EACA,kBAAA;EACA,yBAAA;EACA,WAAA;EACA,0CAAA;EACA,kBAAA;EACA,UAAA;EACA,mBAAA;EACA,sBAAA;AA/BZ;AAiCY;EACI,mBAAA;AA/BhB;AAkCY;EACI,aAAA;AAhChB;AAmCY;EACI,yBAAA;EACA,gBAAA;EACA,mBAAA;EACA,uBAAA;EACA,YAAA;AAjChB;AAmCgB;EACI,iBAAA;EACA,cAAA;AAjCpB;AAsCQ;EACI,cAAA;EACA,kBAAA;EACA,aAAA;EACA,sEAAA;EACA,mBAAA;EACA,eAAA;AApCZ;AAsCY;EACI,cAAA;EACA,iBAAA;EACA,aAAA;EACA,mBAAA;EACA,YAAA;AApChB;AAuCY;EACI,cAAA;EACA,YAAA;AArChB;AAuCgB;EACI,UAAA;AArCpB;AAyCY;EACI,cAAA;EACA,YAAA;AAvChB;AAyCgB;EACI,UAAA;AAvCpB;AA2CY;EACI,cAAA;EACA,YAAA;AAzChB;AA0CgB;EACI,UAAA;AAxCpB;AA4CY;EACI,cAAA;EACA,YAAA;AA1ChB;AA2CgB;EACI,UAAA;AAzCpB;AA6CY;EACI,cAAA;EACA,gBAAA;EACA,UAAA;EACA,aAAA;EACA,mBAAA;EACA,YAAA;EACA,wCAAA;AA3ChB;AA8CY;EACI,cAAA;EACA,YAAA;AA5ChB;AA8CgB;EACI,UAAA;AA5CpB;AAgDY;EACI,cAAA;AA9ChB;AAiDY;EACI,WAAA;EACA,cAAA;AA/ChB;AAmDQ;EACI,cAAA;EACA,aAAA;EACA,wCAAA;EACA,mBAAA;AAjDZ;AAmDY;EACI,cAAA;EACA,YAAA;AAjDhB;AAmDgB;EACI,UAAA;AAjDpB;AAqDY;EACI,WAAA;EACA,cAAA;AAnDhB;AAuDQ;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,8CAAA;AArDZ;AAuDY;EACI,cAAA;AArDhB;AAsDgB;EACI,WAAA;EACA,YAAA;EACA,oBAAA;AApDpB;AAwDY;EACI,cAAA;AAtDhB;AAyDY;EACI,cAAA;AAvDhB;AA0DY;EACI,WAAA;EACA,cAAA;AAxDhB;AA4DQ;EACI,uBAAA;EACA,mBAAA;EACA,gBAAA;EACA,YAAA;EACA,iBAAA;EACA,mBAAA;EACA,YAAA;EACA,eAAA;AA1DZ;AA4DY;EACI,+CAAA;EACA,eAAA;EACA,aAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;EACA,aAAA;AA1DhB",sourcesContent:[`#ge-scene-explorer-host {\r + position: absolute;\r + left: 0px;\r + top: 0px;\r + bottom: 0px;\r + * {\r + font-family: "acumin-pro-condensed";\r + }\r + &:focus {\r + outline: none;\r + }\r +}\r +\r +#ge-__resizable_base__ {\r + display: none;\r +}\r +\r +.ge-context-menu {\r + background: #e2e2e2;\r +\r + .react-contextmenu-item {\r + padding: 10px;\r + cursor: pointer;\r +\r + &:hover {\r + background: #e2e2e2;\r + }\r + }\r +}\r +\r +.ge-eact-contextmenu.context-menu.react-contextmenu--visible {\r + z-index: 99;\r + transform: scale(1);\r +}\r +\r +#ge-sceneExplorer {\r + background: #e2e2e2;\r + height: 100%;\r + margin: 0;\r + padding: 0;\r + display: grid;\r + grid-template-rows: auto 1fr;\r + font: 16px "acumin-pro-condensed";\r +\r + &:focus {\r + outline: none;\r + }\r +\r + #header {\r + height: 30px;\r + font-size: 16px;\r + color: black;\r + background: #e2e2e2;\r + grid-row: 1;\r + text-align: center;\r + display: grid;\r + grid-template-columns: 30px 1fr 50px;\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 + #commands {\r + grid-column: 3;\r + display: grid;\r + align-items: center;\r + grid-template-columns: 1fr 1fr;\r +\r + .expand {\r + grid-column: 1;\r + display: grid;\r + align-items: center;\r + justify-items: center;\r + cursor: pointer;\r + }\r +\r + .close {\r + grid-column: 2;\r + display: grid;\r + align-items: center;\r + justify-items: center;\r + cursor: pointer;\r + }\r + }\r + }\r +\r + #tree {\r + grid-row: 2;\r +\r + overflow-x: hidden;\r + overflow-y: auto;\r + }\r +\r + .filter {\r + display: flex;\r + align-items: stretch;\r +\r + input {\r + width: 100%;\r + margin: 10px 40px 5px 40px;\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: black;\r + }\r +\r + input::placeholder {\r + color: lightgray;\r + }\r +\r + input:focus {\r + box-shadow: none;\r + outline: none;\r + background-position: 0 0;\r + }\r + }\r +\r + .groupContainer {\r + margin-left: 0px;\r + color: black;\r + margin-top: 0px;\r + margin-bottom: 0px;\r + height: 24px;\r +\r + -webkit-user-select: none;\r + -moz-user-select: none;\r + -ms-user-select: none;\r + user-select: none;\r +\r + align-self: center;\r + display: grid;\r + align-items: center;\r +\r + &:hover {\r + background: #bbbbbb;\r + }\r +\r + .expandableHeader {\r + display: grid;\r + grid-template-columns: 1fr 20px;\r +\r + .text {\r + grid-column: 1;\r + display: grid;\r + grid-template-columns: 20px 1fr;\r +\r + .arrow {\r + grid-column: 1;\r + margin-left: 0px;\r + color: black;\r + cursor: pointer;\r + display: inline-block;\r + margin-right: 6px;\r + opacity: 0.5;\r + }\r +\r + .text-value {\r + grid-column: 2;\r + display: flex;\r + align-items: center;\r + }\r + }\r +\r + .expandAll {\r + opacity: 0.5;\r + grid-column: 2;\r + margin-right: 10px;\r + }\r + }\r + }\r +\r + .icon {\r + display: grid;\r + align-items: center;\r + justify-items: center;\r + cursor: pointer;\r + }\r +\r + .addComponent {\r + display: none;\r + }\r +\r + .makeChild {\r + grid-column: 3;\r + }\r +\r + .itemContainer {\r + margin-left: 0px;\r + color: black;\r + margin-top: 0px;\r + margin-bottom: 0px;\r + height: 32px;\r + -webkit-user-select: none;\r + -moz-user-select: none;\r + -ms-user-select: none;\r + user-select: none;\r + display: grid;\r + grid-template-columns: 20px 1fr;\r + border: 2px solid transparent;\r + &.hover {\r + border: 2px solid #527089;\r + cursor: pointer;\r + }\r +\r + &.seAbove {\r + border-top: 2px solid #527089;\r + cursor: pointer;\r + }\r + &.seBelow {\r + border-bottom: 2px solid #527089;\r + cursor: pointer;\r + }\r +\r + &.selected {\r + background: #bfbebe;\r + color: black;\r + }\r +\r + &.dragged {\r + background: transparent;\r + color: black;\r + }\r +\r + &.parent {\r + background: #ffffff;\r + color: black;\r + }\r +\r + .isNotActive {\r + opacity: 0.3;\r + }\r + .arrow {\r + grid-column: 1;\r + color: black;\r + opacity: 0.6;\r + }\r +\r + .popup {\r + width: 200px;\r + visibility: hidden;\r + background-color: #bbbbbb;\r + color: #fff;\r + border: 1px solid rgba(255, 255, 255, 0.5);\r + position: absolute;\r + z-index: 1;\r + margin-left: -180px;\r + box-sizing: border-box;\r +\r + &.show {\r + visibility: visible;\r + }\r +\r + &:focus {\r + outline: none;\r + }\r +\r + .popupMenu {\r + padding: 6px 5px 5px 10px;\r + overflow: hidden;\r + white-space: nowrap;\r + text-overflow: ellipsis;\r + height: 18px;\r +\r + &:hover {\r + background: white;\r + color: #333333;\r + }\r + }\r + }\r +\r + .sceneNode {\r + grid-column: 2;\r + margin-left: -10px;\r + display: grid;\r + grid-template-columns: 1fr 20px 20px 20px 20px 10px 20px 20px auto 5px;\r + align-items: center;\r + cursor: pointer;\r +\r + .sceneTitle {\r + grid-column: 1;\r + margin-right: 5px;\r + display: flex;\r + align-items: center;\r + height: 24px;\r + }\r +\r + .translation {\r + grid-column: 2;\r + opacity: 0.6;\r +\r + &.selected {\r + opacity: 1;\r + }\r + }\r +\r + .rotation {\r + grid-column: 3;\r + opacity: 0.6;\r +\r + &.selected {\r + opacity: 1;\r + }\r + }\r +\r + .scaling {\r + grid-column: 4;\r + opacity: 0.6;\r + &.selected {\r + opacity: 1;\r + }\r + }\r +\r + .bounding {\r + grid-column: 5;\r + opacity: 0.6;\r + &.selected {\r + opacity: 1;\r + }\r + }\r +\r + .separator {\r + grid-column: 6;\r + margin-left: 5px;\r + width: 5px;\r + display: flex;\r + align-items: center;\r + height: 18px;\r + border-left: solid 1px rgb(51, 122, 183);\r + }\r +\r + .pickingMode {\r + grid-column: 7;\r + opacity: 0.6;\r +\r + &.selected {\r + opacity: 1;\r + }\r + }\r +\r + .refresh {\r + grid-column: 8;\r + }\r +\r + .extensions {\r + width: 20px;\r + grid-column: 9;\r + }\r + }\r +\r + .adtextureTools {\r + grid-column: 2;\r + display: grid;\r + grid-template-columns: 1fr 20px auto 5px;\r + align-items: center;\r +\r + .pickingMode {\r + grid-column: 2;\r + opacity: 0.6;\r +\r + &.selected {\r + opacity: 1;\r + }\r + }\r +\r + .extensions {\r + width: 20px;\r + grid-column: 3;\r + }\r + }\r +\r + .controlTools {\r + grid-column: 2;\r + display: grid;\r + align-items: center;\r + grid-template-columns: auto 1fr auto auto auto;\r +\r + .controlType {\r + grid-column: 1;\r + img {\r + width: 32px;\r + height: 32px;\r + filter: invert(100%);\r + }\r + }\r +\r + .highlight {\r + grid-column: 3;\r + }\r +\r + .visibility {\r + grid-column: 4;\r + }\r +\r + .extensions {\r + width: 20px;\r + grid-column: 5;\r + }\r + }\r +\r + .title {\r + background: transparent;\r + white-space: nowrap;\r + overflow: hidden;\r + min-width: 0;\r + margin-right: 5px;\r + align-items: center;\r + height: 24px;\r + cursor: pointer;\r +\r + .titleText {\r + font-family: "acumin-pro-condensed", sans-serif;\r + font-size: 16px;\r + border: unset;\r + white-space: nowrap;\r + text-overflow: ellipsis;\r + overflow: hidden;\r + outline: none;\r + }\r + }\r + }\r +}\r +`],sourceRoot:""}]),f.locals={};const d=f},"../../../../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/guiEditor/dist/diagram/workbenchCanvas.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,`#workbench-canvas { + grid-column: 1; + grid-row: 1; + width: 100%; + height: 100%; + margin: 0; + padding: 0; + font: 14px "acumin-pro-condensed"; + cursor: default; + user-select: none; + overflow: hidden; + background-image: linear-gradient(to right, #4f4e4f 1px, transparent 1px), linear-gradient(to bottom, #4f4e4f 1px, transparent 1px); +} +#workbench-canvas #selection-container { + pointer-events: none; +} +#workbench-canvas #selection-container .selection-box { + z-index: 10; + background: rgba(72, 72, 196, 0.5); + border: blue solid 2px; +} +#workbench-canvas #workbench-container { + width: 100%; + height: 100%; + left: 0; + top: 0; + transform-origin: left top; + display: grid; + grid-template-rows: 100%; + grid-template-columns: 100%; +} +#workbench-canvas #workbench-container #frame-container { + overflow: visible; + grid-row: 1; + grid-column: 1; + position: relative; + width: 100%; + height: 100%; +} +#workbench-canvas #workbench-container .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; +} +#workbench-canvas #workbench-container .frame-box.collapsed { + height: auto !important; + width: 200px !important; + z-index: 3; +} +#workbench-canvas #workbench-container .frame-box.collapsed .frame-box-header { + font-size: 16px; + grid-template-columns: calc(100% - 37px) 30px 7px; +} +#workbench-canvas #workbench-container .frame-box.collapsed .frame-box-header .frame-box-header-collapse { + margin-top: -2px; +} +#workbench-canvas #workbench-container .frame-box.collapsed .frame-box-header .frame-box-header-close { + display: none; +} +#workbench-canvas #workbench-container .frame-box.collapsed .frame-comments.has-comments .frame-comment-span { + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; +} +#workbench-canvas #workbench-container .frame-box .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; +} +#workbench-canvas #workbench-container .frame-box .frame-box-header { + grid-row: 1; + grid-column: 1; + background: rgb(72, 72, 72); + color: white; + font-size: 24px; + text-align: center; + display: grid; + grid-template-rows: 100%; + grid-template-columns: calc(100% - 74px) 30px 7px 30px 7px; + align-content: center; + overflow: hidden; +} +#workbench-canvas #workbench-container .frame-box .frame-box-header .frame-box-header-button { + cursor: pointer; + align-self: center; + transform-origin: 50% 50%; + transform: scale(1); + stroke: transparent; + fill: white; + display: grid; +} +#workbench-canvas #workbench-container .frame-box .frame-box-header .frame-box-header-button.down { + transform: scale(0.9); +} +#workbench-canvas #workbench-container .frame-box .frame-box-header .frame-box-header-collapse { + grid-column: 2; + grid-row: 1; +} +#workbench-canvas #workbench-container .frame-box .frame-box-header .frame-box-header-close { + grid-column: 4; + grid-row: 1; +} +#workbench-canvas #workbench-container .frame-box .frame-box-header .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; +} +#workbench-canvas #workbench-container .frame-box .frame-comments.has-comments { + display: grid; + grid-row: 2; + grid-column: 1; + padding: 0 10px; + font-style: italic; + word-wrap: break-word; +} +#workbench-canvas #workbench-container .frame-box.selected .frame-box-border { + border-color: white; +} +#workbench-canvas #workbench-container .frame-box .right-handle { + grid-area: 1/2/3/2; + width: 4px; + background-color: transparent; + cursor: ew-resize; +} +#workbench-canvas #workbench-container .frame-box .right-handle::after { + content: ""; + width: 8px; + position: absolute; + top: 0; + bottom: 0; + margin-left: -4px; + cursor: ew-resize; +} +#workbench-canvas #workbench-container .frame-box .right-handle.collapsed { + cursor: pointer; +} +#workbench-canvas #workbench-container .frame-box .top-right-corner-handle { + background-color: transparent; + height: 4px; + z-index: 21; + cursor: ne-resize; + width: 4px; + margin-left: -6px; +} +#workbench-canvas #workbench-container .frame-box .top-right-corner-handle::after { + background-color: transparent; + cursor: ne-resize; + margin-left: unset; + top: -4px; + height: 10px; + width: 10px; +} +#workbench-canvas #workbench-container .frame-box .bottom-right-corner-handle { + background-color: transparent; + height: 0px; + z-index: 21; + cursor: nw-resize; + grid-area: 4/2/4/2; + margin-left: -2px; +} +#workbench-canvas #workbench-container .frame-box .bottom-right-corner-handle::after { + background-color: transparent; + height: 10px; + cursor: nw-resize; + top: unset; + bottom: -4px; + width: 10px; +} +#workbench-canvas #workbench-container .frame-box .left-handle { + grid-area: 1/1/3/1; + width: 4px; + background-color: transparent; + cursor: ew-resize; +} +#workbench-canvas #workbench-container .frame-box .left-handle::before { + content: ""; + width: 8px; + position: absolute; + top: 0; + bottom: 0; + margin-left: -4px; +} +#workbench-canvas #workbench-container .frame-box .top-left-corner-handle { + background-color: transparent; + height: 4px; + z-index: 21; + cursor: nw-resize; + width: 4px; + margin-left: -4px; +} +#workbench-canvas #workbench-container .frame-box .top-left-corner-handle::before { + background-color: transparent; + cursor: nw-resize; + margin-left: unset; + top: -4px; + height: 10px; + width: 10px; +} +#workbench-canvas #workbench-container .frame-box .bottom-left-corner-handle { + background-color: transparent; + height: 0px; + z-index: 21; + cursor: sw-resize; + grid-area: 4/1/4/1; +} +#workbench-canvas #workbench-container .frame-box .bottom-left-corner-handle::before { + background-color: transparent; + height: 10px; + cursor: sw-resize; + top: unset; + bottom: -4px; + width: 10px; +} +#workbench-canvas #workbench-container .frame-box .top-handle { + grid-area: 1/1/1/1; + background-color: transparent; + height: 4px; + cursor: ns-resize; +} +#workbench-canvas #workbench-container .frame-box .top-handle::before { + content: ""; + width: 100%; + position: absolute; + top: -4px; + bottom: 100%; + right: 0; + left: 0; + margin-bottom: -8px; + cursor: ns-resize; + height: 8px; +} +#workbench-canvas #workbench-container .frame-box .bottom-handle { + grid-area: 3/1/3/1; + background-color: transparent; + height: 4px; + cursor: ns-resize; +} +#workbench-canvas #workbench-container .frame-box .bottom-handle::after { + content: ""; + width: 100%; + position: absolute; + top: 100%; + bottom: 0; + right: 0; + left: 0; + margin-top: -8px; + cursor: ns-resize; + height: 12px; +} +#workbench-canvas #workbench-container .frame-box.collapsed .top-handle, +#workbench-canvas #workbench-container .frame-box.collapsed .top-right-corner-handle, +#workbench-canvas #workbench-container .frame-box.collapsed .right-handle, +#workbench-canvas #workbench-container .frame-box.collapsed .bottom-right-corner-handle, +#workbench-canvas #workbench-container .frame-box.collapsed .bottom-handle, +#workbench-canvas #workbench-container .frame-box.collapsed .bottom-left-corner-handle, +#workbench-canvas #workbench-container .frame-box.collapsed .left-handle, +#workbench-canvas #workbench-container .frame-box.collapsed .top-left-corner-handle { + cursor: default; +} +#workbench-canvas #workbench-container .frame-box.collapsed .right-handle::after, +#workbench-canvas #workbench-container .frame-box.collapsed .bottom-handle::after, +#workbench-canvas #workbench-container .frame-box.collapsed .top-right-corner-handle::after, +#workbench-canvas #workbench-container .frame-box.collapsed .bottom-right-corner-handle::after { + cursor: default; +} +#workbench-canvas #workbench-container .frame-box.collapsed .left-handle::before, +#workbench-canvas #workbench-container .frame-box.collapsed .top-handle::before, +#workbench-canvas #workbench-container .frame-box.collapsed .top-left-corner-handle::before, +#workbench-canvas #workbench-container .frame-box.collapsed .bottom-left-corner-handle::before { + cursor: default; +} +#workbench-canvas #workbench-container #workbench-svg-container { + grid-row: 1; + grid-column: 1; + position: relative; + width: 100%; + height: 100%; + overflow: visible; + pointer-events: none; + z-index: 2; +} +#workbench-canvas #workbench-container #workbench-svg-container .link { + stroke-width: 4px; +} +#workbench-canvas #workbench-container #workbench-svg-container .link.selected { + stroke: white !important; + stroke-dasharray: 10, 2; +} +#workbench-canvas #workbench-container #workbench-svg-container .link.hidden { + display: none; +} +#workbench-canvas #workbench-container #workbench-svg-container .selection-link { + pointer-events: all; + stroke-width: 16px; + opacity: 0; + transition: opacity 75ms; + stroke: transparent; + cursor: pointer; +} +#workbench-canvas #workbench-container #workbench-svg-container .selection-link.hidden { + display: none; +} +#workbench-canvas #workbench-container #workbench-svg-container .selection-link:hover, #workbench-canvas #workbench-container #workbench-svg-container .selection-link.selected { + stroke: white !important; + opacity: 0.4; +} +#workbench-canvas #workbench-container #workbench-canvas-container { + grid-row: 1; + grid-column: 1; + position: relative; + width: 100%; + height: 100%; +} +#workbench-canvas #workbench-container #workbench-canvas-container .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; +} +#workbench-canvas #workbench-container #workbench-canvas-container .visual.hidden { + display: none; +} +#workbench-canvas #workbench-container #workbench-canvas-container .visual .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; +} +#workbench-canvas #workbench-container #workbench-canvas-container .visual .selection-border { + grid-row: 1/span 3; + grid-column: 1; + margin: -4px; + transition: border-color 100ms; + border: 4px solid black; + border-radius: 12px; +} +#workbench-canvas #workbench-container #workbench-canvas-container .visual.selected .selection-border { + border-color: white; +} +#workbench-canvas #workbench-container #workbench-canvas-container .visual .header { + grid-row: 1; + grid-column: 1; + border: 4px solid black; + border-top-right-radius: 7px; + border-top-left-radius: 7px; + font-size: 16px; + text-align: center; + margin-top: -1px; + margin-left: -1px; + margin-right: -1px; + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; + background: black; + color: white; +} +#workbench-canvas #workbench-container #workbench-canvas-container .visual .header.constant { + border-color: #464348; + background: #464348; +} +#workbench-canvas #workbench-container #workbench-canvas-container .visual .header.inspector { + border-color: #66491b; + background: #66491b; +}`,"",{version:3,sources:["webpack://./../../../tools/guiEditor/dist/diagram/workbenchCanvas.scss"],names:[],mappings:"AAAA;EACI,cAAA;EACA,WAAA;EACA,WAAA;EACA,YAAA;EACA,SAAA;EACA,UAAA;EACA,iCAAA;EACA,eAAA;EACA,iBAAA;EACA,gBAAA;EAEA,mIAAA;AAAJ;AAEI;EACI,oBAAA;AAAR;AAEQ;EACI,WAAA;EACA,kCAAA;EACA,sBAAA;AAAZ;AAII;EACI,WAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;EACA,0BAAA;EACA,aAAA;EACA,wBAAA;EACA,2BAAA;AAFR;AAIQ;EACI,iBAAA;EACA,WAAA;EACA,cAAA;EACA,kBAAA;EACA,WAAA;EACA,YAAA;AAFZ;AAKQ;EACI,kBAAA;EACA,iCAAA;EACA,aAAA;EACA,0CAAA;EACA,2BAAA;EACA,sBAAA;AAHZ;AAKY;EACI,uBAAA;EACA,uBAAA;EACA,UAAA;AAHhB;AAKgB;EACI,eAAA;EACA,iDAAA;AAHpB;AAKoB;EACI,gBAAA;AAHxB;AAMoB;EACI,aAAA;AAJxB;AASoB;EACI,mBAAA;EACA,uBAAA;EACA,gBAAA;AAPxB;AAYY;EACI,kBAAA;EACA,cAAA;EACA,WAAA;EACA,YAAA;EACA,6BAAA;EACA,oBAAA;EACA,sBAAA;AAVhB;AAaY;EACI,WAAA;EACA,cAAA;EACA,2BAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;EACA,aAAA;EACA,wBAAA;EACA,0DAAA;EACA,qBAAA;EACA,gBAAA;AAXhB;AAagB;EACI,eAAA;EACA,kBAAA;EACA,yBAAA;EACA,mBAAA;EACA,mBAAA;EACA,WAAA;EACA,aAAA;AAXpB;AAaoB;EACI,qBAAA;AAXxB;AAegB;EACI,cAAA;EACA,WAAA;AAbpB;AAgBgB;EACI,cAAA;EACA,WAAA;AAdpB;AAiBgB;EACI,cAAA;EACA,WAAA;EACA,aAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,mBAAA;EACA,gBAAA;AAfpB;AAmBY;EACI,aAAA;EACA,WAAA;EACA,cAAA;EACA,eAAA;EACA,kBAAA;EACA,qBAAA;AAjBhB;AAqBgB;EACI,mBAAA;AAnBpB;AAuBY;EACI,kBAAA;EACA,UAAA;EACA,6BAAA;EACA,iBAAA;AArBhB;AAuBgB;EACI,WAAA;EACA,UAAA;EACA,kBAAA;EACA,MAAA;EACA,SAAA;EACA,iBAAA;EACA,iBAAA;AArBpB;AAwBgB;EACI,eAAA;AAtBpB;AA0BY;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,UAAA;EACA,iBAAA;AAxBhB;AA0BgB;EACI,6BAAA;EACA,iBAAA;EACA,kBAAA;EACA,SAAA;EACA,YAAA;EACA,WAAA;AAxBpB;AA4BY;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,kBAAA;EACA,iBAAA;AA1BhB;AA4BgB;EACI,6BAAA;EACA,YAAA;EACA,iBAAA;EACA,UAAA;EACA,YAAA;EACA,WAAA;AA1BpB;AA8BY;EACI,kBAAA;EACA,UAAA;EACA,6BAAA;EACA,iBAAA;AA5BhB;AA8BgB;EACI,WAAA;EACA,UAAA;EACA,kBAAA;EACA,MAAA;EACA,SAAA;EACA,iBAAA;AA5BpB;AAgCY;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,UAAA;EACA,iBAAA;AA9BhB;AAgCgB;EACI,6BAAA;EACA,iBAAA;EACA,kBAAA;EACA,SAAA;EACA,YAAA;EACA,WAAA;AA9BpB;AAkCY;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,kBAAA;AAhChB;AAkCgB;EACI,6BAAA;EACA,YAAA;EACA,iBAAA;EACA,UAAA;EACA,YAAA;EACA,WAAA;AAhCpB;AAoCY;EACI,kBAAA;EACA,6BAAA;EACA,WAAA;EACA,iBAAA;AAlChB;AAoCgB;EACI,WAAA;EACA,WAAA;EACA,kBAAA;EACA,SAAA;EACA,YAAA;EACA,QAAA;EACA,OAAA;EACA,mBAAA;EACA,iBAAA;EACA,WAAA;AAlCpB;AAsCY;EACI,kBAAA;EACA,6BAAA;EACA,WAAA;EACA,iBAAA;AApChB;AAsCgB;EACI,WAAA;EACA,WAAA;EACA,kBAAA;EACA,SAAA;EACA,SAAA;EACA,QAAA;EACA,OAAA;EACA,gBAAA;EACA,iBAAA;EACA,YAAA;AApCpB;AAyCgB;;;;;;;;EAQI,eAAA;AAvCpB;AA8CoB;;;;EACI,eAAA;AAzCxB;AAiDoB;;;;EACI,eAAA;AA5CxB;AAkDQ;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,WAAA;EACA,YAAA;EACA,iBAAA;EACA,oBAAA;EACA,UAAA;AAhDZ;AAkDY;EACI,iBAAA;AAhDhB;AAiDgB;EACI,wBAAA;EACA,uBAAA;AA/CpB;AAkDgB;EACI,aAAA;AAhDpB;AAoDY;EACI,mBAAA;EACA,kBAAA;EACA,UAAA;EACA,wBAAA;EACA,mBAAA;EACA,eAAA;AAlDhB;AAoDgB;EACI,aAAA;AAlDpB;AAqDgB;EAEI,wBAAA;EACA,YAAA;AApDpB;AAyDQ;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,WAAA;EACA,YAAA;AAvDZ;AAyDY;EACI,UAAA;EACA,YAAA;EACA,kBAAA;EACA,OAAA;EACA,MAAA;EACA,gBAAA;EACA,uBAAA;EACA,mBAAA;EACA,aAAA;EACA,6BAAA;EACA,2BAAA;EACA,YAAA;AAvDhB;AAyDgB;EACI,aAAA;AAvDpB;AA0DgB;EACI,kBAAA;EACA,UAAA;EACA,YAAA;EACA,YAAA;EACA,gBAAA;EACA,kBAAA;EACA,YAAA;EACA,aAAA;EACA,qBAAA;EACA,oBAAA;AAxDpB;AA2DgB;EACI,kBAAA;EACA,cAAA;EACA,YAAA;EAEA,8BAAA;EAEA,uBAAA;EACA,mBAAA;AA3DpB;AA+DoB;EACI,mBAAA;AA7DxB;AAiEgB;EACI,WAAA;EACA,cAAA;EACA,uBAAA;EACA,4BAAA;EACA,2BAAA;EACA,eAAA;EACA,kBAAA;EACA,gBAAA;EACA,iBAAA;EACA,kBAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;EACA,iBAAA;EACA,YAAA;AA/DpB;AAiEoB;EACI,qBAAA;EACA,mBAAA;AA/DxB;AAkEoB;EACI,qBAAA;EACA,mBAAA;AAhExB",sourcesContent:[`#workbench-canvas {\r + grid-column: 1;\r + grid-row: 1;\r + width: 100%;\r + height: 100%;\r + margin: 0;\r + padding: 0;\r + font: 14px "acumin-pro-condensed";\r + cursor: default;\r + user-select: none;\r + overflow: hidden;\r +\r + background-image: linear-gradient(to right, #4f4e4f 1px, transparent 1px), linear-gradient(to bottom, #4f4e4f 1px, transparent 1px);\r +\r + #selection-container {\r + pointer-events: none;\r +\r + .selection-box {\r + z-index: 10;\r + background: rgba(72, 72, 196, 0.5);\r + border: blue solid 2px;\r + }\r + }\r +\r + #workbench-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 + #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 + .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 + &.collapsed {\r + height: auto !important;\r + width: 200px !important;\r + z-index: 3;\r +\r + .frame-box-header {\r + font-size: 16px;\r + grid-template-columns: calc(100% - 37px) 30px 7px;\r +\r + .frame-box-header-collapse {\r + margin-top: -2px;\r + }\r +\r + .frame-box-header-close {\r + display: none;\r + }\r + }\r +\r + .frame-comments.has-comments {\r + .frame-comment-span {\r + white-space: nowrap;\r + text-overflow: ellipsis;\r + overflow: hidden;\r + }\r + }\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-box-header {\r + grid-row: 1;\r + grid-column: 1;\r + background: rgba(72, 72, 72, 1);\r + color: white;\r + font-size: 24px;\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 + .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 +\r + .frame-comments.has-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 {\r + .frame-box-border {\r + border-color: white;\r + }\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 + &.collapsed {\r + cursor: pointer;\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 + &.collapsed {\r + .top-handle,\r + .top-right-corner-handle,\r + .right-handle,\r + .bottom-right-corner-handle,\r + .bottom-handle,\r + .bottom-left-corner-handle,\r + .left-handle,\r + .top-left-corner-handle {\r + cursor: default;\r + }\r +\r + .right-handle,\r + .bottom-handle,\r + .top-right-corner-handle,\r + .bottom-right-corner-handle {\r + &::after {\r + cursor: default;\r + }\r + }\r +\r + .left-handle,\r + .top-handle,\r + .top-left-corner-handle,\r + .bottom-left-corner-handle {\r + &::before {\r + cursor: default;\r + }\r + }\r + }\r + }\r +\r + #workbench-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 +\r + .link {\r + stroke-width: 4px;\r + &.selected {\r + stroke: white !important;\r + stroke-dasharray: 10, 2;\r + }\r +\r + &.hidden {\r + display: none;\r + }\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 + &.hidden {\r + display: none;\r + }\r +\r + &:hover,\r + &.selected {\r + stroke: white !important;\r + opacity: 0.4;\r + }\r + }\r + }\r +\r + #workbench-canvas-container {\r + grid-row: 1;\r + grid-column: 1;\r + position: relative;\r + width: 100%;\r + height: 100%;\r +\r + .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 +\r + &.hidden {\r + display: none;\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 + .selection-border {\r + grid-row: 1 / span 3;\r + grid-column: 1;\r + margin: -4px;\r +\r + transition: border-color 100ms;\r +\r + border: 4px solid black;\r + border-radius: 12px;\r + }\r +\r + &.selected {\r + .selection-border {\r + border-color: white;\r + }\r + }\r +\r + .header {\r + grid-row: 1;\r + grid-column: 1;\r + border: 4px solid black;\r + border-top-right-radius: 7px;\r + border-top-left-radius: 7px;\r + font-size: 16px;\r + text-align: center;\r + margin-top: -1px;\r + margin-left: -1px;\r + margin-right: -1px;\r + white-space: nowrap;\r + text-overflow: ellipsis;\r + overflow: hidden;\r + background: black;\r + color: white;\r +\r + &.constant {\r + border-color: #464348;\r + background: #464348;\r + }\r +\r + &.inspector {\r + border-color: #66491b;\r + background: #66491b;\r + }\r + }\r + }\r + }\r + }\r +}\r +`],sourceRoot:""}]),f.locals={};const d=f},"../../../../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/guiEditor/dist/main.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,`:root { + --blackBarHeight: 55px; +} + +#gui-editor-workbench-root { + display: grid; + grid-template-rows: calc(100% - 55px); + height: 100%; + width: 100%; + background: #e2e2e2; + font: 14px "acumin-pro-condensed"; +} + +.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-condensed"; + position: absolute; + top: 0; + left: 0; +} +.wait-screen.hidden { + visibility: hidden; +} + +#leftGrab { + width: 5px; + height: 100%; + cursor: ew-resize; + position: absolute; + right: -1px; + top: 0; +} + +#rightGrab { + cursor: ew-resize; + width: 5px; + bottom: 0; + position: absolute; + top: 0; + left: 0; +} + +.toolbarGrab { + background: #333333; + grid-row: 1/span 3; + grid-column: 2; + height: 100%; + overflow-y: auto; +} +.toolbarGrab .blackLine { + height: 16px; + background: black; + position: relative; +} +.toolbarGrab .arrow { + color: white; + position: absolute; +} +.toolbarGrab .toolbar-label { + color: white; + font-size: 18px; + display: grid; + align-items: center; + cursor: pointer; + user-select: none; + grid-template-columns: 1fr 20px; + grid-template-rows: 100%; + position: relative; +} +.toolbarGrab .toolbar-label.active { + font-weight: bold; + font-size: 20px; +} +.toolbarGrab .toolbar-label:hover { + background: var(--selectionGrey); +} +.toolbarGrab .toolbar-label:hover .sub-items { + display: block; +} +.toolbarGrab .toolbar-icon { + width: 40px; + height: 40px; +} +.toolbarGrab.expanded .toolbar-content-sub1 { + column-count: 2; +} + +.diagram-container { + position: relative; + display: grid; + grid-row: 1; + grid-column: 2; + background: #cccccc; + width: 100%; + height: 100%; + overflow: hidden; +} +.diagram-container .diagram { + display: none; + width: 100%; + height: 100%; +} + +.left-panel { + grid-row: 1/span 2; + grid-column: 1; + display: grid; + grid-template-rows: 100%; + grid-template-columns: 1fr 50px; + position: relative; + overflow: hidden; +} +.left-panel.expand { + grid-template-columns: 1fr 100px; +} + +.right-panel { + grid-row: 1/span 2; + grid-column: 3; + display: grid; + grid-template-rows: 1fr 40px auto 40px; + grid-template-columns: 100%; + overflow-y: auto; + position: relative; +} +.right-panel #propertyTab { + grid-row: 1; + grid-column: 1; +} +.right-panel .button { + display: grid; + justify-content: center; + align-content: center; + height: auto; + width: 14.2857142857%; + cursor: pointer; +} +.right-panel .button:hover { + background: rgb(51, 122, 183); + color: white; + opacity: 0.8; +} +.right-panel .button.selected { + background: rgb(51, 122, 183); + color: white; +} +.right-panel .button.align { + justify-content: stretch; + text-align: center; +} + +.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-condensed", sans-serif; + color: white; + font-size: 24px; + display: grid; + align-content: center; + justify-content: center; + user-select: none; + padding: 20px; + text-align: center; +} + +#log-console { + grid-row: 2; + grid-column: 4; + display: none; +} + +.gizmo * { + user-select: none; +} +.gizmo .bounding-box-line { + background-color: black; + position: absolute; + line-height: 1px; + height: 1px; + pointer-events: none; +} +.gizmo .scale-point-container { + position: absolute; + width: 30px; + height: 30px; +} +.gizmo .scale-point-container .scale-point { + top: 10px; + left: 10px; + position: absolute; + width: 10px; + height: 10px; + background: transparent; + outline: rgb(125, 125, 125) 2px solid; +} +.gizmo .scale-point-container .rotate-click-area { + width: 20px; + height: 20px; + position: absolute; +} +.gizmo .scale-point-container .scale-click-area { + width: 20px; + height: 20px; + position: absolute; +} +.gizmo .pivot-point { + width: 30px; + height: 30px; + background: transparent; + position: absolute; +} + +#workbench-canvas { + position: relative; +} + +.artboard-stroke { + outline: 1px solid black; + position: absolute; + z-index: 2; + pointer-events: none; +} + +.artboard-background { + position: absolute; + background: repeating-conic-gradient(#e2e2e2 0% 25%, white 0% 50%) 50%/10px 10px; + width: 100%; + height: 100%; +}`,"",{version:3,sources:["webpack://./../../../tools/guiEditor/dist/main.scss"],names:[],mappings:"AAAA;EACI,sBAAA;AACJ;;AAEA;EACI,aAAA;EACA,qCAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,iCAAA;AACJ;;AAEA;EACI,aAAA;EACA,uBAAA;EACA,qBAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,aAAA;EACA,YAAA;EACA,iCAAA;EACA,kBAAA;EACA,MAAA;EACA,OAAA;AACJ;AACI;EACI,kBAAA;AACR;;AAGA;EACI,UAAA;EACA,YAAA;EACA,iBAAA;EACA,kBAAA;EACA,WAAA;EACA,MAAA;AAAJ;;AAGA;EACI,iBAAA;EACA,UAAA;EACA,SAAA;EACA,kBAAA;EACA,MAAA;EACA,OAAA;AAAJ;;AAGA;EACI,mBAAA;EACA,kBAAA;EACA,cAAA;EACA,YAAA;EACA,gBAAA;AAAJ;AAEI;EACI,YAAA;EACA,iBAAA;EACA,kBAAA;AAAR;AAEI;EACI,YAAA;EACA,kBAAA;AAAR;AAEI;EACI,YAAA;EACA,eAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;EACA,iBAAA;EACA,+BAAA;EACA,wBAAA;EACA,kBAAA;AAAR;AAEQ;EACI,iBAAA;EACA,eAAA;AAAZ;AAGQ;EACI,gCAAA;AADZ;AAEY;EACI,cAAA;AAAhB;AAII;EACI,WAAA;EACA,YAAA;AAFR;AAKQ;EACI,eAAA;AAHZ;;AAQA;EACI,kBAAA;EACA,aAAA;EACA,WAAA;EACA,cAAA;EACA,mBAAA;EACA,WAAA;EACA,YAAA;EACA,gBAAA;AALJ;AAOI;EACI,aAAA;EACA,WAAA;EACA,YAAA;AALR;;AASA;EACI,kBAAA;EACA,cAAA;EACA,aAAA;EACA,wBAAA;EACA,+BAAA;EACA,kBAAA;EACA,gBAAA;AANJ;AAOI;EACI,gCAAA;AALR;;AASA;EACI,kBAAA;EACA,cAAA;EACA,aAAA;EACA,sCAAA;EACA,2BAAA;EACA,gBAAA;EACA,kBAAA;AANJ;AAQI;EACI,WAAA;EACA,cAAA;AANR;AASI;EACI,aAAA;EACA,uBAAA;EACA,qBAAA;EACA,YAAA;EACA,qBAAA;EACA,eAAA;AAPR;AASQ;EACI,6BAAA;EACA,YAAA;EACA,YAAA;AAPZ;AAUQ;EACI,6BAAA;EACA,YAAA;AARZ;AAWQ;EACI,wBAAA;EACA,kBAAA;AATZ;;AAcA;EACI,kBAAA;EACA,kBAAA;EACA,wBAAA;EACA,YAAA;EACA,MAAA;EACA,OAAA;EAEA,kCAAA;EACA,+CAAA;EACA,YAAA;EACA,eAAA;EAEA,aAAA;EACA,qBAAA;EACA,uBAAA;EAEA,iBAAA;EAEA,aAAA;EACA,kBAAA;AAfJ;;AAkBA;EACI,WAAA;EACA,cAAA;EACA,aAAA;AAfJ;;AAmBI;EACI,iBAAA;AAhBR;AAkBI;EACI,uBAAA;EACA,kBAAA;EACA,gBAAA;EACA,WAAA;EACA,oBAAA;AAhBR;AAkBI;EACI,kBAAA;EACA,WAAA;EACA,YAAA;AAhBR;AAiBQ;EACI,SAAA;EACA,UAAA;EACA,kBAAA;EACA,WAAA;EACA,YAAA;EACA,uBAAA;EACA,qCAAA;AAfZ;AAiBQ;EACI,WAAA;EACA,YAAA;EACA,kBAAA;AAfZ;AAiBQ;EACI,WAAA;EACA,YAAA;EACA,kBAAA;AAfZ;AAkBI;EACI,WAAA;EACA,YAAA;EACA,uBAAA;EACA,kBAAA;AAhBR;;AAmBA;EACI,kBAAA;AAhBJ;;AAkBA;EACI,wBAAA;EACA,kBAAA;EACA,UAAA;EACA,oBAAA;AAfJ;;AAiBA;EACI,kBAAA;EACA,gFAAA;EACA,WAAA;EACA,YAAA;AAdJ",sourcesContent:[`:root {\r + --blackBarHeight: 55px;\r +}\r +\r +#gui-editor-workbench-root {\r + display: grid;\r + grid-template-rows: calc(100% - 55px);\r + height: 100%;\r + width: 100%;\r + background: #e2e2e2;\r + font: 14px "acumin-pro-condensed";\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-condensed";\r + position: absolute;\r + top: 0;\r + left: 0;\r +\r + &.hidden {\r + visibility: hidden;\r + }\r +}\r +\r +#leftGrab {\r + width: 5px;\r + height: 100%;\r + cursor: ew-resize;\r + position: absolute;\r + right: -1px;\r + top: 0;\r +}\r +\r +#rightGrab {\r + cursor: ew-resize;\r + width: 5px;\r + bottom: 0;\r + position: absolute;\r + top: 0;\r + left: 0;\r +}\r +\r +.toolbarGrab {\r + background: #333333;\r + grid-row: 1 / span 3;\r + grid-column: 2;\r + height: 100%;\r + overflow-y: auto;\r +\r + .blackLine {\r + height: 16px;\r + background: black;\r + position: relative;\r + }\r + .arrow {\r + color: white;\r + position: absolute;\r + }\r + .toolbar-label {\r + color: white;\r + font-size: 18px;\r + display: grid;\r + align-items: center;\r + cursor: pointer;\r + user-select: none;\r + grid-template-columns: 1fr 20px;\r + grid-template-rows: 100%;\r + position: relative;\r +\r + &.active {\r + font-weight: bold;\r + font-size: 20px;\r + }\r +\r + &:hover {\r + background: var(--selectionGrey);\r + .sub-items {\r + display: block;\r + }\r + }\r + }\r + .toolbar-icon {\r + width: 40px;\r + height: 40px;\r + }\r + &.expanded {\r + .toolbar-content-sub1 {\r + column-count: 2;\r + }\r + }\r +}\r +\r +.diagram-container {\r + position: relative;\r + display: grid;\r + grid-row: 1;\r + grid-column: 2;\r + background: #cccccc;\r + width: 100%;\r + height: 100%;\r + overflow: hidden;\r +\r + .diagram {\r + display: none;\r + width: 100%;\r + height: 100%;\r + }\r +}\r +\r +.left-panel {\r + grid-row: 1 / span 2;\r + grid-column: 1;\r + display: grid;\r + grid-template-rows: 100%;\r + grid-template-columns: 1fr 50px;\r + position: relative;\r + overflow: hidden;\r + &.expand {\r + grid-template-columns: 1fr 100px;\r + }\r +}\r +\r +.right-panel {\r + grid-row: 1 / span 2;\r + grid-column: 3;\r + display: grid;\r + grid-template-rows: 1fr 40px auto 40px;\r + grid-template-columns: 100%;\r + overflow-y: auto;\r + position: relative;\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 +\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-condensed", sans-serif;\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: 4;\r + display: none;\r +}\r +\r +.gizmo {\r + * {\r + user-select: none;\r + }\r + .bounding-box-line {\r + background-color: black;\r + position: absolute;\r + line-height: 1px;\r + height: 1px;\r + pointer-events: none;\r + }\r + .scale-point-container {\r + position: absolute;\r + width: 30px;\r + height: 30px;\r + .scale-point {\r + top: 10px;\r + left: 10px;\r + position: absolute;\r + width: 10px;\r + height: 10px;\r + background: transparent;\r + outline: rgb(125, 125, 125) 2px solid;\r + }\r + .rotate-click-area {\r + width: 20px;\r + height: 20px;\r + position: absolute;\r + }\r + .scale-click-area {\r + width: 20px;\r + height: 20px;\r + position: absolute;\r + }\r + }\r + .pivot-point {\r + width: 30px;\r + height: 30px;\r + background: transparent;\r + position: absolute;\r + }\r +}\r +#workbench-canvas {\r + position: relative;\r +}\r +.artboard-stroke {\r + outline: 1px solid black;\r + position: absolute;\r + z-index: 2;\r + pointer-events: none;\r +}\r +.artboard-background {\r + position: absolute;\r + background: repeating-conic-gradient(#e2e2e2 0% 25%, white 0% 50%) 50% / 10px 10px;\r + width: 100%;\r + height: 100%;\r +}\r +`],sourceRoot:""}]),f.locals={};const d=f},"../../../../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/guiEditor/dist/scss/commandBar.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,`:root { + --selectionGrey: #666666; +} + +.ge-commands { + grid-row: 1; + grid-column: 1; + user-select: none; +} +.ge-commands * { + font-family: "acumin-pro-condensed"; + font-weight: 600; + font-size: 12px; +} +.ge-commands .commands-left { + float: left; + display: flex; +} +.ge-commands .commands-right { + float: right; + display: flex; +} +.ge-commands .commands-right .beta-flag { + height: 30px; + position: relative; + left: -15px; +} +.ge-commands.background-ts .command-button img, +.ge-commands.background-ts .command-dropdown img { + filter: invert(64%) sepia(78%) saturate(940%) hue-rotate(323deg) brightness(105%) contrast(103%); +} +.ge-commands.background-ts .command-button .command-dropdown-active, +.ge-commands.background-ts .command-dropdown .command-dropdown-active { + color: #333333; +} +.ge-commands.background-ts .command-button:hover img, .ge-commands.background-ts .command-button.activated img, +.ge-commands.background-ts .command-dropdown:hover img, +.ge-commands.background-ts .command-dropdown.activated img { + filter: invert(34%) sepia(21%) saturate(3832%) hue-rotate(324deg) brightness(88%) contrast(82%) !important; +} +.ge-commands.background-js .command-button img, +.ge-commands.background-js .command-dropdown img { + filter: invert(57%) sepia(80%) saturate(2031%) hue-rotate(215deg); +} +.ge-commands.background-js .command-button .command-dropdown-active, +.ge-commands.background-js .command-dropdown .command-dropdown-active { + color: #333333; +} +.ge-commands.background-js .command-button:hover img, .ge-commands.background-js .command-button.activated img, +.ge-commands.background-js .command-dropdown:hover img, +.ge-commands.background-js .command-dropdown.activated img { + filter: invert(17%) !important; +} +.ge-commands .command-button { + cursor: pointer; + width: 55px; + height: 55px; +} +.ge-commands .command-button .command-label { + display: none; +} +.ge-commands .command-button .command-button-icon { + height: 100%; + width: 100%; + display: grid; + color: white; + align-content: center; + justify-content: center; +} +.ge-commands .command-button .active { + transform-origin: center; + background-color: var(--selectionGrey); +} +.ge-commands .command-button img.active { + background-color: var(--selectionGrey); +} +.ge-commands .command-button:hover { + background-color: var(--selectionGrey); +} +.ge-commands .copyAndDeleteDisabled { + pointer-events: none; + color: black; +} +.ge-commands .pasteDisabled { + pointer-events: none; + color: black; +} +.ge-commands .command-dropdown-root { + position: relative; + text-transform: uppercase; + z-index: 1; +} +.ge-commands .command-dropdown { + cursor: pointer; + width: 55px; + height: 55px; +} +.ge-commands .command-dropdown .command-dropdown-icon { + height: 100%; + width: 100%; + display: grid; + align-content: center; + justify-content: center; +} +.ge-commands .command-dropdown .command-dropdown-active { + height: 100%; + width: 100%; + display: grid; + align-content: center; + justify-content: center; + font-size: 14px; +} +.ge-commands .command-dropdown:hover, .ge-commands .command-dropdown.activated { + background-color: #666666; + color: black; +} +.ge-commands .command-dropdown:active { + transform-origin: center; + transform: scale(0.95); +} +.ge-commands .command-dropdown-blocker { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + transform: scale(1); + z-index: 1; +} +.ge-commands.background-js .command-dropdown-content { + background: #333333; +} +.ge-commands.background-js .command-dropdown-content .command-dropdown-label:hover { + background: #333333; +} +.ge-commands.background-ts .command-dropdown-content .command-dropdown-label:hover { + background: #333333; +} +.ge-commands .command-dropdown-content { + background: #333333; + position: absolute; + top: 55px; + width: 55px; + transform: scale(1); +} +.ge-commands .command-dropdown-content.toRight { + width: 120px; +} +.ge-commands .command-dropdown-content .command-dropdown-label { + color: white; + padding: 5px; + padding-left: 7px; + height: 35px; + font-size: 18px; + display: grid; + align-items: center; + cursor: pointer; + user-select: none; + grid-template-columns: 1fr 20px; + grid-template-rows: 100%; + position: relative; +} +.ge-commands .command-dropdown-content .command-dropdown-label.active { + font-weight: bold; + font-size: 20px; +} +.ge-commands .command-dropdown-content .command-dropdown-label:hover { + background: var(--selectionGrey); +} +.ge-commands .command-dropdown-content .command-dropdown-label:hover .sub-items { + display: block; +} +.ge-commands .command-dropdown-content .command-dropdown-label .command-dropdown-label-text { + font-size: 12px; + grid-column: 1; + grid-row: 1; +} +.ge-commands .command-dropdown-content .command-dropdown-label .command-dropdown-label-check { + grid-column: 2; + grid-row: 1; +} +.ge-commands .command-dropdown-content .command-dropdown-label .command-dropdown-arrow { + grid-column: 2; + grid-row: 1; + font-size: 20px; + font-weight: bold; + padding-bottom: 10px; + padding-left: 4px; +} +.ge-commands .command-dropdown-content .command-dropdown-label .sub-items { + position: absolute; + left: 200px; + top: 0; + width: 150px; + display: none; +} +.ge-commands .command-dropdown-content .command-dropdown-label .sub-items.background-js { + background: #bfabff; +} +.ge-commands .command-dropdown-content .command-dropdown-label .sub-items.background-js .sub-item:hover { + background-color: #333333; + color: white; +} +.ge-commands .command-dropdown-content .command-dropdown-label .sub-items.background-ts { + background: #333333; +} +.ge-commands .command-dropdown-content .command-dropdown-label .sub-items.background-ts .sub-item:hover { + background-color: #333333; + color: white; +} +.ge-commands .command-dropdown-content .command-dropdown-label .sub-items .sub-item { + color: white; + padding: 5px; + padding-left: 10px; + height: 35px; + display: grid; +} +.ge-commands .command-dropdown-content .command-dropdown-label .sub-items .sub-item.checked { + background: white; + color: black; +} +.ge-commands .command-dropdown-content .buttonLine { + color: white; + padding: 5px; + padding-left: 7px; + height: 35px; + font-size: 18px; + display: grid; + align-items: center; + cursor: pointer; + user-select: none; + grid-template-columns: 1fr 20px; + grid-template-rows: 100%; + position: relative; + font-size: 12px; + grid-column: 1; + grid-row: 1; +} +.ge-commands .command-dropdown-content .buttonLine input[type=file] { + display: none; +} +.ge-commands .command-dropdown-content .buttonLine.active { + font-weight: bold; + font-size: 20px; + cursor: pointer; +} +.ge-commands .command-dropdown-content .buttonLine:hover { + background: var(--selectionGrey); + cursor: pointer; +} +.ge-commands .command-dropdown-content .buttonLine:hover .sub-items { + display: block; +} +.ge-commands .command-dropdown-content .buttonLine .file-upload { + cursor: pointer; +} +.ge-commands .divider { + display: flex; + align-items: center; + border-right: 1px solid black; + color: white; +} +.ge-commands .divider:last-of-type { + border-right: none; +} +.ge-commands .divider.padded { + padding-left: 10px; + padding-right: 10px; +} +.ge-commands .floatLine, +.ge-commands .checkBoxLine { + display: flex; + align-items: center; +} +.ge-commands .checkBoxLine .icon { + filter: brightness(10); +} +.ge-commands .checkBoxLine .hidden { + display: none; +} +.ge-commands .checkBoxLine .checkBox { + height: 40px; +} +.ge-commands .color3Line { + display: grid; +} +.ge-commands .color3Line .firstLine { + display: flex; + align-items: center; +} +.ge-commands .color3Line .firstLine .label { + padding-right: 5px; +} +.ge-commands .color3Line .firstLine .floatLine .value { + padding-left: 2px; +} +.ge-commands .color3Line .firstLine .copy { + display: none; +} +.ge-commands .color3Line .firstLine .expand { + display: none; +} +.ge-commands .color3Line .secondLine { + display: grid; + padding-right: 5px; + border-left: 1px solid rgb(51, 122, 183); +} +.ge-commands .color3Line .secondLine .numeric { + display: grid; + grid-template-columns: 1fr auto; +} +.ge-commands .color3Line .secondLine .numeric-label { + text-align: right; + grid-column: 1; + display: flex; + align-items: center; + justify-self: right; + margin-right: 10px; +} +.ge-commands .color3Line .secondLine .numeric-value { + width: 120px; + grid-column: 2; + display: flex; + align-items: center; + border: 1px solid rgb(51, 122, 183); +} +.ge-commands .color-picker { + height: 26px; + width: 26px; +} +.ge-commands .color-picker .color-rect-background { + width: calc(100% - 2px); + height: calc(100% - 2px); + border: 1px solid white; + cursor: pointer; + background: repeating-conic-gradient(#e2e2e2 0% 25%, white 0% 50%) 50%/100% 100%; +} +.ge-commands .color-picker .color-rect-background .color-rect { + height: 100%; +} +.ge-commands .color-picker .color-picker-cover { + position: fixed; + top: 0px; + right: 0px; + bottom: 0px; + left: 0px; + z-index: 2; +} +.ge-commands .color-picker .color-picker-float { + position: absolute; + outline: 1px solid black; +} +.ge-commands .color-picker .color-picker-container { + background-color: #e2e2e2; +} +.ge-commands .color-picker input:focus { + outline-color: black; +} +.ge-commands .floatLine input, +.ge-commands .listLine select { + background-color: #000000; + color: white; + padding: 5px; + border: none; +} +.ge-commands input, +.ge-commands .listLine select { + outline-color: transparent; + outline-width: 1px; + outline-offset: -1px; + outline-style: solid; + transition: 0.2s outline; + border: none; +} +.ge-commands .floatLine .value { + position: relative; + margin: 5px; +} +.ge-commands .floatLine input:focus { + outline-color: white; +} +.ge-commands .listLine select { + width: 150px; +} +.ge-commands .hasArrows .arrows { + display: none; + position: absolute; + right: 0; + top: 0; + flex-direction: column; + cursor: grab; + filter: brightness(10); +} +.ge-commands .hasArrows .arrows .downArrowIcon, +.ge-commands .hasArrows .arrows .upArrowIcon { + width: 13px; + height: 13px; +} +.ge-commands .hasArrows:hover .arrows, .ge-commands .hasArrows:focus .arrows, .ge-commands .hasArrows.dragging .arrows { + display: flex; +} +.ge-commands .hasArrows .arrows:hover { + background-color: var(--buttonHoverBackground); + filter: none; +} +.ge-commands .hasArrows.dragging .arrows { + background-color: var(--buttonPressedBackground); +} +.ge-commands .hasArrows.dragging .arrows .downArrowIcon, +.ge-commands .hasArrows.dragging .arrows .upArrowIcon { + filter: none; +} +.ge-commands .hasArrows input::-webkit-outer-spin-button, +.ge-commands .hasArrows input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; +} +.ge-commands .hasArrows input[type=number] { + -moz-appearance: textfield; +}`,"",{version:3,sources:["webpack://./../../../tools/guiEditor/dist/scss/commandBar.scss"],names:[],mappings:"AAAA;EACI,wBAAA;AACJ;;AAEA;EAMI,WAAA;EACA,cAAA;EACA,iBAAA;AAJJ;AAHI;EACI,mCAAA;EACA,gBAAA;EACA,eAAA;AAKR;AACI;EACI,WAAA;EACA,aAAA;AACR;AAEI;EACI,YAAA;EACA,aAAA;AAAR;AACQ;EACI,YAAA;EACA,kBAAA;EACA,WAAA;AACZ;AAMY;;EACI,gGAAA;AAHhB;AAMY;;EACI,cAAA;AAHhB;AAQgB;;;EACI,0GAAA;AAJpB;AAaY;;EACI,iEAAA;AAVhB;AAaY;;EACI,cAAA;AAVhB;AAegB;;;EACI,8BAAA;AAXpB;AAiBI;EACI,eAAA;EACA,WAAA;EACA,YAAA;AAfR;AAiBQ;EACI,aAAA;AAfZ;AAkBQ;EACI,YAAA;EACA,WAAA;EACA,aAAA;EACA,YAAA;EACA,qBAAA;EACA,uBAAA;AAhBZ;AAmBQ;EACI,wBAAA;EACA,sCAAA;AAjBZ;AAqBY;EACI,sCAAA;AAnBhB;AAuBI;EACI,sCAAA;AArBR;AAuBI;EACI,oBAAA;EACA,YAAA;AArBR;AAuBI;EACI,oBAAA;EACA,YAAA;AArBR;AAuBI;EACI,kBAAA;EACA,yBAAA;EACA,UAAA;AArBR;AAwBI;EACI,eAAA;EACA,WAAA;EACA,YAAA;AAtBR;AAwBQ;EACI,YAAA;EACA,WAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;AAtBZ;AAyBQ;EACI,YAAA;EACA,WAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;EACA,eAAA;AAvBZ;AA0BQ;EAEI,yBAAA;EACA,YAAA;AAzBZ;AA4BQ;EACI,wBAAA;EACA,sBAAA;AA1BZ;AA8BI;EACI,kBAAA;EACA,MAAA;EACA,OAAA;EACA,WAAA;EACA,YAAA;EACA,mBAAA;EACA,UAAA;AA5BR;AAgCQ;EACI,mBAAA;AA9BZ;AAgCgB;EACI,mBAAA;AA9BpB;AAuCgB;EACI,mBAAA;AArCpB;AA2CI;EACI,mBAAA;EACA,kBAAA;EACA,SAAA;EACA,WAAA;EACA,mBAAA;AAzCR;AA2CQ;EACI,YAAA;AAzCZ;AA4CQ;EACI,YAAA;EACA,YAAA;EACA,iBAAA;EACA,YAAA;EACA,eAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;EACA,iBAAA;EACA,+BAAA;EACA,wBAAA;EACA,kBAAA;AA1CZ;AA4CY;EACI,iBAAA;EACA,eAAA;AA1ChB;AA6CY;EACI,gCAAA;AA3ChB;AA4CgB;EACI,cAAA;AA1CpB;AA8CY;EACI,eAAA;EACA,cAAA;EACA,WAAA;AA5ChB;AA+CY;EACI,cAAA;EACA,WAAA;AA7ChB;AAgDY;EACI,cAAA;EACA,WAAA;EACA,eAAA;EACA,iBAAA;EACA,oBAAA;EACA,iBAAA;AA9ChB;AAiDY;EACI,kBAAA;EACA,WAAA;EACA,MAAA;EACA,YAAA;EACA,aAAA;AA/ChB;AAiDgB;EACI,mBAAA;AA/CpB;AAiDwB;EACI,yBAAA;EACA,YAAA;AA/C5B;AAoDgB;EACI,mBAAA;AAlDpB;AAoDwB;EACI,yBAAA;EACA,YAAA;AAlD5B;AAuDgB;EACI,YAAA;EACA,YAAA;EACA,kBAAA;EACA,YAAA;EACA,aAAA;AArDpB;AAuDoB;EACI,iBAAA;EACA,YAAA;AArDxB;AA2DQ;EACI,YAAA;EACA,YAAA;EACA,iBAAA;EACA,YAAA;EACA,eAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;EACA,iBAAA;EACA,+BAAA;EACA,wBAAA;EACA,kBAAA;EACA,eAAA;EACA,cAAA;EACA,WAAA;AAzDZ;AA0DY;EACI,aAAA;AAxDhB;AA2DY;EACI,iBAAA;EACA,eAAA;EACA,eAAA;AAzDhB;AA4DY;EACI,gCAAA;EAIA,eAAA;AA7DhB;AA0DgB;EACI,cAAA;AAxDpB;AA6DY;EACI,eAAA;AA3DhB;AAgEI;EACI,aAAA;EACA,mBAAA;EACA,6BAAA;EACA,YAAA;AA9DR;AA+DQ;EACI,kBAAA;AA7DZ;AA+DQ;EACI,kBAAA;EACA,mBAAA;AA7DZ;AAiEI;;EAEI,aAAA;EACA,mBAAA;AA/DR;AAmEQ;EACI,sBAAA;AAjEZ;AAoEQ;EACI,aAAA;AAlEZ;AAqEQ;EACI,YAAA;AAnEZ;AAuEI;EACI,aAAA;AArER;AAuEQ;EACI,aAAA;EACA,mBAAA;AArEZ;AAuEY;EACI,kBAAA;AArEhB;AAyEgB;EACI,iBAAA;AAvEpB;AA2EY;EACI,aAAA;AAzEhB;AA4EY;EACI,aAAA;AA1EhB;AA8EQ;EACI,aAAA;EACA,kBAAA;EACA,wCAAA;AA5EZ;AA8EY;EACI,aAAA;EACA,+BAAA;AA5EhB;AA+EY;EACI,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mBAAA;EACA,kBAAA;AA7EhB;AAgFY;EACI,YAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mCAAA;AA9EhB;AAmFI;EACI,YAAA;EACA,WAAA;AAjFR;AAmFQ;EACI,uBAAA;EACA,wBAAA;EACA,uBAAA;EACA,eAAA;EACA,gFAAA;AAjFZ;AAkFY;EACI,YAAA;AAhFhB;AAoFQ;EACI,eAAA;EACA,QAAA;EACA,UAAA;EACA,WAAA;EACA,SAAA;EACA,UAAA;AAlFZ;AAqFQ;EACI,kBAAA;EACA,wBAAA;AAnFZ;AAsFQ;EACI,yBAAA;AApFZ;AAuFQ;EACI,oBAAA;AArFZ;AAyFI;;EAEI,yBAAA;EACA,YAAA;EACA,YAAA;EACA,YAAA;AAvFR;AA0FI;;EAEI,0BAAA;EACA,kBAAA;EACA,oBAAA;EACA,oBAAA;EACA,wBAAA;EACA,YAAA;AAxFR;AA2FI;EACI,kBAAA;EACA,WAAA;AAzFR;AA4FI;EACI,oBAAA;AA1FR;AA6FI;EACI,YAAA;AA3FR;AA+FQ;EACI,aAAA;EACA,kBAAA;EACA,QAAA;EACA,MAAA;EACA,sBAAA;EACA,YAAA;EAMA,sBAAA;AAlGZ;AA6FY;;EAEI,WAAA;EACA,YAAA;AA3FhB;AA+FQ;EAGI,aAAA;AA/FZ;AAiGQ;EACI,8CAAA;EACA,YAAA;AA/FZ;AAiGQ;EACI,gDAAA;AA/FZ;AAgGY;;EAEI,YAAA;AA9FhB;AAkGI;;EAEI,wBAAA;EACA,SAAA;AAhGR;AAmGI;EACI,0BAAA;AAjGR",sourcesContent:[`:root {\r + --selectionGrey: #666666;\r +}\r +\r +.ge-commands {\r + * {\r + font-family: "acumin-pro-condensed";\r + font-weight: 600;\r + font-size: 12px;\r + }\r + grid-row: 1;\r + grid-column: 1;\r + user-select: none;\r +\r + .commands-left {\r + float: left;\r + display: flex;\r + }\r +\r + .commands-right {\r + float: right;\r + display: flex;\r + .beta-flag {\r + height: 30px;\r + position: relative;\r + left: -15px;\r + }\r + }\r +\r + &.background-ts {\r + .command-button,\r + .command-dropdown {\r + img {\r + filter: invert(64%) sepia(78%) saturate(940%) hue-rotate(323deg) brightness(105%) contrast(103%);\r + }\r +\r + .command-dropdown-active {\r + color: #333333;\r + }\r +\r + &:hover,\r + &.activated {\r + img {\r + filter: invert(34%) sepia(21%) saturate(3832%) hue-rotate(324deg) brightness(88%) contrast(82%) !important;\r + }\r + }\r + }\r + }\r +\r + &.background-js {\r + .command-button,\r + .command-dropdown {\r + img {\r + filter: invert(57%) sepia(80%) saturate(2031%) hue-rotate(215deg);\r + }\r +\r + .command-dropdown-active {\r + color: #333333;\r + }\r +\r + &:hover,\r + &.activated {\r + img {\r + filter: invert(17%) !important;\r + }\r + }\r + }\r + }\r +\r + .command-button {\r + cursor: pointer;\r + width: 55px;\r + height: 55px;\r +\r + .command-label {\r + display: none;\r + }\r +\r + .command-button-icon {\r + height: 100%;\r + width: 100%;\r + display: grid;\r + color: white;\r + align-content: center;\r + justify-content: center;\r + }\r +\r + .active {\r + transform-origin: center;\r + background-color: var(--selectionGrey);\r + }\r +\r + img {\r + &.active {\r + background-color: var(--selectionGrey);\r + }\r + }\r + }\r + .command-button:hover {\r + background-color: var(--selectionGrey);\r + }\r + .copyAndDeleteDisabled {\r + pointer-events: none;\r + color: black;\r + }\r + .pasteDisabled {\r + pointer-events: none;\r + color: black;\r + }\r + .command-dropdown-root {\r + position: relative;\r + text-transform: uppercase;\r + z-index: 1;\r + }\r +\r + .command-dropdown {\r + cursor: pointer;\r + width: 55px;\r + height: 55px;\r +\r + .command-dropdown-icon {\r + height: 100%;\r + width: 100%;\r + display: grid;\r + align-content: center;\r + justify-content: center;\r + }\r +\r + .command-dropdown-active {\r + height: 100%;\r + width: 100%;\r + display: grid;\r + align-content: center;\r + justify-content: center;\r + font-size: 14px;\r + }\r +\r + &:hover,\r + &.activated {\r + background-color: #666666;\r + color: black;\r + }\r +\r + &:active {\r + transform-origin: center;\r + transform: scale(0.95);\r + }\r + }\r +\r + .command-dropdown-blocker {\r + position: absolute;\r + top: 0;\r + left: 0;\r + width: 100%;\r + height: 100%;\r + transform: scale(1);\r + z-index: 1;\r + }\r +\r + &.background-js {\r + .command-dropdown-content {\r + background: #333333;\r + .command-dropdown-label {\r + &:hover {\r + background: #333333;\r + }\r + }\r + }\r + }\r +\r + &.background-ts {\r + .command-dropdown-content {\r + .command-dropdown-label {\r + &:hover {\r + background: #333333;\r + }\r + }\r + }\r + }\r +\r + .command-dropdown-content {\r + background: #333333;\r + position: absolute;\r + top: 55px;\r + width: 55px;\r + transform: scale(1);\r +\r + &.toRight {\r + width: 120px;\r + }\r +\r + .command-dropdown-label {\r + color: white;\r + padding: 5px;\r + padding-left: 7px;\r + height: 35px;\r + font-size: 18px;\r + display: grid;\r + align-items: center;\r + cursor: pointer;\r + user-select: none;\r + grid-template-columns: 1fr 20px;\r + grid-template-rows: 100%;\r + position: relative;\r +\r + &.active {\r + font-weight: bold;\r + font-size: 20px;\r + }\r +\r + &:hover {\r + background: var(--selectionGrey);\r + .sub-items {\r + display: block;\r + }\r + }\r +\r + .command-dropdown-label-text {\r + font-size: 12px;\r + grid-column: 1;\r + grid-row: 1;\r + }\r +\r + .command-dropdown-label-check {\r + grid-column: 2;\r + grid-row: 1;\r + }\r +\r + .command-dropdown-arrow {\r + grid-column: 2;\r + grid-row: 1;\r + font-size: 20px;\r + font-weight: bold;\r + padding-bottom: 10px;\r + padding-left: 4px;\r + }\r +\r + .sub-items {\r + position: absolute;\r + left: 200px;\r + top: 0;\r + width: 150px;\r + display: none;\r +\r + &.background-js {\r + background: #bfabff;\r + .sub-item {\r + &:hover {\r + background-color: #333333;\r + color: white;\r + }\r + }\r + }\r +\r + &.background-ts {\r + background: #333333;\r + .sub-item {\r + &:hover {\r + background-color: #333333;\r + color: white;\r + }\r + }\r + }\r +\r + .sub-item {\r + color: white;\r + padding: 5px;\r + padding-left: 10px;\r + height: 35px;\r + display: grid;\r +\r + &.checked {\r + background: white;\r + color: black;\r + }\r + }\r + }\r + }\r +\r + .buttonLine {\r + color: white;\r + padding: 5px;\r + padding-left: 7px;\r + height: 35px;\r + font-size: 18px;\r + display: grid;\r + align-items: center;\r + cursor: pointer;\r + user-select: none;\r + grid-template-columns: 1fr 20px;\r + grid-template-rows: 100%;\r + position: relative;\r + font-size: 12px;\r + grid-column: 1;\r + grid-row: 1;\r + input[type="file"] {\r + display: none;\r + }\r +\r + &.active {\r + font-weight: bold;\r + font-size: 20px;\r + cursor: pointer;\r + }\r +\r + &:hover {\r + background: var(--selectionGrey);\r + .sub-items {\r + display: block;\r + }\r + cursor: pointer;\r + }\r +\r + .file-upload {\r + cursor: pointer;\r + }\r + }\r + }\r +\r + .divider {\r + display: flex;\r + align-items: center;\r + border-right: 1px solid black;\r + color: white;\r + &:last-of-type {\r + border-right: none;\r + }\r + &.padded {\r + padding-left: 10px;\r + padding-right: 10px;\r + }\r + }\r +\r + .floatLine,\r + .checkBoxLine {\r + display: flex;\r + align-items: center;\r + }\r +\r + .checkBoxLine {\r + .icon {\r + filter: brightness(10);\r + }\r +\r + .hidden {\r + display: none;\r + }\r +\r + .checkBox {\r + height: 40px;\r + }\r + }\r +\r + .color3Line {\r + display: grid;\r +\r + .firstLine {\r + display: flex;\r + align-items: center;\r +\r + .label {\r + padding-right: 5px;\r + }\r +\r + .floatLine {\r + .value {\r + padding-left: 2px;\r + }\r + }\r +\r + .copy {\r + display: none;\r + }\r +\r + .expand {\r + display: none;\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 + .color-picker {\r + height: 26px;\r + width: 26px;\r +\r + .color-rect-background {\r + width: calc(100% - 2px);\r + height: calc(100% - 2px);\r + border: 1px solid white;\r + cursor: pointer;\r + background: repeating-conic-gradient(#e2e2e2 0% 25%, white 0% 50%) 50% / 100% 100%;\r + .color-rect {\r + height: 100%;\r + }\r + }\r +\r + .color-picker-cover {\r + position: fixed;\r + top: 0px;\r + right: 0px;\r + bottom: 0px;\r + left: 0px;\r + z-index: 2;\r + }\r +\r + .color-picker-float {\r + position: absolute;\r + outline: 1px solid black;\r + }\r +\r + .color-picker-container {\r + background-color: #e2e2e2;\r + }\r +\r + input:focus {\r + outline-color: black;\r + }\r + }\r +\r + .floatLine input,\r + .listLine select {\r + background-color: #000000;\r + color: white;\r + padding: 5px;\r + border: none;\r + }\r +\r + input,\r + .listLine select {\r + outline-color: transparent;\r + outline-width: 1px;\r + outline-offset: -1px;\r + outline-style: solid;\r + transition: 0.2s outline;\r + border: none;\r + }\r +\r + .floatLine .value {\r + position: relative;\r + margin: 5px;\r + }\r +\r + .floatLine input:focus {\r + outline-color: white;\r + }\r +\r + .listLine select {\r + width: 150px;\r + }\r +\r + .hasArrows {\r + .arrows {\r + display: none;\r + position: absolute;\r + right: 0;\r + top: 0;\r + flex-direction: column;\r + cursor: grab;\r + .downArrowIcon,\r + .upArrowIcon {\r + width: 13px;\r + height: 13px;\r + }\r + filter: brightness(10);\r + }\r + &:hover .arrows,\r + &:focus .arrows,\r + &.dragging .arrows {\r + display: flex;\r + }\r + .arrows:hover {\r + background-color: var(--buttonHoverBackground);\r + filter: none;\r + }\r + &.dragging .arrows {\r + background-color: var(--buttonPressedBackground);\r + .downArrowIcon,\r + .upArrowIcon {\r + filter: none;\r + }\r + }\r + }\r + .hasArrows input::-webkit-outer-spin-button,\r + .hasArrows input::-webkit-inner-spin-button {\r + -webkit-appearance: none;\r + margin: 0;\r + }\r +\r + .hasArrows input[type="number"] {\r + -moz-appearance: textfield;\r + }\r +}\r +`],sourceRoot:""}]),f.locals={};const d=f},"../../../../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/guiEditor/dist/scss/header.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,`#ge-header { + width: 100%; + grid-column: 2/4; + grid-row: 1; + padding: 0; + margin: 0; + display: grid; + grid-template-columns: auto 1fr; + grid-template-rows: 100%; + background: #333333; +} +#ge-header .command-bar { + padding-left: 15px; + grid-row: 1; + grid-column: 2; + width: 100%; +} +#ge-header .command-bar .language-button { + grid-row: 1; + grid-column: 2; + color: white; + width: 144px; + font-size: 18px; + text-align: center; + display: grid; + align-content: center; + border-top-left-radius: 14px; + transform: scale(1); + user-select: none; +} +#ge-header .command-bar .language-button.active { + width: 74px; + cursor: pointer; + grid-column: 1; + margin-right: -5px; + transform: translateX(10px); +}`,"",{version:3,sources:["webpack://./../../../tools/guiEditor/dist/scss/header.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,gBAAA;EACA,WAAA;EACA,UAAA;EACA,SAAA;EACA,aAAA;EACA,+BAAA;EACA,wBAAA;EACA,mBAAA;AACJ;AACI;EACI,kBAAA;EACA,WAAA;EACA,cAAA;EACA,WAAA;AACR;AACQ;EACI,WAAA;EACA,cAAA;EACA,YAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;EACA,aAAA;EACA,qBAAA;EACA,4BAAA;EACA,mBAAA;EACA,iBAAA;AACZ;AACY;EACI,WAAA;EACA,eAAA;EACA,cAAA;EACA,kBAAA;EACA,2BAAA;AAChB",sourcesContent:[`#ge-header {\r + width: 100%;\r + grid-column: 2 / 4;\r + grid-row: 1;\r + padding: 0;\r + margin: 0;\r + display: grid;\r + grid-template-columns: auto 1fr;\r + grid-template-rows: 100%;\r + background: #333333;\r +\r + .command-bar {\r + padding-left: 15px;\r + grid-row: 1;\r + grid-column: 2;\r + width: 100%;\r +\r + .language-button {\r + grid-row: 1;\r + grid-column: 2;\r + color: white;\r + width: 144px;\r + font-size: 18px;\r + text-align: center;\r + display: grid;\r + align-content: center;\r + border-top-left-radius: 14px;\r + transform: scale(1);\r + user-select: none;\r +\r + &.active {\r + width: 74px;\r + cursor: pointer;\r + grid-column: 1;\r + margin-right: -5px;\r + transform: translateX(10px);\r + }\r + }\r + }\r +}\r +`],sourceRoot:""}]),f.locals={};const d=f},"../../../../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/Button.modules.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>C});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=h("../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../dev/sharedUiComponents/dist/components/Fonts.scss"),d=_()(p());d.i(f.default,"",!0),d.push([l.id,`.\\---------dev-sharedUiComponents-dist-components-Button-modules__button { + width: 55px; + height: 55px; + border: none; + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0 0; +} +.\\---------dev-sharedUiComponents-dist-components-Button-modules__button.\\---------dev-sharedUiComponents-dist-components-Button-modules__wide { + width: 120px; + height: 45px; + justify-content: start; +} +.\\---------dev-sharedUiComponents-dist-components-Button-modules__button.\\---------dev-sharedUiComponents-dist-components-Button-modules__small { + width: 30px; + height: 30px; +} +.\\---------dev-sharedUiComponents-dist-components-Button-modules__button.\\---------dev-sharedUiComponents-dist-components-Button-modules__smaller { + width: 25px; + height: 25px; +} +.\\---------dev-sharedUiComponents-dist-components-Button-modules__button.\\---------dev-sharedUiComponents-dist-components-Button-modules__light { + background-color: #E2E2E2; + color: #333333; +} +.\\---------dev-sharedUiComponents-dist-components-Button-modules__button.\\---------dev-sharedUiComponents-dist-components-Button-modules__light:hover, .\\---------dev-sharedUiComponents-dist-components-Button-modules__button.\\---------dev-sharedUiComponents-dist-components-Button-modules__light.\\---------dev-sharedUiComponents-dist-components-Button-modules__active { + background-color: #FFFFFF; +} +.\\---------dev-sharedUiComponents-dist-components-Button-modules__button.\\---------dev-sharedUiComponents-dist-components-Button-modules__light:disabled { + background-color: #FFFFFF; +} +.\\---------dev-sharedUiComponents-dist-components-Button-modules__button.\\---------dev-sharedUiComponents-dist-components-Button-modules__dark { + background-color: #333333; + color: #FFFFFF; +} +.\\---------dev-sharedUiComponents-dist-components-Button-modules__button.\\---------dev-sharedUiComponents-dist-components-Button-modules__dark:hover, .\\---------dev-sharedUiComponents-dist-components-Button-modules__button.\\---------dev-sharedUiComponents-dist-components-Button-modules__dark.\\---------dev-sharedUiComponents-dist-components-Button-modules__active { + background-color: #666666; +}`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/components/Button.modules.scss"],names:[],mappings:"AACA;EAEI,WAAA;EACA,YAAA;EACA,YAAA;EACA,oBAAA;EACA,mBAAA;EACA,uBAAA;EACA,YAAA;AAOJ;AANI;EACI,YAAA;EACA,YAAA;EACA,sBAAA;AAQR;AANI;EACI,WAAA;EACA,YAAA;AAQR;AANI;EACI,WAAA;EACA,YAAA;AAQR;AANI;EACI,yBAAA;EACA,cAAA;AAQR;AAPQ;EAEI,yBAAA;AAQZ;AANQ;EACI,yBAAA;AAQZ;AALI;EACI,yBAAA;EACA,cAAA;AAOR;AANQ;EAEI,yBAAA;AAOZ",sourcesContent:[`@import "Colors.scss";\r +:local .button {\r + composes: fontRegular from "Fonts.scss";\r + width: 55px;\r + height: 55px;\r + border: none;\r + display: inline-flex;\r + align-items: center;\r + justify-content: center;\r + padding: 0 0;\r + &.wide {\r + width: 120px;\r + height: 45px;\r + justify-content: start;\r + }\r + &.small {\r + width: 30px;\r + height: 30px;\r + }\r + &.smaller {\r + width: 25px;\r + height: 25px;\r + }\r + &.light {\r + background-color: light-background;\r + color: dark-color;\r + &:hover,\r + &.active {\r + background-color: light-active-background;\r + }\r + &:disabled {\r + background-color: light-color;\r + }\r + }\r + &.dark {\r + background-color: dark-background;\r + color: light-color;\r + &:hover,\r + &.active {\r + background-color: dark-active-background;\r + }\r + }\r +}\r +`],sourceRoot:""}]),d.locals={"light-background":"#E2E2E2","light-active-background":"#FFFFFF","light-disabled-background":"#C8C8C8","light-color":"#FFFFFF","dark-background":"#333333","dark-active-background":"#666666","dark-color":"#333333",button:`---------dev-sharedUiComponents-dist-components-Button-modules__button ${f.default.locals.fontRegular}`,wide:"---------dev-sharedUiComponents-dist-components-Button-modules__wide",small:"---------dev-sharedUiComponents-dist-components-Button-modules__small",smaller:"---------dev-sharedUiComponents-dist-components-Button-modules__smaller",light:"---------dev-sharedUiComponents-dist-components-Button-modules__light",active:"---------dev-sharedUiComponents-dist-components-Button-modules__active",dark:"---------dev-sharedUiComponents-dist-components-Button-modules__dark"};const C=d},"../../../../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/Icon.modules.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,`.\\---------dev-sharedUiComponents-dist-components-Icon-modules__light { + filter: brightness(10); +}`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/components/Icon.modules.scss"],names:[],mappings:"AAAA;EACI,sBAAA;AACJ",sourcesContent:[`:local .light {\r + filter: brightness(10);\r +}\r +`],sourceRoot:""}]),f.locals={light:"---------dev-sharedUiComponents-dist-components-Icon-modules__light"};const d=f},"../../../../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":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.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:""}]),f.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 d=f},"../../../../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/TextInputWithSubmit.modules.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,`.\\---------dev-sharedUiComponents-dist-components-TextInputWithSubmit-modules__line { + width: 100%; + height: 100%; + display: flex; + justify-content: space-between; + align-items: center; +} + +.\\---------dev-sharedUiComponents-dist-components-TextInputWithSubmit-modules__input { + border: unset; + background-color: inherit; + flex-grow: 1; + width: 100px; +} + +.\\---------dev-sharedUiComponents-dist-components-TextInputWithSubmit-modules__valid { + background-color: white; +} + +.\\---------dev-sharedUiComponents-dist-components-TextInputWithSubmit-modules__invalid { + background-color: rgba(255, 204, 204, 0.8); +}`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/components/TextInputWithSubmit.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;EACA,aAAA;EACA,8BAAA;EACA,mBAAA;AACJ;;AAEA;EACI,aAAA;EACA,yBAAA;EACA,YAAA;EACA,YAAA;AACJ;;AAEA;EACI,uBAAA;AACJ;;AAEA;EACI,0CAAA;AACJ",sourcesContent:[`.line {\r + width: 100%;\r + height: 100%;\r + display: flex;\r + justify-content: space-between;\r + align-items: center;\r +}\r +\r +.input {\r + border: unset;\r + background-color: inherit;\r + flex-grow: 1;\r + width: 100px;\r +}\r +\r +.valid {\r + background-color: white;\r +}\r +\r +.invalid {\r + background-color: rgba(255, 204, 204, 0.8);\r +}\r +`],sourceRoot:""}]),f.locals={line:"---------dev-sharedUiComponents-dist-components-TextInputWithSubmit-modules__line",input:"---------dev-sharedUiComponents-dist-components-TextInputWithSubmit-modules__input",valid:"---------dev-sharedUiComponents-dist-components-TextInputWithSubmit-modules__valid",invalid:"---------dev-sharedUiComponents-dist-components-TextInputWithSubmit-modules__invalid"};const d=f},"../../../../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/lines/OptionsLineComponent.modules.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,`.\\---------dev-sharedUiComponents-dist-components-lines-OptionsLineComponent-modules__optionsLine { + font-family: "acumin-pro-condensed", sans-serif; + font-size: 12px; + height: 25px; + padding-left: 15px; +} + +.\\---------dev-sharedUiComponents-dist-components-lines-OptionsLineComponent-modules__optionsSelect { + width: 100%; + height: 100%; + border: unset; +}`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/components/lines/OptionsLineComponent.modules.scss"],names:[],mappings:"AAAA;EACI,+CAAA;EACA,eAAA;EACA,YAAA;EACA,kBAAA;AACJ;;AAEA;EACI,WAAA;EACA,YAAA;EACA,aAAA;AACJ",sourcesContent:[`.optionsLine {\r + font-family: "acumin-pro-condensed", sans-serif;\r + font-size: 12px;\r + height: 25px;\r + padding-left: 15px;\r +}\r +\r +.optionsSelect {\r + width: 100%;\r + height: 100%;\r + border: unset;\r +}\r +`],sourceRoot:""}]),f.locals={optionsLine:"---------dev-sharedUiComponents-dist-components-lines-OptionsLineComponent-modules__optionsLine",optionsSelect:"---------dev-sharedUiComponents-dist-components-lines-OptionsLineComponent-modules__optionsSelect"};const d=f},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../dev/sharedUiComponents/dist/components/Fonts.scss":(l,c,h)=>{h.r(c),h.d(c,{default:()=>d});var u=h("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),p=h.n(u),m=h("../../../../node_modules/css-loader/dist/runtime/api.js"),_=h.n(m),f=_()(p());f.push([l.id,"@import url(https://use.typekit.net/xfi0rwe.css);"]),f.push([l.id,`.\\---------dev-sharedUiComponents-dist-components-Fonts__fontRegular { + font-family: "acumin-pro-condensed"; + font-size: 14px; +} +`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/components/Fonts.scss"],names:[],mappings:"AACA;IACI,mCAAmC;IACnC,eAAe;AACnB",sourcesContent:[`@import url(https://use.typekit.net/xfi0rwe.css);\r +:local(.fontRegular) {\r + font-family: "acumin-pro-condensed";\r + font-size: 14px;\r +}\r +`],sourceRoot:""}]),f.locals={fontRegular:"---------dev-sharedUiComponents-dist-components-Fonts__fontRegular"};const d=f},"../../../../node_modules/@fortawesome/react-fontawesome/index.es.js":(l,c,h)=>{h.r(c),h.d(c,{FontAwesomeIcon:()=>H});var u=h("../../../../node_modules/@fortawesome/fontawesome-svg-core/index.mjs"),p=h("../../../../node_modules/prop-types/index.js"),m=h.n(p),_=h("../../../../node_modules/react/index.js");function f(J,te){var re=Object.keys(J);if(Object.getOwnPropertySymbols){var ee=Object.getOwnPropertySymbols(J);te&&(ee=ee.filter(function(oe){return Object.getOwnPropertyDescriptor(J,oe).enumerable})),re.push.apply(re,ee)}return re}function d(J){for(var te=1;te=0)&&(re[oe]=J[oe]);return re}function M(J,te){if(J==null)return{};var re=y(J,te),ee,oe;if(Object.getOwnPropertySymbols){var ae=Object.getOwnPropertySymbols(J);for(oe=0;oe=0)&&(!Object.prototype.propertyIsEnumerable.call(J,ee)||(re[ee]=J[ee]))}return re}function b(J){return E(J)||S(J)||I(J)||R()}function E(J){if(Array.isArray(J))return D(J)}function S(J){if(typeof Symbol<"u"&&J[Symbol.iterator]!=null||J["@@iterator"]!=null)return Array.from(J)}function I(J,te){if(!!J){if(typeof J=="string")return D(J,te);var re=Object.prototype.toString.call(J).slice(8,-1);if(re==="Object"&&J.constructor&&(re=J.constructor.name),re==="Map"||re==="Set")return Array.from(J);if(re==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(re))return D(J,te)}}function D(J,te){(te==null||te>J.length)&&(te=J.length);for(var re=0,ee=new Array(te);re2&&arguments[2]!==void 0?arguments[2]:{};if(typeof te=="string")return te;var ee=(te.children||[]).map(function(me){return ie(J,me)}),oe=Object.keys(te.attributes||{}).reduce(function(me,Fe){var je=te.attributes[Fe];switch(Fe){case"class":me.attrs.className=je,delete te.attributes.class;break;case"style":me.attrs.style=G(je);break;default:Fe.indexOf("aria-")===0||Fe.indexOf("data-")===0?me.attrs[Fe.toLowerCase()]=je:me.attrs[N(Fe)]=je}return me},{attrs:{}}),ae=re.style,fe=ae===void 0?{}:ae,de=M(re,V);return oe.attrs.style=d(d({},oe.attrs.style),fe),J.apply(void 0,[te.tag,d(d({},oe.attrs),de)].concat(b(ee)))}var Z=!1;try{Z=!1}catch{}function q(){if(!Z&&console&&typeof console.error=="function"){var J;(J=console).error.apply(J,arguments)}}function K(J){if(J&&C(J)==="object"&&J.prefix&&J.iconName&&J.icon)return J;if(u.parse.icon)return u.parse.icon(J);if(J===null)return null;if(J&&C(J)==="object"&&J.prefix&&J.iconName)return J;if(Array.isArray(J)&&J.length===2)return{prefix:J[0],iconName:J[1]};if(typeof J=="string")return{prefix:"fas",iconName:J}}function j(J,te){return Array.isArray(te)&&te.length>0||!Array.isArray(te)&&te?v({},J,te):{}}var H=_.forwardRef(function(J,te){var re=J.icon,ee=J.mask,oe=J.symbol,ae=J.className,fe=J.title,de=J.titleId,me=J.maskId,Fe=K(re),je=j("classes",[].concat(b(L(J)),b(ae.split(" ")))),nt=j("transform",typeof J.transform=="string"?u.parse.transform(J.transform):J.transform),we=j("mask",K(ee)),Ke=(0,u.icon)(Fe,d(d(d(d({},je),nt),we),{},{symbol:oe,title:fe,titleId:de,maskId:me}));if(!Ke)return q("Could not find icon",Fe),null;var ft=Ke.abstract,yt={ref:te};return Object.keys(J).forEach(function(Ze){H.defaultProps.hasOwnProperty(Ze)||(yt[Ze]=J[Ze])}),Y(ft[0],yt)});H.displayName="FontAwesomeIcon",H.propTypes={beat:m().bool,border:m().bool,beatFade:m().bool,bounce:m().bool,className:m().string,fade:m().bool,flash:m().bool,mask:m().oneOfType([m().object,m().array,m().string]),maskId:m().string,fixedWidth:m().bool,inverse:m().bool,flip:m().oneOf([!0,!1,"horizontal","vertical","both"]),icon:m().oneOfType([m().object,m().array,m().string]),listItem:m().bool,pull:m().oneOf(["right","left"]),pulse:m().bool,rotation:m().oneOf([0,90,180,270]),shake:m().bool,size:m().oneOf(["2xs","xs","sm","lg","xl","2xl","1x","2x","3x","4x","5x","6x","7x","8x","9x","10x"]),spin:m().bool,spinPulse:m().bool,spinReverse:m().bool,symbol:m().oneOfType([m().bool,m().string]),title:m().string,titleId:m().string,transform:m().oneOfType([m().string,m().object]),swapOpacity:m().bool},H.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 Y=ie.bind(null,_.createElement)},"../../../../node_modules/classnames/index.js":(l,c)=>{var h,u;/*! + Copyright (c) 2018 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames +*/(function(){var p={}.hasOwnProperty;function m(){for(var _=[],f=0;f{l.exports=function(c){var h=[];return h.toString=function(){return this.map(function(p){var m="",_=typeof p[5]<"u";return p[4]&&(m+="@supports (".concat(p[4],") {")),p[2]&&(m+="@media ".concat(p[2]," {")),_&&(m+="@layer".concat(p[5].length>0?" ".concat(p[5]):""," {")),m+=c(p),_&&(m+="}"),p[2]&&(m+="}"),p[4]&&(m+="}"),m}).join("")},h.i=function(p,m,_,f,d){typeof p=="string"&&(p=[[null,p,void 0]]);var C={};if(_)for(var v=0;v"u"||(b[1]="@layer".concat(b[5].length>0?" ".concat(b[5]):""," {").concat(b[1],"}")),b[5]=d),m&&(b[2]&&(b[1]="@media ".concat(b[2]," {").concat(b[1],"}")),b[2]=m),f&&(b[4]?(b[1]="@supports (".concat(b[4],") {").concat(b[1],"}"),b[4]=f):b[4]="".concat(f)),h.push(b))}},h}},"../../../../node_modules/css-loader/dist/runtime/sourceMaps.js":l=>{l.exports=function(c){var h=c[1],u=c[3];if(!u)return h;if(typeof btoa=="function"){var p=btoa(unescape(encodeURIComponent(JSON.stringify(u)))),m="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(p),_="/*# ".concat(m," */");return[h].concat([_]).join(` +`)}return[h].join(` +`)}},"../../../../node_modules/object-assign/index.js":l=>{/* +object-assign +(c) Sindre Sorhus +@license MIT +*/var c=Object.getOwnPropertySymbols,h=Object.prototype.hasOwnProperty,u=Object.prototype.propertyIsEnumerable;function p(_){if(_==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(_)}function m(){try{if(!Object.assign)return!1;var _=new String("abc");if(_[5]="de",Object.getOwnPropertyNames(_)[0]==="5")return!1;for(var f={},d=0;d<10;d++)f["_"+String.fromCharCode(d)]=d;var C=Object.getOwnPropertyNames(f).map(function(y){return f[y]});if(C.join("")!=="0123456789")return!1;var v={};return"abcdefghijklmnopqrst".split("").forEach(function(y){v[y]=y}),Object.keys(Object.assign({},v)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}l.exports=m()?Object.assign:function(_,f){for(var d,C=p(_),v,y=1;y{var u=function(){};{var p=h("../../../../node_modules/prop-types/lib/ReactPropTypesSecret.js"),m={},_=h("../../../../node_modules/prop-types/lib/has.js");u=function(d){var C="Warning: "+d;typeof console<"u"&&console.error(C);try{throw new Error(C)}catch{}}}function f(d,C,v,y,M){for(var b in d)if(_(d,b)){var E;try{if(typeof d[b]!="function"){var S=Error((y||"React class")+": "+v+" type `"+b+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof d[b]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw S.name="Invariant Violation",S}E=d[b](C,b,y,v,null,p)}catch(D){E=D}if(E&&!(E instanceof Error)&&u((y||"React class")+": type specification of "+v+" `"+b+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof E+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."),E instanceof Error&&!(E.message in m)){m[E.message]=!0;var I=M?M():"";u("Failed "+v+" type: "+E.message+(I??""))}}}f.resetWarningCache=function(){m={}},l.exports=f},"../../../../node_modules/prop-types/factoryWithTypeCheckers.js":(l,c,h)=>{var u=h("../../../../node_modules/prop-types/node_modules/react-is/index.js"),p=h("../../../../node_modules/object-assign/index.js"),m=h("../../../../node_modules/prop-types/lib/ReactPropTypesSecret.js"),_=h("../../../../node_modules/prop-types/lib/has.js"),f=h("../../../../node_modules/prop-types/checkPropTypes.js"),d=function(){};d=function(v){var y="Warning: "+v;typeof console<"u"&&console.error(y);try{throw new Error(y)}catch{}};function C(){return null}l.exports=function(v,y){var M=typeof Symbol=="function"&&Symbol.iterator,b="@@iterator";function E(de){var me=de&&(M&&de[M]||de[b]);if(typeof me=="function")return me}var S="<>",I={array:w("array"),bigint:w("bigint"),bool:w("boolean"),func:w("function"),number:w("number"),object:w("object"),string:w("string"),symbol:w("symbol"),any:N(),arrayOf:V,element:W(),elementType:G(),instanceOf:ie,node:j(),objectOf:q,oneOf:Z,oneOfType:K,shape:Y,exact:J};function D(de,me){return de===me?de!==0||1/de===1/me:de!==de&&me!==me}function R(de,me){this.message=de,this.data=me&&typeof me=="object"?me:{},this.stack=""}R.prototype=Error.prototype;function L(de){var me={},Fe=0;function je(we,Ke,ft,yt,Ze,mt,Je){if(yt=yt||S,mt=mt||ft,Je!==m){if(y){var Yt=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 Yt.name="Invariant Violation",Yt}else if(typeof console<"u"){var Vt=yt+":"+ft;!me[Vt]&&Fe<3&&(d("You are manually calling a React.PropTypes validation function for the `"+mt+"` prop on `"+yt+"`. 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."),me[Vt]=!0,Fe++)}}return Ke[ft]==null?we?Ke[ft]===null?new R("The "+Ze+" `"+mt+"` is marked as required "+("in `"+yt+"`, but its value is `null`.")):new R("The "+Ze+" `"+mt+"` is marked as required in "+("`"+yt+"`, but its value is `undefined`.")):null:de(Ke,ft,yt,Ze,mt)}var nt=je.bind(null,!1);return nt.isRequired=je.bind(null,!0),nt}function w(de){function me(Fe,je,nt,we,Ke,ft){var yt=Fe[je],Ze=ee(yt);if(Ze!==de){var mt=oe(yt);return new R("Invalid "+we+" `"+Ke+"` of type "+("`"+mt+"` supplied to `"+nt+"`, expected ")+("`"+de+"`."),{expectedType:de})}return null}return L(me)}function N(){return L(C)}function V(de){function me(Fe,je,nt,we,Ke){if(typeof de!="function")return new R("Property `"+Ke+"` of component `"+nt+"` has invalid PropType notation inside arrayOf.");var ft=Fe[je];if(!Array.isArray(ft)){var yt=ee(ft);return new R("Invalid "+we+" `"+Ke+"` of type "+("`"+yt+"` supplied to `"+nt+"`, expected an array."))}for(var Ze=0;Ze1?d("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])."):d("Invalid argument supplied to oneOf, expected an array."),C;function me(Fe,je,nt,we,Ke){for(var ft=Fe[je],yt=0;yt0?", expected one of type ["+Ze.join(", ")+"]":"";return new R("Invalid "+ft+" `"+yt+"` supplied to "+("`"+Ke+"`"+Vt+"."))}return L(je)}function j(){function de(me,Fe,je,nt,we){return te(me[Fe])?null:new R("Invalid "+nt+" `"+we+"` supplied to "+("`"+je+"`, expected a ReactNode."))}return L(de)}function H(de,me,Fe,je,nt){return new R((de||"React class")+": "+me+" type `"+Fe+"."+je+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+nt+"`.")}function Y(de){function me(Fe,je,nt,we,Ke){var ft=Fe[je],yt=ee(ft);if(yt!=="object")return new R("Invalid "+we+" `"+Ke+"` of type `"+yt+"` "+("supplied to `"+nt+"`, expected `object`."));for(var Ze in de){var mt=de[Ze];if(typeof mt!="function")return H(nt,we,Ke,Ze,oe(mt));var Je=mt(ft,Ze,nt,we,Ke+"."+Ze,m);if(Je)return Je}return null}return L(me)}function J(de){function me(Fe,je,nt,we,Ke){var ft=Fe[je],yt=ee(ft);if(yt!=="object")return new R("Invalid "+we+" `"+Ke+"` of type `"+yt+"` "+("supplied to `"+nt+"`, expected `object`."));var Ze=p({},Fe[je],de);for(var mt in Ze){var Je=de[mt];if(_(de,mt)&&typeof Je!="function")return H(nt,we,Ke,mt,oe(Je));if(!Je)return new R("Invalid "+we+" `"+Ke+"` key `"+mt+"` supplied to `"+nt+"`.\nBad object: "+JSON.stringify(Fe[je],null," ")+` +Valid keys: `+JSON.stringify(Object.keys(de),null," "));var Yt=Je(ft,mt,nt,we,Ke+"."+mt,m);if(Yt)return Yt}return null}return L(me)}function te(de){switch(typeof de){case"number":case"string":case"undefined":return!0;case"boolean":return!de;case"object":if(Array.isArray(de))return de.every(te);if(de===null||v(de))return!0;var me=E(de);if(me){var Fe=me.call(de),je;if(me!==de.entries){for(;!(je=Fe.next()).done;)if(!te(je.value))return!1}else for(;!(je=Fe.next()).done;){var nt=je.value;if(nt&&!te(nt[1]))return!1}}else return!1;return!0;default:return!1}}function re(de,me){return de==="symbol"?!0:me?me["@@toStringTag"]==="Symbol"||typeof Symbol=="function"&&me instanceof Symbol:!1}function ee(de){var me=typeof de;return Array.isArray(de)?"array":de instanceof RegExp?"object":re(me,de)?"symbol":me}function oe(de){if(typeof de>"u"||de===null)return""+de;var me=ee(de);if(me==="object"){if(de instanceof Date)return"date";if(de instanceof RegExp)return"regexp"}return me}function ae(de){var me=oe(de);switch(me){case"array":case"object":return"an "+me;case"boolean":case"date":case"regexp":return"a "+me;default:return me}}function fe(de){return!de.constructor||!de.constructor.name?S:de.constructor.name}return I.checkPropTypes=f,I.resetWarningCache=f.resetWarningCache,I.PropTypes=I,I}},"../../../../node_modules/prop-types/index.js":(l,c,h)=>{{var u=h("../../../../node_modules/prop-types/node_modules/react-is/index.js"),p=!0;l.exports=h("../../../../node_modules/prop-types/factoryWithTypeCheckers.js")(u.isElement,p)}},"../../../../node_modules/prop-types/lib/ReactPropTypesSecret.js":l=>{var c="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";l.exports=c},"../../../../node_modules/prop-types/lib/has.js":l=>{l.exports=Function.call.bind(Object.prototype.hasOwnProperty)},"../../../../node_modules/prop-types/node_modules/react-is/cjs/react-is.development.js":(l,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 h=typeof Symbol=="function"&&Symbol.for,u=h?Symbol.for("react.element"):60103,p=h?Symbol.for("react.portal"):60106,m=h?Symbol.for("react.fragment"):60107,_=h?Symbol.for("react.strict_mode"):60108,f=h?Symbol.for("react.profiler"):60114,d=h?Symbol.for("react.provider"):60109,C=h?Symbol.for("react.context"):60110,v=h?Symbol.for("react.async_mode"):60111,y=h?Symbol.for("react.concurrent_mode"):60111,M=h?Symbol.for("react.forward_ref"):60112,b=h?Symbol.for("react.suspense"):60113,E=h?Symbol.for("react.suspense_list"):60120,S=h?Symbol.for("react.memo"):60115,I=h?Symbol.for("react.lazy"):60116,D=h?Symbol.for("react.block"):60121,R=h?Symbol.for("react.fundamental"):60117,L=h?Symbol.for("react.responder"):60118,w=h?Symbol.for("react.scope"):60119;function N(Je){return typeof Je=="string"||typeof Je=="function"||Je===m||Je===y||Je===f||Je===_||Je===b||Je===E||typeof Je=="object"&&Je!==null&&(Je.$$typeof===I||Je.$$typeof===S||Je.$$typeof===d||Je.$$typeof===C||Je.$$typeof===M||Je.$$typeof===R||Je.$$typeof===L||Je.$$typeof===w||Je.$$typeof===D)}function V(Je){if(typeof Je=="object"&&Je!==null){var Yt=Je.$$typeof;switch(Yt){case u:var Vt=Je.type;switch(Vt){case v:case y:case m:case f:case _:case b:return Vt;default:var Ot=Vt&&Vt.$$typeof;switch(Ot){case C:case M:case I:case S:case d:return Ot;default:return Yt}}case p:return Yt}}}var W=v,G=y,ie=C,Z=d,q=u,K=M,j=m,H=I,Y=S,J=p,te=f,re=_,ee=b,oe=!1;function ae(Je){return oe||(oe=!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.")),fe(Je)||V(Je)===v}function fe(Je){return V(Je)===y}function de(Je){return V(Je)===C}function me(Je){return V(Je)===d}function Fe(Je){return typeof Je=="object"&&Je!==null&&Je.$$typeof===u}function je(Je){return V(Je)===M}function nt(Je){return V(Je)===m}function we(Je){return V(Je)===I}function Ke(Je){return V(Je)===S}function ft(Je){return V(Je)===p}function yt(Je){return V(Je)===f}function Ze(Je){return V(Je)===_}function mt(Je){return V(Je)===b}c.AsyncMode=W,c.ConcurrentMode=G,c.ContextConsumer=ie,c.ContextProvider=Z,c.Element=q,c.ForwardRef=K,c.Fragment=j,c.Lazy=H,c.Memo=Y,c.Portal=J,c.Profiler=te,c.StrictMode=re,c.Suspense=ee,c.isAsyncMode=ae,c.isConcurrentMode=fe,c.isContextConsumer=de,c.isContextProvider=me,c.isElement=Fe,c.isForwardRef=je,c.isFragment=nt,c.isLazy=we,c.isMemo=Ke,c.isPortal=ft,c.isProfiler=yt,c.isStrictMode=Ze,c.isSuspense=mt,c.isValidElementType=N,c.typeOf=V})()},"../../../../node_modules/prop-types/node_modules/react-is/index.js":(l,c,h)=>{l.exports=h("../../../../node_modules/prop-types/node_modules/react-is/cjs/react-is.development.js")},"../../../../node_modules/react-contextmenu/es6/AbstractMenu.js":(l,c,h)=>{function u(V){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(W){return typeof W}:function(W){return W&&typeof Symbol=="function"&&W.constructor===Symbol&&W!==Symbol.prototype?"symbol":typeof W},u(V)}Object.defineProperty(c,"__esModule",{value:!0}),c.default=void 0;var p=C(h("../../../../node_modules/react/index.js")),m=f(h("../../../../node_modules/prop-types/index.js")),_=f(h("../../../../node_modules/react-contextmenu/es6/MenuItem.js"));function f(V){return V&&V.__esModule?V:{default:V}}function d(V){if(typeof WeakMap!="function")return null;var W=new WeakMap,G=new WeakMap;return(d=function(Z){return Z?G:W})(V)}function C(V,W){if(!W&&V&&V.__esModule)return V;if(V===null||u(V)!=="object"&&typeof V!="function")return{default:V};var G=d(W);if(G&&G.has(V))return G.get(V);var ie={},Z=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var q in V)if(q!=="default"&&Object.prototype.hasOwnProperty.call(V,q)){var K=Z?Object.getOwnPropertyDescriptor(V,q):null;K&&(K.get||K.set)?Object.defineProperty(ie,q,K):ie[q]=V[q]}return ie.default=V,G&&G.set(V,ie),ie}function v(V,W){for(var G=0;G"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function L(V){return L=Object.setPrototypeOf?Object.getPrototypeOf:function(G){return G.__proto__||Object.getPrototypeOf(G)},L(V)}function w(V,W,G){return W in V?Object.defineProperty(V,W,{value:G,enumerable:!0,configurable:!0,writable:!0}):V[W]=G,V}var N=function(V){b(G,V);var W=S(G);function G(ie){var Z;return M(this,G),Z=W.call(this,ie),w(D(Z),"handleKeyNavigation",function(q){if(Z.state.isVisible!==!1)switch(q.keyCode){case 37:case 27:q.preventDefault(),Z.hideMenu(q);break;case 38:q.preventDefault(),Z.selectChildren(!0);break;case 40:q.preventDefault(),Z.selectChildren(!1);break;case 39:Z.tryToOpenSubMenu(q);break;case 13:q.preventDefault(),Z.tryToOpenSubMenu(q);{var K=Z.seletedItemRef&&Z.seletedItemRef.props&&Z.seletedItemRef.props.disabled;Z.seletedItemRef&&Z.seletedItemRef.ref instanceof HTMLElement&&!K?Z.seletedItemRef.ref.click():Z.hideMenu(q)}break}}),w(D(Z),"handleForceClose",function(){Z.setState({forceSubMenuOpen:!1})}),w(D(Z),"tryToOpenSubMenu",function(q){Z.state.selectedItem&&Z.state.selectedItem.type===Z.getSubMenuType()&&(q.preventDefault(),Z.setState({forceSubMenuOpen:!0}))}),w(D(Z),"selectChildren",function(q){var K=Z.state.selectedItem,j=[],H=0,Y={},J=function oe(ae,fe){!ae||([_.default,Z.getSubMenuType()].indexOf(ae.type)<0?p.default.Children.forEach(ae.props.children,oe):ae.props.divider||(ae.props.disabled&&(++H,Y[fe]=!0),j.push(ae)))};if(p.default.Children.forEach(Z.props.children,J),H===j.length)return;function te(oe){var ae=oe,fe=function(){q?--ae:++ae,ae<0?ae=j.length-1:ae>=j.length&&(ae=0)};do fe();while(ae!==oe&&Y[ae]);return ae===oe?null:ae}var re=j.indexOf(K),ee=te(re);ee!==null&&Z.setState({selectedItem:j[ee],forceSubMenuOpen:!1})}),w(D(Z),"onChildMouseMove",function(q){Z.state.selectedItem!==q&&Z.setState({selectedItem:q,forceSubMenuOpen:!1})}),w(D(Z),"onChildMouseLeave",function(){Z.setState({selectedItem:null,forceSubMenuOpen:!1})}),w(D(Z),"renderChildren",function(q){return p.default.Children.map(q,function(K){var j={};return p.default.isValidElement(K)?[_.default,Z.getSubMenuType()].indexOf(K.type)<0?(j.children=Z.renderChildren(K.props.children),p.default.cloneElement(K,j)):(j.onMouseLeave=Z.onChildMouseLeave.bind(D(Z)),K.type===Z.getSubMenuType()&&(j.forceOpen=Z.state.forceSubMenuOpen&&Z.state.selectedItem===K,j.forceClose=Z.handleForceClose,j.parentKeyNavigationHandler=Z.handleKeyNavigation),!K.props.divider&&Z.state.selectedItem===K?(j.selected=!0,j.ref=function(H){Z.seletedItemRef=H},p.default.cloneElement(K,j)):(j.onMouseMove=function(){return Z.onChildMouseMove(K)},p.default.cloneElement(K,j))):K})}),Z.seletedItemRef=null,Z.state={selectedItem:null,forceSubMenuOpen:!1},Z}return y(G)}(p.Component);c.default=N,w(N,"propTypes",{children:m.default.node.isRequired})},"../../../../node_modules/react-contextmenu/es6/ContextMenu.js":(l,c,h)=>{function u(Z){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(q){return typeof q}:function(q){return q&&typeof Symbol=="function"&&q.constructor===Symbol&&q!==Symbol.prototype?"symbol":typeof q},u(Z)}Object.defineProperty(c,"__esModule",{value:!0}),c.default=void 0;var p=b(h("../../../../node_modules/react/index.js")),m=b(h("../../../../node_modules/prop-types/index.js")),_=b(h("../../../../node_modules/classnames/index.js")),f=b(h("../../../../node_modules/object-assign/index.js")),d=b(h("../../../../node_modules/react-contextmenu/es6/globalEventListener.js")),C=b(h("../../../../node_modules/react-contextmenu/es6/AbstractMenu.js")),v=b(h("../../../../node_modules/react-contextmenu/es6/SubMenu.js")),y=h("../../../../node_modules/react-contextmenu/es6/actions.js"),M=h("../../../../node_modules/react-contextmenu/es6/helpers.js");function b(Z){return Z&&Z.__esModule?Z:{default:Z}}function E(Z,q){if(!(Z instanceof q))throw new TypeError("Cannot call a class as a function")}function S(Z,q){for(var K=0;K"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function W(Z){return W=Object.setPrototypeOf?Object.getPrototypeOf:function(K){return K.__proto__||Object.getPrototypeOf(K)},W(Z)}function G(Z,q,K){return q in Z?Object.defineProperty(Z,q,{value:K,enumerable:!0,configurable:!0,writable:!0}):Z[q]=K,Z}var ie=function(Z){D(K,Z);var q=L(K);function K(j){var H;return E(this,K),H=q.call(this,j),G(N(H),"registerHandlers",function(){document.addEventListener("mousedown",H.handleOutsideClick),document.addEventListener("touchstart",H.handleOutsideClick),H.props.preventHideOnScroll||document.addEventListener("scroll",H.handleHide),H.props.preventHideOnContextMenu||document.addEventListener("contextmenu",H.handleHide),document.addEventListener("keydown",H.handleKeyNavigation),H.props.preventHideOnResize||window.addEventListener("resize",H.handleHide)}),G(N(H),"unregisterHandlers",function(){document.removeEventListener("mousedown",H.handleOutsideClick),document.removeEventListener("touchstart",H.handleOutsideClick),document.removeEventListener("scroll",H.handleHide),document.removeEventListener("contextmenu",H.handleHide),document.removeEventListener("keydown",H.handleKeyNavigation),window.removeEventListener("resize",H.handleHide)}),G(N(H),"handleShow",function(Y){if(!(Y.detail.id!==H.props.id||H.state.isVisible)){var J=Y.detail.position,te=J.x,re=J.y;H.setState({isVisible:!0,x:te,y:re}),H.registerHandlers(),(0,M.callIfExists)(H.props.onShow,Y)}}),G(N(H),"handleHide",function(Y){H.state.isVisible&&(!Y.detail||!Y.detail.id||Y.detail.id===H.props.id)&&(H.unregisterHandlers(),H.setState({isVisible:!1,selectedItem:null,forceSubMenuOpen:!1}),(0,M.callIfExists)(H.props.onHide,Y))}),G(N(H),"handleOutsideClick",function(Y){H.menu.contains(Y.target)||(0,y.hideMenu)()}),G(N(H),"handleMouseLeave",function(Y){Y.preventDefault(),(0,M.callIfExists)(H.props.onMouseLeave,Y,(0,f.default)({},H.props.data,M.store.data),M.store.target),H.props.hideOnLeave&&(0,y.hideMenu)()}),G(N(H),"handleContextMenu",function(Y){H.handleHide(Y)}),G(N(H),"hideMenu",function(Y){(Y.keyCode===27||Y.keyCode===13)&&(0,y.hideMenu)()}),G(N(H),"getMenuPosition",function(){var Y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,J=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,te={top:J,left:Y};if(!H.menu)return te;var re=window,ee=re.innerWidth,oe=re.innerHeight,ae=H.menu.getBoundingClientRect();return J+ae.height>oe&&(te.top-=ae.height),Y+ae.width>ee&&(te.left-=ae.width),te.top<0&&(te.top=ae.height0&&arguments[0]!==void 0?arguments[0]:0,J=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,te={top:J,left:Y};if(!H.menu)return te;var re=window,ee=re.innerWidth,oe=re.innerHeight,ae=H.menu.getBoundingClientRect();return te.left=Y-ae.width,J+ae.height>oe&&(te.top-=ae.height),te.left<0&&(te.left+=ae.width),te.top<0&&(te.top=ae.heightee&&(te.left=ae.width{function u(ie){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Z){return typeof Z}:function(Z){return Z&&typeof Symbol=="function"&&Z.constructor===Symbol&&Z!==Symbol.prototype?"symbol":typeof Z},u(ie)}Object.defineProperty(c,"__esModule",{value:!0}),c.default=void 0;var p=M(h("../../../../node_modules/react/index.js")),m=v(h("../../../../node_modules/prop-types/index.js")),_=v(h("../../../../node_modules/classnames/index.js")),f=v(h("../../../../node_modules/object-assign/index.js")),d=h("../../../../node_modules/react-contextmenu/es6/actions.js"),C=h("../../../../node_modules/react-contextmenu/es6/helpers.js");function v(ie){return ie&&ie.__esModule?ie:{default:ie}}function y(ie){if(typeof WeakMap!="function")return null;var Z=new WeakMap,q=new WeakMap;return(y=function(j){return j?q:Z})(ie)}function M(ie,Z){if(!Z&&ie&&ie.__esModule)return ie;if(ie===null||u(ie)!=="object"&&typeof ie!="function")return{default:ie};var q=y(Z);if(q&&q.has(ie))return q.get(ie);var K={},j=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var H in ie)if(H!=="default"&&Object.prototype.hasOwnProperty.call(ie,H)){var Y=j?Object.getOwnPropertyDescriptor(ie,H):null;Y&&(Y.get||Y.set)?Object.defineProperty(K,H,Y):K[H]=ie[H]}return K.default=ie,q&&q.set(ie,K),K}function b(ie,Z){if(!(ie instanceof Z))throw new TypeError("Cannot call a class as a function")}function E(ie,Z){for(var q=0;q"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function V(ie){return V=Object.setPrototypeOf?Object.getPrototypeOf:function(q){return q.__proto__||Object.getPrototypeOf(q)},V(ie)}function W(ie,Z,q){return Z in ie?Object.defineProperty(ie,Z,{value:q,enumerable:!0,configurable:!0,writable:!0}):ie[Z]=q,ie}var G=function(ie){I(q,ie);var Z=R(q);function q(){var K;b(this,q);for(var j=arguments.length,H=new Array(j),Y=0;Y=0&&J.button===0&&(J.persist(),J.stopPropagation(),K.mouseDownTimeoutId=setTimeout(function(){return K.handleContextClick(J)},K.props.holdToDisplay)),(0,C.callIfExists)(K.props.attributes.onMouseDown,J)}),W(w(K),"handleMouseUp",function(J){J.button===0&&clearTimeout(K.mouseDownTimeoutId),(0,C.callIfExists)(K.props.attributes.onMouseUp,J)}),W(w(K),"handleMouseOut",function(J){J.button===0&&clearTimeout(K.mouseDownTimeoutId),(0,C.callIfExists)(K.props.attributes.onMouseOut,J)}),W(w(K),"handleTouchstart",function(J){K.touchHandled=!1,K.props.holdToDisplay>=0&&(J.persist(),J.stopPropagation(),K.touchstartTimeoutId=setTimeout(function(){K.handleContextClick(J),K.touchHandled=!0},K.props.holdToDisplay)),(0,C.callIfExists)(K.props.attributes.onTouchStart,J)}),W(w(K),"handleTouchEnd",function(J){K.touchHandled&&J.preventDefault(),clearTimeout(K.touchstartTimeoutId),(0,C.callIfExists)(K.props.attributes.onTouchEnd,J)}),W(w(K),"handleContextMenu",function(J){J.button===K.props.mouseButton&&K.handleContextClick(J),(0,C.callIfExists)(K.props.attributes.onContextMenu,J)}),W(w(K),"handleMouseClick",function(J){J.button===K.props.mouseButton&&K.handleContextClick(J),(0,C.callIfExists)(K.props.attributes.onClick,J)}),W(w(K),"handleContextClick",function(J){if(!K.props.disable&&!(K.props.disableIfShiftIsPressed&&J.shiftKey)){J.preventDefault(),J.stopPropagation();var te=J.clientX||J.touches&&J.touches[0].pageX,re=J.clientY||J.touches&&J.touches[0].pageY;K.props.posX&&(te-=K.props.posX),K.props.posY&&(re-=K.props.posY),(0,d.hideMenu)();var ee=(0,C.callIfExists)(K.props.collect,K.props),oe={position:{x:te,y:re},target:K.elem,id:K.props.id};ee&&typeof ee.then=="function"?ee.then(function(ae){oe.data=(0,f.default)({},ae,{target:J.target}),(0,d.showMenu)(oe)}):(oe.data=(0,f.default)({},ee,{target:J.target}),(0,d.showMenu)(oe))}}),W(w(K),"elemRef",function(J){K.elem=J}),K}return S(q,[{key:"render",value:function(){var j=this.props,H=j.renderTag,Y=j.attributes,J=j.children,te=(0,f.default)({},Y,{className:(0,_.default)(C.cssClasses.menuWrapper,Y.className),onContextMenu:this.handleContextMenu,onClick:this.handleMouseClick,onMouseDown:this.handleMouseDown,onMouseUp:this.handleMouseUp,onTouchStart:this.handleTouchstart,onTouchEnd:this.handleTouchEnd,onMouseOut:this.handleMouseOut,ref:this.elemRef});return p.default.createElement(H,te,J)}}]),q}(p.Component);c.default=G,W(G,"propTypes",{id:m.default.string.isRequired,children:m.default.node.isRequired,attributes:m.default.object,collect:m.default.func,disable:m.default.bool,holdToDisplay:m.default.number,posX:m.default.number,posY:m.default.number,renderTag:m.default.elementType,mouseButton:m.default.number,disableIfShiftIsPressed:m.default.bool}),W(G,"defaultProps",{attributes:{},collect:function(){return null},disable:!1,holdToDisplay:1e3,renderTag:"div",posX:0,posY:0,mouseButton:2,disableIfShiftIsPressed:!1})},"../../../../node_modules/react-contextmenu/es6/MenuItem.js":(l,c,h)=>{function u(Z){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(q){return typeof q}:function(q){return q&&typeof Symbol=="function"&&q.constructor===Symbol&&q!==Symbol.prototype?"symbol":typeof q},u(Z)}Object.defineProperty(c,"__esModule",{value:!0}),c.default=void 0;var p=M(h("../../../../node_modules/react/index.js")),m=v(h("../../../../node_modules/prop-types/index.js")),_=v(h("../../../../node_modules/classnames/index.js")),f=v(h("../../../../node_modules/object-assign/index.js")),d=h("../../../../node_modules/react-contextmenu/es6/actions.js"),C=h("../../../../node_modules/react-contextmenu/es6/helpers.js");function v(Z){return Z&&Z.__esModule?Z:{default:Z}}function y(Z){if(typeof WeakMap!="function")return null;var q=new WeakMap,K=new WeakMap;return(y=function(H){return H?K:q})(Z)}function M(Z,q){if(!q&&Z&&Z.__esModule)return Z;if(Z===null||u(Z)!=="object"&&typeof Z!="function")return{default:Z};var K=y(q);if(K&&K.has(Z))return K.get(Z);var j={},H=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var Y in Z)if(Y!=="default"&&Object.prototype.hasOwnProperty.call(Z,Y)){var J=H?Object.getOwnPropertyDescriptor(Z,Y):null;J&&(J.get||J.set)?Object.defineProperty(j,Y,J):j[Y]=Z[Y]}return j.default=Z,K&&K.set(Z,j),j}function b(){return b=Object.assign||function(Z){for(var q=1;q"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function W(Z){return W=Object.setPrototypeOf?Object.getPrototypeOf:function(K){return K.__proto__||Object.getPrototypeOf(K)},W(Z)}function G(Z,q,K){return q in Z?Object.defineProperty(Z,q,{value:K,enumerable:!0,configurable:!0,writable:!0}):Z[q]=K,Z}var ie=function(Z){D(K,Z);var q=L(K);function K(){var j;E(this,K);for(var H=arguments.length,Y=new Array(H),J=0;J{function u(Z){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(q){return typeof q}:function(q){return q&&typeof Symbol=="function"&&q.constructor===Symbol&&q!==Symbol.prototype?"symbol":typeof q},u(Z)}Object.defineProperty(c,"__esModule",{value:!0}),c.default=void 0;var p=M(h("../../../../node_modules/react/index.js")),m=M(h("../../../../node_modules/prop-types/index.js")),_=M(h("../../../../node_modules/classnames/index.js")),f=M(h("../../../../node_modules/object-assign/index.js")),d=h("../../../../node_modules/react-contextmenu/es6/actions.js"),C=M(h("../../../../node_modules/react-contextmenu/es6/AbstractMenu.js")),v=h("../../../../node_modules/react-contextmenu/es6/helpers.js"),y=M(h("../../../../node_modules/react-contextmenu/es6/globalEventListener.js"));function M(Z){return Z&&Z.__esModule?Z:{default:Z}}function b(){return b=Object.assign||function(Z){for(var q=1;q"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function W(Z){return W=Object.setPrototypeOf?Object.getPrototypeOf:function(K){return K.__proto__||Object.getPrototypeOf(K)},W(Z)}function G(Z,q,K){return q in Z?Object.defineProperty(Z,q,{value:K,enumerable:!0,configurable:!0,writable:!0}):Z[q]=K,Z}var ie=function(Z){D(K,Z);var q=L(K);function K(j){var H;return E(this,K),H=q.call(this,j),G(N(H),"getMenuPosition",function(){var Y=window,J=Y.innerWidth,te=Y.innerHeight,re=H.subMenu.getBoundingClientRect(),ee={};return re.bottom>te?ee.bottom=0:ee.top=0,re.rightJ?re.bottom=0:re.top=0,te.left<0?re.left="100%":re.right="100%",re}),G(N(H),"hideMenu",function(Y){Y.preventDefault(),H.hideSubMenu(Y)}),G(N(H),"hideSubMenu",function(Y){Y.detail&&Y.detail.id&&H.menu&&Y.detail.id!==H.menu.id||(H.props.forceOpen&&H.props.forceClose(),H.setState({visible:!1,selectedItem:null}),H.unregisterHandlers())}),G(N(H),"handleClick",function(Y){Y.preventDefault(),!H.props.disabled&&((0,v.callIfExists)(H.props.onClick,Y,(0,f.default)({},H.props.data,v.store.data),v.store.target),!(!H.props.onClick||H.props.preventCloseOnClick)&&(0,d.hideMenu)())}),G(N(H),"handleMouseEnter",function(){H.closetimer&&clearTimeout(H.closetimer),!(H.props.disabled||H.state.visible)&&(H.opentimer=setTimeout(function(){return H.setState({visible:!0,selectedItem:null})},H.props.hoverDelay))}),G(N(H),"handleMouseLeave",function(){H.opentimer&&clearTimeout(H.opentimer),H.state.visible&&(H.closetimer=setTimeout(function(){return H.setState({visible:!1,selectedItem:null})},H.props.hoverDelay))}),G(N(H),"menuRef",function(Y){H.menu=Y}),G(N(H),"subMenuRef",function(Y){H.subMenu=Y}),G(N(H),"registerHandlers",function(){document.removeEventListener("keydown",H.props.parentKeyNavigationHandler),document.addEventListener("keydown",H.handleKeyNavigation)}),G(N(H),"unregisterHandlers",function(Y){document.removeEventListener("keydown",H.handleKeyNavigation),Y||document.addEventListener("keydown",H.props.parentKeyNavigationHandler)}),H.state=(0,f.default)({},H.state,{visible:!1}),H}return I(K,[{key:"componentDidMount",value:function(){this.listenId=y.default.register(function(){},this.hideSubMenu)}},{key:"getSubMenuType",value:function(){return K}},{key:"shouldComponentUpdate",value:function(H,Y){return this.isVisibilityChange=(this.state.visible!==Y.visible||this.props.forceOpen!==H.forceOpen)&&!(this.state.visible&&H.forceOpen)&&!(this.props.forceOpen&&Y.visible),!0}},{key:"componentDidUpdate",value:function(){var H=this;if(!!this.isVisibilityChange)if(this.props.forceOpen||this.state.visible){var Y=window.requestAnimationFrame||setTimeout;Y(function(){var te=H.props.rtl?H.getRTLMenuPosition():H.getMenuPosition();H.subMenu.style.removeProperty("top"),H.subMenu.style.removeProperty("bottom"),H.subMenu.style.removeProperty("left"),H.subMenu.style.removeProperty("right"),(0,v.hasOwnProp)(te,"top")&&(H.subMenu.style.top=te.top),(0,v.hasOwnProp)(te,"left")&&(H.subMenu.style.left=te.left),(0,v.hasOwnProp)(te,"bottom")&&(H.subMenu.style.bottom=te.bottom),(0,v.hasOwnProp)(te,"right")&&(H.subMenu.style.right=te.right),H.subMenu.classList.add(v.cssClasses.menuVisible),H.registerHandlers(),H.setState({selectedItem:null})})}else{var J=function te(){H.subMenu.removeEventListener("transitionend",te),H.subMenu.style.removeProperty("bottom"),H.subMenu.style.removeProperty("right"),H.subMenu.style.top=0,H.subMenu.style.left="100%",H.unregisterHandlers()};this.subMenu.addEventListener("transitionend",J),this.subMenu.classList.remove(v.cssClasses.menuVisible)}}},{key:"componentWillUnmount",value:function(){this.listenId&&y.default.unregister(this.listenId),this.opentimer&&clearTimeout(this.opentimer),this.closetimer&&clearTimeout(this.closetimer),this.unregisterHandlers(!0)}},{key:"render",value:function(){var H,Y=this.props,J=Y.children,te=Y.attributes,re=Y.disabled,ee=Y.title,oe=Y.selected,ae=this.state.visible,fe={ref:this.menuRef,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave,className:(0,_.default)(v.cssClasses.menuItem,v.cssClasses.subMenu,te.listClassName),style:{position:"relative"}},de={className:(0,_.default)(v.cssClasses.menuItem,te.className,(H={},G(H,(0,_.default)(v.cssClasses.menuItemDisabled,te.disabledClassName),re),G(H,(0,_.default)(v.cssClasses.menuItemActive,te.visibleClassName),ae),G(H,(0,_.default)(v.cssClasses.menuItemSelected,te.selectedClassName),oe),H)),onMouseMove:this.props.onMouseMove,onMouseOut:this.props.onMouseOut,onClick:this.handleClick},me={ref:this.subMenuRef,style:{position:"absolute",transition:"opacity 1ms",top:0,left:"100%"},className:(0,_.default)(v.cssClasses.menu,this.props.className)};return p.default.createElement("nav",b({},fe,{role:"menuitem",tabIndex:"-1","aria-haspopup":"true"}),p.default.createElement("div",b({},te,de),ee),p.default.createElement("nav",b({},me,{role:"menu",tabIndex:"-1"}),this.renderChildren(J)))}}]),K}(C.default);c.default=ie,G(ie,"propTypes",{children:m.default.node.isRequired,attributes:m.default.object,title:m.default.node.isRequired,className:m.default.string,disabled:m.default.bool,hoverDelay:m.default.number,rtl:m.default.bool,selected:m.default.bool,onMouseMove:m.default.func,onMouseOut:m.default.func,forceOpen:m.default.bool,forceClose:m.default.func,parentKeyNavigationHandler:m.default.func}),G(ie,"defaultProps",{disabled:!1,hoverDelay:500,attributes:{},className:"",rtl:!1,selected:!1,onMouseMove:function(){return null},onMouseOut:function(){return null},forceOpen:!1,forceClose:function(){return null},parentKeyNavigationHandler:function(){return null}})},"../../../../node_modules/react-contextmenu/es6/actions.js":(l,c,h)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.MENU_SHOW=c.MENU_HIDE=void 0,c.dispatchGlobalEvent=d,c.hideMenu=v,c.showMenu=C;var u=m(h("../../../../node_modules/object-assign/index.js")),p=h("../../../../node_modules/react-contextmenu/es6/helpers.js");function m(y){return y&&y.__esModule?y:{default:y}}var _="REACT_CONTEXTMENU_SHOW";c.MENU_SHOW=_;var f="REACT_CONTEXTMENU_HIDE";c.MENU_HIDE=f;function d(y,M){var b=arguments.length>2&&arguments[2]!==void 0?arguments[2]:window,E;typeof window.CustomEvent=="function"?E=new window.CustomEvent(y,{detail:M}):(E=document.createEvent("CustomEvent"),E.initCustomEvent(y,!1,!0,M)),b&&(b.dispatchEvent(E),(0,u.default)(p.store,M))}function C(){var y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},M=arguments.length>1?arguments[1]:void 0;d(_,(0,u.default)({},y,{type:_}),M)}function v(){var y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},M=arguments.length>1?arguments[1]:void 0;d(f,(0,u.default)({},y,{type:f}),M)}},"../../../../node_modules/react-contextmenu/es6/connectMenu.js":(l,c,h)=>{function u(H){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Y){return typeof Y}:function(Y){return Y&&typeof Symbol=="function"&&Y.constructor===Symbol&&Y!==Symbol.prototype?"symbol":typeof Y},u(H)}Object.defineProperty(c,"__esModule",{value:!0}),c.default=j;var p=C(h("../../../../node_modules/react/index.js")),m=f(h("../../../../node_modules/react-contextmenu/es6/ContextMenuTrigger.js")),_=f(h("../../../../node_modules/react-contextmenu/es6/globalEventListener.js"));function f(H){return H&&H.__esModule?H:{default:H}}function d(H){if(typeof WeakMap!="function")return null;var Y=new WeakMap,J=new WeakMap;return(d=function(re){return re?J:Y})(H)}function C(H,Y){if(!Y&&H&&H.__esModule)return H;if(H===null||u(H)!=="object"&&typeof H!="function")return{default:H};var J=d(Y);if(J&&J.has(H))return J.get(H);var te={},re=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var ee in H)if(ee!=="default"&&Object.prototype.hasOwnProperty.call(H,ee)){var oe=re?Object.getOwnPropertyDescriptor(H,ee):null;oe&&(oe.get||oe.set)?Object.defineProperty(te,ee,oe):te[ee]=H[ee]}return te.default=H,J&&J.set(H,te),te}function v(){return v=Object.assign||function(H){for(var Y=1;Y"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function w(H){return w=Object.setPrototypeOf?Object.getPrototypeOf:function(J){return J.__proto__||Object.getPrototypeOf(J)},w(H)}function N(H,Y,J){return Y in H?Object.defineProperty(H,Y,{value:J,enumerable:!0,configurable:!0,writable:!0}):H[Y]=J,H}function V(H){return Z(H)||ie(H)||G(H)||W()}function W(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function G(H,Y){if(!!H){if(typeof H=="string")return q(H,Y);var J=Object.prototype.toString.call(H).slice(8,-1);if(J==="Object"&&H.constructor&&(J=H.constructor.name),J==="Map"||J==="Set")return Array.from(H);if(J==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(J))return q(H,Y)}}function ie(H){if(typeof Symbol<"u"&&H[Symbol.iterator]!=null||H["@@iterator"]!=null)return Array.from(H)}function Z(H){if(Array.isArray(H))return q(H)}function q(H,Y){(Y==null||Y>H.length)&&(Y=H.length);for(var J=0,te=new Array(Y);J{Object.defineProperty(c,"__esModule",{value:!0}),c.default=void 0;var u=h("../../../../node_modules/react-contextmenu/es6/actions.js"),p=h("../../../../node_modules/react-contextmenu/es6/helpers.js");function m(y,M){for(var b=0;b{Object.defineProperty(c,"__esModule",{value:!0}),c.callIfExists=h,c.cssClasses=c.canUseDOM=void 0,c.hasOwnProp=u,c.store=void 0,c.uniqueId=p;function h(d){for(var C=arguments.length,v=new Array(C>1?C-1:0),y=1;y{Object.defineProperty(c,"__esModule",{value:!0}),Object.defineProperty(c,"ContextMenu",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(c,"ContextMenuTrigger",{enumerable:!0,get:function(){return p.default}}),Object.defineProperty(c,"MenuItem",{enumerable:!0,get:function(){return m.default}}),Object.defineProperty(c,"SubMenu",{enumerable:!0,get:function(){return _.default}}),Object.defineProperty(c,"connectMenu",{enumerable:!0,get:function(){return f.default}}),Object.defineProperty(c,"hideMenu",{enumerable:!0,get:function(){return d.hideMenu}}),Object.defineProperty(c,"showMenu",{enumerable:!0,get:function(){return d.showMenu}});var u=C(h("../../../../node_modules/react-contextmenu/es6/ContextMenu.js")),p=C(h("../../../../node_modules/react-contextmenu/es6/ContextMenuTrigger.js")),m=C(h("../../../../node_modules/react-contextmenu/es6/MenuItem.js")),_=C(h("../../../../node_modules/react-contextmenu/es6/SubMenu.js")),f=C(h("../../../../node_modules/react-contextmenu/es6/connectMenu.js")),d=h("../../../../node_modules/react-contextmenu/es6/actions.js");function C(v){return v&&v.__esModule?v:{default:v}}},"../../../../node_modules/react-dom/cjs/react-dom.development.js":(l,c,h)=>{/** @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 u=h("../../../../node_modules/react/index.js"),p=h("../../../../node_modules/object-assign/index.js"),m=h("../../../../node_modules/scheduler/index.js"),_=h("../../../../node_modules/scheduler/tracing.js"),f=u.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function d(x){{for(var T=arguments.length,B=new Array(T>1?T-1:0),U=1;U1?T-1:0),U=1;U2&&(x[0]==="o"||x[0]==="O")&&(x[1]==="n"||x[1]==="N")}function Yi(x,T,B,U){if(B!==null&&B.type===ft)return!1;switch(typeof T){case"function":case"symbol":return!0;case"boolean":{if(U)return!1;if(B!==null)return!B.acceptsBooleans;var Q=x.toLowerCase().slice(0,5);return Q!=="data-"&&Q!=="aria-"}default:return!1}}function Vi(x,T,B,U){if(T===null||typeof T>"u"||Yi(x,T,B,U))return!0;if(U)return!1;if(B!==null)switch(B.type){case mt:return!T;case Je:return T===!1;case Yt:return isNaN(T);case Vt:return isNaN(T)||T<1}return!1}function Ji(x){return Ht.hasOwnProperty(x)?Ht[x]:null}function st(x,T,B,U,Q,g,A){this.acceptsBooleans=T===Ze||T===mt||T===Je,this.attributeName=U,this.attributeNamespace=Q,this.mustUseProperty=B,this.propertyName=x,this.type=T,this.sanitizeURL=g,this.removeEmptyString=A}var Ht={},kt=["children","dangerouslySetInnerHTML","defaultValue","defaultChecked","innerHTML","suppressContentEditableWarning","suppressHydrationWarning","style"];kt.forEach(function(x){Ht[x]=new st(x,ft,!1,x,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(x){var T=x[0],B=x[1];Ht[T]=new st(T,yt,!1,B,null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(x){Ht[x]=new st(x,Ze,!1,x.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(x){Ht[x]=new st(x,Ze,!1,x,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(x){Ht[x]=new st(x,mt,!1,x.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(x){Ht[x]=new st(x,mt,!0,x,null,!1,!1)}),["capture","download"].forEach(function(x){Ht[x]=new st(x,Je,!1,x,null,!1,!1)}),["cols","rows","size","span"].forEach(function(x){Ht[x]=new st(x,Vt,!1,x,null,!1,!1)}),["rowSpan","start"].forEach(function(x){Ht[x]=new st(x,Yt,!1,x.toLowerCase(),null,!1,!1)});var si=/[\-\:]([a-z])/g,Qt=function(x){return x[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(x){var T=x.replace(si,Qt);Ht[T]=new st(T,yt,!1,x,null,!1,!1)}),["xlink:actuate","xlink:arcrole","xlink:role","xlink:show","xlink:title","xlink:type"].forEach(function(x){var T=x.replace(si,Qt);Ht[T]=new st(T,yt,!1,x,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(x){var T=x.replace(si,Qt);Ht[T]=new st(T,yt,!1,x,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(x){Ht[x]=new st(x,yt,!1,x.toLowerCase(),null,!1,!1)});var Ci="xlinkHref";Ht[Ci]=new st("xlinkHref",yt,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(x){Ht[x]=new st(x,yt,!1,x.toLowerCase(),null,!0,!0)});var Ni=/^[\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,Ts=!1;function Dt(x){!Ts&&Ni.test(x)&&(Ts=!0,C("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(x)))}function xt(x,T,B,U){if(U.mustUseProperty){var Q=U.propertyName;return x[Q]}else{U.sanitizeURL&&Dt(""+B);var g=U.attributeName,A=null;if(U.type===Je){if(x.hasAttribute(g)){var P=x.getAttribute(g);return P===""?!0:Vi(T,B,U,!1)?P:P===""+B?B:P}}else if(x.hasAttribute(g)){if(Vi(T,B,U,!1))return x.getAttribute(g);if(U.type===mt)return B;A=x.getAttribute(g)}return Vi(T,B,U,!1)?A===null?B:A:A===""+B?B:A}}function Wt(x,T,B){{if(!Ri(T))return;if(MS(B))return B;if(!x.hasAttribute(T))return B===void 0?void 0:null;var U=x.getAttribute(T);return U===""+B?B:U}}function Tt(x,T,B,U){var Q=Ji(T);if(!Bi(T,Q,U)){if(Vi(T,B,Q,U)&&(B=null),U||Q===null){if(Ri(T)){var g=T;B===null?x.removeAttribute(g):x.setAttribute(g,""+B)}return}var A=Q.mustUseProperty;if(A){var P=Q.propertyName;if(B===null){var F=Q.type;x[P]=F===mt?!1:""}else x[P]=B;return}var k=Q.attributeName,$=Q.attributeNamespace;if(B===null)x.removeAttribute(k);else{var ne=Q.type,ce;ne===mt||ne===Je&&B===!0?ce="":(ce=""+B,Q.sanitizeURL&&Dt(ce.toString())),$?x.setAttributeNS($,k,ce):x.setAttribute(k,ce)}}}var $i=60103,Di=60106,is=60107,Qi=60108,St=60114,Gi=60109,Ai=60110,fr=60112,or=60113,en=60120,rn=60115,sn=60116,pt=60121,bi=60119,Zi=60128,Ss=60129,_r=60130,ot=60131;if(typeof Symbol=="function"&&Symbol.for){var ei=Symbol.for;$i=ei("react.element"),Di=ei("react.portal"),is=ei("react.fragment"),Qi=ei("react.strict_mode"),St=ei("react.profiler"),Gi=ei("react.provider"),Ai=ei("react.context"),fr=ei("react.forward_ref"),or=ei("react.suspense"),en=ei("react.suspense_list"),rn=ei("react.memo"),sn=ei("react.lazy"),pt=ei("react.block"),ei("react.server.block"),ei("react.fundamental"),bi=ei("react.scope"),Zi=ei("react.opaque.id"),Ss=ei("react.debug_trace_mode"),_r=ei("react.offscreen"),ot=ei("react.legacy_hidden")}var Ei=typeof Symbol=="function"&&Symbol.iterator,gs="@@iterator";function us(x){if(x===null||typeof x!="object")return null;var T=Ei&&x[Ei]||x[gs];return typeof T=="function"?T:null}var js=0,Is,lr,qr,Gs,jr,eo,ia;function tc(){}tc.__reactDisabledLog=!0;function nn(){{if(js===0){Is=console.log,lr=console.info,qr=console.warn,Gs=console.error,jr=console.group,eo=console.groupCollapsed,ia=console.groupEnd;var x={configurable:!0,enumerable:!0,value:tc,writable:!0};Object.defineProperties(console,{info:x,log:x,warn:x,error:x,group:x,groupCollapsed:x,groupEnd:x})}js++}}function ya(){{if(js--,js===0){var x={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:p({},x,{value:Is}),info:p({},x,{value:lr}),warn:p({},x,{value:qr}),error:p({},x,{value:Gs}),group:p({},x,{value:jr}),groupCollapsed:p({},x,{value:eo}),groupEnd:p({},x,{value:ia})})}js<0&&C("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ic=f.ReactCurrentDispatcher,Ho;function fa(x,T,B){{if(Ho===void 0)try{throw Error()}catch(Q){var U=Q.stack.trim().match(/\n( *(at )?)/);Ho=U&&U[1]||""}return` +`+Ho+x}}var Xn=!1,pa;{var yo=typeof WeakMap=="function"?WeakMap:Map;pa=new yo}function tl(x,T){if(!x||Xn)return"";{var B=pa.get(x);if(B!==void 0)return B}var U;Xn=!0;var Q=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var g;g=ic.current,ic.current=null,nn();try{if(T){var A=function(){throw Error()};if(Object.defineProperty(A.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(A,[])}catch(Re){U=Re}Reflect.construct(x,[],A)}else{try{A.call()}catch(Re){U=Re}x.call(A.prototype)}}else{try{throw Error()}catch(Re){U=Re}x()}}catch(Re){if(Re&&U&&typeof Re.stack=="string"){for(var P=Re.stack.split(` +`),F=U.stack.split(` +`),k=P.length-1,$=F.length-1;k>=1&&$>=0&&P[k]!==F[$];)$--;for(;k>=1&&$>=0;k--,$--)if(P[k]!==F[$]){if(k!==1||$!==1)do if(k--,$--,$<0||P[k]!==F[$]){var ne=` +`+P[k].replace(" at new "," at ");return typeof x=="function"&&pa.set(x,ne),ne}while(k>=1&&$>=0);break}}}finally{Xn=!1,ic.current=g,ya(),Error.prepareStackTrace=Q}var ce=x?x.displayName||x.name:"",_e=ce?fa(ce):"";return typeof x=="function"&&pa.set(x,_e),_e}function Ma(x,T,B){return tl(x,!0)}function ma(x,T,B){return tl(x,!1)}function Vl(x){var T=x.prototype;return!!(T&&T.isReactComponent)}function jo(x,T,B){if(x==null)return"";if(typeof x=="function")return tl(x,Vl(x));if(typeof x=="string")return fa(x);switch(x){case or:return fa("Suspense");case en:return fa("SuspenseList")}if(typeof x=="object")switch(x.$$typeof){case fr:return ma(x.render);case rn:return jo(x.type,T,B);case pt:return ma(x._render);case sn:{var U=x,Q=U._payload,g=U._init;try{return jo(g(Q),T,B)}catch{}}}return""}function zl(x){switch(x._debugOwner&&x._debugOwner.type,x._debugSource,x.tag){case I:return fa(x.type);case q:return fa("Lazy");case G:return fa("Suspense");case H:return fa("SuspenseList");case y:case b:case Z:return ma(x.type);case V:return ma(x.type.render);case te:return ma(x.type._render);case M:return Ma(x.type);default:return""}}function Nh(x){try{var T="",B=x;do T+=zl(B),B=B.return;while(B);return T}catch(U){return` +Error generating stack: `+U.message+` +`+U.stack}}function wa(x,T,B){var U=T.displayName||T.name||"";return x.displayName||(U!==""?B+"("+U+")":B)}function Bc(x){return x.displayName||"Context"}function cs(x){if(x==null)return null;if(typeof x.tag=="number"&&C("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."),typeof x=="function")return x.displayName||x.name||null;if(typeof x=="string")return x;switch(x){case is:return"Fragment";case Di:return"Portal";case St:return"Profiler";case Qi:return"StrictMode";case or:return"Suspense";case en:return"SuspenseList"}if(typeof x=="object")switch(x.$$typeof){case Ai:var T=x;return Bc(T)+".Consumer";case Gi:var B=x;return Bc(B._context)+".Provider";case fr:return wa(x,x.render,"ForwardRef");case rn:return cs(x.type);case pt:return cs(x._render);case sn:{var U=x,Q=U._payload,g=U._init;try{return cs(g(Q))}catch{return null}}}return null}var mc=f.ReactDebugCurrentFrame,Ta=null,to=!1;function Ul(){{if(Ta===null)return null;var x=Ta._debugOwner;if(x!==null&&typeof x<"u")return cs(x.type)}return null}function ns(){return Ta===null?"":Nh(Ta)}function sa(){mc.getCurrentStack=null,Ta=null,to=!1}function Hr(x){mc.getCurrentStack=ns,Ta=x,to=!1}function bn(x){to=x}function kl(){return to}function En(x){return""+x}function vn(x){switch(typeof x){case"boolean":case"number":case"object":case"string":case"undefined":return x;default:return""}}var kn={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0};function Nn(x,T){kn[T.type]||T.onChange||T.onInput||T.readOnly||T.disabled||T.value==null||C("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`."),T.onChange||T.readOnly||T.disabled||T.checked==null||C("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 Fc(x){var T=x.type,B=x.nodeName;return B&&B.toLowerCase()==="input"&&(T==="checkbox"||T==="radio")}function Ln(x){return x._valueTracker}function io(x){x._valueTracker=null}function Bh(x){var T="";return x&&(Fc(x)?T=x.checked?"true":"false":T=x.value),T}function Le(x){var T=Fc(x)?"checked":"value",B=Object.getOwnPropertyDescriptor(x.constructor.prototype,T),U=""+x[T];if(!(x.hasOwnProperty(T)||typeof B>"u"||typeof B.get!="function"||typeof B.set!="function")){var Q=B.get,g=B.set;Object.defineProperty(x,T,{configurable:!0,get:function(){return Q.call(this)},set:function(P){U=""+P,g.call(this,P)}}),Object.defineProperty(x,T,{enumerable:B.enumerable});var A={getValue:function(){return U},setValue:function(P){U=""+P},stopTracking:function(){io(x),delete x[T]}};return A}}function It(x){Ln(x)||(x._valueTracker=Le(x))}function ti(x){if(!x)return!1;var T=Ln(x);if(!T)return!0;var B=T.getValue(),U=Bh(x);return U!==B?(T.setValue(U),!0):!1}function fi(x){if(x=x||(typeof document<"u"?document:void 0),typeof x>"u")return null;try{return x.activeElement||x.body}catch{return x.body}}var vs=!1,Ee=!1,ht=!1,Rt=!1;function ri(x){var T=x.type==="checkbox"||x.type==="radio";return T?x.checked!=null:x.value!=null}function yi(x,T){var B=x,U=T.checked,Q=p({},T,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:U??B._wrapperState.initialChecked});return Q}function bs(x,T){Nn("input",T),T.checked!==void 0&&T.defaultChecked!==void 0&&!Ee&&(C("%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",Ul()||"A component",T.type),Ee=!0),T.value!==void 0&&T.defaultValue!==void 0&&!vs&&(C("%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",Ul()||"A component",T.type),vs=!0);var B=x,U=T.defaultValue==null?"":T.defaultValue;B._wrapperState={initialChecked:T.checked!=null?T.checked:T.defaultChecked,initialValue:vn(T.value!=null?T.value:U),controlled:ri(T)}}function Es(x,T){var B=x,U=T.checked;U!=null&&Tt(B,"checked",U,!1)}function Ds(x,T){var B=x;{var U=ri(T);!B._wrapperState.controlled&&U&&!Rt&&(C("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"),Rt=!0),B._wrapperState.controlled&&!U&&!ht&&(C("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"),ht=!0)}Es(x,T);var Q=vn(T.value),g=T.type;if(Q!=null)g==="number"?(Q===0&&B.value===""||B.value!=Q)&&(B.value=En(Q)):B.value!==En(Q)&&(B.value=En(Q));else if(g==="submit"||g==="reset"){B.removeAttribute("value");return}T.hasOwnProperty("value")?on(B,T.type,Q):T.hasOwnProperty("defaultValue")&&on(B,T.type,vn(T.defaultValue)),T.checked==null&&T.defaultChecked!=null&&(B.defaultChecked=!!T.defaultChecked)}function Tr(x,T,B){var U=x;if(T.hasOwnProperty("value")||T.hasOwnProperty("defaultValue")){var Q=T.type,g=Q==="submit"||Q==="reset";if(g&&(T.value===void 0||T.value===null))return;var A=En(U._wrapperState.initialValue);B||A!==U.value&&(U.value=A),U.defaultValue=A}var P=U.name;P!==""&&(U.name=""),U.defaultChecked=!U.defaultChecked,U.defaultChecked=!!U._wrapperState.initialChecked,P!==""&&(U.name=P)}function tr(x,T){var B=x;Ds(B,T),an(B,T)}function an(x,T){var B=T.name;if(T.type==="radio"&&B!=null){for(var U=x;U.parentNode;)U=U.parentNode;for(var Q=U.querySelectorAll("input[name="+JSON.stringify(""+B)+'][type="radio"]'),g=0;g children."))))}),T.selected!=null&&!Kn&&(C("Use the `defaultValue` or `value` props on must be a scalar value if `multiple` is false.%s",B,zc())}}}}function vl(x,T,B,U){var Q=x.options;if(T){for(var g=B,A={},P=0;P.");var U=p({},T,{value:void 0,defaultValue:void 0,children:En(B._wrapperState.initialValue)});return U}function r2(x,T){var B=x;Nn("textarea",T),T.value!==void 0&&T.defaultValue!==void 0&&!mu&&(C("%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",Ul()||"A component"),mu=!0);var U=T.value;if(U==null){var Q=T.children,g=T.defaultValue;if(Q!=null){C("Use the `defaultValue` or `value` props instead of setting children on