import{k as cc,l as uc,W as ot,j as i0,P as Hr,n as s0,m as al,B as ol,o as dc,p as fc,q as _c,r as pc,s as gc,t as mc,u as vc,v as xc,w as bc,x as yc,y as Tc,z as Sc,A as Ac,D as X0,E as ll,_ as hl,R as cl}from"./index-97b4652c.js";import{V as Ec,f as zt,c as Oi,i as K0,l as hr,m as xs,z as Cc,T as Rc,B as Y0,C as Ic,D as Mc,s as qi,E as ji,w as Pc,a2 as q0,j as ga,h as wc,_ as Dc,a as Fc,b as Oc,o as Lc,d as Bc}from"./vuetify-52f40ce5.js";import{E as Nc,b as Uc,a as kc}from"./codemirror-0a1db0c7.js";import"./overlayscrollbars-44d87bcf.js";import"./echarts-9bc570b0.js";function Vc(a,e){return e===void 0&&(e={}),function(t,i){cc(e,t,i),uc(function(s,n){(s.props||(s.props={}))[a]=e,(s.computed||(s.computed={}))[n]={get:function(){return this[a]},set:function(r){this.$emit("update:"+a,r)}}})(t,i)}}class Gc{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 Wc{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1}}class ee{static FromPromise(e,t){const i=new ee;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 Gc(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,n=!1){if(!e)return null;const r=new Wc(e,t,s);return r.unregisterOnNextCall=n,i?this._observers.unshift(r):this._observers.push(r),this._onObserverAdded&&this._onObserverAdded(r),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(r,this._lastNotifiedValue),r}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return e&&this._observers.indexOf(e)!==-1?(this._deferUnregister(e),!0):!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,n){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const r=this._eventState;r.mask=t,r.target=i,r.currentTarget=s,r.skipNextObservers=!1,r.lastReturnValue=e,r.userInfo=n;for(const o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?r.lastReturnValue=o.callback.apply(o.scope,[e,r]):r.lastReturnValue=o.callback(e,r)),r.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(){this._observers.length=0,this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new ee;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}}class zc{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,s=1,n=2,r=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=s,this.samplingMode=n,this._comparisonFunction=r,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}var ze;(function(a){a[a.Unknown=0]="Unknown",a[a.Url=1]="Url",a[a.Temp=2]="Temp",a[a.Raw=3]="Raw",a[a.Dynamic=4]="Dynamic",a[a.RenderTarget=5]="RenderTarget",a[a.MultiRenderTarget=6]="MultiRenderTarget",a[a.Cube=7]="Cube",a[a.CubeRaw=8]="CubeRaw",a[a.CubePrefiltered=9]="CubePrefiltered",a[a.Raw3D=10]="Raw3D",a[a.Raw2DArray=11]="Raw2DArray",a[a.DepthStencil=12]="DepthStencil",a[a.CubeRawRGBD=13]="CubeRawRGBD",a[a.Depth=14]="Depth"})(ze||(ze={}));class Dt extends zc{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new ee,this.onErrorObservable=new ee,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=ze.Unknown,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._engine=e,this._source=t,this._uniqueId=Dt._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var e;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const i=this.onRebuildCallback(this),s=n=>{n._swapAndDie(this,!1),this.isReady=i.isReady};i.isAsync?i.proxy.then(s):s(i.proxy);return}let t;switch(this.source){case ze.Temp:break;case ze.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 ze.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 ze.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 ze.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 ze.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 ze.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 ze.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 ze.CubeRawRGBD:return;case ze.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 n=s.indexOf(this);n!==-1&&s.splice(n,1),n=s.indexOf(e),n===-1&&s.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._references===0&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}}Dt._Counter=0;function Pt(){return typeof window<"u"}function n0(){return typeof navigator<"u"}function kn(){return typeof document<"u"}function Xr(a){let e="",t=a.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}const Da={IsWindowObjectExist:Pt,IsNavigatorAvailable:n0,IsDocumentAvailable:kn,GetDOMTextContent:Xr};class Ie{static get LastCreatedEngine(){return this.Instances.length===0?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}Ie.Instances=new Array;Ie.OnEnginesDisposedObservable=new ee;Ie._LastCreatedScene=null;Ie.UseFallbackTexture=!0;Ie.FallbackTexture="";function Ae(a){return"".concat(a," needs to be imported before as it contains a side-effect required by your code.")}class H{static _CheckLimit(e,t){let i=H._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},H._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var i;const s=H._LogLimitOutputs[e];if(!s||!H.MessageLimitReached)return;const n=this._Levels[t];s.current===s.limit&&H[n.name](H.MessageLimitReached.replace(/%LIMIT%/g,""+s.limit).replace(/%TYPE%/g,(i=n.name)!==null&&i!==void 0?i:""))}static _AddLogEntry(e){H._LogCache=e+H._LogCache,H.OnNewCacheEntry&&H.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&&!H._CheckLimit(t,i))return;const s=H._FormatMessage(t),n=this._Levels[e];n.logFunc&&n.logFunc("BJS - "+s);const r="
").concat(s,"

");H._AddLogEntry(r),H._GenerateLimitMessage(t,e)}static get LogCache(){return H._LogCache}static ClearLogCache(){H._LogCache="",H._LogLimitOutputs={},H.errorsCount=0}static set LogLevels(e){H.Log=H._LogDisabled,H.Warn=H._LogDisabled,H.Error=H._LogDisabled,[H.MessageLogLevel,H.WarningLogLevel,H.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];H[i.name]=H._LogEnabled.bind(H,t)}})}}H.NoneLogLevel=0;H.MessageLogLevel=1;H.WarningLogLevel=2;H.ErrorLogLevel=4;H.AllLogLevel=7;H.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";H._LogCache="";H._LogLimitOutputs={};H._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];H.errorsCount=0;H.Log=H._LogEnabled.bind(H,H.MessageLogLevel);H.Warn=H._LogEnabled.bind(H,H.WarningLogLevel);H.Error=H._LogEnabled.bind(H,H.ErrorLogLevel);const Hc="attribute",Xc="varying";class wn{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,s,n,r,o,l;let h="";if(this.line){let c=this.line;const u=t.processor;if(u){u.lineProcessor&&(c=u.lineProcessor(c,t.isFragment,t.processingContext));const d=(s=(i=t.processor)===null||i===void 0?void 0:i.attributeKeywordName)!==null&&s!==void 0?s:Hc,_=t.isFragment&&(!((n=t.processor)===null||n===void 0)&&n.varyingFragmentKeywordName)?(r=t.processor)===null||r===void 0?void 0:r.varyingFragmentKeywordName:!t.isFragment&&(!((o=t.processor)===null||o===void 0)&&o.varyingVertexKeywordName)?(l=t.processor)===null||l===void 0?void 0:l.varyingVertexKeywordName:Xc;!t.isFragment&&u.attributeProcessor&&this.line.startsWith(d)?c=u.attributeProcessor(this.line,e,t.processingContext):u.varyingProcessor&&this.line.startsWith(_)?c=u.varyingProcessor(this.line,t.isFragment,e,t.processingContext):u.uniformProcessor&&u.uniformRegexp&&u.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(c=u.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):u.uniformBufferProcessor&&u.uniformBufferRegexp&&u.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(c=u.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):u.textureProcessor&&u.textureRegexp&&u.textureRegexp.test(this.line)?c=u.textureProcessor(this.line,t.isFragment,e,t.processingContext):(u.uniformProcessor||u.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?u.uniformProcessor&&(c=u.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):u.uniformBufferProcessor&&(c=u.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&this.line.indexOf("}")!==-1&&(t.lookForClosingBracketForUniformBuffer=!1,u.endOfUniformBufferProcessor&&(c=u.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}h+=c+"\r\n"}return this.children.forEach(c=>{h+=c.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),h}}class Kc{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex{h=h.trim(),h!==""&&(t.push(h),h="")},n=c=>{iii._Stack[i],o=()=>i===-1?"!!INVALID EXPRESSION!!":ii._Stack[i--];let l=0,h="";for(;l1){for(s();i!==-1&&ii._OperatorPriority[r()]>=ii._OperatorPriority[u];)t.push(o());n(u),l++}else h+=c;l++}for(s();i!==-1;)r()==="("?o():t.push(o());return t}}ii._OperatorPriority={")":0,"(":1,"||":2,"&&":3};ii._Stack=["","","","","","","","","","","","","","","","","","","",""];class cr extends ii{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=e[this.define]!==void 0;return this.not&&(t=!t),t}}class qc extends ii{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class jc extends ii{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class $c extends ii{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}isTrue(e){let t=e[this.define];t===void 0&&(t=this.define);let i=!1;const s=parseInt(t),n=parseInt(this.testValue);switch(this.operand){case">":i=s>n;break;case"<":i=s=":i=s>=n;break;case"==":i=s===n;break}return i}}var at;(function(a){a[a.GLSL=0]="GLSL",a[a.WGSL=1]="WGSL"})(at||(at={}));const Zc=/defined\s*?\((.+?)\)/g,va=/defined\s*?\[(.+?)\]/g,j0=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g;class Qi{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,s){var n;!((n=t.processor)===null||n===void 0)&&n.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,r=>{t.processCodeAfterIncludes&&(r=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",r));const o=this._ProcessShaderConversion(r,t,s);i(o,r)})}static PreProcess(e,t,i,s){var n;!((n=t.processor)===null||n===void 0)&&n.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,r=>{t.processCodeAfterIncludes&&(r=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",r));const o=this._ApplyPreProcessing(r,t,s);i(o,r)})}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;\n"+e:e="precision mediump float;\n"+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 cr(i[1].trim(),e[0]==="!");const s=["==",">=","<=","<",">"];let n="",r=0;for(n of s)if(r=e.indexOf(n),r>-1)break;if(r===-1)return new cr(e);const o=e.substring(0,r).trim(),l=e.substring(r+n.length).trim();return new $c(o,n,l)}static _BuildSubExpression(e){e=e.replace(Zc,"defined[$1]");const t=ii.infixToPostfix(e),i=[];for(const n of t)if(n!=="||"&&n!=="&&")i.push(n);else if(i.length>=2){let r=i[i.length-1],o=i[i.length-2];i.length-=2;const l=n=="&&"?new jc:new qc;typeof r=="string"&&(r=r.replace(va,"defined($1)")),typeof o=="string"&&(o=o.replace(va,"defined($1)")),l.leftOperand=typeof o=="string"?this._ExtractOperation(o):o,l.rightOperand=typeof r=="string"?this._ExtractOperation(r):r,i.push(l)}let s=i[i.length-1];return typeof s=="string"&&(s=s.replace(va,"defined($1)")),typeof s=="string"?this._ExtractOperation(s):s}static _BuildExpression(e,t){const i=new Yc,s=e.substring(0,t);let n=e.substring(t);return n=n.substring(0,(n.indexOf("//")+1||n.length+1)-1).trim(),s==="#ifdef"?i.testExpression=new cr(n):s==="#ifndef"?i.testExpression=new cr(n,!0):i.testExpression=this._BuildSubExpression(n),i}static _MoveCursorWithinIf(e,t,i){let s=e.currentLine;for(;this._MoveCursor(e,i);){s=e.currentLine;const n=s.substring(0,5).toLowerCase();if(n==="#else"){const r=new wn;t.children.push(r),this._MoveCursor(e,r);return}else if(n==="#elif"){const r=this._BuildExpression(s,5);t.children.push(r),i=r}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine,n=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/.exec(i);if(n&&n.length)switch(n[0]){case"#ifdef":{const o=new ma;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 ma;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 ma,l=this._BuildExpression(i,3);t.children.push(o),o.children.push(l),this._MoveCursorWithinIf(e,o,l);break}}else{const r=new wn;if(r.line=i,t.children.push(r),i[0]==="#"&&i[1]==="d"){const o=i.replace(";","").split(" ");r.additionalDefineKey=o[1],o.length===3&&(r.additionalDefineValue=o[2])}}}return!1}static _EvaluatePreProcessors(e,t,i){const s=new wn,n=new Kc;return n.lineIndex=-1,n.lines=e.split("\n"),this._MoveCursor(n,s),s.process(t,i)}static _PreparePreProcessors(e,t){var i;const s=e.defines,n={};for(const r of s){const l=r.replace("#define","").replace(";","").trim().split(" ");n[l[0]]=l.length>1?l[1]:""}return((i=e.processor)===null||i===void 0?void 0:i.shaderLanguage)===at.GLSL&&(n.GL_ES="true"),n.__VERSION__=e.version,n[e.platformName]="true",t._getGlobalDefines(n),n}static _ProcessShaderConversion(e,t,i){let s=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===at.GLSL&&s.indexOf("#version 3")!==-1&&(s=s.replace("#version 300 es",""),!t.processor.parseGLES3))return s;const n=t.defines,r=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(s=t.processor.preProcessor(s,n,t.isFragment,t.processingContext)),s=this._EvaluatePreProcessors(s,r,t),t.processor.postProcessor&&(s=t.processor.postProcessor(s,n,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}static _ApplyPreProcessing(e,t,i){var s,n;let r=e;const o=t.defines,l=this._PreparePreProcessors(t,i);return!((s=t.processor)===null||s===void 0)&&s.preProcessor&&(r=t.processor.preProcessor(r,o,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,l,t),!((n=t.processor)===null||n===void 0)&&n.postProcessor&&(r=t.processor.postProcessor(r,o,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ProcessIncludes(e,t,i){let s=j0.exec(e),n=new String(e),r=!1;for(;s!=null;){let o=s[1];if(o.indexOf("__decl__")!==-1&&(o=o.replace(/__decl__/,""),t.supportsUniformBuffers&&(o=o.replace(/Vertex/,"Ubo"),o=o.replace(/Fragment/,"Ubo")),o=o+"Declaration"),t.includesShadersStore[o]){let l=t.includesShadersStore[o];if(s[2]){const h=s[3].split(",");for(let c=0;cp+"{X}")),l+=_.replace(/\{X\}/g,f.toString())+"\n"}else t.supportsUniformBuffers||(l=l.replace(/light\{X\}.(\w*)/g,(c,u)=>u+"{X}")),l=l.replace(/\{X\}/g,h)}n=n.replace(s[0],l),r=r||l.indexOf("#include<")>=0||l.indexOf("#include <")>=0}else{const l=t.shadersRepository+"ShadersInclude/"+o+".fx";Qi._FileToolsLoadFile(l,h=>{t.includesShadersStore[o]=h,this._ProcessIncludes(n,t,i)});return}s=j0.exec(e)}r?this._ProcessIncludes(n.toString(),t,i):i(n)}static _FileToolsLoadFile(e,t,i,s,n,r){throw Ae("FileTools")}}class te{static GetShadersRepository(e=at.GLSL){return e===at.GLSL?te.ShadersRepository:te.ShadersRepositoryWGSL}static GetShadersStore(e=at.GLSL){return e===at.GLSL?te.ShadersStore:te.ShadersStoreWGSL}static GetIncludesShadersStore(e=at.GLSL){return e===at.GLSL?te.IncludesShadersStore:te.IncludesShadersStoreWGSL}}te.ShadersRepository="src/Shaders/";te.ShadersStore={};te.IncludesShadersStore={};te.ShadersRepositoryWGSL="src/ShadersWGSL/";te.ShadersStoreWGSL={};te.IncludesShadersStoreWGSL={};class wt{static get ShadersRepository(){return te.ShadersRepository}static set ShadersRepository(e){te.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new ee),this._onBindObservable}constructor(e,t,i,s=null,n,r=null,o=null,l=null,h=null,c,u="",d=at.GLSL){var _,f,g;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new ee,this.onErrorObservable=new ee,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 p,x=null;if(t.attributes){const P=t;if(this._engine=i,this._attributesNames=P.attributes,this._uniformsNames=P.uniformsNames.concat(P.samplers),this._samplerList=P.samplers.slice(),this.defines=P.defines,this.onError=P.onError,this.onCompiled=P.onCompiled,this._fallbacks=P.fallbacks,this._indexParameters=P.indexParameters,this._transformFeedbackVaryings=P.transformFeedbackVaryings||null,this._multiTarget=!!P.multiTarget,this._shaderLanguage=(_=P.shaderLanguage)!==null&&_!==void 0?_:at.GLSL,P.uniformBuffersNames){this._uniformBuffersNamesList=P.uniformBuffersNames.slice();for(let C=0;C{if(y[0]&&y[1]){b.isFragment=!0;const[P,C]=y;Qi.Process(C,b,(R,w)=>{this._fragmentSourceCodeBeforeMigration=w,x&&(R=x("fragment",R));const D=Qi.Finalize(P,R,b);b=null,this._useFinalCode(D.vertexCode,D.fragmentCode,e)},this._engine)}};this._loadShader(m,"Vertex","",P=>{Qi.Initialize(b),Qi.Process(P,b,(C,R)=>{this._rawVertexSourceCode=P,this._vertexSourceCodeBeforeMigration=R,x&&(C=x("vertex",C)),y[0]=C,E()},this._engine)}),this._loadShader(T,"Fragment","Pixel",P=>{this._rawFragmentSourceCode=P,y[1]=P,E()})}_useFinalCode(e,t,i){if(i){const s=i.vertexElement||i.vertex||i.spectorName||i,n=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===at.WGSL?"//":"")+"#define SHADER_NAME vertex:"+s+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===at.WGSL?"//":"")+"#define SHADER_NAME fragment:"+n+"\n"+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=Xr(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 n=te.GetShadersStore(this._shaderLanguage);if(n[e+t+"Shader"]){s(n[e+t+"Shader"]);return}if(i&&n[e+i+"Shader"]){s(n[e+i+"Shader"]);return}let r;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?r=e:r=te.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(r+"."+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=(n,r)=>{s&&s(r)},this.onCompiled=()=>{const n=this.getEngine().scenes;if(n)for(let r=0;r{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,e,this._attributes),e)for(let r=0;r=o&&(n="Offending line [".concat(o,"] in ").concat(i?"fragment":"vertex"," code: ").concat(l[o-1]))}}return[e,n]}_processCompilationErrors(e,t=null){var i,s,n;this._compilationError=e.message;const r=this._attributesNames,o=this._fallbacks;if(H.Error("Unable to compile effect:"),H.Error("Uniforms: "+this._uniformsNames.map(function(h){return" "+h})),H.Error("Attributes: "+r.map(function(h){return" "+h})),H.Error("Defines:\r\n"+this.defines),wt.LogShaderCodeOnCompilationError){let h=null,c=null,u=null;!((i=this._pipelineContext)===null||i===void 0)&&i._getVertexShaderCode()&&([u,h]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),u&&(H.Error("Vertex code:"),H.Error(u))),!((s=this._pipelineContext)===null||s===void 0)&&s._getFragmentShaderCode()&&([u,c]=this._getShaderCodeAndErrorLine((n=this._pipelineContext)===null||n===void 0?void 0:n._getFragmentShaderCode(),this._compilationError,!0),u&&(H.Error("Fragment code:"),H.Error(u))),h&&H.Error(h),c&&H.Error(c)}H.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,H.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 r=1;r{s[i[_]]=d}),this._uniforms=s;let u;for(u=0;u{r[d]=_});for(const d of h.getAttributes(this,o))l.push(d)}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||s.length!==2)return s=[t,i],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),n}_cacheFloat3(e,t,i,s){let n=this._valueCache[e];if(!n||n.length!==3)return n=[t,i,s],this._valueCache[e]=n,!0;let r=!1;return n[0]!==t&&(n[0]=t,r=!0),n[1]!==i&&(n[1]=i,r=!0),n[2]!==s&&(n[2]=s,r=!0),r}_cacheFloat4(e,t,i,s,n){let r=this._valueCache[e];if(!r||r.length!==4)return r=[t,i,s,n],this._valueCache[e]=r,!0;let o=!1;return r[0]!==t&&(r[0]=t,o=!0),r[1]!==i&&(r[1]=i,o=!0),r[2]!==s&&(r[2]=s,o=!0),r[3]!==n&&(r[3]=n,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,n){this._cacheFloat4(e,t,i,s,n)&&(this.engine.setInt4(this._uniforms[e],t,i,s,n)||(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,n){this._cacheFloat4(e,t,i,s,n)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,n)||(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,n){this._cacheFloat4(e,t,i,s,n)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,n)||(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 Mt{static SetMatrixPrecision(e){if(Mt.MatrixTrackPrecisionChange=!1,e&&!Mt.MatrixUse64Bits&&Mt.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 Ee._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,s){var n,r,o,l,h,c,u,d,_,f,g;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 ee,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 ee,this.onContextRestoredObservable=new ee,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new ul,this._stencilStateComposer=new fl,this._stencilState=new ls,this._alphaState=new Qc,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 ee,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=Pi.Now;let p=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=s!=null?s:!1,this._stencilStateComposer.stencilGlobal=this._stencilState,Mt.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=t!=null?t:i.antialias,i.deterministicLockstep=(n=i.deterministicLockstep)!==null&&n!==void 0?n:!1,i.lockstepMaxSteps=(r=i.lockstepMaxSteps)!==null&&r!==void 0?r: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=(h=i.stencil)!==null&&h!==void 0?h:!0,this._audioContext=(u=(c=i.audioEngineOptions)===null||c===void 0?void 0:c.audioContext)!==null&&u!==void 0?u:null,this._audioDestination=(_=(d=i.audioEngineOptions)===null||d===void 0?void 0:d.audioDestination)!==null&&_!==void 0?_:null,this.premultipliedAlpha=(f=i.premultipliedAlpha)!==null&&f!==void 0?f:!0,this.useExactSrgbConversions=(g=i.useExactSrgbConversions)!==null&&g!==void 0?g:!1,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,s=s||i.adaptToDeviceRatio||!1;const x=Pt()&&window.devicePixelRatio||1,m=i.limitDeviceRatio||x;if(this._hardwareScalingLevel=s?1/Math.min(m,x):1,this._lastDevicePixelRatio=x,!e)return;if(e.getContext){if(p=e,this._renderingCanvas=p,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const S=navigator.userAgent;for(const b of Ee.ExceptionList){const y=b.key,E=b.targets;if(new RegExp(y).test(S)){if(b.capture&&b.captureConstraint){const C=b.capture,R=b.captureConstraint,D=new RegExp(C).exec(S);if(D&&D.length>0&&parseInt(D[D.length-1])>=R)continue}for(const C of E)switch(C){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=S=>{S.preventDefault(),this._contextWasLost=!0,H.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(this._initGLContext.bind(this))},p.addEventListener("webglcontextlost",this._onContextLost,!1),p.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=p.getContext("webgl2",i)||p.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(!p)throw new Error("The provided canvas is null or undefined.");try{this._gl=p.getContext("webgl",i)||p.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 S=this._gl.getContextAttributes();S&&(i.stencil=S.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 S=0;S1?new eu:new Jc,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const T="Babylon.js v".concat(Ee.Version);console.log(T+" - ".concat(this.description)),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",T)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&kn()&&"ontouchend"in document},this._checkForMobile(),Pt()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null;const i=this._depthCullingState.depthTest,s=this._depthCullingState.depthFunc,n=this._depthCullingState.depthMask,r=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=n,this._stencilState.stencilTest=r,H.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()}wt.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")),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;else{const i=this._gl.getExtension("EXT_sRGB");i!=null&&(this._caps.supportSRGBBuffers=!0,this._gl.SRGB=i.SRGB_EXT,this._gl.SRGB8=i.SRGB_ALPHA_EXT,this._gl.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)}_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 Pt()?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 Ee.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){const n=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=n;let r=0;t&&e&&(this._gl.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),r|=this._gl.COLOR_BUFFER_BIT),i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),r|=this._gl.DEPTH_BUFFER_BIT),s&&(this._gl.clearStencil(0),r|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(r)}_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(),n=i||this.getRenderHeight(),r=e.x||0,o=e.y||0;this._cachedViewport=e,this._viewport(r*s,o*n,s*e.width,n*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const s=Pt()&&window.devicePixelRatio||1,n=this._lastDevicePixelRatio/s;this._lastDevicePixelRatio=s,this._hardwareScalingLevel*=n}Pt()?(t=this._renderingCanvas?this._renderingCanvas.clientWidth||this._renderingCanvas.width:window.innerWidth,i=this._renderingCanvas?this._renderingCanvas.clientHeight||this._renderingCanvas.height:window.innerHeight):(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,n,r=0,o=0){var l,h,c,u,d;const _=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(_._MSAAFramebuffer?_._MSAAFramebuffer:_._framebuffer);const f=this._gl;e.isMulti||(e.is2DArray?f.framebufferTextureLayer(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,(l=e.texture._hardwareTexture)===null||l===void 0?void 0:l.underlyingResource,r,o):e.isCube&&f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_CUBE_MAP_POSITIVE_X+t,(h=e.texture._hardwareTexture)===null||h===void 0?void 0:h.underlyingResource,r));const g=e._depthStencilTexture;if(g){const p=e._depthStencilTextureWithStencil?f.DEPTH_STENCIL_ATTACHMENT:f.DEPTH_ATTACHMENT;e.is2DArray?f.framebufferTextureLayer(f.FRAMEBUFFER,p,(c=g._hardwareTexture)===null||c===void 0?void 0:c.underlyingResource,r,o):e.isCube?f.framebufferTexture2D(f.FRAMEBUFFER,p,f.TEXTURE_CUBE_MAP_POSITIVE_X+t,(u=g._hardwareTexture)===null||u===void 0?void 0:u.underlyingResource,r):f.framebufferTexture2D(f.FRAMEBUFFER,p,f.TEXTURE_2D,(d=g._hardwareTexture)===null||d===void 0?void 0:d.underlyingResource,r)}this._cachedViewport&&!n?this.setViewport(this._cachedViewport,i,s):(i||(i=e.width,r&&(i=i/Math.pow(2,r))),s||(s=e.height,r&&(s=s/Math.pow(2,r))),this._viewport(0,0,i,s)),this.wipeCaches()}setState(e,t=0,i,s=!1,n,r,o=0){var l,h;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const c=!((h=(l=this.cullBackFaces)!==null&&l!==void 0?l:n)!==null&&h!==void 0)||h?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==c||i)&&(this._depthCullingState.cullFace=c),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=r}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 n=e;this._currentRenderTarget=null;const r=this._gl;if(n._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}r.bindFramebuffer(r.READ_FRAMEBUFFER,n._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,n._framebuffer),r.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,r.COLOR_BUFFER_BIT,r.NEAREST)}!((s=e.texture)===null||s===void 0)&&s.generateMipMaps&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(n._MSAAFramebuffer&&this._bindUnboundFramebuffer(n._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 Vn(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 Vn(i);if(!i)throw new Error("Unable to create index buffer");this.bindIndexBuffer(s);const n=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),s.references=1,s.is32Bits=n.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,n=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,n,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,n,r,o){const l=this._currentBufferPointers[t];if(!l)return;let h=!1;l.active?(l.buffer!==e&&(l.buffer=e,h=!0),l.size!==i&&(l.size=i,h=!0),l.type!==s&&(l.type=s,h=!0),l.normalized!==n&&(l.normalized=n,h=!0),l.stride!==r&&(l.stride=r,h=!0),l.offset!==o&&(l.offset=o,h=!0)):(h=!0,l.active=!0,l.index=t,l.size=i,l.type=s,l.normalized=n,l.stride=r,l.offset=o,l.buffer=e),(h||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,r,o):this._gl.vertexAttribPointer(t,i,s,n,r,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 n=0;n=0){const o=s[n];let l=null;if(i&&(l=i[o]),l||(l=e[o]),!l)continue;this._gl.enableVertexAttribArray(r),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[r]=!0);const h=l.getBuffer();h&&(this._vertexAttribPointer(h,r,l.getSize(),l.type,l.normalized,l.byteStride,l.byteOffset),l.getIsInstanced()&&(this._gl.vertexAttribDivisor(r,l.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(h))))}}}recordVertexArrayObject(e,t,i,s){const n=this._gl.createVertexArray();if(!n)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(n),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),n}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,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;const r=n.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let o=0;for(let l=0;l=0&&(this._gl.enableVertexAttribArray(h),this._vertexAttribArraysEnabled[h]=!0,this._vertexAttribPointer(e,h,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\n#define WEBGL2 \n":"",l=this._compileShader(t,"vertex",s,o),h=this._compileShader(i,"fragment",s,o);return this._createShaderProgram(e,l,h,n,r)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new tu;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,s,n=null){const r=s.createProgram();if(e.program=r,!r)throw new Error("Unable to create program");return s.attachShader(r,t),s.attachShader(r,i),s.linkProgram(r),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),r}_finalizePipelineContext(e){const t=e.context,i=e.vertexShader,s=e.fragmentShader,n=e.program;if(!t.getProgramParameter(n,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(n);if(o)throw e.programLinkError=o,new Error(o)}if(this.validateShaderPrograms&&(t.validateProgram(n),!t.getProgramParameter(n,t.VALIDATE_STATUS))){const l=t.getProgramInfoLog(n);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,n,r,o,l,h,c){const u=e;s?u.program=this.createRawShaderProgram(u,t,i,void 0,h):u.program=this.createShaderProgram(u,t,i,l,void 0,h),u.program.__SPECTOR_rebuildProgram=o}_isRenderingStateCompiled(e){const t=e;return 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 n=0;n1||this.isWebGPU)),(o===1&&!this._caps.textureFloatLinearFiltering||o===2&&!this._caps.textureHalfFloatLinearFiltering)&&(l=1),o===1&&!this._caps.textureFloat&&(o=0,H.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const _=this._gl,f=new Dt(this,s),g=e.width||e,p=e.height||e,x=e.layers||0,m=this._getSamplingParameters(l,r),T=x!==0?_.TEXTURE_2D_ARRAY:_.TEXTURE_2D,S=this._getRGBABufferInternalSizedFormat(o,h,c),b=this._getInternalFormat(h),y=this._getWebGLTextureType(o);return this._bindTextureDirectly(T,f),x!==0?(f.is2DArray=!0,_.texImage3D(T,0,S,g,p,x,0,b,y,null)):_.texImage2D(T,0,S,g,p,0,b,y,null),_.texParameteri(T,_.TEXTURE_MAG_FILTER,m.mag),_.texParameteri(T,_.TEXTURE_MIN_FILTER,m.min),_.texParameteri(T,_.TEXTURE_WRAP_S,_.CLAMP_TO_EDGE),_.texParameteri(T,_.TEXTURE_WRAP_T,_.CLAMP_TO_EDGE),r&&this._gl.generateMipmap(T),this._bindTextureDirectly(T,null),f._useSRGBBuffer=c,f.baseWidth=g,f.baseHeight=p,f.width=g,f.height=p,f.depth=x,f.isReady=!0,f.samples=u,f.generateMipMaps=r,f.samplingMode=l,f.type=o,f.format=h,f.label=d,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,s,n=3,r=null,o=null,l,h,c=null,u=null,d=null,_=null,f,g,p){e=e||"";const x=e.substr(0,5)==="data:",m=e.substr(0,5)==="blob:",T=x&&e.indexOf(";base64,")!==-1,S=u||new Dt(this,ze.Url);S!==u&&(S.label=e.substring(0,60));const b=e;this._transformTextureUrl&&!T&&!u&&!c&&(e=this._transformTextureUrl(e)),b!==e&&(S._originalUrl=b);const y=e.lastIndexOf(".");let E=_||(y>-1?e.substring(y).toLowerCase():""),P=null;E.indexOf("?")>-1&&(E=E.split("?")[0]);for(const D of Ee._TextureLoaders)if(D.canLoad(E,f)){P=D;break}s&&s.addPendingData(S),S.url=e,S.generateMipMaps=!t,S.samplingMode=n,S.invertY=i,S._useSRGBBuffer=this._getUseSRGBBuffer(!!p,t),this._doNotHandleContextLost||(S._buffer=c);let R=null;r&&!u&&(R=S.onLoadedObservable.add(r)),u||this._internalTexturesCache.push(S);const w=(D,W)=>{s&&s.removePendingData(S),e===b?(R&&S.onLoadedObservable.remove(R),Ie.UseFallbackTexture&&this._createTextureBase(Ie.FallbackTexture,t,S.invertY,s,n,null,o,l,h,c,S),D=(D||"Unknown error")+(Ie.UseFallbackTexture?" - Fallback texture was used":""),S.onErrorObservable.notifyObservers({message:D,exception:W}),o&&o(D,W)):(H.Warn("Failed to load ".concat(e,", falling back to ").concat(b)),this._createTextureBase(b,t,S.invertY,s,n,r,o,l,h,c,S,d,_,f,g,p))};if(P){const D=W=>{P.loadData(W,S,(L,z,K,ae,$,U)=>{U?w("TextureLoader failed to load data"):l(S,E,s,{width:L,height:z},S.invertY,!K,ae,()=>($(),!1),n)},g)};c?c instanceof ArrayBuffer?D(new Uint8Array(c)):ArrayBuffer.isView(c)?D(c):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,W=>D(new Uint8Array(W)),void 0,s?s.offlineProvider:void 0,!0,(W,L)=>{w("Unable to load "+(W&&W.responseURL,L))})}else{const D=W=>{m&&!this._doNotHandleContextLost&&(S._buffer=W),l(S,E,s,W,S.invertY,t,!1,h,n)};!x||T?c&&(typeof c.decoding=="string"||c.close)?D(c):Ee._FileToolsLoadImage(e,D,w,s?s.offlineProvider:null,f,S.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof c=="string"||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?Ee._FileToolsLoadImage(c,D,w,s?s.offlineProvider:null,f,S.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):c&&D(c)}return S}createTexture(e,t,i,s,n=3,r=null,o=null,l=null,h=null,c=null,u=null,d,_,f,g){return this._createTextureBase(e,t,i,s,n,r,o,this._prepareWebGLTexture.bind(this),(p,x,m,T,S,b)=>{const y=this._gl,E=m.width===p&&m.height===x,P=c?this._getInternalFormat(c,S._useSRGBBuffer):T===".jpg"&&!S._useSRGBBuffer?y.RGB:S._useSRGBBuffer?y.SRGB8_ALPHA8:y.RGBA;let C=c?this._getInternalFormat(c):T===".jpg"&&!S._useSRGBBuffer?y.RGB:y.RGBA;if(S._useSRGBBuffer&&this.webGLVersion===1&&(C=P),E)return y.texImage2D(y.TEXTURE_2D,0,P,C,y.UNSIGNED_BYTE,m),!1;const R=this._caps.maxTextureSize;if(m.width>R||m.height>R||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=p,this._workingCanvas.height=x,this._workingContext.drawImage(m,0,0,m.width,m.height,0,0,p,x),y.texImage2D(y.TEXTURE_2D,0,P,C,y.UNSIGNED_BYTE,this._workingCanvas),S.width=p,S.height=x),!1;{const w=new Dt(this,ze.Temp);this._bindTextureDirectly(y.TEXTURE_2D,w,!0),y.texImage2D(y.TEXTURE_2D,0,P,C,y.UNSIGNED_BYTE,m),this._rescaleTexture(w,S,s,P,()=>{this._releaseTexture(w),this._bindTextureDirectly(y.TEXTURE_2D,S,!0),b()})}return!0},l,h,c,u,d,_,g)}static _FileToolsLoadImage(e,t,i,s,n,r){throw Ae("FileTools")}_rescaleTexture(e,t,i,s,n){}createRawTexture(e,t,i,s,n,r,o,l=null,h=0,c=0,u=!1){throw Ae("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,n,r,o,l=null){throw Ae("Engine.RawTexture")}createRawTexture3D(e,t,i,s,n,r,o,l,h=null,c=0){throw Ae("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,n,r,o,l,h=null,c=0){throw Ae("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),n=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,n.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,n.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 n=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(n,null)}_setupDepthStencilTexture(e,t,i,s,n,r=1){const o=t.width||t,l=t.height||t,h=t.layers||0;e.baseWidth=o,e.baseHeight=l,e.width=o,e.height=l,e.is2DArray=h>0,e.depth=h,e.isReady=!0,e.samples=r,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=n;const c=this._gl,u=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(n===0?(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,n),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,s,n,r=0,o=0){const l=this._gl;let h=l.TEXTURE_2D;if(e.isCube&&(h=l.TEXTURE_CUBE_MAP_POSITIVE_X+r),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(h,o,t,i,s,0,n)}_uploadDataToTextureDirectly(e,t,i=0,s=0,n,r=!1){const o=this._gl,l=this._getWebGLTextureType(e.type),h=this._getInternalFormat(e.format),c=n===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(n,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let u=o.TEXTURE_2D;e.isCube&&(u=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const d=Math.round(Math.log(e.width)*Math.LOG2E),_=Math.round(Math.log(e.height)*Math.LOG2E),f=r?e.width:Math.pow(2,Math.max(d-s,0)),g=r?e.height:Math.pow(2,Math.max(_-s,0));o.texImage2D(u,s,c,f,g,0,h,l,t)}updateTextureData(e,t,i,s,n,r,o=0,l=0,h=!1){const c=this._gl,u=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let _=c.TEXTURE_2D,f=c.TEXTURE_2D;e.isCube&&(f=c.TEXTURE_CUBE_MAP_POSITIVE_X+o,_=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(_,e,!0),c.texSubImage2D(f,l,i,s,n,r,d,u,t),h&&this._gl.generateMipmap(f),this._bindTextureDirectly(_,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const n=this._gl,r=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(r,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(r,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,n){const r=this._gl;if(!r)return;const o=this._getSamplingParameters(n,!i);r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,o.mag),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,o.min),!i&&!s&&r.generateMipmap(r.TEXTURE_2D),this._bindTextureDirectly(r.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,n,r,o,l,h=3){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?Ee.GetExponentOfTwo(s.width,c):s.width),d=Math.min(c,this.needPOTTextures?Ee.GetExponentOfTwo(s.height,c):s.height),_=this._gl;if(_){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(_.TEXTURE_2D,e,!0),this._unpackFlipY(n===void 0?!0:!!n),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=d,e.isReady=!0,!l(u,d,s,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,r,o,h)})&&this._prepareWebGLTextureContinuation(e,i,r,o,h)}}_setupFramebufferDepthAttachments(e,t,i,s,n=1){const r=this._gl;if(e&&t)return this._createRenderBuffer(i,s,n,r.DEPTH_STENCIL,r.DEPTH24_STENCIL8,r.DEPTH_STENCIL_ATTACHMENT);if(t){let o=r.DEPTH_COMPONENT16;return this._webGLVersion>1&&(o=r.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,n,o,o,r.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,n,r.STENCIL_INDEX8,r.STENCIL_INDEX8,r.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,n,r,o=!0){const h=this._gl.createRenderbuffer();return this._updateRenderBuffer(h,e,t,i,s,n,r,o)}_updateRenderBuffer(e,t,i,s,n,r,o,l=!0){const h=this._gl;return h.bindRenderbuffer(h.RENDERBUFFER,e),s>1&&h.renderbufferStorageMultisample?h.renderbufferStorageMultisample(h.RENDERBUFFER,s,r,t,i):h.renderbufferStorage(h.RENDERBUFFER,n,t,i),h.framebufferRenderbuffer(h.FRAMEBUFFER,o,h.RENDERBUFFER,e),l&&h.bindRenderbuffer(h.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,(r=(n=t==null?void 0:t._hardwareTexture)===null||n===void 0?void 0:n.underlyingResource)!==null&&r!==void 0?r: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,n=""){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,t.update();else if(t.delayLoadState===4)return t.delayLoad(),!1;let r;s?r=t.depthStencilTexture:t.isReady()?r=t.getInternalTexture():t.isCube?r=this.emptyCubeTexture:t.is3D?r=this.emptyTexture3D:t.is2DArray?r=this.emptyTexture2DArray:r=this.emptyTexture,!i&&r&&(r._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===r&&(i||this._bindSamplerUniformToChannel(r._associatedChannel,e),o=!1),this._activeChannel=e;const l=this._getTextureTarget(r);if(o&&this._bindTextureDirectly(l,r,i),r&&!r.isMultiview){if(r.isCube&&r._cachedCoordinatesMode!==t.coordinatesMode){r._cachedCoordinatesMode=t.coordinatesMode;const h=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=h,t.wrapV=h}r._cachedWrapU!==t.wrapU&&(r._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),r)),r._cachedWrapV!==t.wrapV&&(r._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),r)),r.is3D&&r._cachedWrapR!==t.wrapR&&(r._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),r)),this._setAnisotropicLevel(l,r,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 n=0;n=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={},Pt()&&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,wt.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 n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const r=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&r===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,h=new Uint8Array(4);t.readPixels(0,0,1,1,o,l,h),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(n),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._gl.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._gl.SRGB:this._gl.RGB;break;case 5:i=t?this._gl.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._gl.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._gl.SRGB8:this._gl.RGB8;case 5:return i?this._gl.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._gl.SRGB8_ALPHA8:this._gl.RGBA8}_getRGBAMultiSampleBufferFormat(e){return e===1?this._gl.RGBA32F:e===2?this._gl.RGBA16F:this._gl.RGBA8}_loadFile(e,t,i,s,n,r){const o=Ee._FileToolsLoadFile(e,t,i,s,n,r);return this._activeRequests.push(o),o.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),o}static _FileToolsLoadFile(e,t,i,s,n,r){throw Ae("FileTools")}readPixels(e,t,i,s,n=!0,r=!0){const o=n?4:3,l=n?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(s*i*o);return r&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,l,this._gl.UNSIGNED_BYTE,h),Promise.resolve(h)}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=Ee.CeilingPOT(e),i=Ee.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let s;switch(i){case 1:s=Ee.FloorPOT(e);break;case 2:s=Ee.NearestPOT(e);break;case 3:default:s=Ee.CeilingPOT(e);break}return Math.min(s,t)}static QueueNewFrame(e,t){if(Pt()){const{requestPostAnimationFrame:i,requestAnimationFrame:s}=t||window;if(typeof i=="function")return i(e);if(typeof s=="function")return s(e)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:kn()?document:null}}Ee.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"]}];Ee._TextureLoaders=[];Ee.CollisionsEpsilon=.001;Ee._IsSupported=null;Ee._HasMajorPerformanceCaveat=null;class su{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new nu(e)}sampleFrame(e=Pi.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 nu{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}}class Gi{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){Gi.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){Gi.Enabled&&(this._startMonitoringTime=Pi.Now)}endMonitoring(e=!0){if(!Gi.Enabled)return;e&&this.fetchNewFrame();const t=Pi.Now;this._current=t-this._startMonitoringTime,e&&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=Pi.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}Gi.Enabled=!0;Ee.prototype.setAlphaConstants=function(a,e,t,i){this._alphaState.setAlphaBlendConstants(a,e,t,i)};Ee.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};Ee.prototype.getAlphaMode=function(){return this._alphaMode};Ee.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}};Ee.prototype.getAlphaEquation=function(){return this._alphaEquation};function Fa(a,e,t=!1,i){switch(a){case 3:{const n=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e);return i&&n.set(new Int8Array(i)),n}case 0:{const n=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&n.set(new Uint8Array(i)),n}case 4:{const n=e instanceof ArrayBuffer?new Int16Array(e):new Int16Array(t?e/2:e);return i&&n.set(new Int16Array(i)),n}case 5:case 8:case 9:case 10:case 2:{const n=e instanceof ArrayBuffer?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&n.set(new Uint16Array(i)),n}case 6:{const n=e instanceof ArrayBuffer?new Int32Array(e):new Int32Array(t?e/4:e);return i&&n.set(new Int32Array(i)),n}case 7:case 11:case 12:case 13:case 14:case 15:{const n=e instanceof ArrayBuffer?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&n.set(new Uint32Array(i)),n}case 1:{const n=e instanceof ArrayBuffer?new Float32Array(e):new Float32Array(t?e/4:e);return i&&n.set(new Float32Array(i)),n}}const s=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}Ee.prototype._readTexturePixelsSync=function(a,e,t,i=-1,s=0,n=null,r=!0,o=!1,l=0,h=0){var c,u;const d=this._gl;if(!d)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const f=d.createFramebuffer();if(!f)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=f}d.bindFramebuffer(d.FRAMEBUFFER,this._dummyFramebuffer),i>-1?d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+i,(c=a._hardwareTexture)===null||c===void 0?void 0:c.underlyingResource,s):d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,(u=a._hardwareTexture)===null||u===void 0?void 0:u.underlyingResource,s);let _=a.type!==void 0?this._getWebGLTextureType(a.type):d.UNSIGNED_BYTE;if(o)n||(n=Fa(a.type,4*e*t));else switch(_){case d.UNSIGNED_BYTE:n||(n=new Uint8Array(4*e*t)),_=d.UNSIGNED_BYTE;break;default:n||(n=new Float32Array(4*e*t)),_=d.FLOAT;break}return r&&this.flushFramebuffer(),d.readPixels(l,h,e,t,d.RGBA,_,n),d.bindFramebuffer(d.FRAMEBUFFER,this._currentFramebuffer),n};Ee.prototype._readTexturePixels=function(a,e,t,i=-1,s=0,n=null,r=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(a,e,t,i,s,n,r,o,l,h))};Ee.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()};Ee.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 Y extends Ee{static get NpmPackage(){return Ee.NpmPackage}static get Version(){return Ee.Version}static get Instances(){return Ie.Instances}static get LastCreatedEngine(){return Ie.LastCreatedEngine}static get LastCreatedScene(){return Ie.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise((s,n)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{this.createImageBitmap(r,t).then(o=>{s(o)})})},r.onerror=()=>{n("Error loading image ".concat(r.src))},r.src=e})}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const n=this.createCanvas(t,i).getContext("2d");if(!n)throw new Error("Unable to get 2d context for resizeImageBitmap");return n.drawImage(e,0,0),n.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(),!Y.audioEngine&&this._creationOptions.audioEngine&&Y.AudioEngineFactory&&(Y.audioEngine=Y.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),kn()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&Y._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=Y.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 n=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),n}scissorClear(e,t,i,s,n){this.enableScissor(e,t,i,s),this.clear(n,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const n=this._gl;n.enable(n.SCISSOR_TEST),n.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 Ae("WebVRCamera")}_prepareVRComponent(){}_connectVREvents(e,t){}_submitVRFrame(){}disableVR(){}isVRPresenting(){return!1}_requestVRFrame(){}_loadFileAsync(e,t,i){return new Promise((s,n)=>{this._loadFile(e,r=>{s(r)},void 0,t,i,(r,o)=>{n(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 n=null;t&&(t._textures.data[t._currentRenderTextureInd]?n=t._textures.data[t._currentRenderTextureInd]:t._forcedOutputTexture&&(n=t._forcedOutputTexture)),this._bindTexture(e,(s=n==null?void 0:n.texture)!==null&&s!==void 0?s:null,i)}setTextureFromPostProcessOutput(e,t,i){var s,n;this._bindTexture(e,(n=(s=t==null?void 0:t._outputTexture)===null||s===void 0?void 0:s.texture)!==null&&n!==void 0?n: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&&Y._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&Y._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&Y._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){Y._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&&n){const o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(r,n),e.transformFeedback=o}return s.linkProgram(r),this.webGLVersion>1&&n&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),r}_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=++Y._RenderPassIdCounter;return this._renderPassNames[t]=e!=null?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],r,!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(r),r.dispose(),n&&n()}))}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 dl(e,this._gl),n=new Dt(this,ze.Unknown,!0);return n._hardwareTexture=s,n.isReady=!0,n.useMipMaps=t,this.updateTextureSamplingMode(i,n),n}_uploadImageToTexture(e,t,i=0,s=0){const n=this._gl,r=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,o),h=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(h,e,!0),this._unpackFlipY(e.invertY);let c=n.TEXTURE_2D;e.isCube&&(c=n.TEXTURE_CUBE_MAP_POSITIVE_X+i),n.texImage2D(c,s,l,o,r,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){H.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 Vn(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((n,r)=>{const o=()=>{const l=s.clientWaitSync(e,t,0);if(l==s.WAIT_FAILED){r();return}if(l==s.TIMEOUT_EXPIRED){setTimeout(o,i);return}n()};o()})}_readPixelsAsync(e,t,i,s,n,r,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const l=this._gl,h=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.bufferData(l.PIXEL_PACK_BUFFER,o.byteLength,l.STREAM_READ),l.readPixels(e,t,i,s,n,r,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null);const c=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return c?(l.flush(),this._clientWaitAsync(c,0,10).then(()=>(l.deleteSync(c),l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,o),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(h),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();Ie.Instances.length===1&&Y.audioEngine&&(Y.audioEngine.dispose(),Y.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)),kn()&&(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=Ie.Instances.indexOf(this);t>=0&&Ie.Instances.splice(t,1),Y.Instances.length||(Ie.OnEnginesDisposedObservable.notifyObservers(this),Ie.OnEnginesDisposedObservable.clear()),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(!Pt())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!Pt())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Y.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: ".concat(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 n=0,r=0;try{r=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",n=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:n,height:r,descent:r-n}}}Y.ALPHA_DISABLE=0;Y.ALPHA_ADD=1;Y.ALPHA_COMBINE=2;Y.ALPHA_SUBTRACT=3;Y.ALPHA_MULTIPLY=4;Y.ALPHA_MAXIMIZED=5;Y.ALPHA_ONEONE=6;Y.ALPHA_PREMULTIPLIED=7;Y.ALPHA_PREMULTIPLIED_PORTERDUFF=8;Y.ALPHA_INTERPOLATE=9;Y.ALPHA_SCREENMODE=10;Y.DELAYLOADSTATE_NONE=0;Y.DELAYLOADSTATE_LOADED=1;Y.DELAYLOADSTATE_LOADING=2;Y.DELAYLOADSTATE_NOTLOADED=4;Y.NEVER=512;Y.ALWAYS=519;Y.LESS=513;Y.EQUAL=514;Y.LEQUAL=515;Y.GREATER=516;Y.GEQUAL=518;Y.NOTEQUAL=517;Y.KEEP=7680;Y.REPLACE=7681;Y.INCR=7682;Y.DECR=7683;Y.INVERT=5386;Y.INCR_WRAP=34055;Y.DECR_WRAP=34056;Y.TEXTURE_CLAMP_ADDRESSMODE=0;Y.TEXTURE_WRAP_ADDRESSMODE=1;Y.TEXTURE_MIRROR_ADDRESSMODE=2;Y.TEXTUREFORMAT_ALPHA=0;Y.TEXTUREFORMAT_LUMINANCE=1;Y.TEXTUREFORMAT_LUMINANCE_ALPHA=2;Y.TEXTUREFORMAT_RGB=4;Y.TEXTUREFORMAT_RGBA=5;Y.TEXTUREFORMAT_RED=6;Y.TEXTUREFORMAT_R=6;Y.TEXTUREFORMAT_RG=7;Y.TEXTUREFORMAT_RED_INTEGER=8;Y.TEXTUREFORMAT_R_INTEGER=8;Y.TEXTUREFORMAT_RG_INTEGER=9;Y.TEXTUREFORMAT_RGB_INTEGER=10;Y.TEXTUREFORMAT_RGBA_INTEGER=11;Y.TEXTURETYPE_UNSIGNED_BYTE=0;Y.TEXTURETYPE_UNSIGNED_INT=0;Y.TEXTURETYPE_FLOAT=1;Y.TEXTURETYPE_HALF_FLOAT=2;Y.TEXTURETYPE_BYTE=3;Y.TEXTURETYPE_SHORT=4;Y.TEXTURETYPE_UNSIGNED_SHORT=5;Y.TEXTURETYPE_INT=6;Y.TEXTURETYPE_UNSIGNED_INTEGER=7;Y.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;Y.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;Y.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;Y.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;Y.TEXTURETYPE_UNSIGNED_INT_24_8=12;Y.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;Y.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;Y.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;Y.TEXTURE_NEAREST_SAMPLINGMODE=1;Y.TEXTURE_BILINEAR_SAMPLINGMODE=2;Y.TEXTURE_TRILINEAR_SAMPLINGMODE=3;Y.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;Y.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;Y.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;Y.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;Y.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;Y.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;Y.TEXTURE_NEAREST_LINEAR=7;Y.TEXTURE_NEAREST_NEAREST=1;Y.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;Y.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;Y.TEXTURE_LINEAR_LINEAR=2;Y.TEXTURE_LINEAR_NEAREST=12;Y.TEXTURE_EXPLICIT_MODE=0;Y.TEXTURE_SPHERICAL_MODE=1;Y.TEXTURE_PLANAR_MODE=2;Y.TEXTURE_CUBIC_MODE=3;Y.TEXTURE_PROJECTION_MODE=4;Y.TEXTURE_SKYBOX_MODE=5;Y.TEXTURE_INVCUBIC_MODE=6;Y.TEXTURE_EQUIRECTANGULAR_MODE=7;Y.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;Y.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;Y.SCALEMODE_FLOOR=1;Y.SCALEMODE_NEAREST=2;Y.SCALEMODE_CEILING=3;Y._RescalePostProcessFactory=null;Y._RenderPassIdCounter=0;class me{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=me.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=me.Repeat(e,t*2);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=me.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+me.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=me.DeltaAngle(e,t);let n=0;return-i180&&(s-=360),e+s*me.Clamp(i)}static InverseLerp(e,t,i){let s=0;return e!=t?s=me.Clamp((i-e)/(t-e)):s=0,s}static Hermite(e,t,i,s,n){const r=n*n,o=n*r,l=2*o-3*r+1,h=-2*o+3*r,c=o-2*r+n,u=o-r;return e*l+i*h+t*c+s*u}static Hermite1stDerivative(e,t,i,s,n){const r=n*n;return(r-n)*6*e+(3*r-4*n+1)*t+(-r+n)*6*i+(3*r-2*n)*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-=me.TwoPi*Math.floor((e+Math.PI)/me.TwoPi),e}static HCF(e,t){const i=e%t;return i===0?t:me.HCF(t,i)}}me.TwoPi=Math.PI*2;const ru=1/2.2,au=2.2,xt=(1+Math.sqrt(5))/2,Ge=.001;class kt{static BuildArray(e,t){const i=[];for(let s=0;s{const n=s.previous;if(!n)return;const r=s.next;r?(n.next=r,r.previous=n):(n.next=void 0,a[e]=n),s.next=void 0,s.previous=void 0}}const lu=["push","splice","pop","shift","unshift"];function _l(a,e){const t=lu.map(i=>ou(a,i,e));return()=>{t.forEach(i=>{i==null||i()})}}const pl={};function Vt(a,e){pl[a]=e}function $s(a){return pl[a]}const hi=a=>parseInt(a.toString().replace(/\W/g,""));class fe{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return"{X: ".concat(this.x," Y: ").concat(this.y,"}")}getClassName(){return"Vector2"}getHashCode(){const e=hi(this.x),t=hi(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 fe.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=Ge){return e&&me.WithinEpsilon(this.x,e.x,t)&&me.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),n=i*this.x-s*this.y,r=s*this.x+i*this.y;return t.x=n,t.y=r,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 fe.NormalizeToRef(this,this),this}clone(){return new this.constructor(this.x,this.y)}static Zero(){return new fe(0,0)}static One(){return new fe(1,1)}static Random(e=0,t=1){return new fe(me.RandomRange(e,t),me.RandomRange(e,t))}static get ZeroReadOnly(){return fe._ZeroReadOnly}static FromArray(e,t=0){return new fe(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,n){const r=n*n,o=n*r,l=.5*(2*t.x+(-e.x+i.x)*n+(2*e.x-5*t.x+4*i.x-s.x)*r+(-e.x+3*t.x-3*i.x+s.x)*o),h=.5*(2*t.y+(-e.y+i.y)*n+(2*e.y-5*t.y+4*i.y-s.y)*r+(-e.y+3*t.y-3*i.y+s.y)*o);return new e.constructor(l,h)}static Clamp(e,t,i){let s=e.x;s=s>i.x?i.x:s,s=si.y?i.y:n,n=nt.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 fe.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){const s=t.m,n=e.x*s[0]+e.y*s[4]+s[12],r=e.x*s[1]+e.y*s[5]+s[13];return i.x=n,i.y=r,i}static PointInTriangle(e,t,i,s){const n=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),r=n<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*r,l=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*r;return o>0&&l>0&&o+l<2*n*r}static Distance(e,t){return Math.sqrt(fe.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 fe.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=fe.DistanceSquared(t,i);if(s===0)return fe.Distance(e,t);const n=i.subtract(t),r=Math.max(0,Math.min(1,fe.Dot(e.subtract(t),n)/s)),o=t.add(n.multiplyByFloats(r,r));return fe.Distance(e,o)}}fe._ZeroReadOnly=fe.Zero();class v{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: ".concat(this._x," Y: ").concat(this._y," Z: ").concat(this._z,"}")}getClassName(){return"Vector3"}getHashCode(){const e=hi(this._x),t=hi(this._y),i=hi(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 v.FromArrayToRef(e,t,this),this}toQuaternion(){return ue.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 n=t*Math.sin(i)*Math.cos(s),r=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(n,r,o),e}applyRotationQuaternionToRef(e,t){const i=e._w*this._x+e._y*this._z-e._z*this._y,s=e._w*this._y+e._z*this._x-e._x*this._z,n=e._w*this._z+e._x*this._y-e._y*this._x,r=-e._x*this._x-e._y*this._y-e._z*this._z;return t._x=i*e._w+r*-e._x+s*-e._z-n*-e._y,t._y=s*e._w+r*-e._y+n*-e._x-i*-e._z,t._z=n*e._w+r*-e._z+i*-e._y-s*-e._x,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,n=e.d,r=_e.Vector3[0];this.subtractToRef(t,r),r.normalize();const o=v.Dot(r,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(!me.WithinEpsilon(t,i,e))return!0;const s=Math.abs(this._z);return!me.WithinEpsilon(t,s,e)||!me.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:(_e.Vector3[0].copyFrom(this),["x","y","z"].forEach((t,i)=>{this[t]=_e.Vector3[0][e[i]]}),this)}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(_e.Matrix[0]),v.TransformCoordinatesToRef(this,_e.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,_e.Vector3[0]),_e.Vector3[0].rotateByQuaternionToRef(e,_e.Vector3[0]),t.addToRef(_e.Vector3[0],i),i}cross(e){const t=new this.constructor;return v.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 n=v.Dot(e,i)-s,r=v.Dot(t,i)-s;return n/(n-r)}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(_e.Vector3[1]),n=t.normalizeToRef(_e.Vector3[2]);let r=v.Dot(s,n);r=me.Clamp(r,-1,1);const o=Math.acos(r),l=_e.Vector3[3];return v.CrossToRef(s,n,l),v.Dot(l,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(r)}static GetAngleBetweenVectorsOnPlane(e,t,i){_e.Vector3[0].copyFrom(e);const s=_e.Vector3[0];_e.Vector3[1].copyFrom(t);const n=_e.Vector3[1];_e.Vector3[2].copyFrom(i);const r=_e.Vector3[2],o=_e.Vector3[3],l=_e.Vector3[4];s.normalize(),n.normalize(),r.normalize(),v.CrossToRef(r,s,o),v.CrossToRef(o,r,l);const h=Math.atan2(v.Dot(n,o),v.Dot(n,l));return me.NormalizeRadians(h)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=G.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=v.Zero();return v.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=me.Clamp(i,0,1);const n=_e.Vector3[0],r=_e.Vector3[1];n.copyFrom(e);const o=n.length();n.normalizeFromLength(o),r.copyFrom(t);const l=r.length();r.normalizeFromLength(l);const h=v.Dot(n,r);let c,u;if(h<1-Ge){const d=Math.acos(h),_=1/Math.sin(d);c=Math.sin((1-i)*d)*_,u=Math.sin(i*d)*_}else c=1-i,u=i;return n.scaleInPlace(c),r.scaleInPlace(u),s.copyFrom(n).addInPlace(r),s.scaleInPlace(me.Lerp(o,l,i)),s}static SmoothToRef(e,t,i,s,n){return v.SlerpToRef(e,t,s===0?1:i/s,n),n}static FromArray(e,t=0){return new v(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return v.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 v.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new v(0,0,0)}static One(){return new v(1,1,1)}static Up(){return new v(0,1,0)}static get UpReadOnly(){return v._UpReadOnly}static get DownReadOnly(){return v._DownReadOnly}static get RightReadOnly(){return v._RightReadOnly}static get LeftReadOnly(){return v._LeftReadOnly}static get LeftHandedForwardReadOnly(){return v._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return v._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return v._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return v._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return v._ZeroReadOnly}static Down(){return new v(0,-1,0)}static Forward(e=!1){return new v(0,0,e?-1:1)}static Backward(e=!1){return new v(0,0,e?1:-1)}static Right(){return new v(1,0,0)}static Left(){return new v(-1,0,0)}static Random(e=0,t=1){return new v(me.RandomRange(e,t),me.RandomRange(e,t),me.RandomRange(e,t))}static TransformCoordinates(e,t){const i=v.Zero();return v.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return v.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,n){const r=s.m,o=e*r[0]+t*r[4]+i*r[8]+r[12],l=e*r[1]+t*r[5]+i*r[9]+r[13],h=e*r[2]+t*r[6]+i*r[10]+r[14],c=1/(e*r[3]+t*r[7]+i*r[11]+r[15]);return n._x=o*c,n._y=l*c,n._z=h*c,n._isDirty=!0,n}static TransformNormal(e,t){const i=v.Zero();return v.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,n){const r=s.m;return n._x=e*r[0]+t*r[4]+i*r[8],n._y=e*r[1]+t*r[5]+i*r[9],n._z=e*r[2]+t*r[6]+i*r[10],n._isDirty=!0,n}static CatmullRom(e,t,i,s,n){const r=n*n,o=n*r,l=.5*(2*t._x+(-e._x+i._x)*n+(2*e._x-5*t._x+4*i._x-s._x)*r+(-e._x+3*t._x-3*i._x+s._x)*o),h=.5*(2*t._y+(-e._y+i._y)*n+(2*e._y-5*t._y+4*i._y-s._y)*r+(-e._y+3*t._y-3*i._y+s._y)*o),c=.5*(2*t._z+(-e._z+i._z)*n+(2*e._z-5*t._z+4*i._z-s._z)*r+(-e._z+3*t._z-3*i._z+s._z)*o);return new e.constructor(l,h,c)}static Clamp(e,t,i){const s=new e.constructor;return v.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let n=e._x;n=n>i._x?i._x:n,n=ni._y?i._y:r,r=ri._z?i._z:o,o=o0&&R<0?(D.copyFrom(r),W=t,L=i):R>0&&w<0?(D.copyFrom(l),W=i,L=s):(D.copyFrom(o).scaleInPlace(-1),W=s,L=t);const z=_e.Vector3[9],K=_e.Vector3[4];if(W.subtractToRef(m,y),L.subtractToRef(m,z),v.CrossToRef(y,z,K),!(v.Dot(K,h)<0))return n.copyFrom(m),Math.abs(g*p);const $=_e.Vector3[5];v.CrossToRef(D,K,$),$.normalize();const U=_e.Vector3[9];U.copyFrom(W).subtractInPlace(m);const V=U.length();if(Vthis.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 v(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 Ye(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 Ye.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,n){return n.x=e,n.y=t,n.z=i,n.w=s,n}static Zero(){return new Ye(0,0,0,0)}static One(){return new Ye(1,1,1,1)}static Random(e=0,t=1){return new Ye(me.RandomRange(e,t),me.RandomRange(e,t),me.RandomRange(e,t),me.RandomRange(e,t))}static get ZeroReadOnly(){return Ye._ZeroReadOnly}static Normalize(e){const t=Ye.Zero();return Ye.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(Ye.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,n=e.z-t.z,r=e.w-t.w;return i*i+s*s+n*n+r*r}static Center(e,t){return Ye.CenterToRef(e,t,Ye.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=Ye.Zero();return Ye.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return Ye.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,n){const r=s.m,o=e*r[0]+t*r[4]+i*r[8]+r[12],l=e*r[1]+t*r[5]+i*r[9]+r[13],h=e*r[2]+t*r[6]+i*r[10]+r[14],c=e*r[3]+t*r[7]+i*r[11]+r[15];return n.x=o,n.y=l,n.z=h,n.w=c,n}static TransformNormal(e,t){const i=new e.constructor;return Ye.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){const s=t.m,n=e.x*s[0]+e.y*s[4]+e.z*s[8],r=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=n,i.y=r,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,n,r){const o=n.m;return r.x=e*o[0]+t*o[4]+i*o[8],r.y=e*o[1]+t*o[5]+i*o[9],r.z=e*o[2]+t*o[6]+i*o[10],r.w=s,r}static FromVector3(e,t=0){return new Ye(e._x,e._y,e._z,t)}}Ye._ZeroReadOnly=Ye.Zero();class ue{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: ".concat(this._x," Y: ").concat(this._y," Z: ").concat(this._z," W: ").concat(this._w,"}")}getClassName(){return"Quaternion"}getHashCode(){const e=hi(this._x),t=hi(this._y),i=hi(this._z),s=hi(this._w);let n=e;return n=n*397^t,n=n*397^i,n=n*397^s,n}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=Ge){return e&&me.WithinEpsilon(this._x,e._x,t)&&me.WithinEpsilon(this._y,e._y,t)&&me.WithinEpsilon(this._z,e._z,t)&&me.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,n=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,r=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,n,r),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=v.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,n=this._w,r=s*t-i*n,o=.4999999;if(r<-o)e._y=2*Math.atan2(s,n),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(r>o)e._y=2*Math.atan2(s,n),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const l=n*n,h=t*t,c=i*i,u=s*s;e._z=Math.atan2(2*(i*s+t*n),-h-c+u+l),e._x=Math.asin(-2*r),e._y=Math.atan2(2*(t*i+s*n),h-c-u+l),e._isDirty=!0}return e}toRotationMatrix(e){return N.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return ue.FromRotationMatrixToRef(e,this),this}static FromRotationMatrix(e){const t=new ue;return ue.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],n=i[4],r=i[8],o=i[1],l=i[5],h=i[9],c=i[2],u=i[6],d=i[10],_=s+l+d;let f;return _>0?(f=.5/Math.sqrt(_+1),t._w=.25/f,t._x=(u-h)*f,t._y=(r-c)*f,t._z=(o-n)*f,t._isDirty=!0):s>l&&s>d?(f=2*Math.sqrt(1+s-l-d),t._w=(u-h)/f,t._x=.25*f,t._y=(n+o)/f,t._z=(r+c)/f,t._isDirty=!0):l>d?(f=2*Math.sqrt(1+l-s-d),t._w=(r-c)/f,t._x=(n+o)/f,t._y=.25*f,t._z=(h+u)/f,t._isDirty=!0):(f=2*Math.sqrt(1+d-s-l),t._w=(o-n)/f,t._x=(r+c)/f,t._y=(h+u)/f,t._z=.25*f,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=ue.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,n){let r=s===0?1:i/s;return r=me.Clamp(r,0,1),ue.SlerpToRef(e,t,r,n),n}static Zero(){return new ue(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 ue(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 ue.RotationAxisToRef(e,t,new ue)}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 ue(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 ue;return ue.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return ue.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new ue;return ue.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return ue.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i){const s=v.Dot(e,t)+1;return sMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(v.CrossToRef(e,t,G.Vector3[0]),i.set(G.Vector3[0].x,G.Vector3[0].y,G.Vector3[0].z,s)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new ue;return ue.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const n=i*.5,r=t*.5,o=e*.5,l=Math.sin(n),h=Math.cos(n),c=Math.sin(r),u=Math.cos(r),d=Math.sin(o),_=Math.cos(o);return s._x=_*c*h+d*u*l,s._y=d*u*h-_*c*l,s._z=_*u*l-d*c*h,s._w=_*u*h+d*c*l,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new ue;return ue.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const n=(i+e)*.5,r=(i-e)*.5,o=t*.5;return s._x=Math.cos(r)*Math.sin(o),s._y=Math.sin(r)*Math.sin(o),s._z=Math.sin(n)*Math.cos(o),s._w=Math.cos(n)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new ue(0,0,0,0);return ue.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const n=_e.Matrix[0];return N.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),n),ue.FromRotationMatrixToRef(n,s),s}static FromLookDirectionLH(e,t){const i=new ue;return ue.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=_e.Matrix[0];return N.LookDirectionLHToRef(e,t,s),ue.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new ue;return ue.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=_e.Matrix[0];return N.LookDirectionRHToRef(e,t,s),ue.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=ue.Identity();return ue.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let n,r,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)r=1-i,n=l?-i:i;else{const h=Math.acos(o),c=1/Math.sin(h);r=Math.sin((1-i)*h)*c,n=l?-Math.sin(i*h)*c:Math.sin(i*h)*c}return s._x=r*e._x+n*t._x,s._y=r*e._y+n*t._y,s._z=r*e._z+n*t._z,s._w=r*e._w+n*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,n){const r=n*n,o=n*r,l=2*o-3*r+1,h=-2*o+3*r,c=o-2*r+n,u=o-r,d=e._x*l+i._x*h+t._x*c+s._x*u,_=e._y*l+i._y*h+t._y*c+s._y*u,f=e._z*l+i._z*h+t._z*c+s._z*u,g=e._w*l+i._w*h+t._w*c+s._w*u;return new e.constructor(d,_,f,g)}static Hermite1stDerivative(e,t,i,s,n){const r=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,n,r),r}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const o=n*n;return r._x=(o-n)*6*e._x+(3*o-4*n+1)*t._x+(-o+n)*6*i._x+(3*o-2*n)*s._x,r._y=(o-n)*6*e._y+(3*o-4*n+1)*t._y+(-o+n)*6*i._y+(3*o-2*n)*s._y,r._z=(o-n)*6*e._z+(3*o-4*n+1)*t._z+(-o+n)*6*i._z+(3*o-2*n)*s._z,r._w=(o-n)*6*e._w+(3*o-4*n+1)*t._w+(-o+n)*6*i._w+(3*o-2*n)*s._w,r._isDirty=!0,r}}class N{static get Use64Bits(){return Mt.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=N._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,Mt.MatrixTrackPrecisionChange&&Mt.MatrixTrackedMatrices.push(this),this._m=new Mt.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],n=e[3],r=e[4],o=e[5],l=e[6],h=e[7],c=e[8],u=e[9],d=e[10],_=e[11],f=e[12],g=e[13],p=e[14],x=e[15],m=d*x-p*_,T=u*x-g*_,S=u*p-g*d,b=c*x-f*_,y=c*p-d*f,E=c*g-f*u,P=+(o*m-l*T+h*S),C=-(r*m-l*b+h*y),R=+(r*T-o*b+h*E),w=-(r*S-o*y+l*E);return t*P+i*C+s*R+n*w}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return N.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,n=e.m;for(let r=0;r<16;r++)s[r]=i[r]+n[r];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 N.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],n=t[2],r=t[3],o=t[4],l=t[5],h=t[6],c=t[7],u=t[8],d=t[9],_=t[10],f=t[11],g=t[12],p=t[13],x=t[14],m=t[15],T=_*m-x*f,S=d*m-p*f,b=d*x-p*_,y=u*m-g*f,E=u*x-_*g,P=u*p-g*d,C=+(l*T-h*S+c*b),R=-(o*T-h*y+c*E),w=+(o*S-l*y+c*P),D=-(o*b-l*E+h*P),W=i*C+s*R+n*w+r*D;if(W===0)return e.copyFrom(this),e;const L=1/W,z=h*m-x*c,K=l*m-p*c,ae=l*x-p*h,$=o*m-g*c,U=o*x-g*h,V=o*p-g*l,M=h*f-_*c,k=l*f-d*c,X=l*_-d*h,Q=o*f-u*c,ge=o*_-u*h,ye=o*d-u*l,Te=-(s*T-n*S+r*b),Pe=+(i*T-n*y+r*E),De=-(i*S-s*y+r*P),nt=+(i*b-s*E+n*P),Ce=+(s*z-n*K+r*ae),le=-(i*z-n*$+r*U),Fe=+(i*K-s*$+r*V),ke=-(i*ae-s*U+n*V),Xe=-(s*M-n*k+r*X),tt=+(i*M-n*Q+r*ge),Gt=-(i*k-s*Q+r*ye),Rt=+(i*X-s*ge+n*ye);return N.FromValuesToRef(C*L,Te*L,Ce*L,Xe*L,R*L,Pe*L,le*L,tt*L,w*L,De*L,Fe*L,Gt*L,D*L,nt*L,ke*L,Rt*L,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 v(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 N.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,n=e.m,r=s[0],o=s[1],l=s[2],h=s[3],c=s[4],u=s[5],d=s[6],_=s[7],f=s[8],g=s[9],p=s[10],x=s[11],m=s[12],T=s[13],S=s[14],b=s[15],y=n[0],E=n[1],P=n[2],C=n[3],R=n[4],w=n[5],D=n[6],W=n[7],L=n[8],z=n[9],K=n[10],ae=n[11],$=n[12],U=n[13],V=n[14],M=n[15];return t[i]=r*y+o*R+l*L+h*$,t[i+1]=r*E+o*w+l*z+h*U,t[i+2]=r*P+o*D+l*K+h*V,t[i+3]=r*C+o*W+l*ae+h*M,t[i+4]=c*y+u*R+d*L+_*$,t[i+5]=c*E+u*w+d*z+_*U,t[i+6]=c*P+u*D+d*K+_*V,t[i+7]=c*C+u*W+d*ae+_*M,t[i+8]=f*y+g*R+p*L+x*$,t[i+9]=f*E+g*w+p*z+x*U,t[i+10]=f*P+g*D+p*K+x*V,t[i+11]=f*C+g*W+p*ae+x*M,t[i+12]=m*y+T*R+S*L+b*$,t[i+13]=m*E+T*w+S*z+b*U,t[i+14]=m*P+T*D+S*K+b*V,t[i+15]=m*C+T*W+S*ae+b*M,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=hi(this._m[0]);for(let t=1;t<16;t++)e=e*397^hi(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new ue,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 n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),e=e||_e.Vector3[0],e.x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const r=s.scaling.x<0?-1:1,o=s.scaling.y<0?-1:1,l=s.scaling.z<0?-1:1;e.x*=r,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 r=1/e._x,o=1/e._y,l=1/e._z;N.FromValuesToRef(n[0]*r,n[1]*r,n[2]*r,0,n[4]*o,n[5]*o,n[6]*o,0,n[8]*l,n[9]*l,n[10]*l,0,0,0,0,1,_e.Matrix[0]),ue.FromRotationMatrixToRef(_e.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new Ye(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 N.TransposeToRef(this,e),e}transposeToRef(e){return N.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,n){if(e<0||e>3)return this;const r=e*4;return this._m[r+0]=t,this._m[r+1]=i,this._m[r+2]=s,this._m[r+3]=n,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=_e.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return N.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=_e.Vector3[0];if(!this.decompose(t))return N.IdentityToRef(e),e;const i=this._m,s=1/t._x,n=1/t._y,r=1/t._z;return N.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*n,i[5]*n,i[6]*n,0,i[8]*r,i[9]*r,i[10]*r,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 N;return N.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 n=0;n<16;n++)s._m[n]=e[n+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return N._IdentityReadOnly}static FromValuesToRef(e,t,i,s,n,r,o,l,h,c,u,d,_,f,g,p,x){const m=x._m;m[0]=e,m[1]=t,m[2]=i,m[3]=s,m[4]=n,m[5]=r,m[6]=o,m[7]=l,m[8]=h,m[9]=c,m[10]=u,m[11]=d,m[12]=_,m[13]=f,m[14]=g,m[15]=p,x.markAsUpdated()}static FromValues(e,t,i,s,n,r,o,l,h,c,u,d,_,f,g,p){const x=new N,m=x._m;return m[0]=e,m[1]=t,m[2]=i,m[3]=s,m[4]=n,m[5]=r,m[6]=o,m[7]=l,m[8]=h,m[9]=c,m[10]=u,m[11]=d,m[12]=_,m[13]=f,m[14]=g,m[15]=p,x.markAsUpdated(),x}static Compose(e,t,i){const s=new N;return N.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const n=s._m,r=t._x,o=t._y,l=t._z,h=t._w,c=r+r,u=o+o,d=l+l,_=r*c,f=r*u,g=r*d,p=o*u,x=o*d,m=l*d,T=h*c,S=h*u,b=h*d,y=e._x,E=e._y,P=e._z;return n[0]=(1-(p+m))*y,n[1]=(f+b)*y,n[2]=(g-S)*y,n[3]=0,n[4]=(f-b)*E,n[5]=(1-(_+m))*E,n[6]=(x+T)*E,n[7]=0,n[8]=(g+S)*P,n[9]=(x-T)*P,n[10]=(1-(_+p))*P,n[11]=0,n[12]=i._x,n[13]=i._y,n[14]=i._z,n[15]=1,s.markAsUpdated(),s}static Identity(){const e=N.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 N.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=N.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 N;return N.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 N.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 N;return N.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return N.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 N;return N.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return N.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 N;return N.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),n=Math.cos(-t),r=1-n;e.normalize();const o=i._m;return o[0]=e._x*e._x*r+n,o[1]=e._x*e._y*r-e._z*s,o[2]=e._x*e._z*r+e._y*s,o[3]=0,o[4]=e._y*e._x*r+e._z*s,o[5]=e._y*e._y*r+n,o[6]=e._y*e._z*r-e._x*s,o[7]=0,o[8]=e._z*e._x*r-e._y*s,o[9]=e._z*e._y*r+e._x*s,o[10]=e._z*e._z*r+n,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i){const s=v.Dot(t,e),n=i._m;if(s<-1+Ge)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0;else{const r=v.Cross(t,e),o=1/(1+s);n[0]=r._x*r._x*o+s,n[1]=r._y*r._x*o-r._z,n[2]=r._z*r._x*o+r._y,n[3]=0,n[4]=r._x*r._y*o+r._z,n[5]=r._y*r._y*o+s,n[6]=r._z*r._y*o-r._x,n[7]=0,n[8]=r._x*r._z*o-r._y,n[9]=r._y*r._z*o+r._x,n[10]=r._z*r._z*o+s,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 N;return N.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return ue.RotationYawPitchRollToRef(e,t,i,_e.Quaternion[0]),_e.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new N;return N.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return N.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 N;return N.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return N.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 N.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const n=s._m,r=e.m,o=t.m;for(let l=0;l<16;l++)n[l]=r[l]*(1-i)+o[l]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new e.constructor;return N.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const n=_e.Vector3[0],r=_e.Quaternion[0],o=_e.Vector3[1];e.decompose(n,r,o);const l=_e.Vector3[2],h=_e.Quaternion[1],c=_e.Vector3[3];t.decompose(l,h,c);const u=_e.Vector3[4];v.LerpToRef(n,l,i,u);const d=_e.Quaternion[2];ue.SlerpToRef(r,h,i,d);const _=_e.Vector3[5];return v.LerpToRef(o,c,i,_),N.ComposeToRef(u,d,_,s),s}static LookAtLH(e,t,i){const s=new N;return N.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const n=_e.Vector3[0],r=_e.Vector3[1],o=_e.Vector3[2];t.subtractToRef(e,o),o.normalize(),v.CrossToRef(i,o,n);const l=n.lengthSquared();l===0?n.x=1:n.normalizeFromLength(Math.sqrt(l)),v.CrossToRef(o,n,r),r.normalize();const h=-v.Dot(n,e),c=-v.Dot(r,e),u=-v.Dot(o,e);N.FromValuesToRef(n._x,r._x,o._x,0,n._y,r._y,o._y,0,n._z,r._z,o._z,0,h,c,u,1,s)}static LookAtRH(e,t,i){const s=new N;return N.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const n=_e.Vector3[0],r=_e.Vector3[1],o=_e.Vector3[2];e.subtractToRef(t,o),o.normalize(),v.CrossToRef(i,o,n);const l=n.lengthSquared();l===0?n.x=1:n.normalizeFromLength(Math.sqrt(l)),v.CrossToRef(o,n,r),r.normalize();const h=-v.Dot(n,e),c=-v.Dot(r,e),u=-v.Dot(o,e);return N.FromValuesToRef(n._x,r._x,o._x,0,n._y,r._y,o._y,0,n._z,r._z,o._z,0,h,c,u,1,s),s}static LookDirectionLH(e,t){const i=new N;return N.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=_e.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const n=_e.Vector3[1];return v.CrossToRef(t,s,n),N.FromValuesToRef(n._x,n._y,n._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 N;return N.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=_e.Vector3[2];return v.CrossToRef(t,e,s),N.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,n){const r=new N;return N.OrthoLHToRef(e,t,i,s,r,n),r}static OrthoLHToRef(e,t,i,s,n,r){const o=i,l=s,h=2/e,c=2/t,u=2/(l-o),d=-(l+o)/(l-o);return N.FromValuesToRef(h,0,0,0,0,c,0,0,0,0,u,0,0,0,d,1,n),r&&n.multiplyToRef(bs,n),n._updateIdentityStatus(h===1&&c===1&&u===1&&d===0),n}static OrthoOffCenterLH(e,t,i,s,n,r,o){const l=new N;return N.OrthoOffCenterLHToRef(e,t,i,s,n,r,l,o),l}static OrthoOffCenterLHToRef(e,t,i,s,n,r,o,l){const h=n,c=r,u=2/(t-e),d=2/(s-i),_=2/(c-h),f=-(c+h)/(c-h),g=(e+t)/(e-t),p=(s+i)/(i-s);return N.FromValuesToRef(u,0,0,0,0,d,0,0,0,0,_,0,g,p,f,1,o),l&&o.multiplyToRef(bs,o),o.markAsUpdated(),o}static OrthoOffCenterRH(e,t,i,s,n,r,o){const l=new N;return N.OrthoOffCenterRHToRef(e,t,i,s,n,r,l,o),l}static OrthoOffCenterRHToRef(e,t,i,s,n,r,o,l){return N.OrthoOffCenterLHToRef(e,t,i,s,n,r,o,l),o._m[10]*=-1,o}static PerspectiveLH(e,t,i,s,n,r=0){const o=new N,l=i,h=s,c=2*l/e,u=2*l/t,d=(h+l)/(h-l),_=-2*h*l/(h-l),f=Math.tan(r);return N.FromValuesToRef(c,0,0,0,0,u,0,f,0,0,d,1,0,0,_,0,o),n&&o.multiplyToRef(bs,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,n,r=0,o=!1){const l=new N;return N.PerspectiveFovLHToRef(e,t,i,s,l,!0,n,r,o),l}static PerspectiveFovLHToRef(e,t,i,s,n,r=!0,o,l=0,h=!1){const c=i,u=s,d=1/Math.tan(e*.5),_=r?d/t:d,f=r?d:d*t,g=h&&c===0?-1:u!==0?(u+c)/(u-c):1,p=h&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,x=Math.tan(l);return N.FromValuesToRef(_,0,0,0,0,f,0,x,0,0,g,1,0,0,p,0,n),o&&n.multiplyToRef(bs,n),n._updateIdentityStatus(!1),n}static PerspectiveFovReverseLHToRef(e,t,i,s,n,r=!0,o,l=0){const h=1/Math.tan(e*.5),c=r?h/t:h,u=r?h:h*t,d=Math.tan(l);return N.FromValuesToRef(c,0,0,0,0,u,0,d,0,0,-i,1,0,0,1,0,n),o&&n.multiplyToRef(bs,n),n._updateIdentityStatus(!1),n}static PerspectiveFovRH(e,t,i,s,n,r=0,o=!1){const l=new N;return N.PerspectiveFovRHToRef(e,t,i,s,l,!0,n,r,o),l}static PerspectiveFovRHToRef(e,t,i,s,n,r=!0,o,l=0,h=!1){const c=i,u=s,d=1/Math.tan(e*.5),_=r?d/t:d,f=r?d:d*t,g=h&&c===0?1:u!==0?-(u+c)/(u-c):-1,p=h&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,x=Math.tan(l);return N.FromValuesToRef(_,0,0,0,0,f,0,x,0,0,g,-1,0,0,p,0,n),o&&n.multiplyToRef(bs,n),n._updateIdentityStatus(!1),n}static PerspectiveFovReverseRHToRef(e,t,i,s,n,r=!0,o,l=0){const h=1/Math.tan(e*.5),c=r?h/t:h,u=r?h:h*t,d=Math.tan(l);return N.FromValuesToRef(c,0,0,0,0,u,0,d,0,0,-i,-1,0,0,-1,0,n),o&&n.multiplyToRef(bs,n),n._updateIdentityStatus(!1),n}static PerspectiveFovWebVRToRef(e,t,i,s,n=!1,r,o=0){const l=n?-1:1,h=Math.tan(e.upDegrees*Math.PI/180),c=Math.tan(e.downDegrees*Math.PI/180),u=Math.tan(e.leftDegrees*Math.PI/180),d=Math.tan(e.rightDegrees*Math.PI/180),_=2/(u+d),f=2/(h+c),g=Math.tan(o),p=s._m;return p[0]=_,p[1]=p[2]=p[3]=p[4]=0,p[5]=f,p[6]=0,p[7]=g,p[8]=(u-d)*_*.5,p[9]=-((h-c)*f*.5),p[10]=-i/(t-i),p[11]=1*l,p[12]=p[13]=p[15]=0,p[14]=-(2*i*t)/(i-t),r&&s.multiplyToRef(bs,s),s.markAsUpdated(),s}static GetFinalMatrix(e,t,i,s,n,r){const o=e.width,l=e.height,h=e.x,c=e.y,u=N.FromValues(o/2,0,0,0,0,-l/2,0,0,0,0,r-n,0,h+o/2,l/2+c,n,1),d=new t.constructor;return t.multiplyToRef(i,d),d.multiplyToRef(s,d),d.multiplyToRef(u,d)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return Mt.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 Mt.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return N.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 N;return N.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,n=e.normal.z,r=-2*i,o=-2*s,l=-2*n;return N.FromValuesToRef(r*i+1,o*i,l*i,0,r*s,o*s+1,l*s,0,r*n,o*n,l*n+1,0,r*e.d,o*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return N.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,n=e._z*e._z,r=e._x*e._y,o=e._z*e._w,l=e._z*e._x,h=e._y*e._w,c=e._y*e._z,u=e._x*e._w;return t._m[0]=1-2*(s+n),t._m[1]=2*(r+o),t._m[2]=2*(l-h),t._m[3]=0,t._m[4]=2*(r-o),t._m[5]=1-2*(n+i),t._m[6]=2*(c+u),t._m[7]=0,t._m[8]=2*(l+h),t._m[9]=2*(c-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}}N._UpdateFlagSeed=0;N._IdentityReadOnly=N.Identity();class _e{}_e.Vector3=kt.BuildTuple(11,v.Zero);_e.Matrix=kt.BuildTuple(2,N.Identity);_e.Quaternion=kt.BuildTuple(3,ue.Zero);class G{}G.Vector2=kt.BuildTuple(3,fe.Zero);G.Vector3=kt.BuildTuple(13,v.Zero);G.Vector4=kt.BuildTuple(3,Ye.Zero);G.Quaternion=kt.BuildTuple(2,ue.Zero);G.Matrix=kt.BuildTuple(8,N.Identity);Vt("BABYLON.Vector2",fe);Vt("BABYLON.Vector3",v);Vt("BABYLON.Vector4",Ye);Vt("BABYLON.Matrix",N);const bs=N.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);var Nt;(function(a){a[a.LOCAL=0]="LOCAL",a[a.WORLD=1]="WORLD",a[a.BONE=2]="BONE"})(Nt||(Nt={}));class Qt{}Qt.X=new v(1,0,0);Qt.Y=new v(0,1,0);Qt.Z=new v(0,0,1);var $0;(function(a){a[a.X=0]="X",a[a.Y=1]="Y",a[a.Z=2]="Z"})($0||($0={}));function un(a){return Math.pow(a,au)}function dn(a){return a<=.04045?.0773993808*a:Math.pow(.947867299*(a+.055),2.4)}function fn(a){return Math.pow(a,ru)}function _n(a){return a<=.0031308?12.92*a:1.055*Math.pow(a,.41666)-.055}class he{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 he.FromArrayToRef(e,t,this),this}toColor4(e=1){return new q(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 he(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 he(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=me.Clamp(this.r,e,t),i.g=me.Clamp(this.g,e,t),i.b=me.Clamp(this.b,e,t),this}add(e){return new he(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 he(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 he(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"#"+me.ToHex(e)+me.ToHex(t)+me.ToHex(i)}toHSV(){const e=new he;return this.toHSVToRef(e),e}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,n=Math.max(t,i,s),r=Math.min(t,i,s);let o=0,l=0;const h=n,c=n-r;n!==0&&(l=c/n),n!=r&&(n==t?(o=(i-s)/c,i=0&&r<=1?(l=n,h=o):r>=1&&r<=2?(l=o,h=n):r>=2&&r<=3?(h=n,c=o):r>=3&&r<=4?(h=o,c=n):r>=4&&r<=5?(l=o,c=n):r>=5&&r<=6&&(l=n,c=o);const u=i-n;s.set(l+u,h+u,c+u)}static FromHSV(e,t,i){const s=new he(0,0,0);return he.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==7)return new he(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 he.FromInts(t,i,s)}static FromArray(e,t=0){return new he(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 he(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new he(0,0,0);return he.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,n){const r=n*n,o=n*r,l=2*o-3*r+1,h=-2*o+3*r,c=o-2*r+n,u=o-r,d=e.r*l+i.r*h+t.r*c+s.r*u,_=e.g*l+i.g*h+t.g*c+s.g*u,f=e.b*l+i.b*h+t.b*c+s.b*u;return new he(d,_,f)}static Hermite1stDerivative(e,t,i,s,n){const r=he.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,n,r),r}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const o=n*n;r.r=(o-n)*6*e.r+(3*o-4*n+1)*t.r+(-o+n)*6*i.r+(3*o-2*n)*s.r,r.g=(o-n)*6*e.g+(3*o-4*n+1)*t.g+(-o+n)*6*i.g+(3*o-2*n)*s.g,r.b=(o-n)*6*e.b+(3*o-4*n+1)*t.b+(-o+n)*6*i.b+(3*o-2*n)*s.b}static Red(){return new he(1,0,0)}static Green(){return new he(0,1,0)}static Blue(){return new he(0,0,1)}static Black(){return new he(0,0,0)}static get BlackReadOnly(){return he._BlackReadOnly}static White(){return new he(1,1,1)}static Purple(){return new he(.5,0,.5)}static Magenta(){return new he(1,0,1)}static Yellow(){return new he(1,1,0)}static Gray(){return new he(.5,.5,.5)}static Teal(){return new he(0,1,1)}static Random(){return new he(Math.random(),Math.random(),Math.random())}}he._BlackReadOnly=he.Black();let q=class Ht{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 Ht.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 Ht(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new Ht(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 Ht(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=me.Clamp(this.r,e,t),i.g=me.Clamp(this.g,e,t),i.b=me.Clamp(this.b,e,t),i.a=me.Clamp(this.a,e,t),this}multiply(e){return new Ht(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 Ht(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"#"+me.ToHex(t)+me.ToHex(i)+me.ToHex(s);const n=Math.round(this.a*255);return"#"+me.ToHex(t)+me.ToHex(i)+me.ToHex(s)+me.ToHex(n)}toLinearSpace(e=!1){const t=new Ht;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=dn(this.r),e.g=dn(this.g),e.b=dn(this.b)):(e.r=un(this.r),e.g=un(this.g),e.b=un(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ht;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=_n(this.r),e.g=_n(this.g),e.b=_n(this.b)):(e.r=fn(this.r),e.g=fn(this.g),e.b=fn(this.b)),e.a=this.a,this}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==9&&e.length!==7)return new Ht(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),n=e.length===9?parseInt(e.substring(7,9),16):255;return Ht.FromInts(t,i,s,n)}static Lerp(e,t,i){const s=new Ht(0,0,0,0);return Ht.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,n){const r=n*n,o=n*r,l=2*o-3*r+1,h=-2*o+3*r,c=o-2*r+n,u=o-r,d=e.r*l+i.r*h+t.r*c+s.r*u,_=e.g*l+i.g*h+t.g*c+s.g*u,f=e.b*l+i.b*h+t.b*c+s.b*u,g=e.a*l+i.a*h+t.a*c+s.a*u;return new Ht(d,_,f,g)}static Hermite1stDerivative(e,t,i,s,n){const r=new Ht;return this.Hermite1stDerivativeToRef(e,t,i,s,n,r),r}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const o=n*n;r.r=(o-n)*6*e.r+(3*o-4*n+1)*t.r+(-o+n)*6*i.r+(3*o-2*n)*s.r,r.g=(o-n)*6*e.g+(3*o-4*n+1)*t.g+(-o+n)*6*i.g+(3*o-2*n)*s.g,r.b=(o-n)*6*e.b+(3*o-4*n+1)*t.b+(-o+n)*6*i.b+(3*o-2*n)*s.b,r.a=(o-n)*6*e.a+(3*o-4*n+1)*t.a+(-o+n)*6*i.a+(3*o-2*n)*s.a}static FromColor3(e,t=1){return new Ht(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ht(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 Ht(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let s=0;snew q(0,0,0,0));Vt("BABYLON.Color3",he);Vt("BABYLON.Color4",q);class ni{constructor(e,t,i,s){this.normal=new v(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new ni(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=ni._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,n=this.normal.y,r=this.normal.z,o=this.d,l=s*i[0]+n*i[1]+r*i[2]+o*i[3],h=s*i[4]+n*i[5]+r*i[6]+o*i[7],c=s*i[8]+n*i[9]+r*i[10]+o*i[11],u=s*i[12]+n*i[13]+r*i[14]+o*i[15];return new ni(l,h,c,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,n=t.y-e.y,r=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,c=n*h-r*l,u=r*o-s*h,d=s*l-n*o,_=Math.sqrt(c*c+u*u+d*d);let f;return _!==0?f=1/_:f=0,this.normal.x=c*f,this.normal.y=u*f,this.normal.z=d*f,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return v.Dot(this.normal,e)<=t}signedDistanceTo(e){return v.Dot(e,this.normal)+this.d}static FromArray(e){return new ni(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new ni(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new ni(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 v.Dot(i,t)+s}}ni._TmpMatrix=N.Identity();class Ri{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new ni(0,0,0,0));return Ri.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){Ri.GetNearPlaneToRef(e,t[0]),Ri.GetFarPlaneToRef(e,t[1]),Ri.GetLeftPlaneToRef(e,t[2]),Ri.GetRightPlaneToRef(e,t[3]),Ri.GetTopPlaneToRef(e,t[4]),Ri.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}}var pn;(function(a){a[a.CW=0]="CW",a[a.CCW=1]="CCW"})(pn||(pn={}));class Is{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 Is(s)}static FromRadians(e){return new Is(e)}static FromDegrees(e){return new Is(e*Math.PI/180)}}class hu{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),n=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,r=(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 fe((n*(t.y-i.y)-r*(e.y-t.y))/o,((e.x-t.x)*r-(t.x-i.x)*n)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Is.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let h=Is.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=Is.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();h-l>180&&(h-=360),h-l<-180&&(h+=360),c-h>180&&(c-=360),c-h<-180&&(c+=360),this.orientation=h-l<0?pn.CW:pn.CCW,this.angle=Is.FromDegrees(this.orientation===pn.CW?l-c:c-l)}}class r0{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new fe(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new fe(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,n=36){if(this.closed)return this;const r=this._points[this._points.length-1],o=new fe(e,t),l=new fe(i,s),h=new hu(r,o,l);let c=h.angle.radians()/n;h.orientation===pn.CW&&(c*=-1);let u=h.startAngle.radians()+c;for(let d=0;d1)return fe.Zero();const t=e*this.length();let i=0;for(let s=0;s=i&&t<=h){const c=l.normalize(),u=t-i;return new fe(r.x+c.x*u,r.y+c.y*u)}i=h}return fe.Zero()}static StartingAt(e,t){return new r0(e,t)}}class Gn{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:v.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:N.Identity()};for(let n=0;nt){const h=e;e=t,t=h}const i=this.getCurve(),s=this.getPointAt(e);let n=this.getPreviousPointIndexAt(e);const r=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(n++,l.push(s)),l.push(...i.slice(n,o)),(t!==1||e===1)&&l.push(r),new Gn(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 n;me.WithinEpsilon(Math.abs(e.y)/s,1,Ge)?me.WithinEpsilon(Math.abs(e.x)/s,1,Ge)?me.WithinEpsilon(Math.abs(e.z)/s,1,Ge)?n=v.Zero():n=new v(0,0,1):n=new v(1,0,0):n=new v(0,-1,0),i=v.Cross(e,n)}else i=v.Cross(e,t),v.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],n,r=0;const o=e*this.length();for(let l=1;lo){const u=(r-o)/h,d=s.subtract(n),_=n.add(d.scaleInPlace(u));return this._setPointAtData(e,1-u,_,l-1,t)}s=n}return this._pointAtData}_setPointAtData(e,t,i,s,n){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=n,n&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=N.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(),n=this._binormals[e].clone(),r=this._tangents[t].clone(),o=this._normals[t].clone(),l=this._binormals[t].clone(),h=ue.RotationQuaternionFromAxis(s,n,i),c=ue.RotationQuaternionFromAxis(o,l,r);ue.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class Ui{constructor(e,t){this.width=e,this.height=t}toString(){return"{W: ".concat(this.width,", H: ").concat(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 Ui(this.width*e,this.height*t)}clone(){return new Ui(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 Ui(0,0)}add(e){return new Ui(this.width+e.width,this.height+e.height)}subtract(e){return new Ui(this.width-e.width,this.height-e.height)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,n=e.height+(t.height-e.height)*i;return new Ui(s,n)}}class mn{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new mn(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 mn(this.x,this.y,this.width,this.height)}}var Z0;(function(a){a.LowPower="low-power",a.HighPerformance="high-performance"})(Z0||(Z0={}));var Ss;(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"})(Ss||(Ss={}));var Q0;(function(a){a.Unmapped="unmapped",a.Pending="pending",a.Mapped="mapped"})(Q0||(Q0={}));var Je;(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"})(Je||(Je={}));var Xs;(function(a){a[a.Read=1]="Read",a[a.Write=2]="Write"})(Xs||(Xs={}));var Mi;(function(a){a.E1d="1d",a.E2d="2d",a.E3d="3d"})(Mi||(Mi={}));var it;(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"})(it||(it={}));var $e;(function(a){a.E1d="1d",a.E2d="2d",a.E2dArray="2d-array",a.Cube="cube",a.CubeArray="cube-array",a.E3d="3d"})($e||($e={}));var $i;(function(a){a.All="all",a.StencilOnly="stencil-only",a.DepthOnly="depth-only"})($i||($i={}));var I;(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"})(I||(I={}));var hn;(function(a){a.ClampToEdge="clamp-to-edge",a.Repeat="repeat",a.MirrorRepeat="mirror-repeat"})(hn||(hn={}));var Be;(function(a){a.Nearest="nearest",a.Linear="linear"})(Be||(Be={}));var J0;(function(a){a.Nearest="nearest",a.Linear="linear"})(J0||(J0={}));var It;(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"})(It||(It={}));var As;(function(a){a[a.Vertex=1]="Vertex",a[a.Fragment=2]="Fragment",a[a.Compute=4]="Compute"})(As||(As={}));var Ps;(function(a){a.Uniform="uniform",a.Storage="storage",a.ReadOnlyStorage="read-only-storage"})(Ps||(Ps={}));var ws;(function(a){a.Filtering="filtering",a.NonFiltering="non-filtering",a.Comparison="comparison"})(ws||(ws={}));var pi;(function(a){a.Float="float",a.UnfilterableFloat="unfilterable-float",a.Depth="depth",a.Sint="sint",a.Uint="uint"})(pi||(pi={}));var Oa;(function(a){a.WriteOnly="write-only"})(Oa||(Oa={}));var eo;(function(a){a.Error="error",a.Warning="warning",a.Info="info"})(eo||(eo={}));var to;(function(a){a.Validation="validation",a.Internal="internal"})(to||(to={}));var Wn;(function(a){a.Auto="auto"})(Wn||(Wn={}));var _i;(function(a){a.PointList="point-list",a.LineList="line-list",a.LineStrip="line-strip",a.TriangleList="triangle-list",a.TriangleStrip="triangle-strip"})(_i||(_i={}));var Er;(function(a){a.CCW="ccw",a.CW="cw"})(Er||(Er={}));var Dn;(function(a){a.None="none",a.Front="front",a.Back="back"})(Dn||(Dn={}));var io;(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"})(io||(io={}));var Xt;(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"})(Xt||(Xt={}));var Es;(function(a){a.Add="add",a.Subtract="subtract",a.ReverseSubtract="reverse-subtract",a.Min="min",a.Max="max"})(Es||(Es={}));var Li;(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"})(Li||(Li={}));var Ds;(function(a){a.Uint16="uint16",a.Uint32="uint32"})(Ds||(Ds={}));var ht;(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"})(ht||(ht={}));var Cr;(function(a){a.Vertex="vertex",a.Instance="instance"})(Cr||(Cr={}));var so;(function(a){a.Beginning="beginning",a.End="end"})(so||(so={}));var no;(function(a){a.Beginning="beginning",a.End="end"})(no||(no={}));var bt;(function(a){a.Load="load",a.Clear="clear"})(bt||(bt={}));var mi;(function(a){a.Store="store",a.Discard="discard"})(mi||(mi={}));var Rr;(function(a){a.Occlusion="occlusion",a.Timestamp="timestamp"})(Rr||(Rr={}));var Ir;(function(a){a.Opaque="opaque",a.Premultiplied="premultiplied"})(Ir||(Ir={}));var ro;(function(a){a.Unknown="unknown",a.Destroyed="destroyed"})(ro||(ro={}));var ao;(function(a){a.Validation="validation",a.OutOfMemory="out-of-memory",a.Internal="internal"})(ao||(ao={}));class zn{constructor(e,t,i,s=0,n=!1,r=!1,o=!1,l){this._isAlreadyOwned=!1,e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=r,this._divisor=l||1,t instanceof Sn?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=o?s:s*Float32Array.BYTES_PER_ELEMENT,n||this.create()}createVertexBuffer(e,t,i,s,n,r=!1,o){const l=r?t:t*Float32Array.BYTES_PER_ELEMENT,h=s?r?s:s*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new A(this._engine,this,e,this._updatable,!0,h,n===void 0?this._instanced:n,l,i,void 0,void 0,!0,this._divisor||o)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data,e&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e),this._data=e):this._buffer=this._engine.createVertexBuffer(e)))}_rebuild(){this._buffer=null,this.create(this._data)}update(e){this.create(e)}updateDirectly(e,t,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),t===0&&i===void 0?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null,this._data=null)}}class A{get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}constructor(e,t,i,s,n,r,o,l,h,c,u=!1,d=!1,_=1,f=!1){if(t instanceof zn?(this._buffer=t,this._ownsBuffer=f):(this._buffer=new zn(e,t,s,r,n,o,d),this._ownsBuffer=!0),this.uniqueId=A._Counter++,this._kind=i,c==null){const p=this.getData();this.type=A.FLOAT,p instanceof Int8Array?this.type=A.BYTE:p instanceof Uint8Array?this.type=A.UNSIGNED_BYTE:p instanceof Int16Array?this.type=A.SHORT:p instanceof Uint16Array?this.type=A.UNSIGNED_SHORT:p instanceof Int32Array?this.type=A.INT:p instanceof Uint32Array&&(this.type=A.UNSIGNED_INT)}else this.type=c;const g=A.GetTypeByteLength(this.type);d?(this._size=h||(r?r/g:A.DeduceStride(i)),this.byteStride=r||this._buffer.byteStride||this._size*g,this.byteOffset=l||0):(this._size=h||r||A.DeduceStride(i),this.byteStride=r?r*g:this._buffer.byteStride||this._size*g,this.byteOffset=(l||0)*g),this.normalized=u,this._instanced=o!==void 0?o:!1,this._instanceDivisor=o?_:0,this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer&&this._buffer._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();if(!i)return null;const s=this.getSize()*A.GetTypeByteLength(this.type),n=e*this.getSize();if(this.type!==A.FLOAT||this.byteStride!==s){const r=new Float32Array(n);return this.forEach(n,(o,l)=>r[l]=o),r}if(!(i instanceof Array||i instanceof Float32Array)||this.byteOffset!==0||i.length!==n)if(i instanceof Array){const r=this.byteOffset/4;return i.slice(r,r+n)}else{if(i instanceof ArrayBuffer)return new Float32Array(i,this.byteOffset,n);{let r=i.byteOffset+this.byteOffset;if(t){const l=new Float32Array(n),h=new Float32Array(i.buffer,r,n);return l.set(h),l}const o=r%4;return o&&(r=Math.max(0,r-o)),new Float32Array(i.buffer,r,n)}}return t?i.slice():i}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/A.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/A.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*A.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){A.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}static DeduceStride(e){switch(e){case A.UVKind:case A.UV2Kind:case A.UV3Kind:case A.UV4Kind:case A.UV5Kind:case A.UV6Kind:return 2;case A.NormalKind:case A.PositionKind:return 3;case A.ColorKind:case A.MatricesIndicesKind:case A.MatricesIndicesExtraKind:case A.MatricesWeightsKind:case A.MatricesWeightsExtraKind:case A.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetTypeByteLength(e){switch(e){case A.BYTE:case A.UNSIGNED_BYTE:return 1;case A.SHORT:case A.UNSIGNED_SHORT:return 2;case A.INT:case A.UNSIGNED_INT:case A.FLOAT:return 4;default:throw new Error("Invalid type '".concat(e,"'"))}}static ForEach(e,t,i,s,n,r,o,l){if(e instanceof Array){let h=t/4;const c=i/4;for(let u=0;u!a||a.getClassName&&a.getClassName()==="Mesh"?null:a.getClassName&&a.getClassName()==="SubMesh"?a.clone(e):a.clone?a.clone():null;function cu(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 a0{static DeepCopy(e,t,i,s){const n=cu(e);for(const r of n){if(r[0]==="_"&&(!s||s.indexOf(r)===-1)||r.endsWith("Observable")||i&&i.indexOf(r)!==-1)continue;const o=e[r],l=typeof o;if(l!=="function")try{if(l==="object")if(o instanceof Array){if(t[r]=[],o.length>0)if(typeof o[0]=="object")for(let h=0;hs.status!==0||n>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,n)*t}}class vn extends Error{}vn._setPrototypeOf=Object.setPrototypeOf||((a,e)=>(a.__proto__=e,a));const Ks={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class hs extends vn{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",vn._setPrototypeOf(this,hs.prototype)}}const gl=a=>{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,s,n,r,o,l,h,c=0;const u=ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);for(;c>2,o=(i&3)<<4|s>>4,l=(s&15)<<2|n>>6,h=n&63,isNaN(s)?l=h=64:isNaN(n)&&(h=64),t+=e.charAt(r)+e.charAt(o)+e.charAt(l)+e.charAt(h);return t},ml=a=>atob(a),fu=a=>{const e=ml(a),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let s=0;sa},xl=a=>(a=a.replace(/#/gm,"%23"),a),l0=(a,e)=>{if(!(a&&a.indexOf("data:")===0)&&Ut.CorsBehavior)if(typeof Ut.CorsBehavior=="string"||Ut.CorsBehavior instanceof String)e.crossOrigin=Ut.CorsBehavior;else{const t=Ut.CorsBehavior(a);t&&(e.crossOrigin=t)}},h0=(a,e,t,i,s="",n)=>{var r;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:".concat(s,";base64,")+gl(a):a instanceof Blob?(o=URL.createObjectURL(a),l=!0):(o=xl(a),o=Ut.PreprocessUrl(a));const h=Ie.LastCreatedEngine,c=y=>{if(t){const E=o||a.toString();t("Error while trying to load image: ".concat(E.indexOf("http")===0||E.length<=128?E:E.slice(0,128)+"..."),y)}};if(typeof Image>"u"||(r=h==null?void 0:h._features.forceBitmapOverHTMLImageElement)!==null&&r!==void 0&&r)return Fs(o,y=>{h.createImageBitmap(new Blob([y],{type:s}),{premultiplyAlpha:"none",...n}).then(E=>{e(E),l&&URL.revokeObjectURL(o)}).catch(E=>{t&&t("Error while trying to load image: "+a,E)})},void 0,i||void 0,!0,(y,E)=>{c(E)}),null;const u=new Image;l0(o,u);const d=[],_=()=>{d.forEach(y=>{y.target.addEventListener(y.name,y.handler)})},f=()=>{d.forEach(y=>{y.target.removeEventListener(y.name,y.handler)}),d.length=0},g=()=>{f(),e(u),l&&u.src&&URL.revokeObjectURL(u.src)},p=y=>{f(),c(y),l&&u.src&&URL.revokeObjectURL(u.src)},x=y=>{if(y.blockedURI!==u.src)return;f();const E=new Error("CSP violation of policy ".concat(y.effectiveDirective," ").concat(y.blockedURI,". Current policy is ").concat(y.originalPolicy));Ie.UseFallbackTexture=!1,c(E),l&&u.src&&URL.revokeObjectURL(u.src),u.src=""};d.push({target:u,name:"load",handler:g}),d.push({target:u,name:"error",handler:p}),d.push({target:document,name:"securitypolicyviolation",handler:x}),_();const m=o.substring(0,5)==="blob:",T=o.substring(0,5)==="data:",S=()=>{m||T?u.src=o:Fs(o,(y,E,P)=>{const C=!s&&P?P:s,R=new Blob([y],{type:C}),w=URL.createObjectURL(R);l=!0,u.src=w},void 0,i||void 0,!0,(y,E)=>{c(E)})},b=()=>{i&&i.loadImage(o,u)};if(!m&&!T&&i&&i.enableTexturesOffline)i.open(b,S);else{if(o.indexOf("file:")!==-1){const y=decodeURIComponent(o.substring(5).toLowerCase());if(Fn.FilesToLoad[y]&&typeof URL<"u"){try{let E;try{E=URL.createObjectURL(Fn.FilesToLoad[y])}catch{E=URL.createObjectURL(Fn.FilesToLoad[y])}u.src=E,l=!0}catch{u.src=""}return u}}S()}return u},Hn=(a,e,t,i,s)=>{const n=new FileReader,r={onCompleteObservable:new ee,abort:()=>n.abort()};return n.onloadend=()=>r.onCompleteObservable.notifyObservers(r),s&&(n.onerror=()=>{s(new o0("Unable to read ".concat(a.name),a))}),n.onload=o=>{e(o.target.result)},t&&(n.onprogress=t),i?n.readAsArrayBuffer(a):n.readAsText(a),r},Fs=(a,e,t,i,s,n,r)=>{if(a.name)return Hn(a,e,t,s,n?c=>{n(void 0,c)}:void 0);const o=a;if(o.indexOf("file:")!==-1){let c=decodeURIComponent(o.substring(5).toLowerCase());c.indexOf("./")===0&&(c=c.substring(2));const u=Fn.FilesToLoad[c];if(u)return Hn(u,e,t,s,n?d=>n(void 0,new Pr(d.message,d.file)):void 0)}const{match:l,type:h}=_u(o);if(l){const c={onCompleteObservable:new ee,abort:()=>()=>{}};try{const u=s?d0(o):yl(o);e(u,void 0,h)}catch(u){n?n(void 0,u):H.Error(u.message||"Failed to parse the Data URL")}return Mr.SetImmediate(()=>{c.onCompleteObservable.notifyObservers(c)}),c}return c0(o,(c,u)=>{e(c,u==null?void 0:u.responseURL,u==null?void 0:u.getResponseHeader("content-type"))},t,i,s,n?c=>{n(c.request,new Pr(c.message,c.request))}:void 0,r)},c0=(a,e,t,i,s,n,r)=>{a=xl(a),a=Ut.PreprocessUrl(a);const o=Ut.BaseUrl+a;let l=!1;const h={onCompleteObservable:new ee,abort:()=>l=!0},c=()=>{let u=new Jt,d=null,_;const f=()=>{u&&(t&&u.removeEventListener("progress",t),_&&u.removeEventListener("readystatechange",_),u.removeEventListener("loadend",g))};let g=()=>{f(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),t=void 0,_=null,g=null,n=void 0,r=void 0,e=void 0};h.abort=()=>{l=!0,g&&g(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),d!==null&&(clearTimeout(d),d=null),u=null};const p=m=>{const T=m.message||"Unknown error";n&&u?n(new wr(T,u)):H.Error(T)},x=m=>{if(u){if(u.open("GET",o),r)try{r(u)}catch(T){p(T);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),g&&u.addEventListener("loadend",g),_=()=>{if(!(l||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(_&&u.removeEventListener("readystatechange",_),u.status>=200&&u.status<300||u.status===0&&(!Pt()||bl())){try{e&&e(s?u.response:u.responseText,u)}catch(b){p(b)}return}const T=Ut.DefaultRetryStrategy;if(T){const b=T(o,u,m);if(b!==-1){f(),u=new Jt,d=setTimeout(()=>x(m+1),b);return}}const S=new wr("Error status: "+u.status+" "+u.statusText+" - Unable to load "+o,u);n&&n(S)}},u.addEventListener("readystatechange",_),u.send()}};x(0)};if(i&&i.enableSceneOffline){const u=_=>{_&&_.status>400?n&&n(_):c()},d=()=>{i&&i.loadFile(Ut.BaseUrl+a,_=>{!l&&e&&e(_),h.onCompleteObservable.notifyObservers(h)},t?_=>{!l&&t&&t(_)}:void 0,u,s)};i.open(d,u)}else c();return h},bl=()=>typeof location<"u"&&location.protocol==="file:",u0=a=>vl.test(a),_u=a=>{const e=vl.exec(a);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function d0(a){return fu(a.split(",")[1])}const yl=a=>ml(a.split(",")[1]),pu=()=>{Ee._FileToolsLoadImage=h0,Ee._FileToolsLoadFile=Fs,Qi._FileToolsLoadFile=Fs};pu();let Cn;const gu=(a,e,t,i,s,n,r,o,l,h)=>{Cn={DecodeBase64UrlToBinary:a,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:s,LoadFile:n,LoadImage:r,ReadFile:o,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(Cn,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(c){t.DefaultRetryStrategy=c}}),Object.defineProperty(Cn,"BaseUrl",{get:function(){return t.BaseUrl},set:function(c){t.BaseUrl=c}}),Object.defineProperty(Cn,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(c){t.PreprocessUrl=c}}),Object.defineProperty(Cn,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(c){t.CorsBehavior=c}})};gu(d0,yl,Ut,u0,bl,Fs,h0,Hn,c0,l0);class On{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=$s(e);if(t)return t;H.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let n=0,r=i.length;n{const e=Math.random()*16|0;return(a==="x"?e:e&3|8).toString(16)})}class re{static get BaseUrl(){return Ut.BaseUrl}static set BaseUrl(e){Ut.BaseUrl=e}static get DefaultRetryStrategy(){return Ut.DefaultRetryStrategy}static set DefaultRetryStrategy(e){Ut.DefaultRetryStrategy=e}static get CorsBehavior(){return Ut.CorsBehavior}static set CorsBehavior(e){Ut.CorsBehavior=e}static get UseFallbackTexture(){return Ie.UseFallbackTexture}static set UseFallbackTexture(e){Ie.UseFallbackTexture=e}static get RegisteredExternalClasses(){return On.RegisteredExternalClasses}static set RegisteredExternalClasses(e){On.RegisteredExternalClasses=e}static get fallbackTexture(){return Ie.FallbackTexture}static set fallbackTexture(e){Ie.FallbackTexture=e}static FetchToRef(e,t,i,s,n,r){const o=Math.abs(e)*i%i|0,l=Math.abs(t)*s%s|0,h=(o+l*i)*4;r.r=n[h]/255,r.g=n[h+1]/255,r.b=n[h+2]/255,r.a=n[h+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return On.Instantiate(e)}static SetImmediate(e){Mr.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do t*=2;while(t{Fs(e,n=>{i(n)},void 0,void 0,t,(n,r)=>{s(r)})})}static LoadScript(e,t,i,s){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(o){i==null||i("Unable to load script '".concat(e,"' in worker"),o)}return}else if(!Pt()){i==null||i("Cannot load script '".concat(e,"' outside of a window or a worker"));return}const n=document.getElementsByTagName("head")[0],r=document.createElement("script");r.setAttribute("type","text/javascript"),r.setAttribute("src",e),s&&(r.id=s),r.onload=()=>{t&&t()},r.onerror=o=>{i&&i("Unable to load script '".concat(e,"'"),o)},n.appendChild(r)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(s,n)=>{i(n||new Error(s))})})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,n={onCompleteObservable:new ee,abort:()=>s.abort()};return s.onloadend=()=>{n.onCompleteObservable.notifyObservers(n)},s.onload=r=>{t(r.target.result)},s.onprogress=i,s.readAsDataURL(e),n}static ReadFile(e,t,i,s,n){return Hn(e,t,i,s,n)}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){a0.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(r,o).split(",")[1]),h=l.length,c=new Uint8Array(h);for(let u=0;u"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,n="image/png"){throw Ae("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png"){throw Ae("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,n="image/png",r=1,o=!1,l){throw Ae("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",n=1,r=!1,o){throw Ae("ScreenshotTools")}static RandomId(){return Tl()}static IsBase64(e){return u0(e)}static DecodeBase64(e){return d0(e)}static get errorsCount(){return H.errorsCount}static Log(e){H.Log(e)}static Warn(e){H.Warn(e)}static Error(e){H.Error(e)}static get LogCache(){return H.LogCache}static ClearLogCache(){H.ClearLogCache()}static set LogLevels(e){H.LogLevels=e}static set PerformanceLogLevel(e){if((e&re.PerformanceUserMarkLogLevel)===re.PerformanceUserMarkLogLevel){re.StartPerformanceCounter=re._StartUserMark,re.EndPerformanceCounter=re._EndUserMark;return}if((e&re.PerformanceConsoleLogLevel)===re.PerformanceConsoleLogLevel){re.StartPerformanceCounter=re._StartPerformanceConsole,re.EndPerformanceCounter=re._EndPerformanceConsole;return}re.StartPerformanceCounter=re._StartPerformanceCounterDisabled,re.EndPerformanceCounter=re._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!re._Performance){if(!Pt())return;re._Performance=window.performance}!t||!re._Performance.mark||re._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!re._Performance.mark||(re._Performance.mark(e+"-End"),re._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(re._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(re._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return Pi.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 n=t?e:Object.getPrototypeOf(e);i=n.constructor.__bjsclassName__,s=n.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 n0()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}re.UseCustomRequestHeaders=!1;re.CustomRequestHeaders=Jt.CustomRequestHeaders;re._TmpFloatArray=new Float32Array(1);re.GetDOMTextContent=Xr;re.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.")};re.NoneLogLevel=H.NoneLogLevel;re.MessageLogLevel=H.MessageLogLevel;re.WarningLogLevel=H.WarningLogLevel;re.ErrorLogLevel=H.ErrorLogLevel;re.AllLogLevel=H.AllLogLevel;re.IsWindowObjectExist=Pt;re.PerformanceNoneLogLevel=0;re.PerformanceUserMarkLogLevel=1;re.PerformanceConsoleLogLevel=2;re.StartPerformanceCounter=re._StartPerformanceCounterDisabled;re.EndPerformanceCounter=re._EndPerformanceCounterDisabled;class Dr{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{n&&n()?o.breakLoop():setTimeout(()=>{for(let l=0;l=e)break;if(i(h),n&&n()){o.breakLoop();break}}o.executeNext()},r)},s)}}Ie.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";Ee.prototype.createUniformBuffer=function(a){const e=this._gl.createBuffer();if(!e)throw new Error("Unable to create uniform buffer");const t=new Vn(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};Ee.prototype.createDynamicUniformBuffer=function(a){const e=this._gl.createBuffer();if(!e)throw new Error("Unable to create dynamic uniform buffer");const t=new Vn(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};Ee.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)};Ee.prototype.bindUniformBuffer=function(a){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,a?a.underlyingResource:null)};Ee.prototype.bindUniformBufferBase=function(a,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,a?a.underlyingResource:null)};Ee.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 oe{constructor(e,t,i,s,n=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||n,this._dynamic=i,this._name=s!=null?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 n=0;n0){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 r=(4-t)*i;t=t*i+r}s=[];for(let n=0;n1&&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&&(oe._UpdatedUbosInFrame[this._name]||(oe._UpdatedUbosInFrame[this._name]=0),oe._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){H.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 n=0;n=0&&(d.push(o[u]),_.push(f))}this.shaderProcessingContext.attributeNamesFromEffect=d,this.shaderProcessingContext.attributeLocationsFromEffect=_}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new oe(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=rt.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,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt4(e,t,i,s,n)}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,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt4(e,t,i,s,n)}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,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat4(e,t,i,s,n)}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 vu=4,xu=65536,lo={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class bi{static get KnownUBOs(){return bi._SimplifiedKnownBindings?bi._SimplifiedKnownUBOs:bi._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=bi.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=lo[e])!==null&&i!==void 0?i:1)*(t||1),s}getVaryingNextLocation(e,t=0){var i;const s=this._varyingNextLocation;return this._varyingNextLocation+=((i=lo[e])!==null&&i!==void 0?i:1)*(t||1),s}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>xu-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===vu)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}}bi._SimplifiedKnownBindings=!0;bi._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}}};bi._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 bu extends rt{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=at.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const n=e.indexOf("["),r=e.indexOf("]");if(n>0&&r>0){const o=e.substring(n+1,r);s=+o,isNaN(s)&&(s=+i[o.trim()]),e=e.substr(0,n)}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\r\nuniform ".concat(rt.InternalsUBOName," {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n"),s=e.indexOf("// Internals UBO")!==-1;return t?(this._fragmentIsGLES3=e.indexOf("#version 3")!==-1,this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=e.indexOf("#version 3")!==-1,this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingProcessor(e,t,i){this._preProcessors=i;const s=/\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,n=/\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,l=(t&&this._fragmentIsGLES3?n:!t&&this._vertexIsGLES3?s:r).exec(e);if(l!==null){const h=l[1],c=l[2];let u;t?(u=this._webgpuProcessingContext.availableVaryings[c],this._missingVaryings[u]="",u===void 0&&H.Warn('Invalid fragment shader: The varying named "'.concat(c,'" is not declared in the vertex shader! This declaration will be ignored.'))):(u=this._webgpuProcessingContext.getVaryingNextLocation(h,this._getArraySize(c,h,i)[2]),this._webgpuProcessingContext.availableVaryings[c]=u,this._missingVaryings[u]="layout(location = ".concat(u,") in ").concat(h," ").concat(c,";")),e=e.replace(l[0],u===void 0?"":"layout(location = ".concat(u,") ").concat(t?"in":"out"," ").concat(h," ").concat(c,";"))}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,r=(this._vertexIsGLES3?i:s).exec(e);if(r!==null){const o=r[1],l=r[2],h=this._webgpuProcessingContext.getAttributeNextLocation(o,this._getArraySize(l,o,t)[2]);this._webgpuProcessingContext.availableAttributes[l]=h,this._webgpuProcessingContext.orderedAttributes[h]=l,e=e.replace(r[0],"layout(location = ".concat(h,") in ").concat(o," ").concat(l,";"))}return e}uniformProcessor(e,t,i){var s;this._preProcessors=i;const r=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(r!==null){let o=r[1],l=r[2];if(o.indexOf("sampler")===0||o.indexOf("sampler")===1){let h=0;[l,o,h]=this._getArraySize(l,o,i);let c=this._webgpuProcessingContext.availableTextures[l];if(!c){c={autoBindSampler:!0,isTextureArray:h>0,isStorageTexture:!1,textures:[],sampleType:pi.Float};for(let P=0;P<(h||1);++P)c.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const u=(s=rt._SamplerTypeByWebGLSamplerType[o])!==null&&s!==void 0?s:"sampler",d=!!rt._IsComparisonSamplerByWebGPUSamplerType[u],_=d?ws.Comparison:ws.Filtering,f=l+rt.AutoSamplerSuffix;let g=this._webgpuProcessingContext.availableSamplers[f];g||(g={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:_});const p=o.charAt(0)==="u"?"u":o.charAt(0)==="i"?"i":"";p&&(o=o.substr(1));const x=d?pi.Depth:p==="u"?pi.Uint:p==="i"?pi.Sint:pi.Float;c.sampleType=x;const m=h>0,T=g.binding.groupIndex,S=g.binding.bindingIndex,b=rt._SamplerFunctionByWebGLSamplerType[o],y=rt._TextureTypeByWebGLSamplerType[o],E=rt._GpuTextureViewDimensionByWebGPUTextureType[y];if(!m)h=1,e="layout(set = ".concat(T,", binding = ").concat(S,") uniform ").concat(p).concat(u," ").concat(f,";\n layout(set = ").concat(c.textures[0].groupIndex,", binding = ").concat(c.textures[0].bindingIndex,") uniform ").concat(y," ").concat(l,"Texture;\n #define ").concat(l," ").concat(p).concat(b,"(").concat(l,"Texture, ").concat(f,")");else{const P=[];P.push("layout(set = ".concat(T,", binding = ").concat(S,") uniform ").concat(p).concat(u," ").concat(f,";")),e="\r\n";for(let C=0;C0?"\r\n":"","#define ").concat(l).concat(C," ").concat(p).concat(b,"(").concat(l,"Texture").concat(C,", ").concat(f,")")}e=P.join("\r\n")+e,this._textureArrayProcessing.push(l)}this._webgpuProcessingContext.availableTextures[l]=c,this._webgpuProcessingContext.availableSamplers[f]=g,this._addSamplerBindingDescription(f,g,!t);for(let P=0;P=0,h="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",c=l?"vec4 glFragCoord_;\n":"";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,(r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");else{const u=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);u!==null&&(e=e.substring(0,u.index)+"layout(location = 0) "+e.substring(u.index))}e=e.replace(/dFdy/g,"(-yFactor_)*dFdy"),e=e.replace("##INJECTCODE##",c),l&&(e=this._injectStartingAndEndingCode(e,"void main",h))}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\nlayout (num_views = 2) in;\n"+e;if(!i){const l=e.lastIndexOf("}");e=e.substring(0,l),e+="gl_Position.y *= yFactor_;\n",n.isNDCHalfZRange||(e+="gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"),e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let s=i.exec(e);for(;s!==null;){const n=s[1];let r=+n;this._preProcessors&&isNaN(r)&&(r=+this._preProcessors[n.trim()]),e=e.replace(s[0],t+r),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i="layout(set = ".concat(t.binding.groupIndex,", binding = ").concat(t.binding.bindingIndex,") uniform ").concat(e," {\n ");for(const s of this._webgpuProcessingContext.leftOverUniforms)s.length>0?i+=" ".concat(s.type," ").concat(s.name,"[").concat(s.length,"];\n"):i+=" ".concat(s.type," ").concat(s.name,";\n");return i+="};\n\n",i}finalizeShaders(e,t){for(let s=0;s0&&(t=n+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,{vertexCode:e,fragmentCode:t}}}function ur(a,e,t,i){let s=i,n=0,r="";for(;s=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e==95}function La(a){let e=0,t="",i=!1;const s=[];for(;e=0&&a.charAt(e)!==t;)e--;return e}function Tu(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Su="bonesDeclaration",Au="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;\nattribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;\nattribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;\nuniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{\nlet offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2(offset+0,0),0);\nlet m1=textureLoad(smp,vec2(offset+1,0),0);\nlet m2=textureLoad(smp,vec2(offset+2,0),0);\nlet m3=textureLoad(smp,vec2(offset+3,0),0);\nreturn mat4x4(m0,m1,m2,m3);\n}\n#endif\n#endif\n#endif\n";te.IncludesShadersStoreWGSL[Su]=Au;const Eu="bonesVertex",Cu="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";te.IncludesShadersStoreWGSL[Eu]=Cu;const Ru="bakedVertexAnimationDeclaration",Iu="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;\nuniform bakedVertexAnimationTextureSizeInverted: vec2;\nuniform bakedVertexAnimationSettings: vec4;\nvar bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{\nlet offset=i32(index)*4;\nlet frameUV=i32(frame);\nlet m0=textureLoad(smp,vec2(offset+0,frameUV),0);\nlet m1=textureLoad(smp,vec2(offset+1,frameUV),0);\nlet m2=textureLoad(smp,vec2(offset+2,frameUV),0);\nlet m3=textureLoad(smp,vec2(offset+3,frameUV),0);\nreturn mat4x4(m0,m1,m2,m3);\n}\n#endif\n";te.IncludesShadersStoreWGSL[Ru]=Iu;const Mu="bakedVertexAnimation",Pu="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;\nlet VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;\nlet VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;\nlet VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;\nlet VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;\nlet VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;\nlet VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;\nlet time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;\nlet frameCorrection: f32=select(1.0,0.0,time<1.0);\nlet numOfFrames: f32=totalFrames-frameCorrection;\nvar VATFrameNum: f32=fract(time)*numOfFrames;\nVATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;\nVATFrameNum=floor(VATFrameNum);\nVATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;\nvar VATInfluence : mat4x4;\nVATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;\n}\n#endif\n";te.IncludesShadersStoreWGSL[Mu]=Pu;const wu="clipPlaneFragment",Du="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{\ndiscard;\n}\n#endif\n";te.IncludesShadersStoreWGSL[wu]=Du;const Fu="clipPlaneFragmentDeclaration",Ou="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";te.IncludesShadersStoreWGSL[Fu]=Ou;const Lu="clipPlaneVertex",Bu="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";te.IncludesShadersStoreWGSL[Lu]=Bu;const Nu="clipPlaneVertexDeclaration",Uu="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;\nvarying fClipDistance6: f32;\n#endif\n";te.IncludesShadersStoreWGSL[Nu]=Uu;const ku="instancesDeclaration",Vu="#ifdef INSTANCES\nattribute world0 : vec4;\nattribute world1 : vec4;\nattribute world2 : vec4;\nattribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;\nattribute previousWorld1 : vec4;\nattribute previousWorld2 : vec4;\nattribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";te.IncludesShadersStoreWGSL[ku]=Vu;const Gu="instancesVertex",Wu="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\n#endif\n#endif\n";te.IncludesShadersStoreWGSL[Gu]=Wu;const zu="meshUboDeclaration",Hu="struct Mesh {\nworld : mat4x4,\nvisibility : f32,\n};\nvar mesh : Mesh;\n#define WORLD_UBO\n";te.IncludesShadersStoreWGSL[zu]=Hu;const Xu="morphTargetsVertex",Ku="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE \nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;\npositionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";te.IncludesShadersStoreWGSL[Xu]=Ku;const Yu="morphTargetsVertexDeclaration",qu="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#endif\n#endif\n";te.IncludesShadersStoreWGSL[Yu]=qu;const ju="morphTargetsVertexGlobal",$u="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";te.IncludesShadersStoreWGSL[ju]=$u;const Zu="morphTargetsVertexGlobalDeclaration",Qu="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;\nuniform morphTargetTextureInfo : vec3;\nvar morphTargets : texture_2d_array;\nvar morphTargetsSampler : sampler;\nfn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);\nlet x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;\nlet textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);\nreturn textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;\n}\n#endif\n#endif\n";te.IncludesShadersStoreWGSL[Zu]=Qu;const Ju="sceneUboDeclaration",ed="struct Scene {\nviewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,\n};\nvar scene : Scene;\n";te.IncludesShadersStoreWGSL[Ju]=ed;const co="fragmentOutputs.fragDepth",td="uniforms",id="internals",sd={texture_1d:$e.E1d,texture_2d:$e.E2d,texture_2d_array:$e.E2dArray,texture_3d:$e.E3d,texture_cube:$e.Cube,texture_cube_array:$e.CubeArray,texture_multisampled_2d:$e.E2d,texture_depth_2d:$e.E2d,texture_depth_2d_array:$e.E2dArray,texture_depth_cube:$e.Cube,texture_depth_cube_array:$e.CubeArray,texture_depth_multisampled_2d:$e.E2d,texture_storage_1d:$e.E1d,texture_storage_2d:$e.E2d,texture_storage_2d_array:$e.E2dArray,texture_storage_3d:$e.E3d,texture_external:null};class nd extends rt{constructor(){super(...arguments),this.shaderLanguage=at.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 n=t.lastIndexOf(">");if(t.indexOf("array")>=0&&n>0){let r=n;for(;r>0&&t.charAt(r)!==" "&&t.charAt(r)!==",";)r--;const o=t.substring(r+1,n);for(s=+o,isNaN(s)&&(s=+i[o.trim()]);r>0&&(t.charAt(r)===" "||t.charAt(r)===",");)r--;t=t.substring(t.indexOf("<")+1,r+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesWGSL=[],this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return"struct ".concat(rt.InternalsUBOName," {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar ").concat(id," : ").concat(rt.InternalsUBOName,";\n")+La(e)}varyingProcessor(e,t,i){const n=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(n!==null){const r=n[2],o=n[1];let l;t?(l=this._webgpuProcessingContext.availableVaryings[o],l===void 0&&H.Warn('Invalid fragment shader: The varying named "'.concat(o,'" is not declared in the vertex shader! This declaration will be ignored.'))):(l=this._webgpuProcessingContext.getVaryingNextLocation(r,this._getArraySize(o,r,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=l,this._varyingsWGSL.push(" @location(".concat(l,") ").concat(o," : ").concat(r,",")),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 n=s[2],r=s[1],o=this._webgpuProcessingContext.getAttributeNextLocation(n,this._getArraySize(r,n,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=o,this._webgpuProcessingContext.orderedAttributes[o]=r,this._attributesWGSL.push("@location(".concat(o,") ").concat(r," : ").concat(n,",")),e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(s!==null){const n=s[2],r=s[1];this._addUniformToLeftOverUBO(r,n,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(s!==null){const n=s[1],r=s[2],o=!!s[3],l=s[4],h=l.indexOf("storage")>0,c=s[6],u=h?c.substring(0,c.indexOf(",")).trim():null;let d=o?this._getArraySize(n,r,i)[2]:0,_=this._webgpuProcessingContext.availableTextures[n];if(_)d=_.textures.length;else{_={isTextureArray:d>0,isStorageTexture:h,textures:[],sampleType:pi.Float},d=d||1;for(let x=0;x0,g=sd[l],p=f?pi.Depth:c==="u32"?pi.Uint:c==="i32"?pi.Sint:pi.Float;if(_.sampleType=p,g===void 0)throw"Can't get the texture dimension corresponding to the texture function \"".concat(l,'"!');for(let x=0;x=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";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 n="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesWGSL.length>0&&(n+=this._attributesWGSL.join("\n")),n+="\n};\nvar vertexInputs : VertexInputs;\n";let r="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(r+=this._varyingsWGSL.join("\n")),r+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=n+r+e;const o="\n vertexInputs = input;\n",l=" vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n 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 h="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(h+=this._varyingsWGSL.join("\n")),h+="\n};\nvar fragmentInputs : FragmentInputs;\n";let c="struct FragmentOutputs {\n @location(0) color : vec4,\n",u=!1,d=0;for(;!u&&(d=t.indexOf(co,d),!(d<0));){const g=d;for(u=!0;d>1&&t.charAt(d)!=="\n";){if(t.charAt(d)==="/"&&t.charAt(d-1)==="/"){u=!1;break}d--}d=g+co.length}u&&(c+=" @builtin(frag_depth) fragDepth: f32,\n"),c+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=h+c+t;const _=" fragmentInputs = input;\n "+i,f=" return fragmentOutputs;";return t=this._injectStartingAndEndingCode(t,"fn main",_,f),this._collectBindingNames(),this._preCreateBindGroupEntries(),{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s="struct ".concat(e," {\n");for(const n of this._webgpuProcessingContext.leftOverUniforms){const r=n.type.replace(/^(.*?)(<.*>)?$/,"$1"),o=rt.UniformSizes[r];if(n.length>0)if(o<=2){const l="".concat(e,"_").concat(this._stridedUniformArrays.length,"_strided_arr");i+="struct ".concat(l," {\n @size(16)\n el: ").concat(r,",\n }"),this._stridedUniformArrays.push(n.name),s+=" @align(16) ".concat(n.name," : array<").concat(l,", ").concat(n.length,">,\n")}else s+=" ".concat(n.name," : array<").concat(n.type,", ").concat(n.length,">,\n");else s+=" ".concat(n.name," : ").concat(n.type,",\n")}return s+="};\n",s="".concat(i,"\n").concat(s),s+="@group(".concat(t.binding.groupIndex,") @binding(").concat(t.binding.bindingIndex,") var ").concat(td," : ").concat(e,";\n"),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 n=s[1],r=s[2],o=n.indexOf(rt.AutoSamplerSuffix)===n.length-rt.AutoSamplerSuffix.length?n.substring(0,n.indexOf(rt.AutoSamplerSuffix)):null,l=r==="sampler_comparison"?ws.Comparison:ws.Filtering;if(o){const _=this._webgpuProcessingContext.availableTextures[o];_&&(_.autoBindSampler=!0)}let h=this._webgpuProcessingContext.availableSamplers[n];h||(h={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:l},this._webgpuProcessingContext.availableSamplers[n]=h),this._addSamplerBindingDescription(n,h,t);const c=e.substring(0,s.index),u="@group(".concat(h.binding.groupIndex,") @binding(").concat(h.binding.bindingIndex,") "),d=e.substring(s.index);e=c+u+d,i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const s=i.exec(e);if(s===null)break;const n=s[1],r=s[3];let o=s[4];const l=s[5];let h=this._webgpuProcessingContext.availableBuffers[o];if(!h){const g=n==="uniform"?bi.KnownUBOs[l]:null;let p;g?(o=l,p=g.binding,p.groupIndex===-1&&(p=this._webgpuProcessingContext.getNextFreeUBOBinding())):p=this._webgpuProcessingContext.getNextFreeUBOBinding(),h={binding:p},this._webgpuProcessingContext.availableBuffers[o]=h}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],r==="read_write"?Ps.Storage:n==="storage"?Ps.ReadOnlyStorage:Ps.Uniform,t);const c=h.binding.groupIndex,u=h.binding.bindingIndex,d=e.substring(0,s.index),_="@group(".concat(c,") @binding(").concat(u,") "),f=e.substring(s.index);e=d+_+f,i.lastIndex+=_.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp("".concat(t,"\\s*\\[(.*)\\]"),"g"),"".concat(t,"[$1].el"));return e}}class xr{get underlyingResource(){return this._webgpuTexture}get msaaTexture(){return this._webgpuMSAATexture}set msaaTexture(e){this._webgpuMSAATexture=e}constructor(e=null){this.format=I.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,n){t=e===ze.RenderTarget?!1:t,this.createView({format:this.format,dimension:i?$e.Cube:$e.E2d,mipLevelCount:t?me.ILog2(Math.max(s,n))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:$i.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,i;(e=this._webgpuTexture)===null||e===void 0||e.destroy(),(t=this._webgpuMSAATexture)===null||t===void 0||t.destroy(),(i=this._copyInvertYTempTexture)===null||i===void 0||i.destroy(),this.reset()}}const rd="\n 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));\n 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));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",ad="\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n ",Sl="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n 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));\n 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));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",od="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n ",ld=Sl,hd="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n ",cd="\n 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));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",ud="\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n ",dd="\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n \n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n ",fd="\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ",_d="\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n ";var Ci;(function(a){a[a.MipMap=0]="MipMap",a[a.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",a[a.Clear=2]="Clear",a[a.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(Ci||(Ci={}));var cn;(function(a){a[a.DontInvertY=0]="DontInvertY",a[a.InvertY=1]="InvertY"})(cn||(cn={}));const uo=[{vertex:rd,fragment:ad},{vertex:Sl,fragment:od},{vertex:cd,fragment:ud},{vertex:ld,fragment:hd}],Ln={"":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,"depth24unorm-stencil8":37,"depth32float-stencil8":38};class Qe{static ComputeNumMipmapLevels(e,t){return me.ILog2(Math.max(e,t))+1}constructor(e,t,i,s){this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=s,this._mipmapSampler=e.createSampler({minFilter:Be.Linear}),this._videoSampler=e.createSampler({minFilter:Be.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,Je.Uniform|Je.CopyDst).underlyingResource,this._getPipeline(I.RGBA8Unorm),this._getVideoPipeline(I.RGBA8Unorm)}_getPipeline(e,t=Ci.MipMap,i){const s=t===Ci.MipMap?1:t===Ci.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Ci.Clear?8:t===Ci.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let n=this._pipelines[e][s];if(!n){let r="#version 450\r\n";(t===Ci.InvertYPremultiplyAlpha||t===Ci.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(r+="#define INVERTY\r\n"),i.premultiplyAlpha&&(r+="#define PREMULTIPLYALPHA\r\n"));let o=this._compiledShaders[s];if(!o){let h=this._glslang.compileGLSL(r+uo[t].vertex,"vertex"),c=this._glslang.compileGLSL(r+uo[t].fragment,"fragment");this._tintWASM&&(h=this._tintWASM.convertSpirV2WGSL(h),c=this._tintWASM.convertSpirV2WGSL(c));const u=this._device.createShaderModule({code:h}),d=this._device.createShaderModule({code:c});o=this._compiledShaders[s]=[u,d]}const l=this._device.createRenderPipeline({layout:Wn.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:_i.TriangleStrip,stripIndexFormat:Ds.Uint16}});n=this._pipelines[e][s]=[l,l.getBindGroupLayout(0)]}return n}_getVideoPipeline(e,t=cn.DontInvertY){const i=t===cn.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let n=this._videoCompiledShaders[i];if(!n){const o=this._device.createShaderModule({code:dd}),l=this._device.createShaderModule({code:i===0?fd:_d});n=this._videoCompiledShaders[i]=[o,l]}const r=this._device.createRenderPipeline({label:"CopyVideoToTexture_".concat(e,"_").concat(i===0?"DontInvertY":"InvertY"),layout:Wn.Auto,vertex:{module:n[0],entryPoint:"main"},fragment:{module:n[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:_i.TriangleStrip,stripIndexFormat:Ds.Uint16}});s=this._videoPipelines[e][i]=[r,r.getBindGroupLayout(0)]}return s}static _GetTextureTypeFromFormat(e){switch(e){case I.R8Unorm:case I.R8Snorm:case I.R8Uint:case I.R8Sint:case I.RG8Unorm:case I.RG8Snorm:case I.RG8Uint:case I.RG8Sint:case I.RGBA8Unorm:case I.RGBA8UnormSRGB:case I.RGBA8Snorm:case I.RGBA8Uint:case I.RGBA8Sint:case I.BGRA8Unorm:case I.BGRA8UnormSRGB:case I.RGB10A2Unorm:case I.RGB9E5UFloat:case I.RG11B10UFloat:case I.Depth24UnormStencil8:case I.Depth32FloatStencil8:case I.BC7RGBAUnorm:case I.BC7RGBAUnormSRGB:case I.BC6HRGBUFloat:case I.BC6HRGBFloat:case I.BC5RGUnorm:case I.BC5RGSnorm:case I.BC3RGBAUnorm:case I.BC3RGBAUnormSRGB:case I.BC2RGBAUnorm:case I.BC2RGBAUnormSRGB:case I.BC4RUnorm:case I.BC4RSnorm:case I.BC1RGBAUnorm:case I.BC1RGBAUnormSRGB:case I.ETC2RGB8Unorm:case I.ETC2RGB8UnormSRGB:case I.ETC2RGB8A1Unorm:case I.ETC2RGB8A1UnormSRGB:case I.ETC2RGBA8Unorm:case I.ETC2RGBA8UnormSRGB:case I.EACR11Unorm:case I.EACR11Snorm:case I.EACRG11Unorm:case I.EACRG11Snorm:case I.ASTC4x4Unorm:case I.ASTC4x4UnormSRGB:case I.ASTC5x4Unorm:case I.ASTC5x4UnormSRGB:case I.ASTC5x5Unorm:case I.ASTC5x5UnormSRGB:case I.ASTC6x5Unorm:case I.ASTC6x5UnormSRGB:case I.ASTC6x6Unorm:case I.ASTC6x6UnormSRGB:case I.ASTC8x5Unorm:case I.ASTC8x5UnormSRGB:case I.ASTC8x6Unorm:case I.ASTC8x6UnormSRGB:case I.ASTC8x8Unorm:case I.ASTC8x8UnormSRGB:case I.ASTC10x5Unorm:case I.ASTC10x5UnormSRGB:case I.ASTC10x6Unorm:case I.ASTC10x6UnormSRGB:case I.ASTC10x8Unorm:case I.ASTC10x8UnormSRGB:case I.ASTC10x10Unorm:case I.ASTC10x10UnormSRGB:case I.ASTC12x10Unorm:case I.ASTC12x10UnormSRGB:case I.ASTC12x12Unorm:case I.ASTC12x12UnormSRGB:return 0;case I.R16Uint:case I.R16Sint:case I.RG16Uint:case I.RG16Sint:case I.RGBA16Uint:case I.RGBA16Sint:case I.Depth16Unorm:return 5;case I.R16Float:case I.RG16Float:case I.RGBA16Float:return 2;case I.R32Uint:case I.R32Sint:case I.RG32Uint:case I.RG32Sint:case I.RGBA32Uint:case I.RGBA32Sint:return 7;case I.R32Float:case I.RG32Float:case I.RGBA32Float:case I.Depth32Float:return 1;case I.Stencil8:throw"No fixed size for Stencil8 format!";case I.Depth24Plus:throw"No fixed size for Depth24Plus format!";case I.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0}static _GetBlockInformationFromFormat(e){switch(e){case I.R8Unorm:case I.R8Snorm:case I.R8Uint:case I.R8Sint:return{width:1,height:1,length:1};case I.R16Uint:case I.R16Sint:case I.R16Float:case I.RG8Unorm:case I.RG8Snorm:case I.RG8Uint:case I.RG8Sint:return{width:1,height:1,length:2};case I.R32Uint:case I.R32Sint:case I.R32Float:case I.RG16Uint:case I.RG16Sint:case I.RG16Float:case I.RGBA8Unorm:case I.RGBA8UnormSRGB:case I.RGBA8Snorm:case I.RGBA8Uint:case I.RGBA8Sint:case I.BGRA8Unorm:case I.BGRA8UnormSRGB:case I.RGB9E5UFloat:case I.RGB10A2Unorm:case I.RG11B10UFloat:return{width:1,height:1,length:4};case I.RG32Uint:case I.RG32Sint:case I.RG32Float:case I.RGBA16Uint:case I.RGBA16Sint:case I.RGBA16Float:return{width:1,height:1,length:8};case I.RGBA32Uint:case I.RGBA32Sint:case I.RGBA32Float:return{width:1,height:1,length:16};case I.Stencil8:throw"No fixed size for Stencil8 format!";case I.Depth16Unorm:return{width:1,height:1,length:2};case I.Depth24Plus:throw"No fixed size for Depth24Plus format!";case I.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case I.Depth32Float:return{width:1,height:1,length:4};case I.Depth24UnormStencil8:return{width:1,height:1,length:4};case I.Depth32FloatStencil8:return{width:1,height:1,length:5};case I.BC7RGBAUnorm:case I.BC7RGBAUnormSRGB:case I.BC6HRGBUFloat:case I.BC6HRGBFloat:case I.BC5RGUnorm:case I.BC5RGSnorm:case I.BC3RGBAUnorm:case I.BC3RGBAUnormSRGB:case I.BC2RGBAUnorm:case I.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case I.BC4RUnorm:case I.BC4RSnorm:case I.BC1RGBAUnorm:case I.BC1RGBAUnormSRGB:return{width:4,height:4,length:8};case I.ETC2RGB8Unorm:case I.ETC2RGB8UnormSRGB:case I.ETC2RGB8A1Unorm:case I.ETC2RGB8A1UnormSRGB:case I.EACR11Unorm:case I.EACR11Snorm:return{width:4,height:4,length:8};case I.ETC2RGBA8Unorm:case I.ETC2RGBA8UnormSRGB:case I.EACRG11Unorm:case I.EACRG11Snorm:return{width:4,height:4,length:16};case I.ASTC4x4Unorm:case I.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case I.ASTC5x4Unorm:case I.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case I.ASTC5x5Unorm:case I.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case I.ASTC6x5Unorm:case I.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case I.ASTC6x6Unorm:case I.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case I.ASTC8x5Unorm:case I.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case I.ASTC8x6Unorm:case I.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case I.ASTC8x8Unorm:case I.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case I.ASTC10x5Unorm:case I.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case I.ASTC10x6Unorm:case I.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case I.ASTC10x8Unorm:case I.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case I.ASTC10x10Unorm:case I.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case I.ASTC12x10Unorm:case I.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case I.ASTC12x12Unorm:case I.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 I.BC7RGBAUnormSRGB:case I.BC7RGBAUnorm:case I.BC6HRGBFloat:case I.BC6HRGBUFloat:case I.BC5RGSnorm:case I.BC5RGUnorm:case I.BC4RSnorm:case I.BC4RUnorm:case I.BC3RGBAUnormSRGB:case I.BC3RGBAUnorm:case I.BC2RGBAUnormSRGB:case I.BC2RGBAUnorm:case I.BC1RGBAUnormSRGB:case I.BC1RGBAUnorm:case I.ETC2RGB8Unorm:case I.ETC2RGB8UnormSRGB:case I.ETC2RGB8A1Unorm:case I.ETC2RGB8A1UnormSRGB:case I.ETC2RGBA8Unorm:case I.ETC2RGBA8UnormSRGB:case I.EACR11Unorm:case I.EACR11Snorm:case I.EACRG11Unorm:case I.EACRG11Snorm:case I.ASTC4x4Unorm:case I.ASTC4x4UnormSRGB:case I.ASTC5x4Unorm:case I.ASTC5x4UnormSRGB:case I.ASTC5x5Unorm:case I.ASTC5x5UnormSRGB:case I.ASTC6x5Unorm:case I.ASTC6x5UnormSRGB:case I.ASTC6x6Unorm:case I.ASTC6x6UnormSRGB:case I.ASTC8x5Unorm:case I.ASTC8x5UnormSRGB:case I.ASTC8x6Unorm:case I.ASTC8x6UnormSRGB:case I.ASTC8x8Unorm:case I.ASTC8x8UnormSRGB:case I.ASTC10x5Unorm:case I.ASTC10x5UnormSRGB:case I.ASTC10x6Unorm:case I.ASTC10x6UnormSRGB:case I.ASTC10x8Unorm:case I.ASTC10x8UnormSRGB:case I.ASTC10x10Unorm:case I.ASTC10x10UnormSRGB:case I.ASTC12x10Unorm:case I.ASTC12x10UnormSRGB:case I.ASTC12x12Unorm:case I.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return I.Depth16Unorm;case 16:return I.Depth24Plus;case 13:return I.Depth24PlusStencil8;case 14:return I.Depth32Float;case 17:return I.Depth24UnormStencil8;case 18:return I.Depth32FloatStencil8;case 19:return I.Stencil8;case 36492:return i?I.BC7RGBAUnormSRGB:I.BC7RGBAUnorm;case 36495:return I.BC6HRGBUFloat;case 36494:return I.BC6HRGBFloat;case 33779:return i?I.BC3RGBAUnormSRGB:I.BC3RGBAUnorm;case 33778:return i?I.BC2RGBAUnormSRGB:I.BC2RGBAUnorm;case 33777:case 33776:return i?I.BC1RGBAUnormSRGB:I.BC1RGBAUnorm;case 37808:return i?I.ASTC4x4UnormSRGB:I.ASTC4x4Unorm;case 36196:case 37492:return i?I.ETC2RGB8UnormSRGB:I.ETC2RGB8Unorm;case 37496:return i?I.ETC2RGBA8UnormSRGB:I.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return I.R8Snorm;case 7:return I.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return I.R8Sint;case 9:return I.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return I.RGBA8Sint;default:return I.RGBA8Snorm}case 0:switch(t){case 6:return I.R8Unorm;case 7:return I.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?I.RGBA8UnormSRGB:I.RGBA8Unorm;case 12:return i?I.BGRA8UnormSRGB:I.BGRA8Unorm;case 8:return I.R8Uint;case 9:return I.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return I.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 I.RGBA8Unorm}case 4:switch(t){case 8:return I.R16Sint;case 9:return I.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return I.RGBA16Sint;default:return I.RGBA16Sint}case 5:switch(t){case 8:return I.R16Uint;case 9:return I.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return I.RGBA16Uint;default:return I.RGBA16Uint}case 6:switch(t){case 8:return I.R32Sint;case 9:return I.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return I.RGBA32Sint;default:return I.RGBA32Sint}case 7:switch(t){case 8:return I.R32Uint;case 9:return I.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return I.RGBA32Uint;default:return I.RGBA32Uint}case 1:switch(t){case 6:return I.R32Float;case 7:return I.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return I.RGBA32Float;default:return I.RGBA32Float}case 2:switch(t){case 6:return I.R16Float;case 7:return I.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return I.RGBA16Float;default:return I.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:throw"TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV format not supported in WebGPU";case 14:throw"TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV format not supported in WebGPU";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 I.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 I.RGB10A2Unorm}}return i?I.RGBA8UnormSRGB:I.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case I.R8Unorm:case I.R8Snorm:case I.R8Uint:case I.R8Sint:case I.BC4RUnorm:case I.BC4RSnorm:case I.R16Uint:case I.R16Sint:case I.Depth16Unorm:case I.R16Float:case I.R32Uint:case I.R32Sint:case I.R32Float:case I.Depth32Float:case I.Stencil8:case I.Depth24Plus:case I.EACR11Unorm:case I.EACR11Snorm:return 1;case I.RG8Unorm:case I.RG8Snorm:case I.RG8Uint:case I.RG8Sint:case I.Depth24UnormStencil8:case I.Depth32FloatStencil8:case I.BC5RGUnorm:case I.BC5RGSnorm:case I.RG16Uint:case I.RG16Sint:case I.RG16Float:case I.RG32Uint:case I.RG32Sint:case I.RG32Float:case I.Depth24PlusStencil8:case I.EACRG11Unorm:case I.EACRG11Snorm:return 2;case I.RGB9E5UFloat:case I.RG11B10UFloat:case I.BC6HRGBUFloat:case I.BC6HRGBFloat:case I.ETC2RGB8Unorm:case I.ETC2RGB8UnormSRGB:return 3;case I.RGBA8Unorm:case I.RGBA8UnormSRGB:case I.RGBA8Snorm:case I.RGBA8Uint:case I.RGBA8Sint:case I.BGRA8Unorm:case I.BGRA8UnormSRGB:case I.RGB10A2Unorm:case I.BC7RGBAUnorm:case I.BC7RGBAUnormSRGB:case I.BC3RGBAUnorm:case I.BC3RGBAUnormSRGB:case I.BC2RGBAUnorm:case I.BC2RGBAUnormSRGB:case I.BC1RGBAUnorm:case I.BC1RGBAUnormSRGB:case I.RGBA16Uint:case I.RGBA16Sint:case I.RGBA16Float:case I.RGBA32Uint:case I.RGBA32Sint:case I.RGBA32Float:case I.ETC2RGB8A1Unorm:case I.ETC2RGB8A1UnormSRGB:case I.ETC2RGBA8Unorm:case I.ETC2RGBA8UnormSRGB:case I.ASTC4x4Unorm:case I.ASTC4x4UnormSRGB:case I.ASTC5x4Unorm:case I.ASTC5x4UnormSRGB:case I.ASTC5x5Unorm:case I.ASTC5x5UnormSRGB:case I.ASTC6x5Unorm:case I.ASTC6x5UnormSRGB:case I.ASTC6x6Unorm:case I.ASTC6x6UnormSRGB:case I.ASTC8x5Unorm:case I.ASTC8x5UnormSRGB:case I.ASTC8x6Unorm:case I.ASTC8x6UnormSRGB:case I.ASTC8x8Unorm:case I.ASTC8x8UnormSRGB:case I.ASTC10x5Unorm:case I.ASTC10x5UnormSRGB:case I.ASTC10x6Unorm:case I.ASTC10x6UnormSRGB:case I.ASTC10x8Unorm:case I.ASTC10x8UnormSRGB:case I.ASTC10x10Unorm:case I.ASTC10x10UnormSRGB:case I.ASTC12x10Unorm:case I.ASTC12x10UnormSRGB:case I.ASTC12x12Unorm:case I.ASTC12x12UnormSRGB:return 4}throw"Unknown format ".concat(e,"!")}static HasStencilAspect(e){switch(e){case I.Stencil8:case I.Depth24UnormStencil8:case I.Depth32FloatStencil8:case I.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case I.Depth24UnormStencil8:case I.Depth32FloatStencil8:case I.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case I.Depth16Unorm:return I.Depth16Unorm;case I.Depth24Plus:return I.Depth24Plus;case I.Depth24PlusStencil8:return I.Depth24Plus;case I.Depth24UnormStencil8:return I.Depth24Plus;case I.Depth32Float:return I.Depth32Float;case I.Depth32FloatStencil8:return I.Depth32Float}return e}copyVideoToTexture(e,t,i,s=!1,n){var r,o,l,h;const c=n===void 0,[u,d]=this._getVideoPipeline(i,s?cn.InvertY:cn.DontInvertY);c&&(n=this._device.createCommandEncoder({})),(o=(r=n).pushDebugGroup)===null||o===void 0||o.call(r,"copy video to texture - invertY=".concat(s));const f={colorAttachments:[{view:t._hardwareTexture.underlyingResource.createView({format:i,dimension:$e.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:$i.All}),loadOp:bt.Load,storeOp:mi.Store}]},g=n.beginRenderPass(f),p={layout:d,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},x=this._device.createBindGroup(p);g.setPipeline(u),g.setBindGroup(0,x),g.draw(4,1,0,0),g.end(),(h=(l=n).popDebugGroup)===null||h===void 0||h.call(l),c&&(this._device.queue.submit([n.finish()]),n=null)}invertYPreMultiplyAlpha(e,t,i,s,n=!1,r=!1,o=0,l=0,h=1,c=0,u=0,d=0,_=0,f,g){var p,x,m,T,S,b;const y=d!==0,E=f===void 0,[P,C]=this._getPipeline(s,y?Ci.InvertYPremultiplyAlphaWithOfst:Ci.InvertYPremultiplyAlpha,{invertY:n,premultiplyAlpha:r});o=Math.max(o,0),E&&(f=this._device.createCommandEncoder({})),(x=(p=f).pushDebugGroup)===null||x===void 0||x.call(p,"internal process texture - invertY=".concat(n," premultiplyAlpha=").concat(r));let R;if(Qe._IsHardwareTexture(e)?(R=e.underlyingResource,n&&!r&&h===1&&o===0||(e=void 0)):(R=e,e=void 0),!R)return;y&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([c,u,d,_]),0,4*4);const w=e,D=(m=w==null?void 0:w._copyInvertYTempTexture)!==null&&m!==void 0?m:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,f,it.CopySrc|it.RenderAttachment|it.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),W=(T=w==null?void 0:w._copyInvertYRenderPassDescr)!==null&&T!==void 0?T:{colorAttachments:[{view:D.createView({format:s,dimension:$e.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:bt.Load,storeOp:mi.Store}]},L=f.beginRenderPass(W);let z=y?w==null?void 0:w._copyInvertYBindGroupWithOfst:w==null?void 0:w._copyInvertYBindGroup;if(!z){const K={layout:C,entries:[{binding:0,resource:R.createView({format:s,dimension:$e.E2d,baseMipLevel:l,mipLevelCount:1,arrayLayerCount:h,baseArrayLayer:o})}]};y&&K.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),z=this._device.createBindGroup(K)}L.setPipeline(P),L.setBindGroup(0,z),L.draw(4,1,0,0),L.end(),f.copyTextureToTexture({texture:D},{texture:R,mipLevel:l,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),w?(w._copyInvertYTempTexture=D,w._copyInvertYRenderPassDescr=W,y?w._copyInvertYBindGroupWithOfst=z:w._copyInvertYBindGroup=z):this._deferredReleaseTextures.push([D,null]),(b=(S=f).popDebugGroup)===null||b===void 0||b.call(S),E&&(this._device.queue.submit([f.finish()]),f=null)}copyWithInvertY(e,t,i,s){var n,r,o,l;const h=s===void 0,[c,u]=this._getPipeline(t,Ci.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});h&&(s=this._device.createCommandEncoder({})),(r=(n=s).pushDebugGroup)===null||r===void 0||r.call(n,"internal copy texture with invertY");const d=s.beginRenderPass(i),_=this._device.createBindGroup({layout:u,entries:[{binding:0,resource:e}]});d.setPipeline(c),d.setBindGroup(0,_),d.draw(4,1,0,0),d.end(),(l=(o=s).popDebugGroup)===null||l===void 0||l.call(o),h&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,n=!1,r=!1,o=I.RGBA8Unorm,l=1,h,c=-1,u=0,d){l>1&&(l=4);const _=e.layers||1,f={width:e.width,height:e.height,depthOrArrayLayers:_},g=Qe.IsCompressedFormat(o),p=t?Qe.ComputeNumMipmapLevels(e.width,e.height):1,x=c>=0?c:it.CopySrc|it.CopyDst|it.TextureBinding;u|=t&&!g?it.CopySrc|it.RenderAttachment:0,!g&&!r&&(u|=it.RenderAttachment|it.CopyDst);const m=this._device.createTexture({label:"Texture_".concat(d?d+"_":"").concat(f.width,"x").concat(f.height,"x").concat(f.depthOrArrayLayers,"_").concat(t?"wmips":"womips","_").concat(o,"_samples").concat(l),size:f,dimension:r?Mi.E3d:Mi.E2d,format:o,usage:x|u,sampleCount:l,mipLevelCount:p});return Qe.IsImageBitmap(e)&&(this.updateTexture(e,m,e.width,e.height,_,o,0,0,s,n,0,0),t&&i&&this.generateMipmaps(m,o,p,0,h)),m}createCubeTexture(e,t=!1,i=!1,s=!1,n=!1,r=I.RGBA8Unorm,o=1,l,h=-1,c=0,u){o>1&&(o=4);const d=Qe.IsImageBitmapArray(e)?e[0].width:e.width,_=Qe.IsImageBitmapArray(e)?e[0].height:e.height,f=Qe.IsCompressedFormat(r),g=t?Qe.ComputeNumMipmapLevels(d,_):1,p=h>=0?h:it.CopySrc|it.CopyDst|it.TextureBinding;c|=t&&!f?it.CopySrc|it.RenderAttachment:0,f||(c|=it.RenderAttachment|it.CopyDst);const x=this._device.createTexture({label:"TextureCube_".concat(u?u+"_":"").concat(d,"x").concat(_,"x6_").concat(t?"wmips":"womips","_").concat(r,"_samples").concat(o),size:{width:d,height:_,depthOrArrayLayers:6},dimension:Mi.E2d,format:r,usage:p|c,sampleCount:o,mipLevelCount:g});return Qe.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,x,d,_,r,s,n,0,0),t&&i&&this.generateCubeMipmaps(x,r,g,l)),x}generateCubeMipmaps(e,t,i,s){var n,r,o,l;const h=s===void 0;h&&(s=this._device.createCommandEncoder({})),(r=(n=s).pushDebugGroup)===null||r===void 0||r.call(n,"create cube mipmaps - ".concat(i," levels"));for(let c=0;c<6;++c)this.generateMipmaps(e,t,i,c,s);(l=(o=s).popDebugGroup)===null||l===void 0||l.call(o),h&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,n){var r,o,l,h,c,u,d,_;const f=n===void 0,[g,p]=this._getPipeline(t);s=Math.max(s,0),f&&(n=this._device.createCommandEncoder({})),(o=(r=n).pushDebugGroup)===null||o===void 0||o.call(r,"create mipmaps for face #".concat(s," - ").concat(i," levels"));let x;if(Qe._IsHardwareTexture(e)?(x=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(x=e,e=void 0),!x)return;const m=e;for(let T=1;T=0;o--)(r=a[o])&&(n=(s<3?r(n):s>3?r(e,t,n):r(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}class Ws{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),Ws._HandleParenthesisContent(i,t))):e=Ws._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:Ws.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(n=>n==="true");let i;const s=e.split("||");for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)){let r=Ws._SimplifyNegation(s[n].trim());const o=r.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 Ve{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Ve.HasTags(e),e.addTags=t=>Ve.AddTagsTo(e,t),e.removeTags=t=>Ve.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Ve.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){Ve._AddTagTo(e,s)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Ve.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Ve.HasTags(e))return;const i=t.split(" ");for(const s in i)Ve._RemoveTagFrom(e,i[s])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?Ve.HasTags(e):Ws.Eval(t,i=>Ve.HasTags(e)&&e._tags[i])}}const br={},dr={},fo=function(a,e,t){const i=a();Ve&&Ve.HasTags(e)&&Ve.AddTagsTo(i,Ve.GetTags(e,!0));const s=Ba(i);for(const n in s){const r=s[n],o=e[n],l=r.type;if(o!=null&&(n!=="uniqueId"||Se.AllowLoadingUniqueId))switch(l){case 0:case 6:case 11:i[n]=o;break;case 1:i[n]=t||o.isRenderTarget?o:o.clone();break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:i[n]=t?o:o.clone();break}}return i};function gd(a){const e=a.getClassName();return br[e]||(br[e]={}),br[e]}function Ba(a){const e=a.getClassName();if(dr[e])return dr[e];dr[e]={};const t=dr[e];let i=a,s=e;for(;s;){const n=br[s];for(const l in n)t[l]=n[l];let r,o=!1;do{if(r=Object.getPrototypeOf(i),!r.getClassName){o=!0;break}if(r.getClassName()!==s)break;i=r}while(r);if(o)break;s=r.getClassName(),i=r}return t}function Xi(a,e){return(t,i)=>{const s=gd(t);s[i]||(s[i]={type:a,sourceName:e})}}function md(a,e=null){return(t,i)=>{const s=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[s]},set:function(n){typeof this.equals=="function"&&this.equals(n)||this[s]!==n&&(this[s]=n,t[a].apply(this))},enumerable:!0,configurable:!0})}}function je(a,e=null){return md(a,e)}function B(a){return Xi(0,a)}function Si(a){return Xi(1,a)}function _s(a){return Xi(2,a)}function Jn(a){return Xi(3,a)}function Al(a){return Xi(4,a)}function wi(a){return Xi(5,a)}function El(a){return Xi(6,a)}function vd(a){return Xi(7,a)}function f0(a){return Xi(8,a)}function xd(a){return Xi(10,a)}function bd(a){return Xi(11,a)}class Se{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw Ae("ImageProcessingConfiguration")};Se._FresnelParametersParser=a=>{throw Ae("FresnelParameters")};Se._ColorCurvesParser=a=>{throw Ae("ColorCurves")};Se._TextureParser=(a,e,t)=>{throw Ae("Texture")};function Os(a,e,t,i){const s=t.value;t.value=(...n)=>{let r=s;if(typeof _native<"u"&&_native[e]){const o=_native[e];i?r=(...l)=>i(...l)?o(...l):s(...l):r=o}return a[e]=r,r(...n)}}Os.filter=function(a){return(e,t,i)=>Os(e,t,i,a)};class _0{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return this._texture?this._texture.isCube:!1}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return(e==null?void 0:e._shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Ui.Zero(),this._cachedBaseSize=Ui.Zero(),this._initialSamplingMode=2,this._texture=_0._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 ft extends _0{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=Tl()),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=ft.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 ee,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?ft._IsScene(e)?this._scene=e:this._engine=e:this._scene=Ie.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 N.IdentityReadOnly}getReflectionTextureMatrix(){return N.IdentityReadOnly}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,n,r){const o=this._getEngine();if(!o)return null;const l=o._getUseSRGBBuffer(!!n,t),h=o.getLoadedTexturesCache();for(let c=0;c=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=Se.Serialize(this);return Se.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"}}ft.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;F([B()],ft.prototype,"uniqueId",void 0);F([B()],ft.prototype,"name",void 0);F([B()],ft.prototype,"metadata",void 0);F([B("hasAlpha")],ft.prototype,"_hasAlpha",void 0);F([B("getAlphaFromRGB")],ft.prototype,"_getAlphaFromRGB",void 0);F([B()],ft.prototype,"level",void 0);F([B("coordinatesIndex")],ft.prototype,"_coordinatesIndex",void 0);F([B()],ft.prototype,"optimizeUVAllocation",void 0);F([B("coordinatesMode")],ft.prototype,"_coordinatesMode",void 0);F([B()],ft.prototype,"wrapU",null);F([B()],ft.prototype,"wrapV",null);F([B()],ft.prototype,"wrapR",void 0);F([B()],ft.prototype,"anisotropicFilteringLevel",void 0);F([B()],ft.prototype,"isCube",null);F([B()],ft.prototype,"is3D",null);F([B()],ft.prototype,"is2DArray",null);F([B()],ft.prototype,"gammaSpace",null);F([B()],ft.prototype,"invertZ",void 0);F([B()],ft.prototype,"lodLevelInAlpha",void 0);F([B()],ft.prototype,"lodGenerationOffset",null);F([B()],ft.prototype,"lodGenerationScale",null);F([B()],ft.prototype,"linearSpecularLOD",null);F([Si()],ft.prototype,"irradianceTexture",null);F([B()],ft.prototype,"isRenderTarget",void 0);function Cl(a,e,t=!1){const i=e.width,s=e.height;if(a instanceof Float32Array){let h=a.byteLength/a.BYTES_PER_ELEMENT;const c=new Uint8Array(h);for(;--h>=0;){let u=a[h];u<0?u=0:u>1&&(u=1),c[h]=u*255}a=c}const n=document.createElement("canvas");n.width=i,n.height=s;const r=n.getContext("2d");if(!r)return null;const o=r.createImageData(i,s);if(o.data.set(a),r.putImageData(o,0,0),t){const h=document.createElement("canvas");h.width=i,h.height=s;const c=h.getContext("2d");return c?(c.translate(0,s),c.scale(1,-1),c.drawImage(n,0,0),h.toDataURL("image/png")):null}return n.toDataURL("image/png")}function yd(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=a._readPixelsSync(e,t);return s?Cl(s,a.getSize(),i.invertY):null}async function Td(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=await a.readPixels(e,t);return s?Cl(s,a.getSize(),i.invertY):null}class Ne{}Ne.UseOpenGLOrientationForUV=!1;class se extends ft{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,n=se.TRILINEAR_SAMPLINGMODE,r=null,o=null,l=null,h=!1,c,u,d,_,f){var g,p,x,m,T,S,b,y,E;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 ee,this._isBlocking=!0,this.name=e||"",this.url=e;let P,C=!1,R=null;typeof i=="object"&&i!==null?(P=(g=i.noMipmap)!==null&&g!==void 0?g:!1,s=(p=i.invertY)!==null&&p!==void 0?p:!Ne.UseOpenGLOrientationForUV,n=(x=i.samplingMode)!==null&&x!==void 0?x:se.TRILINEAR_SAMPLINGMODE,r=(m=i.onLoad)!==null&&m!==void 0?m:null,o=(T=i.onError)!==null&&T!==void 0?T:null,l=(S=i.buffer)!==null&&S!==void 0?S:null,h=(b=i.deleteBuffer)!==null&&b!==void 0?b:!1,c=i.format,u=i.mimeType,d=i.loaderOptions,_=i.creationFlags,C=(y=i.useSRGBBuffer)!==null&&y!==void 0?y:!1,R=(E=i.internalTexture)!==null&&E!==void 0?E:null):P=!!i,this._noMipmap=P,this._invertY=s===void 0?!Ne.UseOpenGLOrientationForUV:s,this._initialSamplingMode=n,this._buffer=l,this._deleteBuffer=h,this._mimeType=u,this._loaderOptions=d,this._creationFlags=_,this._useSRGBBuffer=C,this._forcedExtension=f,c&&(this._format=c);const w=this.getScene(),D=this._getEngine();if(!D)return;D.onBeforeTextureInitObservable.notifyObservers(this);const W=()=>{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),r&&r(),!this.isBlocking&&w&&w.resetCachedMaterial()},L=(z,K)=>{this._loadingError=!0,this._errorObject={message:z,exception:K},o&&o(z,K),se.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!R){this._delayedOnLoad=W,this._delayedOnError=L;return}if(this._texture=R!=null?R:this._getFromCache(this.url,P,n,this._invertY,C),this._texture)if(this._texture.isReady)Mr.SetImmediate(()=>W());else{const z=this._texture.onLoadedObservable.add(W);this._texture.onErrorObservable.add(K=>{var ae;L(K.message,K.exception),(ae=this._texture)===null||ae===void 0||ae.onLoadedObservable.remove(z)})}else if(!w||!w.useDelayedTextureLoading){try{this._texture=D.createTexture(this.url,P,this._invertY,w,n,W,L,this._buffer,void 0,this._format,this._forcedExtension,u,d,_,C)}catch(z){throw L("error loading",z),z}h&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=W,this._delayedOnError=L}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?Mr.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,v.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=N.Zero(),this._rowGenerationMatrix=new N,this._t0=v.Zero(),this._t1=v.Zero(),this._t2=v.Zero()),N.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(N.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,G.Matrix[0]),N.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,G.Matrix[1]),N.ScalingToRef(this._cachedUScale,this._cachedVScale,0,G.Matrix[2]),N.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,G.Matrix[3]),G.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(G.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(G.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(G.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),N.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===se.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=N.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=N.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 se.PLANAR_MODE:{N.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 se.PROJECTION_MODE:{N.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:N.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 Se.Clone(()=>new se(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;const i=this.name;se.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const s=super.serialize(se._SerializeInternalTextureUniqueId);return s?((se.SerializeBuffers||se.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,"+gl(this._buffer):(se.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(s.base64String=!this._engine||this._engine._features.supportSyncTextureRead?yd(this):Td(this))),s.invertY=this._invertY,s.samplingMode=this.samplingMode,s._creationFlags=this._creationFlags,s._useSRGBBuffer=this._useSRGBBuffer,se._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 h=On.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&h.updateSamplingMode&&h._samplingMode&&h._samplingMode!==e.samplingMode&&h.updateSamplingMode(e.samplingMode),h}if(e.isCube&&!e.isRenderTarget)return se._CubeTextureParser(e,t,i);const s=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!s)return null;let n;if(s){const l=t.getEngine().getLoadedTexturesCache();for(const h of l)if(h.uniqueId===e.internalTextureUniqueId){n=h;break}}const r=l=>{var h;if(l&&l._texture&&(l._texture._cachedWrapU=null,l._texture._cachedWrapV=null,l._texture._cachedWrapR=null),e.samplingMode){const c=e.samplingMode;l&&l.samplingMode!==c&&l.updateSamplingMode(c)}if(l&&e.animations)for(let c=0;c{var l,h,c;let u=!0;if(e.noMipmap&&(u=!1),e.mirrorPlane){const d=se._CreateMirror(e.name,e.renderTargetSize,t,u);return d._waitingRenderList=e.renderList,d.mirrorPlane=ni.FromArray(e.mirrorPlane),r(d),d}else if(e.isRenderTarget){let d=null;if(e.isCube){if(t.reflectionProbes)for(let _=0;_{r(d)},(h=e._creationFlags)!==null&&h!==void 0?h:0,(c=e._useSRGBBuffer)!==null&&c!==void 0?c:!1),d.name=e.name;else{let _;e.name&&e.name.indexOf("://")>0?_=e.name:_=i+e.name,e.url&&(e.url.startsWith("data:")||se.UseSerializedUrlIfAny)&&(_=e.url);const f={noMipmap:!u,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{r(d)},internalTexture:n};d=new se(_,t,f)}return d}},e,t)}static CreateFromBase64String(e,t,i,s,n,r=se.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,c){return new se("data:"+t,i,s,n,r,o,l,e,!1,h,void 0,void 0,c)}static LoadFromDataString(e,t,i,s=!1,n,r=!0,o=se.TRILINEAR_SAMPLINGMODE,l=null,h=null,c=5,u){return e.substr(0,5)!=="data:"&&(e="data:"+e),new se(e,i,n,r,o,l,h,t,s,c,void 0,void 0,u)}}se.SerializeBuffers=!0;se.ForceSerializeBuffers=!1;se.OnTextureLoadErrorObservable=new ee;se._SerializeInternalTextureUniqueId=!1;se._CubeTextureParser=(a,e,t)=>{throw Ae("CubeTexture")};se._CreateMirror=(a,e,t,i)=>{throw Ae("MirrorTexture")};se._CreateRenderTargetTexture=(a,e,t,i,s)=>{throw Ae("RenderTargetTexture")};se.NEAREST_SAMPLINGMODE=1;se.NEAREST_NEAREST_MIPLINEAR=8;se.BILINEAR_SAMPLINGMODE=2;se.LINEAR_LINEAR_MIPNEAREST=11;se.TRILINEAR_SAMPLINGMODE=3;se.LINEAR_LINEAR_MIPLINEAR=3;se.NEAREST_NEAREST_MIPNEAREST=4;se.NEAREST_LINEAR_MIPNEAREST=5;se.NEAREST_LINEAR_MIPLINEAR=6;se.NEAREST_LINEAR=7;se.NEAREST_NEAREST=1;se.LINEAR_NEAREST_MIPNEAREST=9;se.LINEAR_NEAREST_MIPLINEAR=10;se.LINEAR_LINEAR=2;se.LINEAR_NEAREST=12;se.EXPLICIT_MODE=0;se.SPHERICAL_MODE=1;se.PLANAR_MODE=2;se.CUBIC_MODE=3;se.PROJECTION_MODE=4;se.SKYBOX_MODE=5;se.INVCUBIC_MODE=6;se.EQUIRECTANGULAR_MODE=7;se.FIXED_EQUIRECTANGULAR_MODE=8;se.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;se.CLAMP_ADDRESSMODE=0;se.WRAP_ADDRESSMODE=1;se.MIRROR_ADDRESSMODE=2;se.UseSerializedUrlIfAny=!1;F([B()],se.prototype,"url",void 0);F([B()],se.prototype,"uOffset",void 0);F([B()],se.prototype,"vOffset",void 0);F([B()],se.prototype,"uScale",void 0);F([B()],se.prototype,"vScale",void 0);F([B()],se.prototype,"uAng",void 0);F([B()],se.prototype,"vAng",void 0);F([B()],se.prototype,"wAng",void 0);F([B()],se.prototype,"uRotationCenter",void 0);F([B()],se.prototype,"vRotationCenter",void 0);F([B()],se.prototype,"wRotationCenter",void 0);F([B()],se.prototype,"homogeneousRotationInUVTransform",void 0);F([B()],se.prototype,"isBlocking",null);Vt("BABYLON.Texture",se);Se._TextureParser=se.Parse;class Na{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[A.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[A.PositionKind]=new A(this._scene.getEngine(),e,A.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[A.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,n=0,r=!1){var o;const l=this._scene.getEngine();for(let h=0;hh!=null),s.length===0||!this._scene.postProcessesEnabled))return;const l=this._scene.getEngine();for(let h=0,c=s.length;hthis.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}}qt._GlobalId=0;class Vs extends qt{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;tt._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;i0}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){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}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]&&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,n=14,r){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:n,label:r},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,n,r,o,l;let h=null;if(this._isMulti){const c=this.textures;if(c&&c.length>0){let u=!1,d=c.length;const _=c[c.length-1]._source;(_===ze.Depth||_===ze.DepthStencil)&&(u=!0,d--);const f=[],g=[],p=[],x=[],m=[],T=[],S=[],b={};for(let P=0;P1&&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 Ad extends Rl{constructor(e,t,i,s,n){super(e,t,i,s),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._context=n}_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&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=this._depthStencilBuffer,this._engine._bindUnboundFramebuffer(s),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,s=0){var n,r,o,l;if(!e._hardwareTexture)return;const h=this._framebuffer,c=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(h),this._engine.webGLVersion>1){const u=this._context,d=u["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=(r=i!=null?i:(n=this.layerIndices)===null||n===void 0?void 0:n[t])!==null&&r!==void 0?r:0,u.framebufferTextureLayer(u.FRAMEBUFFER,d,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=(l=i!=null?i:(o=this.faceIndices)===null||o===void 0?void 0:o[t])!==null&&l!==void 0?l:0,u.framebufferTexture2D(u.FRAMEBUFFER,d,u.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):u.framebufferTexture2D(u.FRAMEBUFFER,d,u.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const u=this._context,d=u["COLOR_ATTACHMENT"+t+"_WEBGL"],_=i!==void 0?u.TEXTURE_CUBE_MAP_POSITIVE_X+i:u.TEXTURE_2D;u.framebufferTexture2D(u.FRAMEBUFFER,d,_,e._hardwareTexture.underlyingResource,s)}this._engine._bindUnboundFramebuffer(c)}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 n=(s=(i=this._attachments)===null||i===void 0?void 0:i.length)!==null&&s!==void 0?s:this.textures.length;for(let r=0;r1&&(r.format===15?u=i.DEPTH_COMPONENT16:r.format===16?u=i.DEPTH_COMPONENT24:r.format===17||r.format===13?u=i.DEPTH24_STENCIL8:r.format===14?u=i.DEPTH_COMPONENT32F:r.format===18&&(u=i.DEPTH32F_STENCIL8)),r.is2DArray?i.texImage3D(n,0,u,r.width,r.height,s,0,c,h,null):i.texImage2D(n,0,u,r.width,r.height,0,c,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(r);const d=t;if(d._depthStencilBuffer){const _=this._currentFramebuffer;this._bindUnboundFramebuffer(d._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(_),i.deleteRenderbuffer(d._depthStencilBuffer),d._depthStencilBuffer=null}return r};Ee.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 n=this._createRenderBuffer(a.texture.width,a.texture.height,e,-1,this._getRGBAMultiSampleBufferFormat(a.texture.type),t.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(n)}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};Ee.prototype.createRenderTargetCubeTexture=function(a,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,a),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type===1&&!this._caps.textureFloatLinearFiltering||i.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(i.samplingMode=1);const s=this._gl,n=new Dt(this,ze.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,n,!0);const r=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,H.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,r.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,r.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,n.width=a,n.height=a,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=i.generateMipMaps,n.samplingMode=i.samplingMode,n.type=i.type,n.format=i.format,this._internalTexturesCache.push(n),t.setTextures(n),t};const Ed="postprocessVertexShader",Cd="attribute vec2 position;\nuniform vec2 scale;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";te.ShadersStore[Ed]=Cd;const ba={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Rd{constructor(e,t=ba){var i,s;this._fullscreenViewport=new mn(0,0,1,1);const n=(i=t.positions)!==null&&i!==void 0?i:ba.positions,r=(s=t.indices)!==null&&s!==void 0?s:ba.indices;this.engine=e,this._vertexBuffers={[A.PositionKind]:new A(e,n,A.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(r),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(r);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({})}restoreStates(){this.engine.depthCullingState.depthTest=!0,this.engine.stencilState.stencilTest=!0}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return e.renderTarget!==void 0}render(e,t=null){if(!e.effect.isReady())return;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[A.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[A.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class Id{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.onApplyObservable=new ee;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("\n"):"";this._drawWrapper=new Ns(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 wt(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 Il="passPixelShader",Ml="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}";te.ShadersStore[Il]=Ml;const _o={name:Il,shader:Ml};class Yt{static _CreateDumpRenderer(){if(!Yt._DumpToolsEngine){const e=document.createElement("canvas"),t=new Ee(e,!1,{preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1});t.getCaps().parallelShaderCompile=void 0;const i=new Rd(t),s=new Id({engine:t,name:_o.name,fragmentShader:_o.shader,samplerNames:["textureSampler"]});Yt._DumpToolsEngine={canvas:e,engine:t,renderer:i,wrapper:s}}return Yt._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,n="image/png",r){const o=await i.readPixels(0,0,e,t),l=new Uint8Array(o.buffer);Yt.DumpData(e,t,l,s,n,r,!0)}static DumpDataAsync(e,t,i,s="image/png",n,r=!1,o=!1,l){return new Promise(h=>{Yt.DumpData(e,t,i,c=>h(c),s,n,r,o,l)})}static DumpData(e,t,i,s,n="image/png",r,o=!1,l=!1,h){const c=Yt._CreateDumpRenderer();if(c.engine.setSize(e,t,!0),i instanceof Float32Array){const d=new Uint8Array(i.length);let _=i.length;for(;_--;){const f=i[_];d[_]=f<0?0:f>1?1:Math.round(f*255)}i=d}const u=c.engine.createRawTexture(i,e,t,5,!1,!o,1);c.renderer.setViewport(),c.renderer.applyEffectWrapper(c.wrapper),c.wrapper.effect._bindTexture("textureSampler",u),c.renderer.draw(),l?re.ToBlob(c.canvas,d=>{const _=new FileReader;_.onload=f=>{const g=f.target.result;s&&s(g)},_.readAsArrayBuffer(d)},n,h):re.EncodeScreenshotCanvasData(c.canvas,s,n,r,h),u.dispose()}static Dispose(){Yt._DumpToolsEngine&&(Yt._DumpToolsEngine.wrapper.dispose(),Yt._DumpToolsEngine.renderer.dispose(),Yt._DumpToolsEngine.engine.dispose()),Yt._DumpToolsEngine=null}}const Md=()=>{re.DumpData=Yt.DumpData,re.DumpDataAsync=Yt.DumpDataAsync,re.DumpFramebuffer=Yt.DumpFramebuffer};Md();class zi extends se{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=_l(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 D;const W=this._renderList?this._renderList.length:0;(w===0&&W>0||W===0)&&((D=this.getScene())===null||D===void 0||D.meshes.forEach(L=>{L._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new ee,this.onAfterUnbindObservable=new ee,this.onBeforeRenderObservable=new ee,this.onAfterRenderObservable=new ee,this.onClearObservable=new ee,this.onResizeObservable=new ee,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=v.Zero(),i=this.getScene(),!i)return;const C=this.getScene().getEngine();this._coordinatesMode=se.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=C.onResizeObservable.add(()=>{}),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=n,this._renderingManager=new Kt(i),this._renderingManager._useSceneAutoClearSetup=!0,!u&&(this._renderTargetOptions={generateMipMaps:s,type:r,format:(E=this._format)!==null&&E!==void 0?E:void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:c,samples:f,creationFlags:g,noColorAttachment:p,useSRGBBuffer:x,colorAttachment:P,label:this.name},this.samplingMode===se.NEAREST_SAMPLINGMODE&&(this.wrapU=se.CLAMP_ADDRESSMODE,this.wrapV=se.CLAMP_ADDRESSMODE),_||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=se.INVCUBIC_MODE,this._textureMatrix=N.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,f!==void 0&&(this.samples=f)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,n=14){var r;(r=this._renderTarget)===null||r===void 0||r.createDepthStencilTexture(e,t,i,s,n)}_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),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 n=this.getScene();if(!n)return i;const r=n.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let u=0;u1||this.activeCamera&&this.activeCamera!==n.activeCamera)&&n.setTransformMatrix(n.activeCamera.getViewMatrix(),n.activeCamera.getProjectionMatrix(!0)),r.setViewport(n.activeCamera.viewport)),n.resetCachedMaterial(),c}_bestReflectionRenderTargetDimension(e,t){const s=e*t,n=Y.NearestPOT(s+128*128/(128+s));return Math.min(Y.FloorPOT(e),n)}_prepareRenderingManager(e,t,i,s){const n=this.getScene();if(!n)return;this._renderingManager.reset();const r=n.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,n=null){var r,o,l,h,c,u;const d=this.getScene();if(!d)return;const _=d.getEngine();if((r=_._debugPushGroup)===null||r===void 0||r.call(_,"render to face #".concat(e," layer #").concat(s),1),this._prepareFrame(d,e,s,t),this.is2DArray?(_.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(_.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),_.snapshotRendering&&_.snapshotRenderingMode===1)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(_):this.skipInitialClear||_.clear(this.clearColor||d.clearColor,!0,!0,!0);else{let g=null;const p=this.renderList?this.renderList:d.getActiveMeshes().data,x=this.renderList?this.renderList.length:d.getActiveMeshes().length;this.getCustomRenderList&&(g=this.getCustomRenderList(this.is2DArray?s:e,p,x)),g?this._prepareRenderingManager(g,g.length,n,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(p,x,n,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),g=p);for(const T of d._beforeRenderTargetClearStage)T.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(_):this.skipInitialClear||_.clear(this.clearColor||d.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0);for(const T of d._beforeRenderTargetDrawStage)T.action(this,e,s);this._renderingManager.render(this.customRenderFunction,g,this.renderParticles,this.renderSprites);for(const T of d._afterRenderTargetDrawStage)T.action(this,e,s);const m=(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,(h=this._renderTarget)!==null&&h!==void 0?h:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&d.postProcessManager._finalizeFrame(!1,(c=this._renderTarget)!==null&&c!==void 0?c:void 0,e);for(const T of d._afterRenderTargetPostProcessStage)T.action(this,e,s);this._texture&&(this._texture.generateMipMaps=m),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0),i&&Yt.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),_)}this._unbindFrameBuffer(_,e),this._texture&&this.isCube&&e===5&&_.generateMipMapsForCubemap(this._texture),(u=_._debugPopGroup)===null||u===void 0||u.call(_,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 zi(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===zi.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=zi.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}zi.REFRESHRATE_RENDER_ONCE=0;zi.REFRESHRATE_RENDER_ONEVERYFRAME=1;zi.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;se._CreateRenderTargetTexture=(a,e,t,i,s)=>new zi(a,e,t,i);class st{static RegisterShaderCodeProcessing(e,t){if(!t){delete st._CustomShaderCodeProcessing[e!=null?e:""];return}st._CustomShaderCodeProcessing[e!=null?e:""]=t}static _GetShaderCodeProcessing(e){var t;return(t=st._CustomShaderCodeProcessing[e])!==null&&t!==void 0?t:st._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,n,r,o=1,l,h,c=null,u=0,d="postprocess",_,f=!1,g=5,p=at.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 qt(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new fe(1,1),this._texelSize=fe.Zero(),this.onActivateObservable=new ee,this.onSizeChangedObservable=new ee,this.onApplyObservable=new ee,this.onBeforeRenderObservable=new ee,this.onAfterRenderObservable=new ee,this.name=e,r!=null?(this._camera=r,this._scene=r.getScene(),r.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=n,this.renderTargetSamplingMode=o||1,this._reusable=h||!1,this._textureType=u,this._textureFormat=g,this._shaderLanguage=p,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=_,this._drawWrapper=new Ns(this._engine),f||this.updateEffect(c)}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 qt(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,n,r,o,l){var h,c;const u=st._GetShaderCodeProcessing(this.name);if(u!=null&&u.defineCustomBindings){const d=(h=t==null?void 0:t.slice())!==null&&h!==void 0?h:[];d.push(...this._parameters);const _=(c=i==null?void 0:i.slice())!==null&&c!==void 0?c:[];_.push(...this._samplers),e=u.defineCustomBindings(this.name,e,d,_),t=d,i=_}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o!=null?o:this._vertexUrl,fragment:l!=null?l:this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:[],samplers:i||this._samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:n!=null?n:null,onError:r!=null?r:null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:u!=null&&u.processCodeAfterIncludes?(d,_)=>u.processCodeAfterIncludes(this.name,d,_):null,processFinalCode:u!=null&&u.processFinalCode?(d,_)=>u.processFinalCode(this.name,d,_):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let n=0;n=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 r=null;for(let h=0;h{p.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(p,this.samples)}),this._flushTextureCache(),this._renderId++}let g;if(this._shareOutputWithPostProcess)g=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)g=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{g=this.inputTexture;let p;for(let x=0;x=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=Se.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=st.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=$s(e.customType);if(!s||!s._Parse)return null;const n=t?t.getCameraById(e.cameraId):null;return s._Parse(e,n,t,i)}static _Parse(e,t,i,s){return Se.Parse(()=>new st(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)}}st._CustomShaderCodeProcessing={};F([B()],st.prototype,"uniqueId",void 0);F([B()],st.prototype,"name",void 0);F([B()],st.prototype,"width",void 0);F([B()],st.prototype,"height",void 0);F([B()],st.prototype,"renderTargetSamplingMode",void 0);F([f0()],st.prototype,"clearColor",void 0);F([B()],st.prototype,"autoClear",void 0);F([B()],st.prototype,"forceAutoClearInAlphaMode",void 0);F([B()],st.prototype,"alphaMode",void 0);F([B()],st.prototype,"alphaConstants",void 0);F([B()],st.prototype,"enablePixelPerfectMode",void 0);F([B()],st.prototype,"forceFullscreenViewport",void 0);F([B()],st.prototype,"scaleMode",void 0);F([B()],st.prototype,"alwaysForcePOT",void 0);F([B("samples")],st.prototype,"_samples",void 0);F([B()],st.prototype,"adaptScaleToCurrentViewport",void 0);Vt("BABYLON.PostProcess",st);const Pd="passCubePixelShader",wd="varying vec2 vUV;\nuniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";te.ShadersStore[Pd]=wd;class er extends st{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,n,r,o=0,l=!1){super(e,"pass",null,null,t,i,s,n,r,void 0,o,void 0,null,l)}static _Parse(e,t,i,s){return Se.Parse(()=>new er(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}Vt("BABYLON.PassPostProcess",er);Y._RescalePostProcessFactory=a=>new er("rescale",1,null,2,a,!1,0);function Dd(a,e,t,i,s,n,r,o){const l=e.getEngine();return e.isReady=!1,s=s!=null?s:e.samplingMode,i=i!=null?i:e.type,n=n!=null?n:e.format,r=r!=null?r:e.width,o=o!=null?o:e.height,i===-1&&(i=0),new Promise(h=>{const c=new st("postprocess",a,null,null,1,null,s,l,!1,void 0,i,void 0,null,!1,n);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:r,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:i,format:n});c.getEffect().executeWhenCompiled(()=>{c.onApply=d=>{d._bindTexture("textureSampler",e),d.setFloat2("scale",1,1)},t.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(e),c&&c.dispose(),u._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,h(e)})})}function Fd(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))}class p0{static _IsGPUBuffer(e){return e.underlyingResource===void 0}constructor(e){this._deferredReleaseBuffers=[],this._device=e}createRawBuffer(e,t,i=!1){const s=e.byteLength!==void 0?e.byteLength+3&-4:e+3&-4,n={mappedAtCreation:i,size:s,usage:t};return this._device.createBuffer(n)}createBuffer(e,t){const i=e.byteLength!==void 0,s=this.createRawBuffer(e,t),n=new pd(s);return n.references=1,n.capacity=i?e.byteLength:e,i&&this.setSubData(n,0,e),n}setRawData(e,t,i,s,n){this._device.queue.writeBuffer(e,t,i.buffer,s,n)}setSubData(e,t,i,s=0,n=0){const r=e.underlyingResource;n=n||i.byteLength,n=Math.min(n,e.capacity-t);let o=i.byteOffset+s,l=o+n;const h=n+3&-4;if(h!==n){const d=new Uint8Array(i.buffer.slice(o,l));i=new Uint8Array(h),i.set(d),s=0,o=0,l=h,n=h}const c=1024*1024*15;let u=0;for(;l-(o+u)>c;)this._device.queue.writeBuffer(r,t+u,i.buffer,o+u,c),u+=c;this._device.queue.writeBuffer(r,t+u,i.buffer,o+u,n-u)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=Fd(s[e]);return i}readDataFromBuffer(e,t,i,s,n,r,o=0,l=0,h=null,c=!0,u=!1){const d=o===1?2:o===2?1:0;return new Promise((_,f)=>{e.mapAsync(Xs.Read,l,t).then(()=>{const g=e.getMappedRange(l,t);let p=h;if(u)p===null?p=Fa(o,t,!0,g):p=Fa(o,p.buffer,void 0,g);else if(p===null)switch(d){case 0:p=new Uint8Array(t),p.set(new Uint8Array(g));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,g);break;case 2:p=new Float32Array(t/4),p.set(new Float32Array(g));break}else switch(d){case 0:p=new Uint8Array(p.buffer),p.set(new Uint8Array(g));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,g,h);break;case 2:p=new Float32Array(p.buffer),p.set(new Float32Array(g));break}if(n!==r){d===1&&!u&&(n*=2,r*=2);const x=new Uint8Array(p.buffer);let m=n,T=0;for(let S=1;Sf(g))})}releaseBuffer(e){return p0._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 Od[e.samplingMode]+Ld[(e._comparisonFunction||514)-512+1]+Bd[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)+(n<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,n,r,o;const l=e.useMipMaps;switch(e.samplingMode){case 11:i=Be.Linear,s=Be.Linear,n=Be.Nearest,l||(r=o=0);break;case 3:case 3:i=Be.Linear,s=Be.Linear,l?n=Be.Linear:(n=Be.Nearest,r=o=0);break;case 8:i=Be.Nearest,s=Be.Nearest,l?n=Be.Linear:(n=Be.Nearest,r=o=0);break;case 4:i=Be.Nearest,s=Be.Nearest,n=Be.Nearest,l||(r=o=0);break;case 5:i=Be.Nearest,s=Be.Linear,n=Be.Nearest,l||(r=o=0);break;case 6:i=Be.Nearest,s=Be.Linear,l?n=Be.Linear:(n=Be.Nearest,r=o=0);break;case 7:i=Be.Nearest,s=Be.Linear,n=Be.Nearest,r=o=0;break;case 1:case 1:i=Be.Nearest,s=Be.Nearest,n=Be.Nearest,r=o=0;break;case 9:i=Be.Linear,s=Be.Nearest,n=Be.Nearest,l||(r=o=0);break;case 10:i=Be.Linear,s=Be.Nearest,l?n=Be.Linear:(n=Be.Nearest,r=o=0);break;case 2:case 2:i=Be.Linear,s=Be.Linear,n=Be.Nearest,r=o=0;break;case 12:i=Be.Linear,s=Be.Nearest,n=Be.Nearest,r=o=0;break;default:i=Be.Nearest,s=Be.Nearest,n=Be.Nearest,r=o=0;break}return t>1&&(r!==0||o!==0)?{magFilter:Be.Linear,minFilter:Be.Linear,mipmapFilter:Be.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:n,lodMinClamp:r,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return hn.Repeat;case 0:return hn.ClampToEdge;case 2:return hn.MirrorRepeat}return hn.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{...i,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?zs.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:i.anisotropyEnabled?t:1}}static GetCompareFunction(e){switch(e){case 519:return It.Always;case 514:return It.Equal;case 516:return It.Greater;case 518:return It.GreaterEqual;case 513:return It.Less;case 515:return It.LessEqual;case 512:return It.Never;case 517:return It.NotEqual;default:return It.Less}}getSampler(e,t=!1,i=0){if(this.disabled)return this._device.createSampler(zs._GetSamplerDescriptor(e));t?i=0:i===0&&(i=zs.GetSamplerHashCode(e));let s=t?void 0:this._samplers[i];return s||(s=this._device.createSampler(zs._GetSamplerDescriptor(e)),t||(this._samplers[i]=s)),s}}var gt;(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"})(gt||(gt={}));const fr={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},sn={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class ct{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=[I.BGRA8Unorm],this.setColorFormat(I.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(I.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 r=ct._GetTopology(e);return this._setVertexState(t),this._parameter.pipeline=this._createRenderPipeline(t,r,i),ct.NumCacheMiss++,ct._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,ct.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return ct.NumCacheHitWithHash++,this._parameter.pipeline;const n=ct._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,n,i),this._setRenderPipeline(this._parameter),ct.NumCacheMiss++,ct._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){ct.NumPipelineCreationLastFrame=ct._NumPipelineCreationCurrentFrame,ct._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,n,r,o,l){this._depthWriteEnabled=o,this._depthTestEnabled=r,this._depthCompare=(l!=null?l:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(n)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[gt.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,gt.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[gt.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,gt.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=Ln[e!=null?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 n=[0,0];let r=0,o=0,l=0;for(let h=0;h=32&&(o=0,r++)}this._mrtFormats.length=l,(this._mrtAttachments1!==n[0]||this._mrtAttachments2!==n[1])&&(this._mrtAttachments1=n[0],this._mrtAttachments2=n[1],this._states[gt.MRTAttachments1]=n[0],this._states[gt.MRTAttachments2]=n[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,gt.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:Ln[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e!=null?e:519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e!=null?e:519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=e===null?1:sn[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:sn[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:sn[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[gt.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,gt.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[gt.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,gt.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,n,r,o){this._stencilEnabled=e,this._stencilFrontCompare=(t!=null?t:519)-512,this._stencilFrontDepthFailOp=i===null?1:sn[i],this._stencilFrontPassOp=s===null?2:sn[s],this._stencilFrontFailOp=n===null?1:sn[n],this.setStencilReadMask(r),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:return _i.TriangleList;case 2:return _i.PointList;case 1:return _i.LineList;case 3:return _i.PointList;case 4:return _i.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return _i.LineStrip;case 7:return _i.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return _i.TriangleList}}static _GetAphaBlendOperation(e){switch(e){case 32774:return Es.Add;case 32778:return Es.Subtract;case 32779:return Es.ReverseSubtract;case 32775:return Es.Min;case 32776:return Es.Max;default:return Es.Add}}static _GetAphaBlendFactor(e){switch(e){case 0:return Xt.Zero;case 1:return Xt.One;case 768:return Xt.Src;case 769:return Xt.OneMinusSrc;case 770:return Xt.SrcAlpha;case 771:return Xt.OneMinusSrcAlpha;case 772:return Xt.DstAlpha;case 773:return Xt.OneMinusDstAlpha;case 774:return Xt.Dst;case 775:return Xt.OneMinusDst;case 776:return Xt.SrcAlphaSaturated;case 32769:return Xt.Constant;case 32770:return Xt.OneMinusConstant;case 32771:return Xt.Constant;case 32772:return Xt.OneMinusConstant;default:return Xt.One}}static _GetCompareFunction(e){switch(e){case 0:return It.Never;case 1:return It.Less;case 2:return It.Equal;case 3:return It.LessEqual;case 4:return It.Greater;case 5:return It.NotEqual;case 6:return It.GreaterEqual;case 7:return It.Always}return It.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Li.Zero;case 1:return Li.Keep;case 2:return Li.Replace;case 3:return Li.IncrementClamp;case 4:return Li.DecrementClamp;case 5:return Li.Invert;case 6:return Li.IncrementWrap;case 7:return Li.DecrementWrap}return Li.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case A.BYTE:switch(s){case 1:case 2:return i?ht.Snorm8x2:ht.Sint8x2;case 3:case 4:return i?ht.Snorm8x4:ht.Sint8x4}break;case A.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?ht.Unorm8x2:ht.Uint8x2;case 3:case 4:return i?ht.Unorm8x4:ht.Uint8x4}break;case A.SHORT:switch(s){case 1:case 2:return i?ht.Snorm16x2:ht.Sint16x2;case 3:case 4:return i?ht.Snorm16x4:ht.Sint16x4}break;case A.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?ht.Unorm16x2:ht.Uint16x2;case 3:case 4:return i?ht.Unorm16x4:ht.Uint16x4}break;case A.INT:switch(s){case 1:return ht.Sint32;case 2:return ht.Sint32x2;case 3:return ht.Sint32x3;case 4:return ht.Sint32x4}break;case A.UNSIGNED_INT:switch(s){case 1:return ht.Uint32;case 2:return ht.Uint32x2;case 3:return ht.Uint32x3;case 4:return ht.Uint32x4}break;case A.FLOAT:switch(s){case 1:return ht.Float32;case 2:return ht.Float32x2;case 3:return ht.Float32x3;case 4:return ht.Float32x4}break}throw new Error("Invalid Format '".concat(e.getKind(),"' - type=").concat(t,", normalized=").concat(i,", size=").concat(s))}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:ct._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:ct._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:ct._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:ct._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:ct._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:ct._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[gt.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,gt.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace,s=this._cullEnabled?this._cullFace:0,n=this._clampDepth?1:0,r=this._alphaToCoverageEnabled?1:0,o=i-1+(s<<1)+(n<<3)+(r<<4)+(e<<5)+(t<<8);this._rasterizationState!==o&&(this._rasterizationState=o,this._states[gt.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,gt.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:fr[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:fr[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:fr[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:fr[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[gt.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,gt.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[gt.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,gt.DepthStencilState))}_setVertexState(e){var t,i;const s=this._statesLength;let n=gt.VertexState;const r=e._pipelineContext,o=r.shaderProcessingContext.attributeNamesFromEffect,l=r.shaderProcessingContext.attributeLocationsFromEffect;let h,c=0;for(let u=0;u0)for(let p=0;p=this._video.HAVE_CURRENT_DATA}dispose(){}}class Kr{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatTextures(){return this._numFloatTextures>0}constructor(){this.uniqueId=Kr._Counter++,this.updateId=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?zs.GetSamplerHashCode(t):0;const n=s!==i.hashCode;n&&this.updateId++,this.isDirty||(this.isDirty=n)}setTexture(e,t){var i,s,n;let r=this.textures[e],o=-1;r?o=(s=(i=r.texture)===null||i===void 0?void 0:i.uniqueId)!==null&&s!==void 0?s:-1:this.textures[e]=r={texture:t,isFloatTexture:!1,isExternalTexture:!1},r.isExternalTexture&&this._numExternalTextures--,r.isFloatTexture&&this._numFloatTextures--,t?(r.isFloatTexture=t.type===1,r.isExternalTexture=wl.IsExternalTexture(t),r.isFloatTexture&&this._numFloatTextures++,r.isExternalTexture&&this._numExternalTextures++):(r.isFloatTexture=!1,r.isExternalTexture=!1),r.texture=t;const l=o!==((n=t==null?void 0:t.uniqueId)!==null&&n!==void 0?n:-1);l&&this.updateId++,this.isDirty||(this.isDirty=l)}}Kr._Counter=0;class Yr{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(40,Je.CopyDst|Je.Indirect),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=Yr._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(t==null?void 0:t.uniqueId)!==((i=this.buffers[e])===null||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}}Yr._Counter=0;class yr{constructor(){this.values={}}}class _t{static get Statistics(){return{totalCreated:_t.NumBindGroupsCreatedTotal,lastFrameCreated:_t.NumBindGroupsCreatedLastFrame,lookupLastFrame:_t.NumBindGroupsLookupLastFrame,noLookupLastFrame:_t.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){_t.NumBindGroupsCreatedLastFrame=_t._NumBindGroupsCreatedCurrentFrame,_t.NumBindGroupsLookupLastFrame=_t._NumBindGroupsLookupCurrentFrame,_t.NumBindGroupsNoLookupLastFrame=_t._NumBindGroupsNoLookupCurrentFrame,_t._NumBindGroupsCreatedCurrentFrame=0,_t._NumBindGroupsLookupCurrentFrame=0,_t._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var s,n,r,o,l,h,c,u,d,_;let f,g=_t._Cache;const p=this.disabled||i.forceBindGroupCreation;if(!p){if(!t.isDirty(i.updateId)&&!i.isDirty)return _t._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const m of e.shaderProcessingContext.bufferNames){const T=(n=(s=t.buffers[m])===null||s===void 0?void 0:s.uniqueId)!==null&&n!==void 0?n:0;let S=g.values[T];S||(S=new yr,g.values[T]=S),g=S}for(const m of e.shaderProcessingContext.samplerNames){const T=(o=(r=i.samplers[m])===null||r===void 0?void 0:r.hashCode)!==null&&o!==void 0?o:0;let S=g.values[T];S||(S=new yr,g.values[T]=S),g=S}for(const m of e.shaderProcessingContext.textureNames){const T=(c=(h=(l=i.textures[m])===null||l===void 0?void 0:l.texture)===null||h===void 0?void 0:h.uniqueId)!==null&&c!==void 0?c:0;let S=g.values[T];S||(S=new yr,g.values[T]=S),g=S}f=g.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,f)return t.bindGroups=f,_t._NumBindGroupsLookupCurrentFrame++,f;f=[],t.bindGroups=f,p||(g.bindGroups=f),_t.NumBindGroupsCreatedTotal++,_t._NumBindGroupsCreatedCurrentFrame++;const x=e.bindGroupLayouts;for(let m=0;m":W),", materialContext.uniqueId=").concat(i.uniqueId),50);continue}S[y].resource=this._cacheSampler.getSampler(w,!1,R.hashCode)}else H.Error('Sampler "'.concat(C,'" could not be bound. entry=').concat(JSON.stringify(E),", materialContext=").concat(JSON.stringify(i,(w,D)=>w==="texture"||w==="sampler"?"":D)),50)}else if(E.texture||E.storageTexture){const R=i.textures[C];if(R){if(this._engine.dbgSanityChecks&&R.texture===null){H.Error("Trying to bind a null texture! entry=".concat(JSON.stringify(E),", bindingInfo=").concat(JSON.stringify(R,(D,W)=>D==="texture"?"":W),", materialContext.uniqueId=").concat(i.uniqueId),50);continue}const w=R.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!w||E.texture&&!w.view||E.storageTexture&&!w.viewForWriting)){H.Error("Trying to bind a null gpu texture or view! entry=".concat(JSON.stringify(E),", name=").concat(C,", bindingInfo=").concat(JSON.stringify(R,(D,W)=>D==="texture"?"":W),", isReady=").concat((d=R.texture)===null||d===void 0?void 0:d.isReady,", materialContext.uniqueId=").concat(i.uniqueId),50);continue}S[y].resource=E.storageTexture?w.viewForWriting:w.view}else H.Error('Texture "'.concat(C,'" could not be bound. entry=').concat(JSON.stringify(E),", materialContext=").concat(JSON.stringify(i,(w,D)=>w==="texture"||w==="sampler"?"":D)),50)}else if(E.externalTexture){const R=i.textures[C];if(R){if(this._engine.dbgSanityChecks&&R.texture===null){H.Error("Trying to bind a null external texture! entry=".concat(JSON.stringify(E),", name=").concat(C,", bindingInfo=").concat(JSON.stringify(R,(D,W)=>D==="texture"?"":W),", materialContext.uniqueId=").concat(i.uniqueId),50);continue}const w=R.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!w){H.Error("Trying to bind a null gpu external texture! entry=".concat(JSON.stringify(E),", name=").concat(C,", bindingInfo=").concat(JSON.stringify(R,(D,W)=>D==="texture"?"":W),", isReady=").concat((_=R.texture)===null||_===void 0?void 0:_.isReady,", materialContext.uniqueId=").concat(i.uniqueId),50);continue}S[y].resource=this._device.importExternalTexture({source:w})}else H.Error('Texture "'.concat(C,'" could not be bound. entry=').concat(JSON.stringify(E),", materialContext=").concat(JSON.stringify(i,(w,D)=>w==="texture"||w==="sampler"?"":D)),50)}else if(E.buffer){const R=t.buffers[C];if(R){const w=R.underlyingResource;S[y].resource.buffer=w,S[y].resource.size=R.capacity}else H.Error("Can't find buffer \"".concat(C,'". entry=').concat(JSON.stringify(E),", buffers=").concat(JSON.stringify(t.buffers),", drawContext.uniqueId=").concat(t.uniqueId),50)}}const b=x[m];f[m]=this._device.createBindGroup({layout:b,entries:S})}return f}}_t.NumBindGroupsCreatedTotal=0;_t.NumBindGroupsCreatedLastFrame=0;_t.NumBindGroupsLookupLastFrame=0;_t.NumBindGroupsNoLookupLastFrame=0;_t._Cache=new yr;_t._NumBindGroupsCreatedCurrentFrame=0;_t._NumBindGroupsLookupCurrentFrame=0;_t._NumBindGroupsNoLookupCurrentFrame=0;const kd="clearQuadVertexShader",Vd="uniform float depthValue;\nconst vec2 pos[4]={\nvec2(-1.0,1.0),\nvec2(1.0,1.0),\nvec2(-1.0,-1.0),\nvec2(1.0,-1.0)\n};\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=vec4(pos[gl_VertexID],depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";te.ShadersStore[kd]=Vd;const Gd="clearQuadPixelShader",Wd="uniform vec4 color;\nvoid main() {\ngl_FragColor=color;\n}\n";te.ShadersStore[Gd]=Wd;class zd{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 as(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,n=1){var r,o;let l,h=null,c;const u=!!this._engine._currentRenderTarget;if(e)l=e;else{let m=0;this._keyTemp.length=0;for(let S=0;S1?2**36:0)+T*2**37,c=this._keyTemp.join("_"),h=this._bundleCache[c],h)return h;l=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:n})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&Qe.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 d=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,n),_=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),_.uniformBuffer.update();const f=u?this._engine._ubInvertY:this._engine._ubDontInvertY,g=_.uniformBuffer.getBuffer(),p=g.uniqueId+"-"+f.uniqueId;let x=this._bindGroups[p];if(!x){const m=_.bindGroupLayouts;x=this._bindGroups[p]=[],x.push(this._device.createBindGroup({layout:m[0],entries:[]})),bi._SimplifiedKnownBindings||x.push(this._device.createBindGroup({layout:m[1],entries:[]})),x.push(this._device.createBindGroup({layout:m[bi._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:f.underlyingResource,size:f.capacity}},{binding:1,resource:{buffer:g.underlyingResource,size:g.capacity}}]}))}l.setPipeline(d);for(let m=0;m{t!==null&&t>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(t,!0)),this._measureDurationState=0}))}}class Xd{constructor(e,t){this._querySet=new Dl(2,Rr.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 Kd{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}get canBeginQuery(){switch(this._engine._getCurrentRenderPassIndex()){case 0:return this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet!==void 0;case 1:return this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet!==void 0}return!1}constructor(e,t,i,s=50,n=100){this._availableIndices=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=n,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-1]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e}))}_allocateNewIndices(e){e=e!=null?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 qr{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=".concat(this._sourceCode.length,")...")),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&console.log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&_.push(x.substring(m+1))}n!=="void"&&_.push("return"),this._functionDescr.push({name:r,type:n,parameters:_,body:u,callIndex:0}),e=c+1;const f=t>0?this._sourceCode.substring(0,t):"",g=c+1=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:n,body:r}=t;let o=0;for(;o{const c=h[0];return xa(e.charAt(c-1))||xa(e.charAt(c+r))?t[s]:o})}return e}}qr._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class vi{async initTwgsl(e){if(!vi._twgsl)return e=e||{},e={...vi._TWgslDefaultOptions,...e},e.twgsl?(vi._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&(Pt()?await re.LoadScriptAsync(e.jsPath):importScripts(e.jsPath)),self.twgsl?(vi._twgsl=await self.twgsl(e.wasmPath),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=vi._twgsl.convertSpirV2WGSL(e);return vi.ShowWGSLShaderCode&&(console.log(i),console.log("***********************************************")),vi.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}vi._TWgslDefaultOptions={jsPath:"https://preview.babylonjs.com/twgsl/twgsl.js",wasmPath:"https://preview.babylonjs.com/twgsl/twgsl.wasm"};vi.ShowWGSLShaderCode=!1;vi.DisableUniformityAnalysis=!1;vi._twgsl=null;class Yd{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,n,r;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((r=(n=t._bundleLists)===null||n===void 0?void 0:n[t._currentLayer])===null||r===void 0?void 0:r.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!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return H.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 pe(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 po,this._rttRenderPassWrapper=new po,this._pendingDebugCommands=[],this._onAfterUnbindFrameBufferObservable=new ee,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,H.Log("Babylon.js v".concat(Y.Version," - ").concat(this.description," engine")),!navigator.gpu){H.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 bu,this._shaderProcessorWGSL=new nd}initAsync(e,t){var i;return this._initGlslang(e!=null?e:(i=this._options)===null||i===void 0?void 0:i.glslangOptions).then(s=>{var n;return this._glslang=s,this._tintWASM=pe.UseTWGSL?new vi:null,this._tintWASM?this._tintWASM.initTwgsl(t!=null?t:(n=this._options)===null||n===void 0?void 0:n.twgslOptions).then(()=>navigator.gpu.requestAdapter(this._options),r=>{throw H.Error("Can not initialize twgsl!"),H.Error(r),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},s=>{throw H.Error("Can not initialize glslang!"),H.Error(s),Error("WebGPU initializations stopped.")}).then(s=>{var n,r,o;if(s){this._adapter=s,this._adapterSupportedExtensions=[],(n=this._adapter.features)===null||n===void 0||n.forEach(c=>this._adapterSupportedExtensions.push(c)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(c=>{this._adapterInfo=c});const l=(r=this._options.deviceDescriptor)!==null&&r!==void 0?r:{},h=(o=l==null?void 0:l.requiredFeatures)!==null&&o!==void 0?o:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(h){const c=h,u=[];for(const d of c)this._adapterSupportedExtensions.indexOf(d)!==-1&&u.push(d);l.requiredFeatures=u}if(this._options.setMaximumLimits&&!l.requiredLimits){l.requiredLimits={};for(const c in this._adapterSupportedLimits)l.requiredLimits[c]=this._adapterSupportedLimits[c]}return this._adapter.requestDevice(l)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(s=>{var n,r;this._device=s,this._deviceEnabledExtensions=[],(n=this._device.features)===null||n===void 0||n.forEach(l=>this._deviceEnabledExtensions.push(l)),this._deviceLimits=s.limits;let o=-1;this._device.addEventListener("uncapturederror",l=>{++o{this._isDisposed||(this._contextWasLost=!0,H.Warn("WebGPU context lost. "+l),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(this.initAsync.bind(this)))})},s=>{H.Error("Could not retrieve a WebGPU device."),H.Error(s)}).then(()=>{this._bufferManager=new p0(this._device),this._textureHelper=new Qe(this._device,this._glslang,this._tintWASM,this._bufferManager),this._cacheSampler=new zs(this._device),this._cacheBindGroups=new _t(this._device,this._cacheSampler,this),this._timestampQuery=new Hd(this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Kd(this,this._device,this._bufferManager):void 0,this._bundleList=new Fr(this._device),this._bundleListRenderTarget=new Fr(this._device),this._snapshotRendering=new Yd(this,this._snapshotRenderingMode,this._bundleList,this._bundleListRenderTarget),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),Je.Uniform|Je.CopyDst),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),Je.Uniform|Je.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 A(this,[0],"",!1,!1,1,!1,0,1),this._initializeLimits(),this._cacheRenderPipeline=new as(this._device,this._emptyVertexBuffer,!this._caps.textureFloatLinearFiltering),this._depthCullingState=new Ud(this._cacheRenderPipeline),this._stencilStateComposer=new Nd(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 zd(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=>{H.Error("Can not create WebGPU Device and/or context."),H.Error(s),console.trace&&console.trace()})}_initGlslang(e){return e=e||{},e={...pe._GLSLslangDefaultOptions,...e},e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Pt()?re.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(Ss.TextureCompressionASTC)>=0?!0:void 0,s3tc:this._deviceEnabledExtensions.indexOf(Ss.TextureCompressionBC)>=0?!0:void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(Ss.TextureCompressionETC2)>=0?!0:void 0,bptc:this._deviceEnabledExtensions.indexOf(Ss.TextureCompressionBC)>=0?!0:void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(Ss.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(Ss.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 xr],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 n={label:"Texture_MainColor_".concat(this._mainTextureExtends.width,"x").concat(this._mainTextureExtends.height,"_antialiasing"),size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:Mi.E2d,format:this._options.swapChainFormat,usage:it.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(n),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:Mi.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new q(0,0,0,1),loadOp:bt.Clear,storeOp:mi.Store}]}else t=[{view:void 0,clearValue:new q(0,0,0,1),loadOp:bt.Clear,storeOp:mi.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?I.Depth24PlusStencil8:I.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);const i={label:"Texture_MainDepthStencil_".concat(this._mainTextureExtends.width,"x").concat(this._mainTextureExtends.height),size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:Mi.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:it.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:"TextureView_MainDepthStencil_".concat(this._mainTextureExtends.width,"x").concat(this._mainTextureExtends.height),dimension:Mi.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:bt.Clear,depthStoreOp:mi.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?bt.Clear:void 0,stencilStoreOp:this.isStencilEnable?mi.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={colorAttachments:t,depthStencilAttachment:s}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:it.RenderAttachment|it.CopySrc,alphaMode:this.premultipliedAlpha?Ir.Premultiplied:Ir.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,n=t.indexOf(_r)>=0,r=i===at.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===at.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(r,o,i,s,n)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=e.indexOf(_r)>=0,r=t.indexOf(_r)>=0,o="#version 450\n",l=s===at.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),h=s===at.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),c=this._createPipelineStageDescriptor(l,h,s,n,r);return this.onAfterShaderCompilationObservable.notifyObservers(this),c}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new qr(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new mu(e,this)}createMaterialContext(){return new Kr}createDrawContext(){return new Yr(this._bufferManager)}_preparePipelineContext(e,t,i,s,n,r,o,l){const h=e,c=h.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(l),console.log(t),console.log(i),console.log("***********************************************")),h.sources={fragment:i,vertex:t,rawVertex:n,rawFragment:r},s?h.stages=this._compileRawPipelineStageDescriptor(t,i,c):h.stages=this._compilePipelineStageDescriptor(t,i,l,c)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let n=0;n0,h._cachedWrapU=0,h._cachedWrapV=0,h._useSRGBBuffer=l.useSRGBBuffer,h.label=l.label,this._internalTexturesCache.push(h),i||this._textureHelper.createGPUTextureForInternalTexture(h,c,u,d||1,l.creationFlags),h}createTexture(e,t,i,s,n=3,r=null,o=null,l=null,h=null,c=null,u=null,d,_,f,g){return this._createTextureBase(e,t,i,s,n,r,o,(p,x,m,T,S,b,y,E)=>{var P;const C=T;if(p.baseWidth=C.width,p.baseHeight=C.height,p.width=C.width,p.height=C.height,p.format=c!=null?c:-1,E(p.width,p.height,C,x,p,()=>{}),!((P=p._hardwareTexture)===null||P===void 0)&&P.underlyingResource)!b&&!y&&this._generateMipmaps(p,this._uploadEncoder);else{const R=this._textureHelper.createGPUTextureForInternalTexture(p,C.width,C.height,void 0,f);Qe.IsImageBitmap(C)&&(this._textureHelper.updateTexture(C,p,C.width,C.height,p.depth,R.format,0,0,S,!1,0,0),!b&&!y&&this._generateMipmaps(p,this._uploadEncoder))}m&&m.removePendingData(p),p.isReady=!0,p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear()},()=>!1,l,h,c,u,d,_,g)}wrapWebGPUTexture(e){const t=new xr(e),i=new Dt(this,ze.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===ze.RenderTarget||e.source===ze.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 n=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,n)}_setInternalTexture(e,t,i){if(i=i!=null?i:e,this._currentEffect){const n=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),n&&n.autoBindSampler){const r=i+rt.AutoSamplerSuffix;this._currentMaterialContext.setSampler(r,t)}}}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let n=0;nthis.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 ps{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 n in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,n)&&this._BabylonFileParsers[n](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}}ps._BabylonFileParsers={};ps._IndividualBabylonFileParsers={};class y0{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._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,n,r;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=(r=(n=this._externalProperties)===null||n===void 0?void 0:n[e])===null||r===void 0?void 0:r.default;switch(o){case"number":this[e]=l!=null?l:0;break;case"string":this[e]=l!=null?l:"";break;default:this[e]=l!=null?l:!1;break}}toString(){let e="";for(let t=0;tnew dt,this)}serialize(){return Se.Serialize(this)}static Parse(e){return Se.Parse(()=>new dt,e,null,null)}}F([B()],dt.prototype,"_globalHue",void 0);F([B()],dt.prototype,"_globalDensity",void 0);F([B()],dt.prototype,"_globalSaturation",void 0);F([B()],dt.prototype,"_globalExposure",void 0);F([B()],dt.prototype,"_highlightsHue",void 0);F([B()],dt.prototype,"_highlightsDensity",void 0);F([B()],dt.prototype,"_highlightsSaturation",void 0);F([B()],dt.prototype,"_highlightsExposure",void 0);F([B()],dt.prototype,"_midtonesHue",void 0);F([B()],dt.prototype,"_midtonesDensity",void 0);F([B()],dt.prototype,"_midtonesSaturation",void 0);F([B()],dt.prototype,"_midtonesExposure",void 0);Se._ColorCurvesParser=dt.Parse;class He{constructor(){this.colorCurves=new dt,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=He.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new q(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=He.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new ee}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&&dt.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===He._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType){case He.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&&dt.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 n=t!=null?t:s/i;let r=Math.tan(this.vignetteCameraFov*.5),o=r*n;const l=Math.sqrt(o*r);o=re.Mix(o,l,this.vignetteStretch),r=re.Mix(r,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,r,-o*this.vignetteCenterX,-r*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}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 Se.Clone(()=>new He,this)}serialize(){return Se.Serialize(this)}static Parse(e){const t=Se.Parse(()=>new He,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}}He.TONEMAPPING_STANDARD=0;He.TONEMAPPING_ACES=1;He._VIGNETTEMODE_MULTIPLY=0;He._VIGNETTEMODE_OPAQUE=1;F([vd()],He.prototype,"colorCurves",void 0);F([B()],He.prototype,"_colorCurvesEnabled",void 0);F([Si("colorGradingTexture")],He.prototype,"_colorGradingTexture",void 0);F([B()],He.prototype,"_colorGradingEnabled",void 0);F([B()],He.prototype,"_colorGradingWithGreenDepth",void 0);F([B()],He.prototype,"_colorGradingBGR",void 0);F([B()],He.prototype,"_exposure",void 0);F([B()],He.prototype,"_toneMappingEnabled",void 0);F([B()],He.prototype,"_toneMappingType",void 0);F([B()],He.prototype,"_contrast",void 0);F([B()],He.prototype,"vignetteStretch",void 0);F([B()],He.prototype,"vignetteCenterX",void 0);F([B()],He.prototype,"vignetteCenterY",void 0);F([B()],He.prototype,"vignetteWeight",void 0);F([f0()],He.prototype,"vignetteColor",void 0);F([B()],He.prototype,"vignetteCameraFov",void 0);F([B()],He.prototype,"_vignetteBlendMode",void 0);F([B()],He.prototype,"_vignetteEnabled",void 0);F([B()],He.prototype,"_ditheringEnabled",void 0);F([B()],He.prototype,"_ditheringIntensity",void 0);F([B()],He.prototype,"_skipFinalColorClamp",void 0);F([B()],He.prototype,"_applyByPostProcess",void 0);F([B()],He.prototype,"_isEnabled",void 0);Se._ImageProcessingConfigurationParser=He.Parse;class cs{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(A.NormalKind))return null;const i=this.pickedMesh.getIndices();if(!i)return null;let s;if(t){const r=this.pickedMesh.getVerticesData(A.NormalKind);let o=v.FromArray(r,i[this.faceId*3]*3),l=v.FromArray(r,i[this.faceId*3+1]*3),h=v.FromArray(r,i[this.faceId*3+2]*3);o=o.scale(this.bu),l=l.scale(this.bv),h=h.scale(1-this.bu-this.bv),s=new v(o.x+l.x+h.x,o.y+l.y+h.y,o.z+l.z+h.z)}else{const r=this.pickedMesh.getVerticesData(A.PositionKind),o=v.FromArray(r,i[this.faceId*3]*3),l=v.FromArray(r,i[this.faceId*3+1]*3),h=v.FromArray(r,i[this.faceId*3+2]*3),c=o.subtract(l),u=h.subtract(l);s=v.Cross(c,u)}const n=(r,o)=>{let l=r.getWorldMatrix();r.nonUniformScaling&&(G.Matrix[0].copyFrom(l),l=G.Matrix[0],l.setTranslationFromFloats(0,0,0),l.invert(),l.transposeToRef(G.Matrix[1]),l=G.Matrix[1]),v.TransformNormalToRef(o,l,o)};if(e&&n(this.pickedMesh,s),this.ray){const r=G.Vector3[0].copyFrom(s);e||n(this.pickedMesh,r),v.Dot(r,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=A.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=fe.FromArray(i,t[this.faceId*3]*2),n=fe.FromArray(i,t[this.faceId*3+1]*2),r=fe.FromArray(i,t[this.faceId*3+2]*2);return s=s.scale(this.bu),n=n.scale(this.bv),r=r.scale(1-this.bu-this.bv),new fe(s.x+n.x+r.x,s.y+n.y+r.y)}}class Lt{constructor(e,t,i,s,n,r){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=n,this.additionalData=r}static CreateNew(e,t,i){const s=e.getScene();return new Lt(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new Lt(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new Lt(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new Lt(e,t.x,t.y,null,i,s)}}class ve{}ve.NAME_EFFECTLAYER="EffectLayer";ve.NAME_LAYER="Layer";ve.NAME_LENSFLARESYSTEM="LensFlareSystem";ve.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer";ve.NAME_PARTICLESYSTEM="ParticleSystem";ve.NAME_GAMEPAD="Gamepad";ve.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue";ve.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer";ve.NAME_PREPASSRENDERER="PrePassRenderer";ve.NAME_DEPTHRENDERER="DepthRenderer";ve.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer";ve.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager";ve.NAME_SPRITE="Sprite";ve.NAME_SUBSURFACE="SubSurface";ve.NAME_OUTLINERENDERER="Outline";ve.NAME_PROCEDURALTEXTURE="ProceduralTexture";ve.NAME_SHADOWGENERATOR="ShadowGenerator";ve.NAME_OCTREE="Octree";ve.NAME_PHYSICSENGINE="PhysicsEngine";ve.NAME_AUDIO="Audio";ve.NAME_FLUIDRENDERER="FluidRenderer";ve.STEP_ISREADYFORMESH_EFFECTLAYER=0;ve.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0;ve.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0;ve.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0;ve.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1;ve.STEP_BEFORECAMERADRAW_PREPASS=0;ve.STEP_BEFORECAMERADRAW_EFFECTLAYER=1;ve.STEP_BEFORECAMERADRAW_LAYER=2;ve.STEP_BEFORERENDERTARGETDRAW_PREPASS=0;ve.STEP_BEFORERENDERTARGETDRAW_LAYER=1;ve.STEP_BEFORERENDERINGMESH_PREPASS=0;ve.STEP_BEFORERENDERINGMESH_OUTLINE=1;ve.STEP_AFTERRENDERINGMESH_PREPASS=0;ve.STEP_AFTERRENDERINGMESH_OUTLINE=1;ve.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0;ve.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1;ve.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0;ve.STEP_BEFORECAMERAUPDATE_GAMEPAD=1;ve.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0;ve.STEP_BEFORECLEAR_PREPASS=1;ve.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0;ve.STEP_AFTERRENDERTARGETDRAW_PREPASS=0;ve.STEP_AFTERRENDERTARGETDRAW_LAYER=1;ve.STEP_AFTERCAMERADRAW_PREPASS=0;ve.STEP_AFTERCAMERADRAW_EFFECTLAYER=1;ve.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2;ve.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3;ve.STEP_AFTERCAMERADRAW_LAYER=4;ve.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5;ve.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0;ve.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0;ve.STEP_AFTERRENDER_AUDIO=0;ve.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0;ve.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1;ve.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2;ve.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3;ve.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0;ve.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1;ve.STEP_POINTERMOVE_SPRITE=0;ve.STEP_POINTERDOWN_SPRITE=0;ve.STEP_POINTERUP_SPRITE=0;class mt extends Array{constructor(e){super(...e)}static Create(){return Object.create(mt.prototype)}registerStep(e,t,i){let s=0,n=Number.MAX_VALUE;for(;s=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in xi.Triggers)if(Object.prototype.hasOwnProperty.call(xi.Triggers,t)&&parseInt(t)===e)return!0;return!1}}xi.Triggers={};class Xn{}Xn.KEYDOWN=1;Xn.KEYUP=2;class Ua{constructor(e,t){this.type=e,this.event=t}}class xo extends Ua{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 ce;(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"})(ce||(ce={}));var xe;(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"})(xe||(xe={}));var Or;(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"})(Or||(Or={}));var bo;(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"})(bo||(bo={}));var yo;(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"})(yo||(yo={}));var To;(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"})(To||(To={}));var So;(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"})(So||(So={}));var Ao;(function(a){a[a.PointerMove=0]="PointerMove",a[a.PointerDown=1]="PointerDown",a[a.PointerUp=2]="PointerUp"})(Ao||(Ao={}));class tr{}tr.DOM_DELTA_PIXEL=0;tr.DOM_DELTA_LINE=1;tr.DOM_DELTA_PAGE=2;class Gs{static CreateDeviceEvent(e,t,i,s,n,r,o){switch(e){case ce.Keyboard:return this._CreateKeyboardEvent(i,s,n,r);case ce.Mouse:if(i===xe.MouseWheelX||i===xe.MouseWheelY||i===xe.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,n,r);case ce.Touch:return this._CreatePointerEvent(e,t,i,s,n,r,o);default:throw"Unable to generate event for device ".concat(ce[e])}}static _CreatePointerEvent(e,t,i,s,n,r,o){const l=this._CreateMouseEvent(e,t,i,s,n,r);return e===ce.Mouse?(l.deviceType=ce.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=ce.Touch,l.pointerId=o!=null?o:t,l.pointerType="touch"),i===xe.Move?l.type="pointermove":i>=xe.LeftClick&&i<=xe.RightClick&&(l.type=s===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,n,r){const o=this._CreateMouseEvent(e,t,i,s,n,r);switch(o.pointerId=1,o.type="wheel",o.deltaMode=tr.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case xe.MouseWheelX:o.deltaX=s;break;case xe.MouseWheelY:o.deltaY=s;break;case xe.MouseWheelZ:o.deltaZ=s;break}return o}static _CreateMouseEvent(e,t,i,s,n,r){const o=this._CreateEvent(r),l=n.pollInput(e,t,xe.Horizontal),h=n.pollInput(e,t,xe.Vertical);return r?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-r.getBoundingClientRect().x,o.offsetY=o.movementY-r.getBoundingClientRect().y):(o.movementX=n.pollInput(e,t,Or.DeltaHorizontal),o.movementY=n.pollInput(e,t,Or.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,n),o.clientX=l,o.clientY=h,o.x=l,o.y=h,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const n=this._CreateEvent(s);return this._CheckNonCharacterKeys(n,i),n.deviceType=ce.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=t===1?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(ce.Keyboard),s=i&&t.pollInput(ce.Keyboard,0,18)===1,n=i&&t.pollInput(ce.Keyboard,0,17)===1,r=i&&(t.pollInput(ce.Keyboard,0,91)===1||t.pollInput(ce.Keyboard,0,92)===1||t.pollInput(ce.Keyboard,0,93)===1),o=i&&t.pollInput(ce.Keyboard,0,16)===1;e.altKey=s,e.ctrlKey=n,e.metaKey=r,e.shiftKey=o}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class jd{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(s,n,r,o)=>{const l=Gs.CreateDeviceEvent(s,n,r,o,this);i(s,n,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===ce.Mouse||e===ce.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const Eo=255,Co=Object.keys(xe).length/2;class $d{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=re.IsSafari(),this._usingMacOS=n0()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=n=>{},this._keyboardUpEvent=n=>{},this._keyboardBlurEvent=n=>{},this._pointerMoveEvent=n=>{},this._pointerDownEvent=n=>{},this._pointerUpEvent=n=>{},this._pointerCancelEvent=n=>{},this._pointerWheelEvent=n=>{},this._pointerBlurEvent=n=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Da.IsNavigatorAvailable()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=n=>{},this._gamepadDisconnectedEvent=n=>{},this._eventPrefix=re.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 ".concat(ce[e]);e>=ce.DualShock&&e<=ce.DualSense&&this._updateDevice(e,t,i);const n=s[i];if(n===void 0)throw"Unable to find input ".concat(i," for device ").concat(ce[e]," in slot ").concat(t);return i===xe.Move&&re.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n}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,n=t[s];if(n)for(let r=0;r{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ce.Keyboard,0,Eo));const t=this._inputs[ce.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(ce.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ce.Keyboard,0,Eo));const t=this._inputs[ce.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 n=Gs.CreateDeviceEvent(ce.Keyboard,0,s,0,this,this._elementToAttachTo);t[s]=0,this._onInputChanged(ce.Keyboard,0,n)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(ce.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[ce.Keyboard][0];for(let t=0;t{const s=this._getPointerType(i),n=s===ce.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);this._inputs[s]||(this._inputs[s]={}),this._inputs[s][n]||this._addPointerDevice(s,n,i.clientX,i.clientY);const r=this._inputs[s][n];if(r){const o=i;o.inputIndex=xe.Move,r[xe.Horizontal]=i.clientX,r[xe.Vertical]=i.clientY,i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(s,n,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,r[i.button+2]=r[i.button+2]?0:1,this._onInputChanged(s,n,o))}},this._pointerDownEvent=i=>{const s=this._getPointerType(i);let n=s===ce.Mouse?0:i.pointerId;if(s===ce.Touch){const o=this._activeTouchIds.indexOf(-1);if(o>=0)n=o,this._activeTouchIds[o]=i.pointerId;else{re.Warn("Max number of touches exceeded. Ignoring touches in excess of ".concat(this._maxTouchPoints));return}}this._inputs[s]||(this._inputs[s]={}),this._inputs[s][n]?s===ce.Touch&&this._onDeviceConnected(s,n):this._addPointerDevice(s,n,i.clientX,i.clientY);const r=this._inputs[s][n];if(r){const o=r[xe.Horizontal],l=r[xe.Vertical];if(s===ce.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{}r[xe.Horizontal]=i.clientX,r[xe.Vertical]=i.clientY,r[i.button+2]=1;const h=i;h.inputIndex=i.button+2,this._onInputChanged(s,n,h),(o!==i.clientX||l!==i.clientY)&&(h.inputIndex=xe.Move,this._onInputChanged(s,n,h))}},this._pointerUpEvent=i=>{var s,n,r,o,l;const h=this._getPointerType(i),c=h===ce.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(h===ce.Touch){if(c===-1)return;this._activeTouchIds[c]=-1}const u=(s=this._inputs[h])===null||s===void 0?void 0:s[c];if(u&&u[i.button+2]!==0){const d=u[xe.Horizontal],_=u[xe.Vertical];u[xe.Horizontal]=i.clientX,u[xe.Vertical]=i.clientY,u[i.button+2]=0;const f=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(d!==i.clientX||_!==i.clientY)&&(f.inputIndex=xe.Move,this._onInputChanged(h,c,f)),f.inputIndex=i.button+2,h===ce.Mouse&&this._mouseId>=0&&(!((r=(n=this._elementToAttachTo).hasPointerCapture)===null||r===void 0)&&r.call(n,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&(!((l=(o=this._elementToAttachTo).hasPointerCapture)===null||l===void 0)&&l.call(o,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(h,c,f),h===ce.Touch&&this._onDeviceDisconnected(h,c)}},this._pointerCancelEvent=i=>{var s,n,r,o;if(i.pointerType==="mouse"){const l=this._inputs[ce.Mouse][0];this._mouseId>=0&&(!((n=(s=this._elementToAttachTo).hasPointerCapture)===null||n===void 0)&&n.call(s,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=xe.LeftClick;h<=xe.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=Gs.CreateDeviceEvent(ce.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(ce.Mouse,0,c)}}else{const l=this._activeTouchIds.indexOf(i.pointerId);!((o=(r=this._elementToAttachTo).hasPointerCapture)===null||o===void 0)&&o.call(r,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[ce.Touch][l][xe.LeftClick]=0;const h=Gs.CreateDeviceEvent(ce.Touch,l,xe.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(ce.Touch,l,h),this._activeTouchIds[l]=-1,this._onDeviceDisconnected(ce.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,n,r,o;if(this.isDeviceAvailable(ce.Mouse)){const l=this._inputs[ce.Mouse][0];this._mouseId>=0&&(!((s=(i=this._elementToAttachTo).hasPointerCapture)===null||s===void 0)&&s.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=xe.LeftClick;h<=xe.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=Gs.CreateDeviceEvent(ce.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(ce.Mouse,0,c)}}if(this.isDeviceAvailable(ce.Touch)){const l=this._inputs[ce.Touch];for(let h=0;h{const s=ce.Mouse,n=0;this._inputs[s]||(this._inputs[s]=[]),this._inputs[s][n]||(this._pointerActive=!0,this._registerDevice(s,n,Co));const r=this._inputs[s][n];if(r){r[xe.MouseWheelX]=i.deltaX||0,r[xe.MouseWheelY]=i.deltaY||i.wheelDelta||0,r[xe.MouseWheelZ]=i.deltaZ||0;const o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),r[xe.MouseWheelX]!==0&&(o.inputIndex=xe.MouseWheelX,this._onInputChanged(s,n,o)),r[xe.MouseWheelY]!==0&&(o.inputIndex=xe.MouseWheelY,this._onInputChanged(s,n,o)),r[xe.MouseWheelZ]!==0&&(o.inputIndex=xe.MouseWheelZ,this._onInputChanged(s,n,o))}},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(ce.Mouse)){const i=this._inputs[ce.Mouse][0];i[xe.MouseWheelX]=0,i[xe.MouseWheelY]=0,i[xe.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 n=this._inputs[e][t];i>=s.buttons.length?n[i]=s.axes[i-s.buttons.length].valueOf():n[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?ce.DualSense:ce.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?ce.Xbox:e.indexOf("057e")!==-1?ce.Switch:ce.Generic}_getPointerType(e){let t=ce.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=ce.Touch),t}}class Ro{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new ee,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Zd{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=r=>{for(let o=0;o{const o=this._registeredManagers.indexOf(r);o>-1&&this._registeredManagers.splice(o,1)};const t=Object.keys(ce).length/2;this._devices=new Array(t);const i=(r,o)=>{this._devices[r]||(this._devices[r]=new Array),this._devices[r][o]||(this._devices[r][o]=o);for(const l of this._registeredManagers){const h=new Ro(this._deviceInputSystem,r,o);l._addDevice(h)}},s=(r,o)=>{var l;!((l=this._devices[r])===null||l===void 0)&&l[o]&&delete this._devices[r][o];for(const h of this._registeredManagers)h._removeDevice(r,o)},n=(r,o,l)=>{if(l)for(const h of this._registeredManagers)h._onInputChanged(r,o,l)};typeof _native<"u"?this._deviceInputSystem=new jd(i,s,n):this._deviceInputSystem=new $d(e,i,s,n)}dispose(){this._deviceInputSystem.dispose()}}class Qd{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(ce).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Zd(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new ee(i=>{for(const s of this._devices)if(s)for(const n of s)n&&this.onDeviceConnectedObservable.notifyObserver(i,n)}),this.onDeviceDisconnectedObservable=new ee,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 n=(i=this._devices[e])===null||i===void 0?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(n),!((s=this._devices[e])===null||s===void 0)&&s[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var s,n;(n=(s=this._devices[e])===null||s===void 0?void 0:s[t])===null||n===void 0||n.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case ce.Keyboard:case ce.Mouse:this._firstDevice[e]=0;break;case ce.Touch:case ce.DualSense:case ce.DualShock:case ce.Xbox:case ce.Switch:case ce.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i=xe.MouseWheelX&&t.inputIndex<=xe.MouseWheelZ?Re.POINTERWHEEL:Re.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,r));let o;e?(o=new ss(r,t,e),this._setRayOnPointerInfo(e,t)):(o=new ss(r,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,r)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,N.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,n=new qd(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(n.originalPickingInfo=e,n.ray=e.ray,e.originMesh&&(n.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(n,i),!!n.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,!1,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const n=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&n&&this._pointerOverMesh){const r=this._pointerOverMesh._getActionManagerForTrigger();r&&r.hasPointerTriggers&&(n.style.cursor=r.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=xe.Move,!this._checkPrePointerObservable(e,i,Re.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,Re.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e!=null&&e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const r=e.pickedMesh._getActionManagerForTrigger();if(r){if(r.hasPickTriggers)switch(r.processTrigger(5,Lt.CreateNew(e.pickedMesh,t)),t.button){case 0:r.processTrigger(2,Lt.CreateNew(e.pickedMesh,t));break;case 1:r.processTrigger(4,Lt.CreateNew(e.pickedMesh,t));break;case 2:r.processTrigger(3,Lt.CreateNew(e.pickedMesh,t));break}r.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!=null&&o.pickedMesh&&r&&this._totalPointersPressed!==0&&Date.now()-this._startingPointerTime>vt.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,r.processTrigger(8,Lt.CreateNew(o.pickedMesh,t)))},vt.LongPressDelay)}}else for(const r of i._pointerDownStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const n=Re.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,n),s=new ss(n,t,e),this._setRayOnPointerInfo(e,t)):s=new ss(n,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,n)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=xe.Move;const n=new Io;i?n.doubleClick=!0:n.singleClick=!0,!this._checkPrePointerObservable(e,s,Re.POINTERUP)&&this._processPointerUp(e,s,n)}_processPointerUp(e,t,i){const s=this._scene;if(e!=null&&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 r=Re.POINTERPICK,o=new ss(r,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(o,r)}const n=e.pickedMesh._getActionManagerForTrigger();if(n&&!i.ignore){n.processTrigger(7,Lt.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&n.processTrigger(1,Lt.CreateNew(e.pickedMesh,t,e));const r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,Lt.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const n of s._pointerUpStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const n=this._pickedDownMesh._getActionManagerForTrigger(16);n&&n.processTrigger(16,Lt.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const n=new ss(Re.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,Re.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,Re.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=Re.POINTERTAP:i.doubleClick&&(r=Re.POINTERDOUBLETAP),r){const o=new ss(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(o,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const n=this._scene,r=n.getEngine();s||(s=r.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Qd(r),this._initActionManager=o=>{if(!this._meshPickProceed){const l=n.skipPointerUpPicking||n._registeredActions===0&&!this._checkForPicking()&&!n.onPointerUp?null:n.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,n.pointerUpPredicate,!1,n.cameraToUseForPointers);this._currentPickResult=l,l&&(o=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,l,h)=>{if((Date.now()-this._previousStartingPointerTime>vt.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[o])){const c=this._delayedClicks[o].evt,u=Re.POINTERTAP,d=new ss(u,c,this._currentPickResult);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(u)&&n.onPointerObservable.notifyObservers(d,u),this._delayedClicks[o]=null}},this._initClickEvent=(o,l,h,c)=>{var u,d;const _=new Io;this._currentPickResult=null;let f=null,g=o.hasSpecificMask(Re.POINTERPICK)||l.hasSpecificMask(Re.POINTERPICK)||o.hasSpecificMask(Re.POINTERTAP)||l.hasSpecificMask(Re.POINTERTAP)||o.hasSpecificMask(Re.POINTERDOUBLETAP)||l.hasSpecificMask(Re.POINTERDOUBLETAP);!g&&xi&&(f=this._initActionManager(f,_),f&&(g=f.hasPickTriggers));let p=!1;if(g){const x=h.button;if(_.hasSwiped=this._isPointerSwiping(),!_.hasSwiped){let m=!vt.ExclusiveDoubleClickMode;if(m||(m=!o.hasSpecificMask(Re.POINTERDOUBLETAP)&&!l.hasSpecificMask(Re.POINTERDOUBLETAP),m&&!xi.HasSpecificTrigger(6)&&(f=this._initActionManager(f,_),f&&(m=!f.hasSpecificTrigger(6)))),m)(Date.now()-this._previousStartingPointerTime>vt.DoubleClickDelay||x!==this._previousButtonPressed)&&(_.singleClick=!0,c(_,this._currentPickResult),p=!0);else{const S={evt:h,clickInfo:_,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,x,_,c),vt.DoubleClickDelay)};this._delayedClicks[x]=S}let T=o.hasSpecificMask(Re.POINTERDOUBLETAP)||l.hasSpecificMask(Re.POINTERDOUBLETAP);!T&&xi.HasSpecificTrigger(6)&&(f=this._initActionManager(f,_),f&&(T=f.hasSpecificTrigger(6))),T&&(x===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>vt.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>vt.DragMovementThreshold),r.isPointerLock&&r._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=xe.MouseWheelX&&o.inputIndex<=xe.MouseWheelZ?Re.POINTERWHEEL:Re.POINTERMOVE)||!n.cameraToUseForPointers&&!n.activeCamera)return;if(n.skipPointerMovePicking){this._processPointerMove(new cs,o);return}n.pointerMovePredicate||(n.pointerMovePredicate=h=>h.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(h.enablePointerMoveEvents||n.constantlyUpdateMeshUnderPointer||h._getActionManagerForTrigger()!==null)&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&h.layerMask)!==0));const l=n._registeredActions>0?this._pickMove(o):null;this._processPointerMove(l,o)},this._onPointerDown=o=>{var l;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,vt.ExclusiveDoubleClickMode){for(let c=0;cc.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&c.layerMask)!==0)),this._pickedDownMesh=null;let h;n.skipPointerDownPicking||n._registeredActions===0&&!this._checkForPicking()&&!n.onPointerDown?h=new cs:h=n.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,n.pointerDownPredicate,!1,n.cameraToUseForPointers),this._processPointerDown(h,o)},this._onPointerUp=o=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),n.preventDefaultOnPointerUp&&s&&(o.preventDefault(),s.focus()),this._initClickEvent(n.onPrePointerObservable,n.onPointerObservable,o,(l,h)=>{if(n.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,o,Re.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}l.hasSwiped||(l.singleClick&&n.onPrePointerObservable.hasSpecificMask(Re.POINTERTAP)&&this._checkPrePointerObservable(null,o,Re.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&n.onPrePointerObservable.hasSpecificMask(Re.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,Re.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),!(!n.cameraToUseForPointers&&!n.activeCamera)&&(n.pointerUpPredicate||(n.pointerUpPredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&c.layerMask)!==0)),!this._meshPickProceed&&(xi&&xi.HasTriggers||this._checkForPicking()||n.onPointerUp)&&this._initActionManager(null,l),h||(h=this._currentPickResult),this._processPointerUp(h,o,l),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{const l=Xn.KEYDOWN;if(n.onPreKeyboardObservable.hasObservers()){const h=new xo(l,o);if(n.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(n.onKeyboardObservable.hasObservers()){const h=new Ua(l,o);n.onKeyboardObservable.notifyObservers(h,l)}n.actionManager&&n.actionManager.processTrigger(14,Lt.CreateNewFromScene(n,o))},this._onKeyUp=o=>{const l=Xn.KEYUP;if(n.onPreKeyboardObservable.hasObservers()){const h=new xo(l,o);if(n.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(n.onKeyboardObservable.hasObservers()){const h=new Ua(l,o);n.onKeyboardObservable.notifyObservers(h,l)}n.actionManager&&n.actionManager.processTrigger(15,Lt.CreateNewFromScene(n,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===ce.Mouse?o.onInputChangedObservable.add(l=>{l.inputIndex===xe.LeftClick||l.inputIndex===xe.MiddleClick||l.inputIndex===xe.RightClick||l.inputIndex===xe.BrowserBack||l.inputIndex===xe.BrowserForward?t&&o.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&o.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===xe.Move?this._onPointerMove(l):(l.inputIndex===xe.MouseWheelX||l.inputIndex===xe.MouseWheelY||l.inputIndex===xe.MouseWheelZ)&&this._onPointerMove(l))}):o.deviceType===ce.Touch?o.onInputChangedObservable.add(l=>{l.inputIndex===xe.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===xe.Move&&this._onPointerMove(l)}):o.deviceType===ce.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 n=this._meshUnderPointerId[t];let r;n&&(r=n._getActionManagerForTrigger(10),r&&r.processTrigger(10,Lt.CreateNew(n,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,r=e._getActionManagerForTrigger(9),r&&r.processTrigger(9,Lt.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]}}vt.DragMovementThreshold=10;vt.LongPressDelay=500;vt.DoubleClickDelay=300;vt.ExclusiveDoubleClickMode=!1;class Ol{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Ol._UniqueIdCounter=1;class Ke{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Ke.FALLOFF_DEFAULT=0;Ke.FALLOFF_PHYSICAL=1;Ke.FALLOFF_GLTF=2;Ke.FALLOFF_STANDARD=3;Ke.LIGHTMAP_DEFAULT=0;Ke.LIGHTMAP_SPECULAR=1;Ke.LIGHTMAP_SHADOWSONLY=2;Ke.INTENSITYMODE_AUTOMATIC=0;Ke.INTENSITYMODE_LUMINOUSPOWER=1;Ke.INTENSITYMODE_LUMINOUSINTENSITY=2;Ke.INTENSITYMODE_ILLUMINANCE=3;Ke.INTENSITYMODE_LUMINANCE=4;Ke.LIGHTTYPEID_POINTLIGHT=0;Ke.LIGHTTYPEID_DIRECTIONALLIGHT=1;Ke.LIGHTTYPEID_SPOTLIGHT=2;Ke.LIGHTTYPEID_HEMISPHERICLIGHT=3;var Wi;(function(a){a[a.BackwardCompatible=0]="BackwardCompatible",a[a.Intermediate=1]="Intermediate",a[a.Aggressive=2]="Aggressive"})(Wi||(Wi={}));class Me extends ps{static DefaultMaterialFactory(e){throw Ae("StandardMaterial")}static CollisionCoordinatorFactory(){throw Ae("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 Wi.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case Wi.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case Wi.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 unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return vt.DragMovementThreshold}static set DragMovementThreshold(e){vt.DragMovementThreshold=e}static get LongPressDelay(){return vt.LongPressDelay}static set LongPressDelay(e){vt.LongPressDelay=e}static get DoubleClickDelay(){return vt.DoubleClickDelay}static set DoubleClickDelay(e){vt.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return vt.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){vt.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){var s;const n=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:(s=this.activeCamera.globalPosition)!==null&&s!==void 0?s:this.activeCamera.devicePosition,r=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return G.Vector4[0].set(n.x,n.y,n.z,r?-1:1),e&&(i?e.setFloat3(t,G.Vector4[0].x,G.Vector4[0].y,G.Vector4[0].z):e.setVector4(t,G.Vector4[0])),G.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=_l(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=Me.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=Me.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 vt(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new q(.2,.2,.3,1),this.ambientColor=new he(0,0,0),this.environmentIntensity=1,this._performancePriority=Wi.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new ee,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 ee,this._onDisposeObserver=null,this.onBeforeRenderObservable=new ee,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new ee,this.onAfterRenderCameraObservable=new ee,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new ee,this.onAfterAnimationsObservable=new ee,this.onBeforeDrawPhaseObservable=new ee,this.onAfterDrawPhaseObservable=new ee,this.onReadyObservable=new ee,this.onBeforeCameraRenderObservable=new ee,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new ee,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new ee,this.onAfterActiveMeshesEvaluationObservable=new ee,this.onBeforeParticlesRenderingObservable=new ee,this.onAfterParticlesRenderingObservable=new ee,this.onDataLoadedObservable=new ee,this.onNewCameraAddedObservable=new ee,this.onCameraRemovedObservable=new ee,this.onNewLightAddedObservable=new ee,this.onLightRemovedObservable=new ee,this.onNewGeometryAddedObservable=new ee,this.onGeometryRemovedObservable=new ee,this.onNewTransformNodeAddedObservable=new ee,this.onTransformNodeRemovedObservable=new ee,this.onNewMeshAddedObservable=new ee,this.onMeshRemovedObservable=new ee,this.onNewSkeletonAddedObservable=new ee,this.onSkeletonRemovedObservable=new ee,this.onNewMaterialAddedObservable=new ee,this.onNewMultiMaterialAddedObservable=new ee,this.onMaterialRemovedObservable=new ee,this.onMultiMaterialRemovedObservable=new ee,this.onNewTextureAddedObservable=new ee,this.onTextureRemovedObservable=new ee,this.onBeforeRenderTargetsRenderObservable=new ee,this.onAfterRenderTargetsRenderObservable=new ee,this.onBeforeStepObservable=new ee,this.onAfterStepObservable=new ee,this.onActiveCameraChanged=new ee,this.onActiveCamerasChanged=new ee,this.onBeforeRenderingGroupObservable=new ee,this.onAfterRenderingGroupObservable=new ee,this.onMeshImportedObservable=new ee,this.onAnimationFileImportedObservable=new ee,this._registeredForLateAnimationBindings=new Vs(256),this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1,this.onPrePointerObservable=new ee,this.onPointerObservable=new ee,this.onPreKeyboardObservable=new ee,this.onKeyboardObservable=new ee,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Me.FOGMODE_NONE,this.fogColor=new he(.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 v(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 Vs(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Gi,this._activeIndices=new Gi,this._activeParticles=new Gi,this._activeBones=new Gi,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 qt(256),this._processedMaterials=new qt(256),this._renderTargets=new Vs(256),this._materialsRenderTargets=new Vs(256),this._activeParticleSystems=new qt(256),this._activeSkeletons=new Vs(32),this._softwareSkinnedMeshes=new Vs(32),this._activeAnimatables=new Array,this._transformMatrix=N.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=mt.Create(),this._beforeClearStage=mt.Create(),this._beforeRenderTargetClearStage=mt.Create(),this._gatherRenderTargetsStage=mt.Create(),this._gatherActiveCameraRenderTargetsStage=mt.Create(),this._isReadyForMeshStage=mt.Create(),this._beforeEvaluateActiveMeshStage=mt.Create(),this._evaluateSubMeshStage=mt.Create(),this._preActiveMeshStage=mt.Create(),this._cameraDrawRenderTargetStage=mt.Create(),this._beforeCameraDrawStage=mt.Create(),this._beforeRenderTargetDrawStage=mt.Create(),this._beforeRenderingGroupDrawStage=mt.Create(),this._beforeRenderingMeshStage=mt.Create(),this._afterRenderingMeshStage=mt.Create(),this._afterRenderingGroupDrawStage=mt.Create(),this._afterCameraDrawStage=mt.Create(),this._afterCameraPostProcessStage=mt.Create(),this._afterRenderTargetDrawStage=mt.Create(),this._afterRenderTargetPostProcessStage=mt.Create(),this._afterRenderStage=mt.Create(),this._pointerMoveStage=mt.Create(),this._pointerDownStage=mt.Create(),this._pointerUpStage=mt.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={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};this._engine=e||Ie.LastCreatedEngine,i.virtual?this._engine._virtualScenes.push(this):(Ie._LastCreatedScene=this,this._engine.scenes.push(this)),this._uid=null,this._renderingManager=new Kt(this),Na&&(this.postProcessManager=new Na(this)),Pt()&&this.attachControl(),this._createUbo(),He&&(this._imageProcessingConfiguration=new He),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){if(this._isDisposed)return!1;let t;const i=this.getEngine();let s=!0;for(this._pendingData.length>0&&(s=!1),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const l of this._isReadyForMeshStage)l.action(n,r)||(s=!1);if(!e)continue;const o=n.material||this.defaultMaterial;if(o)if(o._storeEffectOnSubMeshes)for(const l of n.subMeshes){const h=l.getMaterial();h&&h.hasRenderTargetTextures&&h.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(h)===-1&&(this._processedMaterials.push(h),this._materialsRenderTargets.concatWithNoDuplicate(h.getRenderTargetTextures()))}else o.hasRenderTargetTextures&&o.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(o)===-1&&(this._processedMaterials.push(o),this._materialsRenderTargets.concatWithNoDuplicate(o.getRenderTargetTextures()))}if(!s||!i.areAllEffectsReady())return!1;if(e){for(t=0;t0){for(const n of this.activeCameras)if(!n.isReady(!0))return!1}else if(this.activeCamera&&!this.activeCamera.isReady(!0))return!1;for(const n of this.particleSystems)if(!n.isReady())return!1;return!0}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=Pi.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?Ri.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Ri.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 oe(this._engine,void 0,!1,e!=null?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 Ol.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}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 n=this.getCameraById(e);if(n)return n;const r=this.getBoneById(e);return r||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 n=this.getCameraByName(e);if(n)return n;const r=this.getBoneByName(e);return r||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=n,this._skipEvaluateActiveMeshesCompletely=e,s)for(let r=0;re.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 n=0;n0&&n.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||n.alwaysSelectAsActiveMesh||n.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(n),this.activeCamera._activeMeshes.push(n),r!==n&&r._activate(this._renderId,!1);for(const o of this._preActiveMeshStage)o.action(n);n._activate(this._renderId,!1)&&(n.isAnInstance?n._internalAbstractMeshDataInfo._actAsRegularMesh&&(r=n):r._internalAbstractMeshDataInfo._onlyForInstances=!1,r._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(n,r)),n._postActivate()}}if(this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let s=0;s0){const s=this.getActiveSubMeshCandidates(t),n=s.length;i=i||n===1;for(let r=0;r0&&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 h of this._gatherActiveCameraRenderTargetsStage)h.action(this._renderTargets);let l=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){re.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let h=0;h0),this._renderId++}for(const h of this._cameraDrawRenderTargetStage)l=h.action(this.activeCamera)||l;this._intermediateRendering=!1}this._engine.currentRenderPassId=(r=(n=(s=e.outputRenderTarget)===null||s===void 0?void 0:s.renderPassId)!==null&&n!==void 0?n:e.renderPassId)!==null&&r!==void 0?r:0,l&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(const h of this._beforeCameraDrawStage)h.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 h of this._afterCameraDrawStage)h.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const h=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,h)}for(const h of this._afterCameraPostProcessStage)h.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(Lt.CreateNew(t,void 0,r)),(!t.actionManager.hasSpecificTrigger(13,h=>{const c=h.mesh?h.mesh:h;return r===c})||s.trigger===13)&&t._intersectionsInProgress.splice(l,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Me.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Me.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const n=this._engine.getLockstepMaxSteps();let r=Math.floor(e/t);for(r=Math.min(r,n);e>0&&s0)for(let l=0;l0),this._intermediateRendering=!0;for(let l=0;l0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(n=o==null?void 0:o.renderPassId)!==null&&n!==void 0?n: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;ln.dispose(!0)),this._disposeList(this.transformNodes,n=>n.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),Ie._LastCreatedScene===this&&(this._engine.scenes.length>0?Ie._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:Ie._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!=null?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 n=s.getBoundingInfo(),r=n.boundingBox.minimumWorld,o=n.boundingBox.maximumWorld;v.CheckExtends(r,t,i),v.CheckExtends(o,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,s,n=!1){throw Ae("Ray")}createPickingRayToRef(e,t,i,s,n,r=!1,o=!1){throw Ae("Ray")}createPickingRayInCameraSpace(e,t,i){throw Ae("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw Ae("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,n,r){return new cs}pickWithBoundingInfo(e,t,i,s,n){return new cs}pickWithRay(e,t,i,s){throw Ae("Ray")}multiPick(e,t,i,s,n){throw Ae("Ray")}multiPickWithRay(e,t,i){throw Ae("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||(n=>{});for(const n in e){const r=e[n];Ve&&Ve.MatchesQuery(r,t)&&(s.push(r),i(r))}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,n,r,o){const l=Fs(e,t,i,s?this.offlineProvider:void 0,n,r,o);return this._activeRequests.push(l),l.onCompleteObservable.add(h=>{this._activeRequests.splice(this._activeRequests.indexOf(h),1)}),l}_loadFileAsync(e,t,i,s,n){return new Promise((r,o)=>{this._loadFile(e,l=>{r(l)},t,i,s,(l,h)=>{o(h)},n)})}_requestFile(e,t,i,s,n,r,o){const l=c0(e,t,i,s?this.offlineProvider:void 0,n,r,o);return this._activeRequests.push(l),l.onCompleteObservable.add(h=>{this._activeRequests.splice(this._activeRequests.indexOf(h),1)}),l}_requestFileAsync(e,t,i,s,n){return new Promise((r,o)=>{this._requestFile(e,l=>{r(l)},t,i,s,l=>{o(l)},n)})}_readFile(e,t,i,s,n){const r=Hn(e,t,i,s,n);return this._activeRequests.push(r),r.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),r}_readFileAsync(e,t,i){return new Promise((s,n)=>{this._readFile(e,r=>{s(r)},t,i,r=>{n(r)})})}getPerfCollector(){throw Ae("performanceViewerSceneExtension")}}Me.FOGMODE_NONE=0;Me.FOGMODE_EXP=1;Me.FOGMODE_EXP2=2;Me.FOGMODE_LINEAR=3;Me.MinDeltaTime=1;Me.MaxDeltaTime=1e3;Me.prototype.setActiveCameraByID=function(a){return this.setActiveCameraById(a)};Me.prototype.getLastMaterialByID=function(a){return this.getLastMaterialById(a)};Me.prototype.getMaterialByID=function(a){return this.getMaterialById(a)};Me.prototype.getTextureByUniqueID=function(a){return this.getTextureByUniqueId(a)};Me.prototype.getCameraByID=function(a){return this.getCameraById(a)};Me.prototype.getCameraByUniqueID=function(a){return this.getCameraByUniqueId(a)};Me.prototype.getBoneByID=function(a){return this.getBoneById(a)};Me.prototype.getLightByID=function(a){return this.getLightById(a)};Me.prototype.getLightByUniqueID=function(a){return this.getLightByUniqueId(a)};Me.prototype.getParticleSystemByID=function(a){return this.getParticleSystemById(a)};Me.prototype.getGeometryByID=function(a){return this.getGeometryById(a)};Me.prototype.getMeshByID=function(a){return this.getMeshById(a)};Me.prototype.getMeshesByID=function(a){return this.getMeshesById(a)};Me.prototype.getTransformNodeByID=function(a){return this.getTransformNodeById(a)};Me.prototype.getTransformNodeByUniqueID=function(a){return this.getTransformNodeByUniqueId(a)};Me.prototype.getTransformNodesByID=function(a){return this.getTransformNodesById(a)};Me.prototype.getMeshByUniqueID=function(a){return this.getMeshByUniqueId(a)};Me.prototype.getLastMeshByID=function(a){return this.getLastMeshById(a)};Me.prototype.getLastEntryByID=function(a){return this.getLastEntryById(a)};Me.prototype.getNodeByID=function(a){return this.getNodeById(a)};Me.prototype.getLastSkeletonByID=function(a){return this.getLastSkeletonById(a)};class Jd{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new ee,this._onClonedObservable=new ee}}class At{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const n=this._NodeConstructors[e];return n?n(t,i,s):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return this._nodeDataStorage._doNotSerialize?!0:this._parentNode?this._parentNode.doNotSerialize:!1}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&this._parentNode._children!==void 0&&this._parentNode._children!==null){const i=this._parentNode._children.indexOf(this);i!==-1&&this._parentNode._children.splice(i,1),!e&&!this._nodeDataStorage._isDisposed&&this._addToSceneRootNodes()}this._parentNode=e,this._parentNode&&((this._parentNode._children===void 0||this._parentNode._children===null)&&(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){this._nodeDataStorage._sceneRootNodesIndex===-1&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(this._nodeDataStorage._sceneRootNodesIndex!==-1){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null){this._isDirty=!1,this._nodeDataStorage=new Jd,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new ee,this._parentContainer=null,this.animations=new Array,this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=N.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new ee,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||Ie.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return this._behaviors.indexOf(e)!==-1?this:(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{e.attach(this)}):e.attach(this),this._behaviors.push(e),this)}removeBehavior(e){const t=this._behaviors.indexOf(e);return t===-1?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,this._updateCache())}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return this._parentNode?this._parentNode._isDirty||this._parentUpdateId!==this._parentNode._childUpdateId?!1:this._parentNode.isSynchronized():!0}isSynchronized(){return this._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):this._parentNode&&!this.isSynchronizedWithParent()?!1:this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return e===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,this._children&&this._children.forEach(e=>{e._syncParentEnabledState()})}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return this.parent?this.parent===e?!0:this.parent.isDescendantOf(e):!1}_getDescendants(e,t=!1,i){if(this._children)for(let 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;t{throw Ae("AnimationRange")};At._NodeConstructors={};F([B()],At.prototype,"name",void 0);F([B()],At.prototype,"id",void 0);F([B()],At.prototype,"uniqueId",void 0);F([B()],At.prototype,"state",void 0);F([B()],At.prototype,"metadata",void 0);class be extends At{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&be.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!==be.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 v(0,0,1),this._up=new v(0,1,0),this._right=new v(1,0,0),this._position=v.Zero(),this._rotation=v.Zero(),this._rotationQuaternion=null,this._scaling=v.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=be.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=N.Zero(),this._usePivotMatrix=!1,this._absolutePosition=v.Zero(),this._absoluteScaling=v.Zero(),this._absoluteRotationQuaternion=ue.Identity(),this._pivotMatrix=N.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new ee,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 v.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return v.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return v.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=N.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==be.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=N.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 n of this.getChildTransformNodes(!0))n.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||ue.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 n=G.Matrix[0];this.parent.getWorldMatrix().invertToRef(n),v.TransformCoordinatesFromFloatsToRef(t,i,s,n,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=v.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=G.Matrix[0];return this._localMatrix.invertToRef(e),v.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=v.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,n=Nt.LOCAL){const r=be._LookAtVectorCache,o=n===Nt.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,r),this.setDirection(r,t,i,s),n===Nt.WORLD&&this.parent)if(this.rotationQuaternion){const l=G.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);const h=G.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),l.multiplyToRef(h,l),this.rotationQuaternion.fromRotationMatrix(l)}else{const l=G.Quaternion[0];ue.FromEulerVectorToRef(this.rotation,l);const h=G.Matrix[0];l.toRotationMatrix(h);const c=G.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),h.multiplyToRef(c,h),l.fromRotationMatrix(h),l.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=v.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return v.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const n=-Math.atan2(e.z,e.x)+Math.PI/2,r=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,r);return this.rotationQuaternion?ue.RotationYawPitchRollToRef(n+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=n+t,this.rotation.z=s),this}setPivotPoint(e,t=Nt.LOCAL){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==Nt.WORLD){const s=G.Matrix[0];i.invertToRef(s),e=v.TransformCoordinates(e,s)}return this.setPivotMatrix(N.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=v.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=v.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),v.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=G.Quaternion[0],n=G.Vector3[0],r=G.Vector3[1],o=G.Matrix[1];N.IdentityToRef(o);const l=G.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=be._TmpRotation,ue.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),N.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(r,s,n,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(r),this.position.copyFrom(n),this.parent=e,i&&this.setPivotMatrix(N.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(),e.getWorldMatrix().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===Nt.LOCAL)s=ue.RotationAxisToRef(e,t,be._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);else{if(this.parent){const n=G.Matrix[0];this.parent.getWorldMatrix().invertToRef(n),e=v.TransformNormal(e,n)}s=ue.RotationAxisToRef(e,t,be._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=ue.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=G.Vector3[0],n=G.Vector3[1],r=G.Vector3[2],o=G.Quaternion[0],l=G.Matrix[0],h=G.Matrix[1],c=G.Matrix[2],u=G.Matrix[3];return e.subtractToRef(this.position,s),N.TranslationToRef(s.x,s.y,s.z,l),N.TranslationToRef(-s.x,-s.y,-s.z,h),N.RotationAxisToRef(t,i,c),h.multiplyToRef(c,u),u.multiplyToRef(l,u),u.decompose(n,o,r),this.position.addInPlace(r),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(!i||i===Nt.LOCAL){const n=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(n)}else this.setAbsolutePosition(this.getAbsolutePosition().add(s));return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=G.Quaternion[1],ue.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const n=G.Quaternion[0];return ue.RotationYawPitchRollToRef(t,e,i,n),s.multiplyInPlace(n),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==be.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 n=this._getEffectiveParent(),r=be._TmpScaling;let o=this._position;if(this._infiniteDistance&&!this.parent&&t){const h=t.getWorldMatrix(),c=new v(h.m[12],h.m[13],h.m[14]);o=be._TmpTranslation,o.copyFromFloats(this._position.x+c.x,this._position.y+c.y,this._position.z+c.z)}r.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(ue.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=be._TmpRotation,ue.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){const h=G.Matrix[1];N.ScalingToRef(r.x,r.y,r.z,h);const c=G.Matrix[0];l.toRotationMatrix(c),this._pivotMatrix.multiplyToRef(h,G.Matrix[4]),G.Matrix[4].multiplyToRef(c,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else N.ComposeToRef(r,l,o,this._localMatrix);if(n&&n.getWorldMatrix){if(e&&n.computeWorldMatrix(e),s.useBillboardPath){this._transformToBoneReferal?n.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),G.Matrix[7]):G.Matrix[7].copyFrom(n.getWorldMatrix());const h=G.Vector3[5],c=G.Vector3[6],u=G.Quaternion[0];G.Matrix[7].decompose(c,u,h),N.ScalingToRef(c.x,c.y,c.z,G.Matrix[7]),G.Matrix[7].setTranslation(h),be.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,h),this._localMatrix.setTranslation(h)),this._localMatrix.multiplyToRef(G.Matrix[7],this._worldMatrix)}else this._transformToBoneReferal?(this._localMatrix.multiplyToRef(n.getWorldMatrix(),G.Matrix[6]),G.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(n.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const h=G.Vector3[0];if(this._worldMatrix.getTranslationToRef(h),G.Matrix[1].copyFrom(t.getViewMatrix()),G.Matrix[1].setTranslationFromFloats(0,0,0),G.Matrix[1].invertToRef(G.Matrix[0]),(this.billboardMode&be.BILLBOARDMODE_ALL)!==be.BILLBOARDMODE_ALL){G.Matrix[0].decompose(void 0,G.Quaternion[0],void 0);const c=G.Vector3[1];G.Quaternion[0].toEulerAnglesToRef(c),(this.billboardMode&be.BILLBOARDMODE_X)!==be.BILLBOARDMODE_X&&(c.x=0),(this.billboardMode&be.BILLBOARDMODE_Y)!==be.BILLBOARDMODE_Y&&(c.y=0),(this.billboardMode&be.BILLBOARDMODE_Z)!==be.BILLBOARDMODE_Z&&(c.z=0),N.RotationYawPitchRollToRef(c.y,c.x,c.z,G.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(G.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(G.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const h=G.Vector3[0];this._worldMatrix.getTranslationToRef(h);const c=t.globalPosition;this._worldMatrix.invertToRef(G.Matrix[1]);const u=G.Vector3[1];v.TransformCoordinatesToRef(c,G.Matrix[1],u),u.normalize();const d=-Math.atan2(u.z,u.x)+Math.PI/2,_=Math.sqrt(u.x*u.x+u.z*u.z),f=-Math.atan2(u.y,_);if(ue.RotationYawPitchRollToRef(d,f,0,G.Quaternion[0]),(this.billboardMode&be.BILLBOARDMODE_ALL)!==be.BILLBOARDMODE_ALL){const g=G.Vector3[1];G.Quaternion[0].toEulerAnglesToRef(g),(this.billboardMode&be.BILLBOARDMODE_X)!==be.BILLBOARDMODE_X&&(g.x=0),(this.billboardMode&be.BILLBOARDMODE_Y)!==be.BILLBOARDMODE_Y&&(g.y=0),(this.billboardMode&be.BILLBOARDMODE_Z)!==be.BILLBOARDMODE_Z&&(g.z=0),N.RotationYawPitchRollToRef(g.y,g.x,g.z,G.Matrix[0])}else N.FromQuaternionToRef(G.Quaternion[0],G.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(G.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(G.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):n&&n._nonUniformScaling?this._updateNonUniformScalingState(n._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=N.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;inew be(e,this.getScene()),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const n=this.getDescendants(!0);for(let r=0;rnew be(e.name,t),e,t,i);return e.localMatrix?s.setPreTransformMatrix(N.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(N.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 be),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,n=null;t&&(this.rotationQuaternion?(n=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const r=this.getHierarchyBoundingVectors(e,i),o=r.max.subtract(r.min),l=Math.max(o.x,o.y,o.z);if(l===0)return this;const h=1/l;return this.scaling.scaleInPlace(h),t&&(this.rotationQuaternion&&n?this.rotationQuaternion.copyFrom(n):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}be.BILLBOARDMODE_NONE=0;be.BILLBOARDMODE_X=1;be.BILLBOARDMODE_Y=2;be.BILLBOARDMODE_Z=4;be.BILLBOARDMODE_ALL=7;be.BILLBOARDMODE_USE_POSITION=128;be.BillboardUseParentOrientation=!1;be._TmpRotation=ue.Zero();be._TmpScaling=v.Zero();be._TmpTranslation=v.Zero();be._LookAtVectorCache=new v(0,0,0);be._RotationAxisCache=new ue;F([wi("position")],be.prototype,"_position",void 0);F([wi("rotation")],be.prototype,"_rotation",void 0);F([xd("rotationQuaternion")],be.prototype,"_rotationQuaternion",void 0);F([wi("scaling")],be.prototype,"_scaling",void 0);F([B("billboardMode")],be.prototype,"_billboardMode",void 0);F([B()],be.prototype,"scalingDeterminant",void 0);F([B("infiniteDistance")],be.prototype,"_infiniteDistance",void 0);F([B()],be.prototype,"ignoreNonUniformScaling",void 0);F([B()],be.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);function ka(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 ef(a=25){let e;return(t,i,s)=>{const n=performance.now();e===void 0||n-e>a?(e=n,setTimeout(()=>{ka(t,i,s)},0)):ka(t,i,s)}}function Ll(a,e,t,i,s){const n=()=>{let r;const o=l=>{l.done?t(l.value):r===void 0?r=!0:n()};do r=void 0,!s||!s.aborted?e(a,o,i):i(new Error("Aborted")),r===void 0&&(r=!1);while(r)};n()}function T0(a,e){let t;return Ll(a,ka,i=>t=i,i=>{throw i},e),t}function tf(a,e,t){return new Promise((i,s)=>{Ll(a,e,i,s,t)})}function sf(a,e){return(...t)=>T0(a(...t),e)}class de extends At{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 n=0,r=0;if(this.mode===de.PERSPECTIVE_CAMERA)this.fovMode===de.FOVMODE_VERTICAL_FIXED?(r=this.minZ*2*Math.tan(this.fov/2),n=this.getEngine().getAspectRatio(this)*r):(n=this.minZ*2*Math.tan(this.fov/2),r=n/this.getEngine().getAspectRatio(this));else{const o=this.getEngine().getRenderWidth()/2,l=this.getEngine().getRenderHeight()/2;n=((e=this.orthoRight)!==null&&e!==void 0?e:o)-((t=this.orthoLeft)!==null&&t!==void 0?t:-o),r=((i=this.orthoTop)!==null&&i!==void 0?i:l)-((s=this.orthoBottom)!==null&&s!==void 0?s:-l)}return n*r}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=v.Zero(),this._upVector=v.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=de.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new mn(0,0,1,1),this.layerMask=268435455,this.fovMode=de.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=de.RIG_MODE_NONE,this.customRenderTargets=new Array,this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new ee,this.onProjectionMatrixChangedObservable=new ee,this.onAfterCheckInputsObservable=new ee,this.onRestoreStateObservable=new ee,this.isRigCamera=!1,this._rigCameras=new Array,this._webvrViewMatrix=N.Identity(),this._skipRendering=!1,this._projectionMatrix=new N,this._postProcesses=new Array,this._activeMeshes=new qt(256),this._globalPosition=v.Zero(),this._computedViewMatrix=N.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=N.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=ue.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 ".concat(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?(H.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 N.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,n,r,o,l,h;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 c=this.getEngine(),u=this.getScene(),d=c.useReverseDepthBuffer;if(this.mode===de.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=c.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let _;u.useRightHandedSystem?_=N.PerspectiveFovRHToRef:_=N.PerspectiveFovLHToRef,_(this.fov,c.getAspectRatio(this),d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===de.FOVMODE_VERTICAL_FIXED,c.isNDCHalfZRange,this.projectionPlaneTilt,d)}else{const _=c.getRenderWidth()/2,f=c.getRenderHeight()/2;u.useRightHandedSystem?N.OrthoOffCenterRHToRef((t=this.orthoLeft)!==null&&t!==void 0?t:-_,(i=this.orthoRight)!==null&&i!==void 0?i:_,(s=this.orthoBottom)!==null&&s!==void 0?s:-f,(n=this.orthoTop)!==null&&n!==void 0?n:f,d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange):N.OrthoOffCenterLHToRef((r=this.orthoLeft)!==null&&r!==void 0?r:-_,(o=this.orthoRight)!==null&&o!==void 0?o:_,(l=this.orthoBottom)!==null&&l!==void 0?l:-f,(h=this.orthoTop)!==null&&h!==void 0?h:f,d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=c.getRenderWidth(),this._cache.renderHeight=c.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?Ri.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Ri.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 Ae("Ray")}getForwardRayToRef(e,t=100,i,s){throw Ae("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!==de.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let s=this._postProcesses.length;for(;--s>=0;){const n=this._postProcesses[s];n&&n.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=re.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==de.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 N.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 N.Identity()}_getWebVRViewMatrix(){return N.Identity()}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=re.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;ede._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=de.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),n=Se.Parse(s,e,t);if(e.parentId!==void 0&&(n._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),n.inputs&&(n.inputs.parse(e),n._setupInputs()),e.upVector&&(n.upVector=v.FromArray(e.upVector)),n.setPosition&&(n.position.copyFromFloats(0,0,0),n.setPosition(v.FromArray(e.position))),e.target&&n.setTarget&&n.setTarget(v.FromArray(e.target)),e.cameraRigMode){const r=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};n.setCameraRigMode(e.cameraRigMode,r)}if(e.animations){for(let r=0;r{throw Ae("UniversalCamera")};de.PERSPECTIVE_CAMERA=0;de.ORTHOGRAPHIC_CAMERA=1;de.FOVMODE_VERTICAL_FIXED=0;de.FOVMODE_HORIZONTAL_FIXED=1;de.RIG_MODE_NONE=0;de.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;de.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;de.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;de.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;de.RIG_MODE_STEREOSCOPIC_INTERLACED=14;de.RIG_MODE_VR=20;de.RIG_MODE_WEBVR=21;de.RIG_MODE_CUSTOM=22;de.ForceAttachControlToAlwaysPreventDefault=!1;F([wi("position")],de.prototype,"_position",void 0);F([wi("upVector")],de.prototype,"_upVector",void 0);F([B()],de.prototype,"orthoLeft",null);F([B()],de.prototype,"orthoRight",null);F([B()],de.prototype,"orthoBottom",null);F([B()],de.prototype,"orthoTop",null);F([B()],de.prototype,"fov",void 0);F([B()],de.prototype,"projectionPlaneTilt",void 0);F([B()],de.prototype,"minZ",void 0);F([B()],de.prototype,"maxZ",void 0);F([B()],de.prototype,"inertia",void 0);F([B()],de.prototype,"mode",null);F([B()],de.prototype,"layerMask",void 0);F([B()],de.prototype,"fovMode",void 0);F([B()],de.prototype,"cameraRigMode",void 0);F([B()],de.prototype,"interaxialDistance",void 0);F([B()],de.prototype,"isStereoscopicSideBySide",void 0);class J{constructor(){this._applyTo=sf(this._applyToCoroutine.bind(this))}set(e,t){switch(e.length||H.Warn("Setting vertex data kind '".concat(t,"' with an empty array")),t){case A.PositionKind:this.positions=e;break;case A.NormalKind:this.normals=e;break;case A.TangentKind:this.tangents=e;break;case A.UVKind:this.uvs=e;break;case A.UV2Kind:this.uvs2=e;break;case A.UV3Kind:this.uvs3=e;break;case A.UV4Kind:this.uvs4=e;break;case A.UV5Kind:this.uvs5=e;break;case A.UV6Kind:this.uvs6=e;break;case A.ColorKind:this.colors=e;break;case A.MatricesIndicesKind:this.matricesIndices=e;break;case A.MatricesWeightsKind:this.matricesWeights=e;break;case A.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case A.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){return this.positions&&(e.setVerticesData(A.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(A.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(A.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(A.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(A.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(A.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(A.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(A.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(A.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(A.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(A.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(A.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(A.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(A.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),this}_update(e,t,i){return this.positions&&e.updateVerticesData(A.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(A.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(A.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(A.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(A.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(A.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(A.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(A.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(A.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(A.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(A.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(A.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(A.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(A.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const n=G.Vector3[0],r=G.Vector3[1];for(let o=i;o({vertexData:n})):[{vertexData:e}];return T0(this._mergeCoroutine(void 0,s,t,!1,i))}*_mergeCoroutine(e,t,i=!1,s,n){var r,o,l,h;this._validate();const c=t.map(f=>f.vertexData);for(const f of c)if(f._validate(),!this.normals!=!f.normals||!this.tangents!=!f.tangents||!this.uvs!=!f.uvs||!this.uvs2!=!f.uvs2||!this.uvs3!=!f.uvs3||!this.uvs4!=!f.uvs4||!this.uvs5!=!f.uvs5||!this.uvs6!=!f.uvs6||!this.colors!=!f.colors||!this.matricesIndices!=!f.matricesIndices||!this.matricesWeights!=!f.matricesWeights||!this.matricesIndicesExtra!=!f.matricesIndicesExtra||!this.matricesWeightsExtra!=!f.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");const u=c.reduce((f,g)=>{var p,x;return f+((x=(p=g.indices)===null||p===void 0?void 0:p.length)!==null&&x!==void 0?x:0)},(o=(r=this.indices)===null||r===void 0?void 0:r.length)!==null&&o!==void 0?o:0);let _=n||c.some(f=>f.indices===this.indices)?(l=this.indices)===null||l===void 0?void 0:l.slice():this.indices;if(u>0){let f=(h=_==null?void 0:_.length)!==null&&h!==void 0?h:0;if(_||(_=new Array(u)),_.length!==u){if(Array.isArray(_))_.length=u;else{const p=i||_ instanceof Uint32Array?new Uint32Array(u):new Uint16Array(u);p.set(_),_=p}e&&e.determinant()<0&&J._FlipFaces(_,0,f)}let g=this.positions?this.positions.length/3:0;for(const{vertexData:p,transform:x}of t)if(p.indices){for(let m=0;m[f.vertexData.positions,f.transform])),s&&(yield),this.normals=J._MergeElement(A.NormalKind,this.normals,e,t.map(f=>[f.vertexData.normals,f.transform])),s&&(yield),this.tangents=J._MergeElement(A.TangentKind,this.tangents,e,t.map(f=>[f.vertexData.tangents,f.transform])),s&&(yield),this.uvs=J._MergeElement(A.UVKind,this.uvs,e,t.map(f=>[f.vertexData.uvs,f.transform])),s&&(yield),this.uvs2=J._MergeElement(A.UV2Kind,this.uvs2,e,t.map(f=>[f.vertexData.uvs2,f.transform])),s&&(yield),this.uvs3=J._MergeElement(A.UV3Kind,this.uvs3,e,t.map(f=>[f.vertexData.uvs3,f.transform])),s&&(yield),this.uvs4=J._MergeElement(A.UV4Kind,this.uvs4,e,t.map(f=>[f.vertexData.uvs4,f.transform])),s&&(yield),this.uvs5=J._MergeElement(A.UV5Kind,this.uvs5,e,t.map(f=>[f.vertexData.uvs5,f.transform])),s&&(yield),this.uvs6=J._MergeElement(A.UV6Kind,this.uvs6,e,t.map(f=>[f.vertexData.uvs6,f.transform])),s&&(yield),this.colors=J._MergeElement(A.ColorKind,this.colors,e,t.map(f=>[f.vertexData.colors,f.transform])),s&&(yield),this.matricesIndices=J._MergeElement(A.MatricesIndicesKind,this.matricesIndices,e,t.map(f=>[f.vertexData.matricesIndices,f.transform])),s&&(yield),this.matricesWeights=J._MergeElement(A.MatricesWeightsKind,this.matricesWeights,e,t.map(f=>[f.vertexData.matricesWeights,f.transform])),s&&(yield),this.matricesIndicesExtra=J._MergeElement(A.MatricesIndicesExtraKind,this.matricesIndicesExtra,e,t.map(f=>[f.vertexData.matricesIndicesExtra,f.transform])),s&&(yield),this.matricesWeightsExtra=J._MergeElement(A.MatricesWeightsExtraKind,this.matricesWeightsExtra,e,t.map(f=>[f.vertexData.matricesWeightsExtra,f.transform])),this}static _MergeElement(e,t,i,s){const n=s.filter(l=>l[0]!==null&&l[0]!==void 0);if(!t&&n.length==0)return t;if(!t)return this._MergeElement(e,n[0][0],n[0][1],n.slice(1));const r=n.reduce((l,h)=>l+h[0].length,t.length),o=e===A.PositionKind?J._TransformVector3Coordinates:e===A.NormalKind?J._TransformVector3Normals:e===A.TangentKind?J._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const l=new Float32Array(r);l.set(t),i&&o(l,i,0,t.length);let h=t.length;for(const[c,u]of n)l.set(c,h),u&&o(l,u,h,c.length),h+=c.length;return l}else{const l=new Array(r);for(let c=0;c{const r=A.DeduceStride(s);if(n.length%r!==0)throw new Error("The "+s+"s array count must be a multiple of "+r);return n.length/r},t=e(A.PositionKind,this.positions),i=(s,n)=>{const r=e(s,n);if(r!==t)throw new Error("The "+s+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(A.NormalKind,this.normals),this.tangents&&i(A.TangentKind,this.tangents),this.uvs&&i(A.UVKind,this.uvs),this.uvs2&&i(A.UV2Kind,this.uvs2),this.uvs3&&i(A.UV3Kind,this.uvs3),this.uvs4&&i(A.UV4Kind,this.uvs4),this.uvs5&&i(A.UV5Kind,this.uvs5),this.uvs6&&i(A.UV6Kind,this.uvs6),this.colors&&i(A.ColorKind,this.colors),this.matricesIndices&&i(A.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(A.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(A.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(A.MatricesWeightsExtraKind,this.matricesWeightsExtra)}serialize(){const e={};return this.positions&&(e.positions=this.positions),this.normals&&(e.normals=this.normals),this.tangents&&(e.tangents=this.tangents),this.uvs&&(e.uvs=this.uvs),this.uvs2&&(e.uvs2=this.uvs2),this.uvs3&&(e.uvs3=this.uvs3),this.uvs4&&(e.uvs4=this.uvs4),this.uvs5&&(e.uvs5=this.uvs5),this.uvs6&&(e.uvs6=this.uvs6),this.colors&&(e.colors=this.colors),this.matricesIndices&&(e.matricesIndices=this.matricesIndices,e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(e.matricesIndicesExtra=this.matricesIndicesExtra,e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=this.matricesWeightsExtra),e.indices=this.indices,e}static ExtractFromMesh(e,t,i){return J._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return J._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new J;return e.isVerticesDataPresent(A.PositionKind)&&(s.positions=e.getVerticesData(A.PositionKind,t,i)),e.isVerticesDataPresent(A.NormalKind)&&(s.normals=e.getVerticesData(A.NormalKind,t,i)),e.isVerticesDataPresent(A.TangentKind)&&(s.tangents=e.getVerticesData(A.TangentKind,t,i)),e.isVerticesDataPresent(A.UVKind)&&(s.uvs=e.getVerticesData(A.UVKind,t,i)),e.isVerticesDataPresent(A.UV2Kind)&&(s.uvs2=e.getVerticesData(A.UV2Kind,t,i)),e.isVerticesDataPresent(A.UV3Kind)&&(s.uvs3=e.getVerticesData(A.UV3Kind,t,i)),e.isVerticesDataPresent(A.UV4Kind)&&(s.uvs4=e.getVerticesData(A.UV4Kind,t,i)),e.isVerticesDataPresent(A.UV5Kind)&&(s.uvs5=e.getVerticesData(A.UV5Kind,t,i)),e.isVerticesDataPresent(A.UV6Kind)&&(s.uvs6=e.getVerticesData(A.UV6Kind,t,i)),e.isVerticesDataPresent(A.ColorKind)&&(s.colors=e.getVerticesData(A.ColorKind,t,i)),e.isVerticesDataPresent(A.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(A.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(A.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(A.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(A.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(A.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(A.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(A.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw Ae("ribbonBuilder")}static CreateBox(e){throw Ae("boxBuilder")}static CreateTiledBox(e){throw Ae("tiledBoxBuilder")}static CreateTiledPlane(e){throw Ae("tiledPlaneBuilder")}static CreateSphere(e){throw Ae("sphereBuilder")}static CreateCylinder(e){throw Ae("cylinderBuilder")}static CreateTorus(e){throw Ae("torusBuilder")}static CreateLineSystem(e){throw Ae("linesBuilder")}static CreateDashedLines(e){throw Ae("linesBuilder")}static CreateGround(e){throw Ae("groundBuilder")}static CreateTiledGround(e){throw Ae("groundBuilder")}static CreateGroundFromHeightMap(e){throw Ae("groundBuilder")}static CreatePlane(e){throw Ae("planeBuilder")}static CreateDisc(e){throw Ae("discBuilder")}static CreatePolygon(e,t,i,s,n,r,o){throw Ae("polygonBuilder")}static CreateIcoSphere(e){throw Ae("icoSphereBuilder")}static CreatePolyhedron(e){throw Ae("polyhedronBuilder")}static CreateCapsule(e={orientation:v.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw Ae("capsuleBuilder")}static CreateTorusKnot(e){throw Ae("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let n=0,r=0,o=0,l=0,h=0,c=0,u=0,d=0,_=0,f=0,g=0,p=0,x=0,m=0,T=0,S=0,b=0,y=0,E=0,P=0,C=!1,R=!1,w=!1,D=!1,W=1,L=0,z=null;s&&(C=!!s.facetNormals,R=!!s.facetPositions,w=!!s.facetPartitioning,W=s.useRightHandedSystem===!0?-1:1,L=s.ratio||0,D=!!s.depthSort,z=s.distanceTo,D&&z===void 0&&(z=v.Zero()));let K=0,ae=0,$=0,U=0;for(w&&s&&s.bbSize&&(K=s.subDiv.X*L/s.bbSize.x,ae=s.subDiv.Y*L/s.bbSize.y,$=s.subDiv.Z*L/s.bbSize.z,U=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),n=0;n!Array.isArray(a))],J,"_TransformVector3Coordinates",null);F([Os.filter((...[a])=>!Array.isArray(a))],J,"_TransformVector3Normals",null);F([Os.filter((...[a])=>!Array.isArray(a))],J,"_TransformVector4Normals",null);F([Os.filter((...[a])=>!Array.isArray(a))],J,"_FlipFaces",null);class Va{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class os{constructor(e,t,i){this.vectors=kt.BuildArray(8,v.Zero),this.center=v.Zero(),this.centerWorld=v.Zero(),this.extendSize=v.Zero(),this.extendSizeWorld=v.Zero(),this.directions=kt.BuildArray(3,v.Zero),this.vectorsWorld=kt.BuildArray(8,v.Zero),this.minimumWorld=v.Zero(),this.maximumWorld=v.Zero(),this.minimum=v.Zero(),this.maximum=v.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,n=e.y,r=e.z,o=t.x,l=t.y,h=t.z,c=this.vectors;this.minimum.copyFromFloats(s,n,r),this.maximum.copyFromFloats(o,l,h),c[0].copyFromFloats(s,n,r),c[1].copyFromFloats(o,l,h),c[2].copyFromFloats(o,n,r),c[3].copyFromFloats(s,l,r),c[4].copyFromFloats(s,n,h),c[5].copyFromFloats(o,l,r),c[6].copyFromFloats(s,l,h),c[7].copyFromFloats(o,n,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||N.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=os._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const n=s*e,r=i.scaleInPlace(n*.5),o=this.center.subtractToRef(r,t[1]),l=this.center.addToRef(r,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,n=this.vectorsWorld,r=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)n[o].copyFrom(r[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=n[o];v.TransformCoordinatesToRef(r[o],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}v.FromArrayToRef(e.m,0,s[0]),v.FromArrayToRef(e.m,4,s[1]),v.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return os.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return os.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,n=t.y,r=t.z,o=i.x,l=i.y,h=i.z,c=e.x,u=e.y,d=e.z,_=-Ge;return!(o-c<_||_>c-s||l-u<_||_>u-n||h-d<_||_>d-r)}intersectsSphere(e){return os.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,n=i.x,r=i.y,o=i.z,l=s.x,h=s.y,c=s.z,u=e.x,d=e.y,_=e.z,f=t.x,g=t.y,p=t.z;return!(lf||hg||c<_||o>p)}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 n=os._TmpVector3[0];return v.ClampToRef(i,e,t,n),v.DistanceSquared(i,n)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let n=0;n<8;++n)if(s.dotCoordinate(e[n])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const n=t[i];for(let r=0;r<8;++r)if(n.dotCoordinate(e[r])>=0){s=!1;break}if(s)return!1}return!0}}os._TmpVector3=kt.BuildArray(3,v.Zero);class Ys{constructor(e,t,i){this.center=v.Zero(),this.centerWorld=v.Zero(),this.minimum=v.Zero(),this.maximum=v.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=v.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=s*.5,this._update(i||N.IdentityReadOnly)}scale(e){const t=this.radius*e,i=Ys._TmpVector3,s=i[0].setAll(t),n=this.center.subtractToRef(s,i[1]),r=this.center.addToRef(s,i[2]);return this.reConstruct(n,r,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{v.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=Ys._TmpVector3[0];v.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=v.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const i=v.Dot(e.centerWorld,a),s=Math.abs(v.Dot(e.directions[0],a))*e.extendSize.x,n=Math.abs(v.Dot(e.directions[1],a))*e.extendSize.y,r=Math.abs(v.Dot(e.directions[2],a))*e.extendSize.z,o=s+n+r;t.min=i-o,t.max=i+o},oi=(a,e,t)=>(Mo(a,e,ya),Mo(a,t,Ta),!(ya.min>Ta.max||Ta.min>ya.max));class yi{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new os(e,t,i),this.boundingSphere=new Ys(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=yi._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=yi._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=v.Minimize(this.minimum,e),i=v.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=G.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=G.Vector3[0];return v.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),v.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,yi._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(!Ys.Intersects(this.boundingSphere,e.boundingSphere)||!os.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!(!oi(i.directions[0],i,s)||!oi(i.directions[1],i,s)||!oi(i.directions[2],i,s)||!oi(s.directions[0],i,s)||!oi(s.directions[1],i,s)||!oi(s.directions[2],i,s)||!oi(v.Cross(i.directions[0],s.directions[0]),i,s)||!oi(v.Cross(i.directions[0],s.directions[1]),i,s)||!oi(v.Cross(i.directions[0],s.directions[2]),i,s)||!oi(v.Cross(i.directions[1],s.directions[0]),i,s)||!oi(v.Cross(i.directions[1],s.directions[1]),i,s)||!oi(v.Cross(i.directions[1],s.directions[2]),i,s)||!oi(v.Cross(i.directions[2],s.directions[0]),i,s)||!oi(v.Cross(i.directions[2],s.directions[1]),i,s)||!oi(v.Cross(i.directions[2],s.directions[2]),i,s))}}yi._TmpVector3=kt.BuildArray(2,v.Zero);class jr{static extractMinAndMaxIndexed(e,t,i,s,n,r){for(let o=i;o!Array.isArray(a)&&!Array.isArray(e))],jr,"extractMinAndMaxIndexed",null);F([Os.filter((...[a])=>!Array.isArray(a))],jr,"extractMinAndMax",null);function nf(a,e,t,i,s=null){const n=new v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new v(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return jr.extractMinAndMaxIndexed(a,e,t,i,n,r),s&&(n.x-=n.x*s.x+s.y,n.y-=n.y*s.x+s.y,n.z-=n.z*s.x+s.y,r.x+=r.x*s.x+s.y,r.y+=r.y*s.x+s.y,r.z+=r.z*s.x+s.y),{minimum:n,maximum:r}}function Bl(a,e,t,i=null,s){const n=new v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new v(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),jr.extractMinAndMax(a,e,t,s,n,r),i&&(n.x-=n.x*i.x+i.y,n.y-=n.y*i.x+i.y,n.z-=n.z*i.x+i.y,r.x+=r.x*i.x+i.y,r.y+=r.y*i.x+i.y,r.z+=r.z*i.x+i.y),{minimum:n,maximum:r}}class Ii{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!=null?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Ns(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 n=this._drawWrapper;n.setEffect(e,t,s),i!==void 0&&(n.materialContext=i),e||(n.defines=null,n.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e);return}else for(const t of this._drawWrappers)t==null||t.dispose();this._drawWrappers=[]}static AddToMesh(e,t,i,s,n,r,o,l=!0){return new Ii(e,t,i,s,n,r,o,l)}constructor(e,t,i,s,n,r,o,l=!0,h=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=n,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=r,this._renderingMesh=o||r,h&&r.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=r.subMeshes.length-1,l&&(this.refreshBoundingInfo(),r.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.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(A.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=nf(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new yi(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=d)}return new Ii(e,o,l-o+1,t,i,s,n,r)}}class Tt{static get ForceFullSceneLoadingForIncremental(){return Tt._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Tt._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Tt._ShowLoadingScreen}static set ShowLoadingScreen(e){Tt._ShowLoadingScreen=e}static get loggingLevel(){return Tt._LoggingLevel}static set loggingLevel(e){Tt._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Tt._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Tt._CleanBoneMatrixWeights=e}}Tt._ForceFullSceneLoadingForIncremental=!1;Tt._ShowLoadingScreen=!0;Tt._CleanBoneMatrixWeights=!1;Tt._LoggingLevel=0;class si{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 si(si.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,n=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||Ie.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={}),n&&(this.applyToMesh(n),n.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,n=s.length;for(let r=0;r0){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 J;t.indices=[];const i=this.getIndices();if(i)for(let l=0;l0){const o=new Float32Array(e,r.positionsAttrDesc.offset,r.positionsAttrDesc.count);t.setVerticesData(A.PositionKind,o,!1)}if(r.normalsAttrDesc&&r.normalsAttrDesc.count>0){const o=new Float32Array(e,r.normalsAttrDesc.offset,r.normalsAttrDesc.count);t.setVerticesData(A.NormalKind,o,!1)}if(r.tangetsAttrDesc&&r.tangetsAttrDesc.count>0){const o=new Float32Array(e,r.tangetsAttrDesc.offset,r.tangetsAttrDesc.count);t.setVerticesData(A.TangentKind,o,!1)}if(r.uvsAttrDesc&&r.uvsAttrDesc.count>0){const o=new Float32Array(e,r.uvsAttrDesc.offset,r.uvsAttrDesc.count);if(Ne.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.uvs2AttrDesc.offset,r.uvs2AttrDesc.count);if(Ne.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.uvs3AttrDesc.offset,r.uvs3AttrDesc.count);if(Ne.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.uvs4AttrDesc.offset,r.uvs4AttrDesc.count);if(Ne.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.uvs5AttrDesc.offset,r.uvs5AttrDesc.count);if(Ne.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.uvs6AttrDesc.offset,r.uvs6AttrDesc.count);if(Ne.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.colorsAttrDesc.offset,r.colorsAttrDesc.count);t.setVerticesData(A.ColorKind,o,!1,r.colorsAttrDesc.stride)}if(r.matricesIndicesAttrDesc&&r.matricesIndicesAttrDesc.count>0){const o=new Int32Array(e,r.matricesIndicesAttrDesc.offset,r.matricesIndicesAttrDesc.count),l=[];for(let h=0;h>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(A.MatricesIndicesKind,l,!1)}if(r.matricesIndicesExtraAttrDesc&&r.matricesIndicesExtraAttrDesc.count>0){const o=new Int32Array(e,r.matricesIndicesExtraAttrDesc.offset,r.matricesIndicesExtraAttrDesc.count),l=[];for(let h=0;h>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(A.MatricesIndicesExtraKind,l,!1)}if(r.matricesWeightsAttrDesc&&r.matricesWeightsAttrDesc.count>0){const o=new Float32Array(e,r.matricesWeightsAttrDesc.offset,r.matricesWeightsAttrDesc.count);t.setVerticesData(A.MatricesWeightsKind,o,!1)}if(r.indicesAttrDesc&&r.indicesAttrDesc.count>0){const o=new Int32Array(e,r.indicesAttrDesc.offset,r.indicesAttrDesc.count);t.setIndices(o,null)}if(r.subMeshesAttrDesc&&r.subMeshesAttrDesc.count>0){const o=new Int32Array(e,r.subMeshesAttrDesc.offset,r.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l>8),r.push((l&16711680)>>16),r.push(l>>24&255)}t.setVerticesData(A.MatricesIndicesKind,r,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(A.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const r=[];for(let o=0;o>8),r.push((l&16711680)>>16),r.push(l>>24&255)}t.setVerticesData(A.MatricesIndicesExtraKind,r,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(si._CleanMatricesWeights(e,t),t.setVerticesData(A.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(A.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let r=0;r-1){const u=t.getScene().getLastSkeletonById(e.skeletonId);if(!u)return;s=u.bones.length}else return;const n=t.getVerticesData(A.MatricesIndicesKind),r=t.getVerticesData(A.MatricesIndicesExtraKind),o=e.matricesWeights,l=e.matricesWeightsExtra,h=e.numBoneInfluencer,c=o.length;for(let u=0;uh-1)&&(_=h-1),d>.001){const f=1/d;for(let g=0;g<4;g++)o[u+g]*=f;if(l)for(let g=0;g<4;g++)l[u+g]*=f}else _>=4?(l[u+_-4]=1-d,r[u+_-4]=s):(o[u+_]=1-d,n[u+_]=s)}t.setVerticesData(A.MatricesIndicesKind,n),e.matricesWeightsExtra&&t.setVerticesData(A.MatricesIndicesExtraKind,r)}static Parse(e,t,i){const s=new si(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,Ve&&Ve.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new yi(v.FromArray(e.boundingBoxMinimum),v.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(A.UVKind),e.hasUVs2&&s._delayInfo.push(A.UV2Kind),e.hasUVs3&&s._delayInfo.push(A.UV3Kind),e.hasUVs4&&s._delayInfo.push(A.UV4Kind),e.hasUVs5&&s._delayInfo.push(A.UV5Kind),e.hasUVs6&&s._delayInfo.push(A.UV6Kind),e.hasColors&&s._delayInfo.push(A.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(A.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(A.MatricesWeightsKind),s._delayLoadingFunction=J.ImportVertexData):J.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class rf{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new v(0,0,0),this._diffPositionForCollisions=new v(0,0,0),this._collisionResponse=!0}}class af{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=v.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class of{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new af,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 rf,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class ei extends be{static get BILLBOARDMODE_NONE(){return be.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return be.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return be.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return be.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return be.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return be.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._markSubMeshesAsMiscDirty()}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 of,this._waitingMaterialId=null,this.cullingStrategy=ei.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new ee,this.onCollisionPositionChangeObservable=new ee,this.onMaterialChangedObservable=new ee,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=he.Red(),this.outlineWidth=.02,this.overlayColor=he.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 v(.5,1,.5),this.ellipsoidOffset=new v(0,0,0),this.edgesWidth=1,this.edgesColor=new q(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 ee,this._onCollisionPositionChange=(i,s,n=null)=>{s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Y.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),n&&this.onCollideObservable.notifyObservers(n),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new oe(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case Wi.Aggressive:this.doNotSyncBoundingInfo=!0;case Wi.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!==be.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 yi(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(A.MatricesIndicesKind)&&this.isVerticesDataPresent(A.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===be.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 N;(this.rotationQuaternion?this.rotationQuaternion:ue.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const r=v.Zero(),o=this.definedFacingForward?-1:1;return v.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,s,r),r}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 v(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=Bl(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new yi(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i0){const u=h.getPositions();u&&(i[o]+=(u[o]-i[o])*c)}}if(n++,s===A.PositionKind&&this._positions&&n===3){n=0;const l=r*3;this._positions[r++].copyFromFloats(i[l],i[l+1],i[l+2])}}}if(i&&e&&this.skeleton){const n=this.getVerticesData(A.MatricesIndicesKind),r=this.getVerticesData(A.MatricesWeightsKind);if(r&&n){const o=this.numBoneInfluencers>4,l=o?this.getVerticesData(A.MatricesIndicesExtraKind):null,h=o?this.getVerticesData(A.MatricesWeightsExtraKind):null,c=this.skeleton.getTransformMatrices(this),u=G.Vector3[0],d=G.Matrix[0],_=G.Matrix[1];let f=0;for(let g=0;g0&&(N.FromFloat32ArrayToRefScaled(c,Math.floor(n[f+p]*16),x,_),d.addToSelf(_));if(o)for(p=0;p<4;p++)x=h[f+p],x>0&&(N.FromFloat32ArrayToRefScaled(c,Math.floor(l[f+p]*16),x,_),d.addToSelf(_));s===A.NormalKind?v.TransformNormalFromFloatsToRef(i[g],i[g+1],i[g+2],d,u):v.TransformCoordinatesFromFloatsToRef(i[g],i[g+1],i[g+2],d,u),u.toArray(i,g),s===A.PositionKind&&this._positions&&this._positions[g/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,A.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,A.PositionKind)}_getPositionData(e,t){var i;let s=this.getVerticesData(A.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 n=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(n.length);for(let r=0;r1||!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(),n=e.getBoundingInfo();if(s.intersects(n,t))return!0;if(i){for(const r of this.getChildMeshes())if(r.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 n=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let o=n;o1&&!r._checkCollision(e)||this._collideForSubMesh(r,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=G.Matrix[0],i=G.Matrix[1];return N.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,n,r=!1){const o=new cs,l=this.getClassName()==="InstancedLinesMesh"||this.getClassName()==="LinesMesh"?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes||!r&&(!e.intersectsSphere(h.boundingSphere,l)||!e.intersectsBox(h.boundingBox,l)))return o;if(s)return o.hit=!r,o.pickedMesh=r?null:this,o.distance=r?0:v.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let _=!1;for(let f=0;f1&&!g.canIntersects(e))continue;const p=g.intersects(e,this._positions,this.getIndices(),t,i);if(p&&(t||!c||p.distance{let o=r.includedOnlyMeshes.indexOf(this);o!==-1&&r.includedOnlyMeshes.splice(o,1),o=r.excludedMeshes.indexOf(this),o!==-1&&r.excludedMeshes.splice(o,1);const l=r.getShadowGenerators();if(l){const h=l.values();for(let c=h.next();c.done!==!0;c=h.next()){const d=c.value.getShadowMap();d&&d.renderList&&(o=d.renderList.indexOf(this),o!==-1&&d.renderList.splice(o,1))}}}),(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes();const n=this.getScene().getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),this.getScene().removeMesh(this),this._parentContainer){const r=this._parentContainer.meshes.indexOf(this);r>-1&&this._parentContainer.meshes.splice(r,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:v.Zero()}e.depthSortedFacets=[];for(let o=0;oGe?n.maximum.x-n.minimum.x:Ge,e.bbSize.y=n.maximum.y-n.minimum.y>Ge?n.maximum.y-n.minimum.y:Ge,e.bbSize.z=n.maximum.z-n.minimum.z>Ge?n.maximum.z-n.minimum.z:Ge;let r=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(r=r>e.bbSize.z?r:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/r),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/r),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/r),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=n,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),v.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&J.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;ln.subDiv.max||o<0||o>n.subDiv.max||l<0||l>n.subDiv.max?null:n.facetPartitioning[r+n.subDiv.max*o+n.subDiv.max*n.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,s,n=!1,r=!0){const o=this.getWorldMatrix(),l=G.Matrix[5];o.invertToRef(l);const h=G.Vector3[8];v.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);const c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,s,n,r);return s&&v.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),c}getClosestFacetAtLocalCoordinates(e,t,i,s,n=!1,r=!0){let o=null,l=0,h=0,c=0,u=0,d=0,_=0,f=0,g=0;const p=this.getFacetLocalPositions(),x=this.getFacetLocalNormals(),m=this.getFacetsAtLocalCoordinates(e,t,i);if(!m)return null;let T=Number.MAX_VALUE,S=T,b,y,E;for(let P=0;P=0||n&&!r&&u<=0)&&(u=y.x*E.x+y.y*E.y+y.z*E.z,d=-(y.x*e+y.y*t+y.z*i-u)/(y.x*y.x+y.y*y.y+y.z*y.z),_=e+y.x*d,f=t+y.y*d,g=i+y.z*d,l=_-e,h=f-t,c=g-i,S=l*l+h*h+c*c,Se.emitter===this)}}ei.OCCLUSION_TYPE_NONE=0;ei.OCCLUSION_TYPE_OPTIMISTIC=1;ei.OCCLUSION_TYPE_STRICT=2;ei.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;ei.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;ei.CULLINGSTRATEGY_STANDARD=0;ei.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;ei.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;ei.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;Vt("BABYLON.AbstractMesh",ei);function S0(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 Nl(a,e,t){var i,s,n,r,o,l;const h=!!((i=a.clipPlane)!==null&&i!==void 0?i:e.clipPlane),c=!!((s=a.clipPlane2)!==null&&s!==void 0?s:e.clipPlane2),u=!!((n=a.clipPlane3)!==null&&n!==void 0?n:e.clipPlane3),d=!!((r=a.clipPlane4)!==null&&r!==void 0?r:e.clipPlane4),_=!!((o=a.clipPlane5)!==null&&o!==void 0?o:e.clipPlane5),f=!!((l=a.clipPlane6)!==null&&l!==void 0?l:e.clipPlane6);h&&t.push("#define CLIPPLANE"),c&&t.push("#define CLIPPLANE2"),u&&t.push("#define CLIPPLANE3"),d&&t.push("#define CLIPPLANE4"),_&&t.push("#define CLIPPLANE5"),f&&t.push("#define CLIPPLANE6")}function lf(a,e,t){var i,s,n,r,o,l;let h=!1;const c=!!((i=a.clipPlane)!==null&&i!==void 0?i:e.clipPlane),u=!!((s=a.clipPlane2)!==null&&s!==void 0?s:e.clipPlane2),d=!!((n=a.clipPlane3)!==null&&n!==void 0?n:e.clipPlane3),_=!!((r=a.clipPlane4)!==null&&r!==void 0?r:e.clipPlane4),f=!!((o=a.clipPlane5)!==null&&o!==void 0?o:e.clipPlane5),g=!!((l=a.clipPlane6)!==null&&l!==void 0?l:e.clipPlane6);return t.CLIPPLANE!==c&&(t.CLIPPLANE=c,h=!0),t.CLIPPLANE2!==u&&(t.CLIPPLANE2=u,h=!0),t.CLIPPLANE3!==d&&(t.CLIPPLANE3=d,h=!0),t.CLIPPLANE4!==_&&(t.CLIPPLANE4=_,h=!0),t.CLIPPLANE5!==f&&(t.CLIPPLANE5=f,h=!0),t.CLIPPLANE6!==g&&(t.CLIPPLANE6=g,h=!0),h}function A0(a,e,t){var i,s,n,r,o,l;let h=(i=e.clipPlane)!==null&&i!==void 0?i:t.clipPlane;nn(a,"vClipPlane",h),h=(s=e.clipPlane2)!==null&&s!==void 0?s:t.clipPlane2,nn(a,"vClipPlane2",h),h=(n=e.clipPlane3)!==null&&n!==void 0?n:t.clipPlane3,nn(a,"vClipPlane3",h),h=(r=e.clipPlane4)!==null&&r!==void 0?r:t.clipPlane4,nn(a,"vClipPlane4",h),h=(o=e.clipPlane5)!==null&&o!==void 0?o:t.clipPlane5,nn(a,"vClipPlane5",h),h=(l=e.clipPlane6)!==null&&l!==void 0?l:t.clipPlane6,nn(a,"vClipPlane6",h)}function nn(a,e,t){t&&a.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}class we{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!==Me.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,s,n,r,o){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=s,o.FOG=n&&this.GetFogState(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=r)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){const s=t.CAMERA_ORTHOGRAPHIC?1:0,n=t.CAMERA_PERSPECTIVE?1:0,r=e.activeCamera.mode===de.ORTHOGRAPHIC_CAMERA?1:0,o=e.activeCamera.mode===de.PERSPECTIVE_CAMERA?1:0;(s^r||n^o)&&(t.CAMERA_ORTHOGRAPHIC=r===1,t.CAMERA_PERSPECTIVE=o===1,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,s,n,r=null,o=!1){let l=we.PrepareDefinesForCamera(e,s);r!==!1&&(l=lf(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,l=!0),s.INSTANCES!==n&&(s.INSTANCES=n,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 n=s.excludedSkinnedMesh.indexOf(e)===-1;t.BONES_VELOCITY_ENABLED=n}}}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,n=!1,r=!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(A.NormalKind),t._needNormals&&e.isVerticesDataPresent(A.TangentKind)&&(t.TANGENT=!0);for(let l=1;l<=6;++l)t["UV"+l]=t._needUVs?e.isVerticesDataPresent("uv".concat(l===1?"":l)):!1;if(i){const l=e.useVertexColors&&e.isVerticesDataPresent(A.ColorKind);t.VERTEXCOLOR=l,t.VERTEXALPHA=e.hasVertexAlpha&&l&&r}return e.isVerticesDataPresent(A.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&this.PrepareDefinesForBones(e,t),n&&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,n=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||n!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const n=[{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;for(let r=0;r0&&(o.shadowEnabled=!0,h.prepareDefines(n,s))}}i.lightmapMode!=Ke.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,n["LIGHTMAPEXCLUDED"+s]=!0,n["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==Ke.LIGHTMAP_SHADOWSONLY):(n["LIGHTMAPEXCLUDED"+s]=!1,n["LIGHTMAPNOSPECULAR"+s]=!1)}static PrepareDefinesForLights(e,t,i,s,n=4,r=!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&&!r){for(const c of t.lightSources)if(this.PrepareDefinesForLight(e,t,c,o,i,s,l),o++,o===n)break}i.SPECULARTERM=l.specularEnabled,i.SHADOWS=l.shadowEnabled;for(let c=o;c0&&(n=s+r,t.addFallback(n,"LIGHT"+r)),e.SHADOWS||(e["SHADOW"+r]&&t.addFallback(s,"SHADOW"+r),e["SHADOWPCF"+r]&&t.addFallback(s,"SHADOWPCF"+r),e["SHADOWPCSS"+r]&&t.addFallback(s,"SHADOWPCSS"+r),e["SHADOWPOISSON"+r]&&t.addFallback(s,"SHADOWPOISSON"+r),e["SHADOWESM"+r]&&t.addFallback(s,"SHADOWESM"+r),e["SHADOWCLOSEESM"+r]&&t.addFallback(s,"SHADOWCLOSEESM"+r));return n++}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&&Ie.LastCreatedEngine){const n=Ie.LastCreatedEngine.getCaps().maxVertexAttribs,r=t.morphTargetManager;if(r!=null&&r.isUsingTextureForTargets)return;const o=r&&r.supportsNormals&&i.NORMAL,l=r&&r.supportsTangents&&i.TANGENT,h=r&&r.supportsUVs&&i.UV1;for(let c=0;cn&&H.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(A.MatricesIndicesKind),e.push(A.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(A.MatricesIndicesExtraKind),e.push(A.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(A.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,n,r=!0){e._bindLight(t,i,s,n,r)}static BindLights(e,t,i,s,n=4){const r=Math.min(t.lightSources.length,n);for(let o=0;o-1){const n=s.getTransformMatrixTexture(e);t.setTexture("boneSampler",n),t.setFloat("boneTextureWidth",4*(s.bones.length+1))}else{const n=s.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),we._CopyBonesTransformationMatrices(n,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===de.ORTHOGRAPHIC_CAMERA&&H.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(s.maxZ+1)/Math.LN2))}}}we._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0};we._TempFogColor=he.Black();class gs{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){Se.Clone(()=>e,this)}serialize(){return Se.Serialize(this)}parse(e,t,i){Se.Parse(()=>this,e,t,i)}}F([B()],gs.prototype,"func",null);F([B()],gs.prototype,"funcRef",null);F([B()],gs.prototype,"funcMask",null);F([B()],gs.prototype,"opStencilFail",null);F([B()],gs.prototype,"opDepthFail",null);F([B()],gs.prototype,"opStencilDepthPass",null);F([B()],gs.prototype,"mask",null);F([B()],gs.prototype,"enabled",null);var Zt;(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"})(Zt||(Zt={}));class j{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(j.MiscDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(j.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(j.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 ee),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 ee),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new ee),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(j.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(j.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case j.WireFrameFillMode:case j.LineListDrawMode:case j.LineLoopDrawMode:case j.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?j.WireFrameFillMode:j.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case j.PointFillMode:case j.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?j.PointFillMode:j.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(j.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 ee,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 gs,this._useUBO=!1,this._fillMode=j.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||Ie.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||re.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Ns(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=j.ClockWiseSideOrientation:this.sideOrientation=j.CounterClockWiseSideOrientation,this._uniformBuffer=new oe(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),j.OnEventObservable.notifyObservers(this,Zt.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===j.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===j.MATERIAL_OPAQUE||this._transparencyMode===j.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(j.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),n=(t==null?this.sideOrientation:t)===j.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,n,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),n}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(Zt.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,we.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(Zt.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Zt.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Zt.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}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 n={clipPlane:!1,useInstances:!1,...i},r=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const l=()=>{if(!this._scene||!this._scene.getEngine())return;const h=r.clipPlane;if(n.clipPlane&&(r.clipPlane=new ni(0,0,0,1)),this._storeEffectOnSubMeshes){let c=!0,u=null;if(e.subMeshes){const d=new Ii(0,0,0,0,0,e,void 0,!1,!1);d.materialDefines&&(d.materialDefines._renderId=-1),this.isReadyForSubMesh(e,d,n.useInstances)||(d.effect&&d.effect.getCompilationError()&&d.effect.allFallbacksProcessed()?u=d.effect.getCompilationError():(c=!1,setTimeout(l,16)))}c&&(this.allowShaderHotSwapping=o,u&&s&&s(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(l,16);n.clipPlane&&(r.clipPlane=h)};l()}forceCompilationAsync(e,t){return new Promise((i,s)=>{this.forceCompilation(e,()=>{i()},t,n=>{s(n)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(j._DirtyCallbackArray.length=0,e&j.TextureDirtyFlag&&j._DirtyCallbackArray.push(j._TextureDirtyCallBack),e&j.LightDirtyFlag&&j._DirtyCallbackArray.push(j._LightsDirtyCallBack),e&j.FresnelDirtyFlag&&j._DirtyCallbackArray.push(j._FresnelDirtyCallBack),e&j.AttributesDirtyFlag&&j._DirtyCallbackArray.push(j._AttributeDirtyCallBack),e&j.MiscDirtyFlag&&j._DirtyCallbackArray.push(j._MiscDirtyCallBack),e&j.PrePassDirtyFlag&&j._DirtyCallbackArray.push(j._PrePassDirtyCallBack),j._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(j._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 n of s._drawWrappers)!n||!n.defines||!n.defines.markAllAsDirty||this._materialContext===n.materialContext&&e(n.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(j._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(j._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(j._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(j._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(j._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(j._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(j._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(j._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(j._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(j._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==Wi.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(Zt.Disposed,this._eventInfo),this._parentContainer){const n=this._parentContainer.materials.indexOf(this);n>-1&&this._parentContainer.materials.splice(n,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(const n in this.meshMap){const r=this.meshMap[n];r&&(r.material=null,this.releaseVertexArrayObject(r,e))}else{const n=s.meshes;for(const r of n)r.material===this&&!r.sourceMesh&&(r.material=null,this.releaseVertexArrayObject(r,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=Se.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,e}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 H.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const n=re.Instantiate(e.customType).Parse(e,t,i);return n._loadedUniqueId=e.uniqueId,n}}j.TriangleFillMode=0;j.WireFrameFillMode=1;j.PointFillMode=2;j.PointListDrawMode=3;j.LineListDrawMode=4;j.LineLoopDrawMode=5;j.LineStripDrawMode=6;j.TriangleStripDrawMode=7;j.TriangleFanDrawMode=8;j.ClockWiseSideOrientation=0;j.CounterClockWiseSideOrientation=1;j.TextureDirtyFlag=1;j.LightDirtyFlag=2;j.FresnelDirtyFlag=4;j.AttributesDirtyFlag=8;j.MiscDirtyFlag=16;j.PrePassDirtyFlag=32;j.AllDirtyFlag=63;j.MATERIAL_OPAQUE=0;j.MATERIAL_ALPHATEST=1;j.MATERIAL_ALPHABLEND=2;j.MATERIAL_ALPHATESTANDBLEND=3;j.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;j.MATERIAL_NORMALBLENDMETHOD_RNM=1;j.OnEventObservable=new ee;Ie.OnEnginesDisposedObservable.addOnce(()=>{j.OnEventObservable.clear()});j._AllDirtyCallBack=a=>a.markAllAsDirty();j._ImageProcessingDirtyCallBack=a=>a.markAsImageProcessingDirty();j._TextureDirtyCallBack=a=>a.markAsTexturesDirty();j._FresnelDirtyCallBack=a=>a.markAsFresnelDirty();j._MiscDirtyCallBack=a=>a.markAsMiscDirty();j._PrePassDirtyCallBack=a=>a.markAsPrePassDirty();j._LightsDirtyCallBack=a=>a.markAsLightDirty();j._AttributeDirtyCallBack=a=>a.markAsAttributesDirty();j._FresnelAndMiscDirtyCallBack=a=>{j._FresnelDirtyCallBack(a),j._MiscDirtyCallBack(a)};j._TextureAndMiscDirtyCallBack=a=>{j._TextureDirtyCallBack(a),j._MiscDirtyCallBack(a)};j._DirtyCallbackArray=[];j._RunDirtyCallBacks=a=>{for(const e of j._DirtyCallbackArray)e(a)};F([B()],j.prototype,"id",void 0);F([B()],j.prototype,"uniqueId",void 0);F([B()],j.prototype,"name",void 0);F([B()],j.prototype,"metadata",void 0);F([B()],j.prototype,"checkReadyOnEveryCall",void 0);F([B()],j.prototype,"checkReadyOnlyOnce",void 0);F([B()],j.prototype,"state",void 0);F([B("alpha")],j.prototype,"_alpha",void 0);F([B("backFaceCulling")],j.prototype,"_backFaceCulling",void 0);F([B("cullBackFaces")],j.prototype,"_cullBackFaces",void 0);F([B()],j.prototype,"sideOrientation",void 0);F([B("alphaMode")],j.prototype,"_alphaMode",void 0);F([B()],j.prototype,"_needDepthPrePass",void 0);F([B()],j.prototype,"disableDepthWrite",void 0);F([B()],j.prototype,"disableColorWrite",void 0);F([B()],j.prototype,"forceDepthWrite",void 0);F([B()],j.prototype,"depthFunction",void 0);F([B()],j.prototype,"separateCullingPass",void 0);F([B("fogEnabled")],j.prototype,"_fogEnabled",void 0);F([B()],j.prototype,"pointSize",void 0);F([B()],j.prototype,"zOffset",void 0);F([B()],j.prototype,"zOffsetUnits",void 0);F([B()],j.prototype,"pointsCloud",null);F([B()],j.prototype,"fillMode",null);F([B()],j.prototype,"transparencyMode",null);class xn extends j{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().multiMaterials.push(this),this.subMaterials=new Array,this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...s)=>{const n=t.apply(e,s);return this._markAllSubMeshesAsTexturesDirty(),n};const i=e.splice;e.splice=(s,n)=>{const r=i.apply(e,[s,n]);return this._markAllSubMeshesAsTexturesDirty(),r}}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(n,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new xn(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Ve&&Ve.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(s=>i.subMaterials.push(t.getLastMaterialById(s))),i}}Vt("BABYLON.MultiMaterial",xn);class hf{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class Ul{}class cf{constructor(){this.visibleInstances={},this.batchCache=new Po,this.batchCacheReplacementModeInFrozenMode=new Po,this.instancesBufferSize=32*16*4}}class Po{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array,this.hardwareInstancedRendering=new Array}}class uf{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class df{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 O extends ei{static _GetDefaultSideOrientation(e){return e||O.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(A.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(A.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 ee),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new ee),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new ee),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new ee),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new ee),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,n,r=!0){if(super(e,t),this._internalMeshDataInfo=new df,this.delayLoadState=0,this.instances=new Array,this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new cf,this._thinInstanceDataStorage=new uf,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=O.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(o,l,h)=>{o&&h&&(this._uniformBuffer?this.transferToEffect(l):h.bindOnlyWorldMatrix(l))},s){if(s._geometry&&s._geometry.applyToMesh(this),a0.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"],["_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,Ve&&Ve.HasTags(s)&&Ve.AddTagsTo(this,Ve.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,!n){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 ee(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 n of this.getChildTransformNodes(!0))n.getClassName()==="InstancedMesh"&&s.getClassName()==="Mesh"&&n.sourceMesh===this?n.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):n.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 H.Warn("You cannot use a mesh as LOD level twice"),this;const i=new hf(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*r)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this),this;for(let l=0;l0||this.hasThinInstances);this.computeWorldMatrix();const d=this.material||c.defaultMaterial;if(d){if(d._storeEffectOnSubMeshes)for(const f of this.subMeshes){const g=f.getMaterial();if(g){if(g._storeEffectOnSubMeshes){if(!g.isReadyForSubMesh(this,f,u))return!1}else if(!g.isReady(this,u))return!1}}else if(!d.isReady(this,u))return!1}const _=h.currentRenderPassId;for(const f of this.lightSources){const g=f.getShadowGenerators();if(!g)continue;const p=g.values();for(let x=p.next();x.done!==!0;x=p.next()){const m=x.value;if(m&&(!(!((i=m.getShadowMap())===null||i===void 0)&&i.renderList)||!((s=m.getShadowMap())===null||s===void 0)&&s.renderList&&((r=(n=m.getShadowMap())===null||n===void 0?void 0:n.renderList)===null||r===void 0?void 0:r.indexOf(this))!==-1)){m.getShadowMap()&&(h.currentRenderPassId=m.getShadowMap().renderPassId);for(const T of this.subMeshes)if(!m.isReady(T,u,(l=(o=T.getMaterial())===null||o===void 0?void 0:o.needAlphaBlendingForMesh(this))!==null&&l!==void 0?l:!1))return h.currentRenderPassId=_,!1;h.currentRenderPassId=_}}}for(const f of this._internalMeshDataInfo._LODLevels)if(f.mesh&&!f.mesh.isReady(u))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_preActivate(){const e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t?this:(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null,this)}_preActivateForIntermediateRendering(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(this._instanceDataStorage.previousRenderId!==void 0&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=t,this._instanceDataStorage.visibleInstances[t]=new Array),this._instanceDataStorage.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getPositionData(e,t),i),this}_createGlobalSubMesh(e){const t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){const i=this.getIndices();if(!i)return null;const s=i.length;let n=!1;if(e)n=!0;else for(const r of this.subMeshes){if(r.indexStart+r.indexCount>s){n=!0;break}if(r.verticesStart+r.verticesCount>t){n=!0;break}}if(!n)return this.subMeshes[0]}return this.releaseSubMeshes(),new Ii(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 n=0;n=t);n++)Ii.CreateFromIndices(0,s,n===e-1?t-s:i,this),s+=i;this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const n=new J;n.set(t,e);const r=this.getScene();new si(si.RandomId(),r,n,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=si.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(A.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(A.PositionKind,i,!1,!1),t){const s=this.getIndices(),n=this.getVerticesData(A.NormalKind);if(!n)return this;J.ComputeNormals(i,s,n),this.updateVerticesData(A.NormalKind,n,!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(si.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 J;s.indices=e;const n=this.getScene();new si(si.RandomId(),n,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 n=this.getScene().getEngine();this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t);let r;if(this._unIndexed)r=null;else switch(this._getRenderingFillMode(i)){case j.PointFillMode:r=null;break;case j.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),n);break;default:case j.TriangleFillMode:r=this._geometry.getIndexBuffer();break}return!s||!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,r):this._geometry._bind(t,r,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 n=this.getScene().getEngine();return this._unIndexed||t==j.PointFillMode?n.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==j.WireFrameFillMode?n.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):n.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(),n=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,r=this._instanceDataStorage.batchCache;if(r.mustReturn=!1,r.renderSelf[e]=t||!n&&this.isEnabled()&&this.isVisible,r.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const o=this._instanceDataStorage.visibleInstances,l=i.getRenderId(),h=s?o.intermediateDefaultRenderId:o.defaultRenderId;r.visibleInstances[e]=o[l],!r.visibleInstances[e]&&h&&(r.visibleInstances[e]=o[h])}return r.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&r.visibleInstances[e]!==null&&r.visibleInstances[e]!==void 0,this._instanceDataStorage.previousBatch=r,r}_renderWithInstances(e,t,i,s,n){var r;const o=i.visibleInstances[e._id],l=o?o.length:0,h=this._instanceDataStorage,c=h.instancesBufferSize;let u=h.instancesBuffer,d=h.instancesPreviousBuffer;const f=(l+1)*16*4;for(;h.instancesBufferSizeb._distanceToCamera>y._distanceToCamera?-1:b._distanceToCamerax&&s++,b!==0&&T++,m+=b,x=b}if(h[T]++,T>r&&(r=T),m===0)n++;else{const S=1/m;let b=0;for(let y=0;yc&&o++}}const u=this.skeleton.bones.length,d=this.getVerticesData(A.MatricesIndicesKind),_=this.getVerticesData(A.MatricesIndicesExtraKind);let f=0;for(let p=0;p=u||m<0)&&f++}const g="Number of Weights = "+i/4+"\nMaximum influences = "+r+"\nMissing Weights = "+n+"\nNot Sorted = "+s+"\nNot Normalized = "+o+"\nWeightCounts = ["+h+"]\nNumber of bones = "+u+"\nBad Bone Indices = "+f;return{skinned:!0,valid:n===0&&o===0&&f===0,report:g}}_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 re.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(A.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(A.PositionKind);const s=v.Zero();let n;for(n=0;n{const u=c.width,d=c.height,f=this.getEngine().createCanvas(u,d).getContext("2d");f.drawImage(c,0,0);const g=f.getImageData(0,0,u,d).data;this.applyDisplacementMapFromBuffer(g,u,d,t,i,n,r,o),s&&s(this)};return re.LoadImage(e,h,()=>{},l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,n,r,o,l=!1){if(!this.isVerticesDataPresent(A.PositionKind)||!this.isVerticesDataPresent(A.NormalKind)||!this.isVerticesDataPresent(A.UVKind))return H.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const h=this.getVerticesData(A.PositionKind,!0,!0),c=this.getVerticesData(A.NormalKind),u=this.getVerticesData(A.UVKind);let d=v.Zero();const _=v.Zero(),f=fe.Zero();r=r||fe.Zero(),o=o||new fe(1,1);for(let g=0;g{const o=s.length-1-r,l=s[o];for(let h=0;h{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 n=0;n4,h=l?this.getVerticesData(A.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(A.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),d=v.Zero(),_=new N,f=new N;let g=0,p;for(let x=0;x0&&(N.FromFloat32ArrayToRefScaled(u,Math.floor(r[g+p]*16),m,f),_.addToSelf(f));if(l)for(p=0;p<4;p++)m=c[g+p],m>0&&(N.FromFloat32ArrayToRefScaled(u,Math.floor(h[g+p]*16),m,f),_.addToSelf(f));v.TransformCoordinatesFromFloatsToRef(i._sourcePositions[x],i._sourcePositions[x+1],i._sourcePositions[x+2],_,d),d.toArray(s,x),t&&(v.TransformNormalFromFloatsToRef(i._sourceNormals[x],i._sourceNormals[x+1],i._sourceNormals[x+2],_,d),d.toArray(n,x)),_.reset()}return this.updateVerticesData(A.PositionKind,s),t&&this.updateVerticesData(A.NormalKind,n),this}static MinMax(e){let t=null,i=null;return e.forEach(function(s){const r=s.getBoundingInfo().boundingBox;!t||!i?(t=r.minimumWorld,i=r.maximumWorld):(t.minimizeInPlace(r.minimumWorld),i.maximizeInPlace(r.maximumWorld))}),!t||!i?{min:v.Zero(),max:v.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?O.MinMax(e):e;return v.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,n,r){return T0(O._MergeMeshesCoroutine(e,t,i,s,n,r,!1))}static MergeMeshesAsync(e,t=!0,i,s,n,r){return tf(O._MergeMeshesCoroutine(e,t,i,s,n,r,!0),ef())}static*_MergeMeshesCoroutine(e,t=!0,i,s,n,r,o){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let E=0;for(l=0;l=65536)return H.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}r&&(n=!1);const h=new Array,c=new Array,u=new Array,d=e[0].overrideMaterialSideOrientation;for(l=0;l{const P=E.computeWorldMatrix(!0);return{vertexData:J.ExtractFromMesh(E,!1,!1),transform:P}},{vertexData:g,transform:p}=f(_);o&&(yield);const x=new Array(e.length-1);for(let E=1;E{throw Ae("GroundMesh")};O._GoldbergMeshParser=(a,e)=>{throw Ae("GoldbergMesh")};O._LinesMeshParser=(a,e)=>{throw Ae("LinesMesh")};Vt("BABYLON.Mesh",O);O.prototype.setMaterialByID=function(a){return this.setMaterialById(a)};O.CreateDisc=O.CreateDisc||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateBox=O.CreateBox||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateSphere=O.CreateSphere||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateCylinder=O.CreateCylinder||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateTorusKnot=O.CreateTorusKnot||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateTorus=O.CreateTorus||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreatePlane=O.CreatePlane||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateGround=O.CreateGround||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateTiledGround=O.CreateTiledGround||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateGroundFromHeightMap=O.CreateGroundFromHeightMap||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateTube=O.CreateTube||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreatePolyhedron=O.CreatePolyhedron||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateIcoSphere=O.CreateIcoSphere||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateDecal=O.CreateDecal||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.CreateCapsule=O.CreateCapsule||(()=>{throw new Error("Import MeshBuilder to populate this function")});O.ExtendToGoldberg=O.ExtendToGoldberg||(()=>{throw new Error("Import MeshBuilder to populate this function")});class ff{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===Re.POINTERDOWN){this._isPointerDown=!0;return}i.type===Re.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=Pi.Now;let s=0;this._lastFrameTime!=null&&(s=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();const n=i-this._lastInteractionTime-this._idleRotationWaitTime,r=Math.max(Math.min(n/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*r,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!=null?e:Pi.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha)=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}}Hi.EASINGMODE_EASEIN=0;Hi.EASINGMODE_EASEOUT=1;Hi.EASINGMODE_EASEINOUT=2;class _f extends Hi{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 pf extends Hi{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)}}var Ga;(function(a){a[a.NONE=0]="NONE",a[a.STEP=1]="STEP"})(Ga||(Ga={}));class $r{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new $r(this.name,this.from,this.to)}}class ne{static _PrepareAnimation(e,t,i,s,n,r,o,l){let h;if(!isNaN(parseFloat(n))&&isFinite(n)?h=ne.ANIMATIONTYPE_FLOAT:n instanceof ue?h=ne.ANIMATIONTYPE_QUATERNION:n instanceof v?h=ne.ANIMATIONTYPE_VECTOR3:n instanceof fe?h=ne.ANIMATIONTYPE_VECTOR2:n instanceof he?h=ne.ANIMATIONTYPE_COLOR3:n instanceof q?h=ne.ANIMATIONTYPE_COLOR4:n instanceof Ui&&(h=ne.ANIMATIONTYPE_SIZE),h==null)return null;const c=new ne(e,t,i,h,o),u=[{frame:0,value:n},{frame:s,value:r}];return c.setKeys(u),l!==void 0&&c.setEasingFunction(l),c}static CreateAnimation(e,t,i,s){const n=new ne(e+"Animation",e,i,t,ne.ANIMATIONLOOPMODE_CONSTANT);return n.setEasingFunction(s),n}static CreateAndStartAnimation(e,t,i,s,n,r,o,l,h,c,u){const d=ne._PrepareAnimation(e,i,s,n,r,o,l,h);return!d||(t.getScene&&(u=t.getScene()),!u)?null:u.beginDirectAnimation(t,[d],0,n,d.loopMode===1,1,c)}static CreateAndStartHierarchyAnimation(e,t,i,s,n,r,o,l,h,c,u){const d=ne._PrepareAnimation(e,s,n,r,o,l,h,c);return d?t.getScene().beginDirectHierarchyAnimation(t,i,[d],0,r,d.loopMode===1,1,u):null}static CreateMergeAndStartAnimation(e,t,i,s,n,r,o,l,h,c){const u=ne._PrepareAnimation(e,i,s,n,r,o,l,h);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,n,u.loopMode===1,1,c)):null}static MakeAnimationAdditive(e,t=0,i,s=!1,n){let r=e;if(s&&(r=e.clone(),r.name=n||r.name),!r._keys.length)return r;t=t>=0?t:0;let o=0;const l=r._keys[0];let h=r._keys.length-1;const c=r._keys[h],u={referenceValue:l.value,referencePosition:G.Vector3[0],referenceQuaternion:G.Quaternion[0],referenceScaling:G.Vector3[1],keyPosition:G.Vector3[2],keyQuaternion:G.Quaternion[1],keyScaling:G.Vector3[3]};let d=!1,_=l.frame,f=c.frame;if(i){const m=r.getRange(i);m&&(_=m.from,f=m.to)}let g=l.frame===_,p=c.frame===f;if(r._keys.length===1){const m=r._getKeyValue(r._keys[0]);u.referenceValue=m.clone?m.clone():m,d=!0}else if(t<=l.frame){const m=r._getKeyValue(l.value);u.referenceValue=m.clone?m.clone():m,d=!0}else if(t>=c.frame){const m=r._getKeyValue(c.value);u.referenceValue=m.clone?m.clone():m,d=!0}let x=0;for(;!d||!g||!p&&x=m.frame&&t<=T.frame){let S;if(t===m.frame)S=r._getKeyValue(m.value);else if(t===T.frame)S=r._getKeyValue(T.value);else{const b={key:x,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};S=r._interpolate(t,b)}u.referenceValue=S.clone?S.clone():S,d=!0}if(!g&&_>=m.frame&&_<=T.frame){if(_===m.frame)o=x;else if(_===T.frame)o=x+1;else{const S={key:x,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},b=r._interpolate(_,S),y={frame:_,value:b.clone?b.clone():b};r._keys.splice(x+1,0,y),o=x+1}g=!0}if(!p&&f>=m.frame&&f<=T.frame){if(f===m.frame)h=x;else if(f===T.frame)h=x+1;else{const S={key:x,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},b=r._interpolate(f,S),y={frame:f,value:b.clone?b.clone():b};r._keys.splice(x+1,0,y),h=x+1}p=!0}x++}for(r.dataType===ne.ANIMATIONTYPE_QUATERNION?u.referenceValue.normalize().conjugateInPlace():r.dataType===ne.ANIMATIONTYPE_MATRIX&&(u.referenceValue.decompose(u.referenceScaling,u.referenceQuaternion,u.referencePosition),u.referenceQuaternion.normalize().conjugateInPlace()),x=o;x<=h;x++){const m=r._keys[x];if(!(x&&r.dataType!==ne.ANIMATIONTYPE_FLOAT&&m.value===l.value))switch(r.dataType){case ne.ANIMATIONTYPE_MATRIX:m.value.decompose(u.keyScaling,u.keyQuaternion,u.keyPosition),u.keyPosition.subtractInPlace(u.referencePosition),u.keyScaling.divideInPlace(u.referenceScaling),u.referenceQuaternion.multiplyToRef(u.keyQuaternion,u.keyQuaternion),N.ComposeToRef(u.keyScaling,u.keyQuaternion,u.keyPosition,m.value);break;case ne.ANIMATIONTYPE_QUATERNION:u.referenceValue.multiplyToRef(m.value,m.value);break;case ne.ANIMATIONTYPE_VECTOR2:case ne.ANIMATIONTYPE_VECTOR3:case ne.ANIMATIONTYPE_COLOR3:case ne.ANIMATIONTYPE_COLOR4:m.value.subtractToRef(u.referenceValue,m.value);break;case ne.ANIMATIONTYPE_SIZE:m.value.width-=u.referenceValue.width,m.value.height-=u.referenceValue.height;break;default:m.value-=u.referenceValue}}return r}static TransitionTo(e,t,i,s,n,r,o,l=null){if(o<=0)return i[e]=t,l&&l(),null;const h=n*(o/1e3);r.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:h,value:t}]),i.animations||(i.animations=[]),i.animations.push(r);const c=s.beginAnimation(i,0,h,!1);return c.onAnimationEnd=l,c}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,n,r){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=n,this.enableBlending=r,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=n===void 0?ne.ANIMATIONLOOPMODE_CYCLE:n,this.uniqueId=ne._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;r--)this._keys[r].frame>=s&&this._keys[r].frame<=n&&this._keys.splice(r,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 i=this._keys,s=i.length;let n=t.key;for(;n>=0&&e=i[n+1].frame;)++n;if(t.key=n,n<0)return this._getKeyValue(i[0].value);if(n+1>s-1)return this._getKeyValue(i[s-1].value);const r=i[n],o=i[n+1],l=this._getKeyValue(r.value),h=this._getKeyValue(o.value);if(r.interpolation===Ga.STEP)return o.frame>e?l:h;const c=r.outTangent!==void 0&&o.inTangent!==void 0,u=o.frame-r.frame;let d=(e-r.frame)/u;const _=this.getEasingFunction();switch(_!==null&&(d=_.ease(d)),this.dataType){case ne.ANIMATIONTYPE_FLOAT:{const f=c?this.floatInterpolateFunctionWithTangents(l,r.outTangent*u,h,o.inTangent*u,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case ne.ANIMATIONLOOPMODE_CYCLE:case ne.ANIMATIONLOOPMODE_CONSTANT:return f;case ne.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+f}break}case ne.ANIMATIONTYPE_QUATERNION:{const f=c?this.quaternionInterpolateFunctionWithTangents(l,r.outTangent.scale(u),h,o.inTangent.scale(u),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case ne.ANIMATIONLOOPMODE_CYCLE:case ne.ANIMATIONLOOPMODE_CONSTANT:return f;case ne.ANIMATIONLOOPMODE_RELATIVE:return f.addInPlace(t.offsetValue.scale(t.repeatCount))}return f}case ne.ANIMATIONTYPE_VECTOR3:{const f=c?this.vector3InterpolateFunctionWithTangents(l,r.outTangent.scale(u),h,o.inTangent.scale(u),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case ne.ANIMATIONLOOPMODE_CYCLE:case ne.ANIMATIONLOOPMODE_CONSTANT:return f;case ne.ANIMATIONLOOPMODE_RELATIVE:return f.add(t.offsetValue.scale(t.repeatCount))}break}case ne.ANIMATIONTYPE_VECTOR2:{const f=c?this.vector2InterpolateFunctionWithTangents(l,r.outTangent.scale(u),h,o.inTangent.scale(u),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case ne.ANIMATIONLOOPMODE_CYCLE:case ne.ANIMATIONLOOPMODE_CONSTANT:return f;case ne.ANIMATIONLOOPMODE_RELATIVE:return f.add(t.offsetValue.scale(t.repeatCount))}break}case ne.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case ne.ANIMATIONLOOPMODE_CYCLE:case ne.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(l,h,d);case ne.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(l,h,d).add(t.offsetValue.scale(t.repeatCount))}break}case ne.ANIMATIONTYPE_COLOR3:{const f=c?this.color3InterpolateFunctionWithTangents(l,r.outTangent.scale(u),h,o.inTangent.scale(u),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case ne.ANIMATIONLOOPMODE_CYCLE:case ne.ANIMATIONLOOPMODE_CONSTANT:return f;case ne.ANIMATIONLOOPMODE_RELATIVE:return f.add(t.offsetValue.scale(t.repeatCount))}break}case ne.ANIMATIONTYPE_COLOR4:{const f=c?this.color4InterpolateFunctionWithTangents(l,r.outTangent.scale(u),h,o.inTangent.scale(u),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case ne.ANIMATIONLOOPMODE_CYCLE:case ne.ANIMATIONLOOPMODE_CONSTANT:return f;case ne.ANIMATIONLOOPMODE_RELATIVE:return f.add(t.offsetValue.scale(t.repeatCount))}break}case ne.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case ne.ANIMATIONLOOPMODE_CYCLE:case ne.ANIMATIONLOOPMODE_CONSTANT:return ne.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,d,t.workValue):l;case ne.ANIMATIONLOOPMODE_RELATIVE:return l}break}}return 0}matrixInterpolateFunction(e,t,i,s){return ne.AllowMatrixDecomposeForInterpolation?s?(N.DecomposeLerpToRef(e,t,i,s),s):N.DecomposeLerp(e,t,i):s?(N.LerpToRef(e,t,i,s),s):N.Lerp(e,t,i)}clone(){const e=new ne(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){this._keys=e.slice(0)}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&&(h=o.values[2]),o.values.length>=4&&(c=o.values[3]);break;case ne.ANIMATIONTYPE_QUATERNION:if(n=ue.FromArray(o.values),o.values.length>=8){const d=ue.FromArray(o.values.slice(4,8));d.equals(ue.Zero())||(l=d)}if(o.values.length>=12){const d=ue.FromArray(o.values.slice(8,12));d.equals(ue.Zero())||(h=d)}o.values.length>=13&&(c=o.values[12]);break;case ne.ANIMATIONTYPE_MATRIX:n=N.FromArray(o.values),o.values.length>=17&&(c=o.values[16]);break;case ne.ANIMATIONTYPE_COLOR3:n=he.FromArray(o.values),o.values[3]&&(l=he.FromArray(o.values[3])),o.values[4]&&(h=he.FromArray(o.values[4])),o.values[5]&&(c=o.values[5]);break;case ne.ANIMATIONTYPE_COLOR4:n=q.FromArray(o.values),o.values[4]&&(l=q.FromArray(o.values[4])),o.values[5]&&(h=q.FromArray(o.values[5])),o.values[6]&&(c=q.FromArray(o.values[6]));break;case ne.ANIMATIONTYPE_VECTOR3:default:n=v.FromArray(o.values),o.values[3]&&(l=v.FromArray(o.values[3])),o.values[4]&&(h=v.FromArray(o.values[4])),o.values[5]&&(c=o.values[5]);break}const u={};u.frame=o.frame,u.value=n,l!=null&&(u.inTangent=l),h!=null&&(u.outTangent=h),c!=null&&(u.interpolation=c),s.push(u)}if(t.setKeys(s),e.ranges)for(r=0;r{const n=new Jt;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){let r=JSON.parse(n.responseText);if(r.animations&&(r=r.animations),r.length){const o=new Array;for(const l of r)o.push(this.Parse(l));i(o)}else{const o=this.Parse(r);e&&(o.name=e),i(o)}}else s("Unable to load the animation")}),n.open("GET",t),n.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{const s=new Jt;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){const n=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(n.animations){const r=JSON.parse(n.animations),o=new Array;for(const l of r.animations){const h=this.Parse(l);h.snippetId=e,o.push(h)}t(o)}else{const r=JSON.parse(n.animation),o=this.Parse(r);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()})}}ne._UniqueIdGenerator=0;ne.AllowMatricesInterpolation=!1;ne.AllowMatrixDecomposeForInterpolation=!0;ne.SnippetUrl="https://snippet.babylonjs.com";ne.ANIMATIONTYPE_FLOAT=0;ne.ANIMATIONTYPE_VECTOR3=1;ne.ANIMATIONTYPE_QUATERNION=2;ne.ANIMATIONTYPE_MATRIX=3;ne.ANIMATIONTYPE_COLOR3=4;ne.ANIMATIONTYPE_COLOR4=7;ne.ANIMATIONTYPE_VECTOR2=5;ne.ANIMATIONTYPE_SIZE=6;ne.ANIMATIONLOOPMODE_RELATIVE=0;ne.ANIMATIONLOOPMODE_CYCLE=1;ne.ANIMATIONLOOPMODE_CONSTANT=2;ne.CreateFromSnippetAsync=ne.ParseFromSnippetAsync;Vt("BABYLON.Animation",ne);At._AnimationRangeFactory=(a,e,t)=>new $r(a,e,t);class qs{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;const t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(i=>{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||(qs.EasingFunction.setEasingMode(qs.EasingMode),this._radiusBounceTransition=ne.CreateAnimation("radius",ne.ANIMATIONTYPE_FLOAT,60,qs.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=ne.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()}}qs.EasingFunction=new _f(.3);qs.EasingMode=Hi.EASINGMODE_EASEOUT;class li{constructor(){this.onTargetFramingAnimationEndObservable=new ee,this._mode=li.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();li.EasingFunction.setEasingMode(li.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===Re.POINTERDOWN){this._isPointerDown=!0;return}i.type===Re.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 v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new v(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let r=0;r{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),c&&this._animatables.push(c)}_calculateLowerRadiusFromModelBoundingSphere(e,t){const s=t.subtract(e).length(),n=this._getFrustumSlope(),o=s*.5*this._radiusScale,l=o*Math.sqrt(1+1/(n.x*n.x)),h=o*Math.sqrt(1+1/(n.y*n.y));let c=Math.max(l,h);const u=this._attachedCamera;return u?(u.lowerRadiusLimit&&this._mode===li.IgnoreBoundsSizeMode&&(c=cu.upperRadiusLimit?u.upperRadiusLimit:c),c):0}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=Pi.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=ne.CreateAnimation("beta",ne.ANIMATIONTYPE_FLOAT,60,li.EasingFunction));const s=ne.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 fe.Zero();const i=e.getScene().getEngine().getAspectRatio(e),s=Math.tan(e.fov/2),n=s*i;return new fe(n,s)}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=Pi.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}}li.EasingFunction=new pf;li.EasingMode=Hi.EASINGMODE_EASEINOUT;li.IgnoreBoundsSizeMode=0;li.FitFrustumSidesMode=1;class Bt extends de{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=v.Zero(),this._tmpTargetVector=v.Zero(),this.cameraDirection=new v(0,0,0),this.cameraRotation=new fe(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new ue,this.rotation=new v(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=v.Zero(),this._initialFocalDistance=1,this._viewMatrix=N.Zero(),this._camMatrix=N.Zero(),this._cameraTransformMatrix=N.Zero(),this._cameraRotationMatrix=N.Zero(),this._referencePoint=new v(0,0,1),this._transformedReferencePoint=v.Zero(),this._defaultUp=v.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 v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new ue(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+=Ge),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),N.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&&ue.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(G.Matrix[0]),v.TransformNormalToRef(this.cameraDirection,G.Matrix[0],G.Vector3[0]),this.position.addInPlace(G.Vector3[0]);return}this.position.addInPlace(this.cameraDirection)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this.rotation),this.rotation.x+=this.cameraRotation.x*e,this.rotation.y+=this.cameraRotation.y*e,this.noRotationConstraint||(this.rotation.x>1.570796&&(this.rotation.x=1.570796),this.rotation.x<-1.570796&&(this.rotation.x=-1.570796)),this.rotationQuaternion&&this.rotation.lengthSquared()&&ue.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)),t&&(Math.abs(this.cameraDirection.x){}}add(e){const t=e.getSimpleName();if(this.attached[t]){H.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=de.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],n=Se.Serialize(s);t[s.getClassName()]=n}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const i in t){const s=Kn[i];if(s){const n=t[i],r=Se.Parse(()=>new s,n,null);this.add(r)}}}else for(const i in this.attached){const s=Kn[this.attached[i].getClassName()];if(s){const n=Se.Parse(()=>new s,e,null);this.remove(this.attached[i]),this.add(n)}}}}class kl{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=re.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,n=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,h;const c=o.event,u=c.pointerType==="touch";if(t.isInVRExclusivePointerMode||o.type!==Re.POINTERMOVE&&this.buttons.indexOf(c.button)===-1)return;const d=c.target;if(this._altKey=c.altKey,this._ctrlKey=c.ctrlKey,this._metaKey=c.metaKey,this._shiftKey=c.shiftKey,this._buttonsPressed=c.buttons,t.isPointerLock){const _=c.movementX,f=c.movementY;this.onTouch(null,_,f),this._pointA=null,this._pointB=null}else{if(o.type!==Re.POINTERDOWN&&u&&((l=this._pointA)===null||l===void 0?void 0:l.pointerId)!==c.pointerId&&((h=this._pointB)===null||h===void 0?void 0:h.pointerId)!==c.pointerId)return;if(o.type===Re.POINTERDOWN&&(this._currentActiveButton===-1||u)){try{d==null||d.setPointerCapture(c.pointerId)}catch{}if(this._pointA===null)this._pointA={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType};else if(this._pointB===null)this._pointB={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType};else return;this._currentActiveButton===-1&&!u&&(this._currentActiveButton=c.button),this.onButtonDown(c),e||(c.preventDefault(),i&&i.focus())}else if(o.type===Re.POINTERDOUBLETAP)this.onDoubleTap(c.pointerType);else if(o.type===Re.POINTERUP&&(this._currentActiveButton===c.button||u)){try{d==null||d.releasePointerCapture(c.pointerId)}catch{}u||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==c.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==c.pointerId?this._pointB=null:this._pointA=this._pointB=null,(s!==0||n)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,n,null),s=0,n=null),this._currentActiveButton=-1,this.onButtonUp(c),e||c.preventDefault()}else if(o.type===Re.POINTERMOVE){if(e||c.preventDefault(),this._pointA&&this._pointB===null){const _=c.clientX-this._pointA.x,f=c.clientY-this._pointA.y;this.onTouch(this._pointA,_,f),this._pointA.x=c.clientX,this._pointA.y=c.clientY}else if(this._pointA&&this._pointB){const _=this._pointA.pointerId===c.pointerId?this._pointA:this._pointB;_.x=c.clientX,_.y=c.clientY;const f=this._pointA.x-this._pointB.x,g=this._pointA.y-this._pointB.y,p=f*f+g*g,x={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:c.pointerId,type:o.type};this.onMultiTouch(this._pointA,this._pointB,s,p,n,x),n=x,s=p}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Re.POINTERDOWN|Re.POINTERUP|Re.POINTERMOVE|Re.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,n=null,this.onLostFocus()},this._contextMenuBind=this.onContextMenu.bind(this),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const r=this.camera.getScene().getEngine().getHostWindow();r&&re.RegisterTopRootEvents(r,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&re.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,n,r){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}F([B()],kl.prototype,"buttons",void 0);class ui extends kl{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.pinchZoom=!0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this.pinchInwards=!0,this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(this.panningSensibility!==0&&e&&t){const i=t.x-e.x,s=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=s/this.panningSensibility}}_computePinchZoom(e,t){const i=this.camera.radius||ui.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){this.panningSensibility!==0&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,s,n,r){i===0&&n===null||s===0&&r===null||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,s),this._computeMultiTouchPanning(n,r)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(s)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(n,r)):this.multiTouchPanning?this._computeMultiTouchPanning(n,r):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}ui.MinimumRadiusForPinch=.001;F([B()],ui.prototype,"buttons",void 0);F([B()],ui.prototype,"angularSensibilityX",void 0);F([B()],ui.prototype,"angularSensibilityY",void 0);F([B()],ui.prototype,"pinchPrecision",void 0);F([B()],ui.prototype,"pinchDeltaPercentage",void 0);F([B()],ui.prototype,"useNaturalPinchZoom",void 0);F([B()],ui.prototype,"pinchZoom",void 0);F([B()],ui.prototype,"panningSensibility",void 0);F([B()],ui.prototype,"multiTouchPanning",void 0);F([B()],ui.prototype,"multiTouchPanAndZoom",void 0);Kn.ArcRotateCameraPointersInput=ui;class Ki{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=re.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===Xn.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=re.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Re.POINTERWHEEL)return;const i=t.event;let s=0;const n=i.deltaMode===tr.DOM_DELTA_LINE?mf:1,r=-(i.deltaY*n);if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(r,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(r,this.camera.radius),s>0){let o=this.camera.radius,l=this.camera.inertialRadiusOffset+s;for(let h=0;h<20&&Math.abs(l)>.001;h++)o-=l,l*=this.camera.inertia;o=me.Clamp(o,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(r,o)}}else s=r/(this.wheelPrecision*40);s&&(this.zoomToMouseLocation&&this._hitPlane?this._zoomToMouse(s):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Re.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=ni.FromPositionAndNormal(e.target,t)}_getPosition(){var e;const t=this.camera,i=t.getScene(),s=i.createPickingRay(i.pointerX,i.pointerY,N.Identity(),t,!1);let n=0;return this._hitPlane&&(n=(e=s.intersectsPlane(this._hitPlane))!==null&&e!==void 0?e:0),s.origin.addInPlace(s.direction.scaleInPlace(n))}_zoomToMouse(e){var t,i;const s=this.camera,n=1-s.inertia;if(s.lowerRadiusLimit){const c=(t=s.lowerRadiusLimit)!==null&&t!==void 0?t:0;s.radius-(s.inertialRadiusOffset+e)/nc&&(e=(s.radius-c)*n-s.inertialRadiusOffset)}const o=e/n/s.radius,l=this._getPosition(),h=G.Vector3[6];l.subtractToRef(s.target,h),h.scaleInPlace(o),h.scaleInPlace(n),this._inertialPanning.addInPlace(h),s.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)()=>new lt(a,0,0,1,v.Zero(),e));class lt extends Bt{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 N,this._upToYMatrix=new N,this._upVector=v.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){N.RotationAlignToRef(v.UpReadOnly,this._upVector,this._yToUpMatrix),N.RotationAlignToRef(this._upVector,v.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 qs,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 li,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 ff,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,n,r,o=!0){super(e,v.Zero(),r,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=v.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=fe.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new N,this.panningAxis=new v(1,1,0),this._transformedDirection=new v,this.mapPanning=!1,this.onMeshTargetChangedObservable=new ee,this.checkCollisions=!1,this.collisionRadius=new v(.5,.5,.5),this._previousPosition=v.Zero(),this._collisionVelocity=v.Zero(),this._newPosition=v.Zero(),this._computationVector=v.Zero(),this._onCollisionPositionChange=(l,h,c=null)=>{c?(this.setPosition(h),this.onCollide&&this.onCollide(c)):this._previousPosition.copyFrom(this._position);const u=Math.cos(this.alpha),d=Math.sin(this.alpha),_=Math.cos(this.beta);let f=Math.sin(this.beta);f===0&&(f=1e-4);const g=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*u*f,this.radius*_,this.radius*d*f),g.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let p=this.upVector;this.allowUpsideDown&&this.beta<0&&(p=p.clone(),p=p.negate()),this._computeViewMatrix(this._position,g,p),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=v.Zero(),n&&this.setTarget(n),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new vf(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new v(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=fe.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 n=arguments;t=re.BackCompatCameraNoPreventDefault(n),this._useCtrlForPanning=i,this._panningMouseButton=s,typeof n[0]=="boolean"&&(n.length>1&&(this._useCtrlForPanning=n[1]),n.length>2&&(this._panningMouseButton=n[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;let t=this.inertialAlphaOffset;this.beta<=0&&(t*=-1),this.getScene().useRightHandedSystem&&(t*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this.alpha+=t*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)&&v.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 n;if(s=(n=this.overrideCloneAlphaBetaRadius)!==null&&n!==void 0?n: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 r=e,o=this._getTargetPosition();if(o&&!i&&o.equals(r))return;this._targetHost=null,this._target=r,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 n=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)&&v.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),n.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const r=this.getScene().collisionCoordinator;this._collider||(this._collider=r.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,r.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let r=this.upVector;this.allowUpsideDown&&s<0&&(r=r.negate()),this._computeViewMatrix(this._position,n,r),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=n,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=O.MinMax(e),s=v.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 n=e||this.getScene().meshes;i=O.MinMax(n),s=v.Distance(i.min,i.max)}else{const n=e;i=n,s=n.distance}this._target=O.Center(i),t||(this.maxZ=s*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case de.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case de.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case de.RIG_MODE_STEREOSCOPIC_OVERUNDER:case de.RIG_MODE_STEREOSCOPIC_INTERLACED:case de.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case de.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const s=new lt(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 de.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case de.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case de.RIG_MODE_STEREOSCOPIC_OVERUNDER:case de.RIG_MODE_STEREOSCOPIC_INTERLACED:case de.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case de.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"}}F([B()],lt.prototype,"alpha",void 0);F([B()],lt.prototype,"beta",void 0);F([B()],lt.prototype,"radius",void 0);F([B()],lt.prototype,"overrideCloneAlphaBetaRadius",void 0);F([wi("target")],lt.prototype,"_target",void 0);F([El("targetHost")],lt.prototype,"_targetHost",void 0);F([B()],lt.prototype,"inertialAlphaOffset",void 0);F([B()],lt.prototype,"inertialBetaOffset",void 0);F([B()],lt.prototype,"inertialRadiusOffset",void 0);F([B()],lt.prototype,"lowerAlphaLimit",void 0);F([B()],lt.prototype,"upperAlphaLimit",void 0);F([B()],lt.prototype,"lowerBetaLimit",void 0);F([B()],lt.prototype,"upperBetaLimit",void 0);F([B()],lt.prototype,"lowerRadiusLimit",void 0);F([B()],lt.prototype,"upperRadiusLimit",void 0);F([B()],lt.prototype,"inertialPanningX",void 0);F([B()],lt.prototype,"inertialPanningY",void 0);F([B()],lt.prototype,"pinchToPanMaxDistance",void 0);F([B()],lt.prototype,"panningDistanceLimit",void 0);F([wi()],lt.prototype,"panningOriginTarget",void 0);F([B()],lt.prototype,"panningInertia",void 0);F([B()],lt.prototype,"zoomToMouseLocation",null);F([B()],lt.prototype,"zoomOnFactor",void 0);F([Al()],lt.prototype,"targetScreenOffset",void 0);F([B()],lt.prototype,"allowUpsideDown",void 0);F([B()],lt.prototype,"useInputToRestoreState",void 0);class Le extends At{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}constructor(e,t){super(e,t),this.diffuse=new he(1,1,1),this.specular=new he(1,1,1),this.falloffType=Le.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=Le.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._isLight=!0,this.getScene().addLight(this),this._uniformBuffer=new oe(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=new Array,this.excludedMeshes=new Array,this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,s,n=!0){var r;const o=e.toString();let l=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+o),this._renderId!==t.getRenderId()||this._lastUseSpecular!==s||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=s;const h=this.getScaledIntensity();this.transferToEffect(i,o),this.diffuse.scaleToRef(h,ln.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",ln.Color3[0],this.range,o),s&&(this.specular.scaleToRef(h,ln.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",ln.Color3[1],this.radius,o)),l=!0}if(this.transferTexturesToEffect(i,o),t.shadowsEnabled&&this.shadowEnabled&&n){const h=(r=this.getShadowGenerator(t.activeCamera))!==null&&r!==void 0?r:this.getShadowGenerator();h&&(h.bindShadowLight(o,i),l=!0)}l?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(let i=0;i0&&this.includedOnlyMeshes.indexOf(e)===-1||this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1||this.includeOnlyWithLayerMask!==0&&!(this.includeOnlyWithLayerMask&e.layerMask)||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0}dispose(e,t=!1){if(this._shadowGenerators){const i=this._shadowGenerators.values();for(let 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=Le.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=Se.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=Se.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)})),Se.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const s=At.Construct("Light_Type_"+e,t,i);return s||null}static Parse(e,t){const i=Le.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=Se.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 n=0;n{const n=t.apply(e,s);for(const r of s)r._resyncLightSource(this);return n};const i=e.splice;e.splice=(s,n)=>{const r=i.apply(e,[s,n]);for(const o of r)o._resyncLightSource(this);return r};for(const s of e)s._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...s)=>{const n=t.apply(e,s);return this._resyncMeshes(),n};const i=e.splice;e.splice=(s,n)=>{const r=i.apply(e,[s,n]);return this._resyncMeshes(),r},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===Le.INTENSITYMODE_AUTOMATIC&&(t===Le.LIGHTTYPEID_DIRECTIONALLIGHT?i=Le.INTENSITYMODE_ILLUMINANCE:i=Le.INTENSITYMODE_LUMINOUSINTENSITY),t){case Le.LIGHTTYPEID_POINTLIGHT:case Le.LIGHTTYPEID_SPOTLIGHT:switch(i){case Le.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Le.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Le.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case Le.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Le.INTENSITYMODE_ILLUMINANCE:e=1;break;case Le.INTENSITYMODE_LUMINANCE:{let s=this.radius;s=Math.max(s,.001),e=2*Math.PI*(1-Math.cos(s));break}}break;case Le.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Le.FALLOFF_DEFAULT=Ke.FALLOFF_DEFAULT;Le.FALLOFF_PHYSICAL=Ke.FALLOFF_PHYSICAL;Le.FALLOFF_GLTF=Ke.FALLOFF_GLTF;Le.FALLOFF_STANDARD=Ke.FALLOFF_STANDARD;Le.LIGHTMAP_DEFAULT=Ke.LIGHTMAP_DEFAULT;Le.LIGHTMAP_SPECULAR=Ke.LIGHTMAP_SPECULAR;Le.LIGHTMAP_SHADOWSONLY=Ke.LIGHTMAP_SHADOWSONLY;Le.INTENSITYMODE_AUTOMATIC=Ke.INTENSITYMODE_AUTOMATIC;Le.INTENSITYMODE_LUMINOUSPOWER=Ke.INTENSITYMODE_LUMINOUSPOWER;Le.INTENSITYMODE_LUMINOUSINTENSITY=Ke.INTENSITYMODE_LUMINOUSINTENSITY;Le.INTENSITYMODE_ILLUMINANCE=Ke.INTENSITYMODE_ILLUMINANCE;Le.INTENSITYMODE_LUMINANCE=Ke.INTENSITYMODE_LUMINANCE;Le.LIGHTTYPEID_POINTLIGHT=Ke.LIGHTTYPEID_POINTLIGHT;Le.LIGHTTYPEID_DIRECTIONALLIGHT=Ke.LIGHTTYPEID_DIRECTIONALLIGHT;Le.LIGHTTYPEID_SPOTLIGHT=Ke.LIGHTTYPEID_SPOTLIGHT;Le.LIGHTTYPEID_HEMISPHERICLIGHT=Ke.LIGHTTYPEID_HEMISPHERICLIGHT;F([_s()],Le.prototype,"diffuse",void 0);F([_s()],Le.prototype,"specular",void 0);F([B()],Le.prototype,"falloffType",void 0);F([B()],Le.prototype,"intensity",void 0);F([B()],Le.prototype,"range",null);F([B()],Le.prototype,"intensityMode",null);F([B()],Le.prototype,"radius",null);F([B()],Le.prototype,"_renderPriority",void 0);F([je("_reorderLightsInScene")],Le.prototype,"renderPriority",void 0);F([B("shadowEnabled")],Le.prototype,"_shadowEnabled",void 0);F([B("excludeWithLayerMask")],Le.prototype,"_excludeWithLayerMask",void 0);F([B("includeOnlyWithLayerMask")],Le.prototype,"_includeOnlyWithLayerMask",void 0);F([B("lightmapMode")],Le.prototype,"_lightmapMode",void 0);class sr extends Le{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=v.Zero()),v.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=v.Zero()),v.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=v.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=v.Cross(this.direction,Qt.Y),t=v.Cross(e,this.direction);return v.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=v.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=N.Identity()),N.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)}}F([wi()],sr.prototype,"position",null);F([wi()],sr.prototype,"direction",null);F([B()],sr.prototype,"shadowMinZ",null);F([B()],sr.prototype,"shadowMaxZ",null);At.AddNodeConstructor("Light_Type_0",(a,e)=>()=>new E0(a,v.Zero(),e));class E0 extends sr{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 Le.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new v(1,0,0);case 1:return new v(-1,0,0);case 2:return new v(0,-1,0);case 3:return new v(0,1,0);case 4:return new v(0,0,1);case 5:return new v(0,0,-1)}return v.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const n=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,r=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;N.PerspectiveFovLHToRef(this.shadowAngle,1,o?r:n,o?n:r,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}}F([B()],E0.prototype,"shadowAngle",null);class wo{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,n){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&t.prePassRenderer.getIndex(2)!==-1){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const r=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==r.frameId&&(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class C0 extends j{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new N,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)}}class Oe{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,Y.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,Y.MarkAllMaterialsAsDirty(1))}}Oe._DiffuseTextureEnabled=!0;Oe._DetailTextureEnabled=!0;Oe._DecalMapEnabled=!0;Oe._AmbientTextureEnabled=!0;Oe._OpacityTextureEnabled=!0;Oe._ReflectionTextureEnabled=!0;Oe._EmissiveTextureEnabled=!0;Oe._SpecularTextureEnabled=!0;Oe._BumpTextureEnabled=!0;Oe._LightmapTextureEnabled=!0;Oe._RefractionTextureEnabled=!0;Oe._ColorGradingTextureEnabled=!0;Oe._FresnelEnabled=!0;Oe._ClearCoatTextureEnabled=!0;Oe._ClearCoatBumpTextureEnabled=!0;Oe._ClearCoatTintTextureEnabled=!0;Oe._SheenTextureEnabled=!0;Oe._AnisotropicTextureEnabled=!0;Oe._ThicknessTextureEnabled=!0;Oe._RefractionIntensityTextureEnabled=!0;Oe._TranslucencyIntensityTextureEnabled=!0;Oe._IridescenceTextureEnabled=!0;const xf="decalFragmentDeclaration",bf="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";te.IncludesShadersStore[xf]=bf;const yf="defaultFragmentDeclaration",Tf="uniform vec4 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\nuniform vec3 vAmbientColor;\nuniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;\nuniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";te.IncludesShadersStore[yf]=Tf;const Sf="sceneUboDeclaration",Af="layout(std140,column_major) uniform;\nuniform Scene {\nmat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;\nmat4 projection;\nvec4 vEyePosition;\n};\n";te.IncludesShadersStore[Sf]=Af;const Ef="meshUboDeclaration",Cf="#ifdef WEBGL2\nuniform mat4 world;\nuniform float visibility;\n#else\nlayout(std140,column_major) uniform;\nuniform Mesh\n{\nmat4 world;\nfloat visibility;\n};\n#endif\n#define WORLD_UBO\n";te.IncludesShadersStore[Ef]=Cf;const Rf="defaultUboDeclaration",If="layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor;\nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix;\nvec2 vTangentSpaceParams;\nfloat pointSize;\nfloat alphaCutOff;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec3 vRefractionPosition;\nvec3 vRefractionSize;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nvec3 vAmbientColor;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";te.IncludesShadersStore[Rf]=If;const Mf="prePassDeclaration",Pf="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n";te.IncludesShadersStore[Mf]=Pf;const wf="oitDeclaration",Df="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;\nlayout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;\nuniform sampler2D oitDepthSampler;\nuniform sampler2D oitFrontColorSampler;\n#endif\n";te.IncludesShadersStore[wf]=Df;const Ff="mainUVVaryingDeclaration",Of="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";te.IncludesShadersStore[Ff]=Of;const Lf="helperFunctions",Bf="const float PI=3.1415926535897932384626433832795;\nconst float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nconst float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{\nvec3 nearZeroSection=0.0773993808*color;\nvec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{\nvec3 nearZeroSection=12.92*color;\nvec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;\nfloat remainingSection=pow(0.947867299*(color+0.055),2.4);\nreturn color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;\nfloat remainingSection=1.055*pow(color,0.41666)-0.055;\nreturn color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nvec3 square(vec3 value)\n{\nreturn value*value;\n}\nfloat pow5(float value) {\nfloat sq=value*value;\nreturn sq*sq*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat normVariance=varianceAmount/255.0;\nfloat dither=mix(-normVariance,normVariance,rand);\nreturn dither;\n}\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=maxEps(max(color.r,max(color.g,color.b)));\nfloat D =max(rgbdMaxRange/maxRGB,1.);\nD =clamp(floor(D)/255.0,0.,1.);\nvec3 rgb=color.rgb*D;\nrgb=toGammaSpace(rgb);\nreturn vec4(clamp(rgb,0.,1.),D); \n}\nvec3 fromRGBD(vec4 rgbd) {\nrgbd.rgb=toLinearSpace(rgbd.rgb);\nreturn rgbd.rgb/rgbd.a;\n}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\nvec3 intersectPositionWS=vertexPos+origVec*distance;\nreturn intersectPositionWS-cubePos;\n}\n";te.IncludesShadersStore[Lf]=Bf;const Nf="lightFragmentDeclaration",Uf="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float cascadeBlendFactor{X};\nvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\nuniform highp sampler2DArray depthSampler{X};\nuniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);\nvec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif\n";te.IncludesShadersStore[Nf]=Uf;const kf="lightUboDeclaration",Vf="#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float cascadeBlendFactor{X};\nvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\nuniform highp sampler2DArray depthSampler{X};\nuniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);\nvec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";te.IncludesShadersStore[kf]=Vf;const Gf="lightsFragmentFunctions",Wf="struct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w==0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}";te.IncludesShadersStore[Gf]=Wf;const zf="shadowsFragmentFunctions",Hf="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\n#define inline\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;\n}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;\n}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;\n}\n}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\nfloat shadow=texture2D(shadowSampler,uvDepthLayer);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nfloat shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);\nshadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);\nshadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);\nshadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);\nshadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);\nshadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);\nshadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat 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)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; ithis._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&&(n.computeBonesUsingShaders=!1);continue}if(!(!n.computeBonesUsingShaders||n.numBoneInfluencers===0)){if(n.material.getEffect()===t)n.computeBonesUsingShaders=!1;else if(n.subMeshes){for(const r of n.subMeshes)if(r.effect===t){n.computeBonesUsingShaders=!1;break}}}}}else{const i=this._defines[this._currentRank];if(i)for(let s=0;ss.priority-n.priority),this._codeInjectionPoints={};const i={};i[Ms._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"));this._defineNamesFromPlugins=i}_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.customCode);break}case Zt.PrepareUniformBuffer:{const s=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const n of this._plugins){const r=n.getUniforms();if(r){if(r.ubo)for(const o of r.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+="".concat(o.type," ").concat(o.name).concat(l>0?"[".concat(l,"]"):"",";\r\n")}this._uniformList.push(o.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\r\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\r\n")}n.getSamplers(this._samplerList),n.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){return(t,i)=>{var s;e&&(i=e(t,i)),this._uboDeclaration&&(i=i.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(i=i.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(i=i.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const n=(s=this._codeInjectionPoints)===null||s===void 0?void 0:s[t];if(!n)return i;for(let r in n){let o="";for(const l of this._activePlugins){const h=l.getCustomCode(t);h!=null&&h[r]&&(o+=h[r]+"\r\n")}if(o.length>0)if(r.charAt(0)==="!"){r=r.substring(1);let l="g";if(r.charAt(0)==="!")l="",r=r.substring(1);else{const d=Np.exec(r);d&&d.length>=2&&(l=d[1],r=r.substring(l.length+1))}l.indexOf("g")<0&&(l+="g");const h=i,c=new RegExp(r,l);let u=c.exec(h);for(;u!==null;){let d=o;for(let _=0;_{e.pluginManager=void 0})),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,n&&this._pluginManager._addPlugin(this),r&&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){Se.Clone(()=>e,this)}serialize(){return Se.Serialize(this)}parse(e,t,i){Se.Parse(()=>this,e,t,i)}}F([B()],Zr.prototype,"name",void 0);F([B()],Zr.prototype,"priority",void 0);F([B()],Zr.prototype,"registerForExtraEvents",void 0);class Up extends y0{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Js extends Zr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new Up,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=j.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&&Oe.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&&Oe.DetailTextureEnabled&&this._isEnabled?(we.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&&Oe.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),we.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Oe.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"}]}}}F([Si("detailTexture"),je("_markAllSubMeshesAsTexturesDirty")],Js.prototype,"texture",void 0);F([B()],Js.prototype,"diffuseBlendLevel",void 0);F([B()],Js.prototype,"roughnessBlendLevel",void 0);F([B()],Js.prototype,"bumpLevel",void 0);F([B(),je("_markAllSubMeshesAsTexturesDirty")],Js.prototype,"normalBlendMethod",void 0);F([B(),je("_markAllSubMeshesAsTexturesDirty")],Js.prototype,"isEnabled",void 0);const Sa={effect:null,subMesh:null};class kp extends y0{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.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_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.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 ie extends C0{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 he(0,0,0),this.diffuseColor=new he(1,1,1),this.specularColor=new he(1,1,1),this.emissiveColor=new he(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._renderTargets=new qt(16),this._worldViewProjectionMatrix=N.Zero(),this._globalAmbientColor=new he(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Js(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new wo,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),ie.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),ie.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 ie.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||ie.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===j.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==j.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(Zt.GetDefineNames,this._eventInfo),t.materialDefines=new kp(this._eventInfo.defineNames));const s=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();n._needNormals=we.PrepareDefinesForLights(s,e,n,!0,this._maxSimultaneousLights,this._disableLighting),we.PrepareDefinesForMultiview(s,n);const o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(we.PrepareDefinesForPrePass(s,n,this.canRenderToMRT&&!o),we.PrepareDefinesForOIT(s,n,o),n._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n._needUVs=!1;for(let h=1;h<=6;++h)n["MAINUV"+h]=!1;if(s.texturesEnabled){if(n.DIFFUSEDIRECTUV=0,n.BUMPDIRECTUV=0,n.AMBIENTDIRECTUV=0,n.OPACITYDIRECTUV=0,n.EMISSIVEDIRECTUV=0,n.SPECULARDIRECTUV=0,n.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&ie.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())we.PrepareDefinesForMergedUV(this._diffuseTexture,n,"DIFFUSE");else return!1;else n.DIFFUSE=!1;if(this._ambientTexture&&ie.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())we.PrepareDefinesForMergedUV(this._ambientTexture,n,"AMBIENT");else return!1;else n.AMBIENT=!1;if(this._opacityTexture&&ie.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())we.PrepareDefinesForMergedUV(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else n.OPACITY=!1;if(this._reflectionTexture&&ie.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(n._needNormals=!0,n.REFLECTION=!0,n.ROUGHNESS=this._roughness>0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===se.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case se.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case se.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case se.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case se.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case se.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case se.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case se.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case se.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case se.CUBIC_MODE:case se.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC");break}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&ie.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())we.PrepareDefinesForMergedUV(this._emissiveTexture,n,"EMISSIVE");else return!1;else n.EMISSIVE=!1;if(this._lightmapTexture&&ie.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())we.PrepareDefinesForMergedUV(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else n.LIGHTMAP=!1;if(this._specularTexture&&ie.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())we.PrepareDefinesForMergedUV(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else n.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&ie.BumpTextureEnabled){if(this._bumpTexture.isReady())we.PrepareDefinesForMergedUV(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&ie.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,n.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(ie.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),we.PrepareDefinesForMisc(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n),we.PrepareDefinesForFrameBoundValues(s,r,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),we.PrepareDefinesForAttributes(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(n.isDirty){const h=n._areLightsDisposed;n.markAsProcessed();const c=new R0;n.REFLECTION&&c.addFallback(0,"REFLECTION"),n.SPECULAR&&c.addFallback(0,"SPECULAR"),n.BUMP&&c.addFallback(0,"BUMP"),n.PARALLAX&&c.addFallback(1,"PARALLAX"),n.PARALLAXOCCLUSION&&c.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&c.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&c.addFallback(1,"FOG"),n.POINTSIZE&&c.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&c.addFallback(0,"LOGARITHMICDEPTH"),we.HandleFallbacksForShadows(n,c,this._maxSimultaneousLights),n.SPECULARTERM&&c.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&c.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&c.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&c.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&c.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&c.addFallback(4,"FRESNEL"),n.MULTIVIEW&&c.addFallback(0,"MULTIVIEW");const u=[A.PositionKind];n.NORMAL&&u.push(A.NormalKind),n.TANGENT&&u.push(A.TangentKind);for(let S=1;S<=6;++S)n["UV"+S]&&u.push("uv".concat(S===1?"":S));n.VERTEXCOLOR&&u.push(A.ColorKind),we.PrepareAttributesForBones(u,e,n,c),we.PrepareAttributesForInstances(u,n),we.PrepareAttributesForMorphTargets(u,e,n),we.PrepareAttributesForBakedVertexAnimation(u,e,n);let d="default";const _=["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"],f=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],g=["Material","Scene","Mesh"];this._eventInfo.fallbacks=c,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=_,this._eventInfo.attributes=u,this._eventInfo.samplers=f,this._eventInfo.uniformBuffersNames=g,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(Zt.PrepareEffect,this._eventInfo),wo.AddUniforms(_),He&&(He.PrepareUniforms(_,n),He.PrepareSamplers(f,n)),we.PrepareUniformsAndSamplersList({uniformsNames:_,uniformBuffersNames:g,samplers:f,defines:n,maxSimultaneousLights:this._maxSimultaneousLights}),S0(_);const p={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,_,g,f,n,u,p));const x=n.toString(),m=t.effect;let T=s.getEngine().createEffect(d,{attributes:u,uniformsNames:_,uniformBuffersNames:g,samplers:f,defines:x,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS},processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:n.PREPASS},r);if(this._eventInfo.customCode=void 0,T)if(this._onEffectCreatedObservable&&(Sa.effect=T,Sa.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Sa)),this.allowShaderHotSwapping&&m&&!T.isReady()){if(T=m,n.markAsUnprocessed(),l=this.isFrozen,h)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(T,n,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(n._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 n=this.getScene(),r=i.materialDefines;if(!r)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,n,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const l=o._forceRebindOnNextCall||this._mustRebind(n,o,t.visibility);we.BindBonesParameters(t,o);const h=this._uniformBuffer;if(l){if(this.bindViewProjection(o),!h.useUbo||!this.isFrozen||!h.isSync||o._forceRebindOnNextCall){if(ie.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(h.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),h.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&h.updateColor4("opacityParts",new he(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(h.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),h.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(h.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),h.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(h.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),h.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),n.texturesEnabled){if(this._diffuseTexture&&ie.DiffuseTextureEnabled&&(h.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),we.BindTextureMatrix(this._diffuseTexture,h,"diffuse")),this._ambientTexture&&ie.AmbientTextureEnabled&&(h.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),we.BindTextureMatrix(this._ambientTexture,h,"ambient")),this._opacityTexture&&ie.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),we.BindTextureMatrix(this._opacityTexture,h,"opacity")),this._hasAlphaChannel()&&h.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&ie.ReflectionTextureEnabled&&(h.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),h.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const c=this._reflectionTexture;h.updateVector3("vReflectionPosition",c.boundingBoxPosition),h.updateVector3("vReflectionSize",c.boundingBoxSize)}if(this._emissiveTexture&&ie.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),we.BindTextureMatrix(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&ie.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),we.BindTextureMatrix(this._lightmapTexture,h,"lightmap")),this._specularTexture&&ie.SpecularTextureEnabled&&(h.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),we.BindTextureMatrix(this._specularTexture,h,"specular")),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&ie.BumpTextureEnabled&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),we.BindTextureMatrix(this._bumpTexture,h,"bump"),n._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&ie.RefractionTextureEnabled){let c=1;if(this._refractionTexture.isCube||(h.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(c=this._refractionTexture.depth)),h.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,c,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const u=this._refractionTexture;h.updateVector3("vRefractionPosition",u.boundingBoxPosition),h.updateVector3("vRefractionSize",u.boundingBoxSize)}}}this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&h.updateColor4("vSpecularColor",this.specularColor,this.specularPower),h.updateColor3("vEmissiveColor",ie.EmissiveTextureEnabled?this.emissiveColor:he.BlackReadOnly),h.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),n.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor)}n.texturesEnabled&&(this._diffuseTexture&&ie.DiffuseTextureEnabled&&o.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&ie.AmbientTextureEnabled&&o.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&ie.OpacityTextureEnabled&&o.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&ie.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?o.setTexture("reflectionCubeSampler",this._reflectionTexture):o.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&ie.EmissiveTextureEnabled&&o.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&ie.LightmapTextureEnabled&&o.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&ie.SpecularTextureEnabled&&o.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&ie.BumpTextureEnabled&&o.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&ie.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),A0(o,this,n),this.bindEyePosition(o)}else n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(n.lightsEnabled&&!this._disableLighting&&we.BindLights(n,t,o,r,this._maxSimultaneousLights),(n.fogEnabled&&t.applyFog&&n.fogMode!==Me.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(o),we.BindFogParameters(n,t,o),r.NUM_MORPH_INFLUENCERS&&we.BindMorphTargetParameters(t,o),r.BAKED_VERTEX_ANIMATION_TEXTURE&&((s=t.bakedVertexAnimationManager)===null||s===void 0||s.bind(o,r.INSTANCES)),this.useLogarithmicDepth&&we.BindLogDepth(r,o,n),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),h.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,n,r,o,l,h,c,u;t&&((i=this._diffuseTexture)===null||i===void 0||i.dispose(),(s=this._ambientTexture)===null||s===void 0||s.dispose(),(n=this._opacityTexture)===null||n===void 0||n.dispose(),(r=this._reflectionTexture)===null||r===void 0||r.dispose(),(o=this._emissiveTexture)===null||o===void 0||o.dispose(),(l=this._specularTexture)===null||l===void 0||l.dispose(),(h=this._bumpTexture)===null||h===void 0||h.dispose(),(c=this._lightmapTexture)===null||c===void 0||c.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){const t=Se.Clone(()=>new ie(e,this.getScene()),this);return t.name=e,t.id=e,this.stencil.copyTo(t.stencil),t}static Parse(e,t,i){const s=Se.Parse(()=>new ie(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),s}static get DiffuseTextureEnabled(){return Oe.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Oe.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Oe.DetailTextureEnabled}static set DetailTextureEnabled(e){Oe.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Oe.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Oe.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Oe.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Oe.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Oe.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Oe.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Oe.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Oe.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Oe.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Oe.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Oe.BumpTextureEnabled}static set BumpTextureEnabled(e){Oe.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Oe.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Oe.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Oe.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Oe.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Oe.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Oe.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Oe.FresnelEnabled}static set FresnelEnabled(e){Oe.FresnelEnabled=e}}F([Si("diffuseTexture")],ie.prototype,"_diffuseTexture",void 0);F([je("_markAllSubMeshesAsTexturesAndMiscDirty")],ie.prototype,"diffuseTexture",void 0);F([Si("ambientTexture")],ie.prototype,"_ambientTexture",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"ambientTexture",void 0);F([Si("opacityTexture")],ie.prototype,"_opacityTexture",void 0);F([je("_markAllSubMeshesAsTexturesAndMiscDirty")],ie.prototype,"opacityTexture",void 0);F([Si("reflectionTexture")],ie.prototype,"_reflectionTexture",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"reflectionTexture",void 0);F([Si("emissiveTexture")],ie.prototype,"_emissiveTexture",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"emissiveTexture",void 0);F([Si("specularTexture")],ie.prototype,"_specularTexture",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"specularTexture",void 0);F([Si("bumpTexture")],ie.prototype,"_bumpTexture",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"bumpTexture",void 0);F([Si("lightmapTexture")],ie.prototype,"_lightmapTexture",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"lightmapTexture",void 0);F([Si("refractionTexture")],ie.prototype,"_refractionTexture",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"refractionTexture",void 0);F([_s("ambient")],ie.prototype,"ambientColor",void 0);F([_s("diffuse")],ie.prototype,"diffuseColor",void 0);F([_s("specular")],ie.prototype,"specularColor",void 0);F([_s("emissive")],ie.prototype,"emissiveColor",void 0);F([B()],ie.prototype,"specularPower",void 0);F([B("useAlphaFromDiffuseTexture")],ie.prototype,"_useAlphaFromDiffuseTexture",void 0);F([je("_markAllSubMeshesAsTexturesAndMiscDirty")],ie.prototype,"useAlphaFromDiffuseTexture",void 0);F([B("useEmissiveAsIllumination")],ie.prototype,"_useEmissiveAsIllumination",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"useEmissiveAsIllumination",void 0);F([B("linkEmissiveWithDiffuse")],ie.prototype,"_linkEmissiveWithDiffuse",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"linkEmissiveWithDiffuse",void 0);F([B("useSpecularOverAlpha")],ie.prototype,"_useSpecularOverAlpha",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"useSpecularOverAlpha",void 0);F([B("useReflectionOverAlpha")],ie.prototype,"_useReflectionOverAlpha",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"useReflectionOverAlpha",void 0);F([B("disableLighting")],ie.prototype,"_disableLighting",void 0);F([je("_markAllSubMeshesAsLightsDirty")],ie.prototype,"disableLighting",void 0);F([B("useObjectSpaceNormalMap")],ie.prototype,"_useObjectSpaceNormalMap",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"useObjectSpaceNormalMap",void 0);F([B("useParallax")],ie.prototype,"_useParallax",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"useParallax",void 0);F([B("useParallaxOcclusion")],ie.prototype,"_useParallaxOcclusion",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"useParallaxOcclusion",void 0);F([B()],ie.prototype,"parallaxScaleBias",void 0);F([B("roughness")],ie.prototype,"_roughness",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"roughness",void 0);F([B()],ie.prototype,"indexOfRefraction",void 0);F([B()],ie.prototype,"invertRefractionY",void 0);F([B()],ie.prototype,"alphaCutOff",void 0);F([B("useLightmapAsShadowmap")],ie.prototype,"_useLightmapAsShadowmap",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"useLightmapAsShadowmap",void 0);F([Jn("diffuseFresnelParameters")],ie.prototype,"_diffuseFresnelParameters",void 0);F([je("_markAllSubMeshesAsFresnelDirty")],ie.prototype,"diffuseFresnelParameters",void 0);F([Jn("opacityFresnelParameters")],ie.prototype,"_opacityFresnelParameters",void 0);F([je("_markAllSubMeshesAsFresnelAndMiscDirty")],ie.prototype,"opacityFresnelParameters",void 0);F([Jn("reflectionFresnelParameters")],ie.prototype,"_reflectionFresnelParameters",void 0);F([je("_markAllSubMeshesAsFresnelDirty")],ie.prototype,"reflectionFresnelParameters",void 0);F([Jn("refractionFresnelParameters")],ie.prototype,"_refractionFresnelParameters",void 0);F([je("_markAllSubMeshesAsFresnelDirty")],ie.prototype,"refractionFresnelParameters",void 0);F([Jn("emissiveFresnelParameters")],ie.prototype,"_emissiveFresnelParameters",void 0);F([je("_markAllSubMeshesAsFresnelDirty")],ie.prototype,"emissiveFresnelParameters",void 0);F([B("useReflectionFresnelFromSpecular")],ie.prototype,"_useReflectionFresnelFromSpecular",void 0);F([je("_markAllSubMeshesAsFresnelDirty")],ie.prototype,"useReflectionFresnelFromSpecular",void 0);F([B("useGlossinessFromSpecularMapAlpha")],ie.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"useGlossinessFromSpecularMapAlpha",void 0);F([B("maxSimultaneousLights")],ie.prototype,"_maxSimultaneousLights",void 0);F([je("_markAllSubMeshesAsLightsDirty")],ie.prototype,"maxSimultaneousLights",void 0);F([B("invertNormalMapX")],ie.prototype,"_invertNormalMapX",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"invertNormalMapX",void 0);F([B("invertNormalMapY")],ie.prototype,"_invertNormalMapY",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"invertNormalMapY",void 0);F([B("twoSidedLighting")],ie.prototype,"_twoSidedLighting",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ie.prototype,"twoSidedLighting",void 0);F([B()],ie.prototype,"useLogarithmicDepth",null);Vt("BABYLON.StandardMaterial",ie);Me.DefaultMaterialFactory=a=>new ie("default material",a);var Cs;(function(a){a[a.Clean=0]="Clean",a[a.Stop=1]="Stop",a[a.Sync=2]="Sync",a[a.NoSync=3]="NoSync"})(Cs||(Cs={}));class Ue{static get ForceFullSceneLoadingForIncremental(){return Tt.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Tt.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Tt.ShowLoadingScreen}static set ShowLoadingScreen(e){Tt.ShowLoadingScreen=e}static get loggingLevel(){return Tt.loggingLevel}static set loggingLevel(e){Tt.loggingLevel=e}static get CleanBoneMatrixWeights(){return Tt.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Tt.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Ue._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=Ue._RegisteredPlugins[e];return t||(H.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"),Ue.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Ue._RegisteredPlugins){const i=Ue._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Ue._RegisteredPlugins[t]}return Ue.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 Ue._GetPluginForExtension(s)}static _GetDirectLoad(e){return e.substr(0,5)==="data:"?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+e.url;return t?s+=": ".concat(t):i&&(s+=": ".concat(i)),s}static _LoadData(e,t,i,s,n,r,o){const l=Ue._GetDirectLoad(e.url),h=o?Ue._GetPluginForExtension(o):l?Ue._GetPluginForDirectLoad(e.url):Ue._GetPluginForFilename(e.url);let c;if(h.plugin.createPlugin!==void 0?c=h.plugin.createPlugin():c=h.plugin,!c)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(Ue.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!u0(e.url))){if(c.directLoad){const T=c.directLoad(t,l);T.then?T.then(S=>{i(c,S)}).catch(S=>{n("Error in directLoad of _loadData: "+S,S)}):i(c,T)}else i(c,l);return c}const u=h.isBinary,d=(T,S)=>{if(t.isDisposed){n("Scene has been disposed");return}i(c,T,S)};let _=null,f=!1;const g=c.onDisposeObservable;g&&g.add(()=>{f=!0,_&&(_.abort(),_=null),r()});const p=()=>{if(f)return;const T=(b,y)=>{n(b==null?void 0:b.statusText,y)},S=e.file||e.url;_=c.loadFile?c.loadFile(t,S,d,s,u,T):t._loadFile(S,d,s,!0,u,T)},x=t.getEngine();let m=x.enableOfflineSupport;if(m){let T=!1;for(const S of t.disableOfflineSupportExceptionRules)if(S.test(e.url)){T=!0;break}m=!T}return m&&Y.OfflineProviderFactory?t.offlineProvider=Y.OfflineProviderFactory(e.url,p,x.disableManifestCheck):p(),c}static _GetFileInfo(e,t){let i,s,n=null;if(!t)i=e,s=re.GetFilename(e),e=re.GetFolderPath(e);else if(t.name){const r=t;i="file:".concat(r.name),s=r.name,n=r}else if(typeof t=="string"&&t.startsWith("data:"))i=t,s="";else{const r=t;if(r.substr(0,1)==="/")return re.Error("Wrong sceneFilename parameter"),null;i=e+r,s=r}return{url:i,rootUrl:e,name:s,file:n}}static GetPluginForExtension(e){return Ue._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Ue._RegisteredPlugins[e]}static RegisterPlugin(e){if(typeof e.extensions=="string"){const t=e.extensions;Ue._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach(i=>{Ue._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",s=Ie.LastCreatedScene,n=null,r=null,o=null,l=null){if(!s)return H.Error("No scene available to import mesh to"),null;const h=Ue._GetFileInfo(t,i);if(!h)return null;const c={};s.addPendingData(c);const u=()=>{s.removePendingData(c)},d=(g,p)=>{const x=Ue._FormatErrorMessage(h,g,p);o?o(s,x,new hs(x,Ks.SceneLoaderError,p)):H.Error(x),u()},_=r?g=>{try{r(g)}catch(p){d("Error in onProgress callback: "+p,p)}}:void 0,f=(g,p,x,m,T,S,b)=>{if(s.importedMeshesFiles.push(h.url),n)try{n(g,p,x,m,T,S,b)}catch(y){d("Error in onSuccess callback: "+y,y)}s.removePendingData(c)};return Ue._LoadData(h,s,(g,p,x)=>{if(g.rewriteRootURL&&(h.rootUrl=g.rewriteRootURL(h.rootUrl,x)),g.importMesh){const m=g,T=new Array,S=new Array,b=new Array;if(!m.importMesh(e,s,p,h.rootUrl,T,S,b,d))return;s.loadingPluginName=g.name,f(T,S,b,[],[],[],[])}else g.importMeshAsync(e,s,p,h.rootUrl,_,h.name).then(T=>{s.loadingPluginName=g.name,f(T.meshes,T.particleSystems,T.skeletons,T.animationGroups,T.transformNodes,T.geometries,T.lights)}).catch(T=>{d(T.message,T)})},_,d,u,l)}static ImportMeshAsync(e,t,i="",s=Ie.LastCreatedScene,n=null,r=null){return new Promise((o,l)=>{Ue.ImportMesh(e,t,i,s,(h,c,u,d,_,f,g)=>{o({meshes:h,particleSystems:c,skeletons:u,animationGroups:d,transformNodes:_,geometries:f,lights:g})},n,(h,c,u)=>{l(u||new Error(c))},r)})}static Load(e,t="",i=Ie.LastCreatedEngine,s=null,n=null,r=null,o=null){return i?Ue.Append(e,t,new Me(i),s,n,r,o):(re.Error("No engine available"),null)}static LoadAsync(e,t="",i=Ie.LastCreatedEngine,s=null,n=null){return new Promise((r,o)=>{Ue.Load(e,t,i,l=>{r(l)},s,(l,h,c)=>{o(c||new Error(h))},n)})}static Append(e,t="",i=Ie.LastCreatedScene,s=null,n=null,r=null,o=null){if(!i)return H.Error("No scene available to append to"),null;const l=Ue._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)};Ue.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));const u=(f,g)=>{const p=Ue._FormatErrorMessage(l,f,g);r?r(i,p,new hs(p,Ks.SceneLoaderError,g)):H.Error(p),c()},d=n?f=>{try{n(f)}catch(g){u("Error in onProgress callback",g)}}:void 0,_=()=>{if(s)try{s(i)}catch(f){u("Error in onSuccess callback",f)}i.removePendingData(h)};return Ue._LoadData(l,i,(f,g)=>{if(f.load){if(!f.load(i,g,l.rootUrl,u))return;i.loadingPluginName=f.name,_()}else f.loadAsync(i,g,l.rootUrl,d,l.name).then(()=>{i.loadingPluginName=f.name,_()}).catch(x=>{u(x.message,x)})},d,u,c,o)}static AppendAsync(e,t="",i=Ie.LastCreatedScene,s=null,n=null){return new Promise((r,o)=>{Ue.Append(e,t,i,l=>{r(l)},s,(l,h,c)=>{o(c||new Error(h))},n)})}static LoadAssetContainer(e,t="",i=Ie.LastCreatedScene,s=null,n=null,r=null,o=null){if(!i)return H.Error("No scene available to load asset container to"),null;const l=Ue._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)},u=(f,g)=>{const p=Ue._FormatErrorMessage(l,f,g);r?r(i,p,new hs(p,Ks.SceneLoaderError,g)):H.Error(p),c()},d=n?f=>{try{n(f)}catch(g){u("Error in onProgress callback",g)}}:void 0,_=f=>{if(s)try{s(f)}catch(g){u("Error in onSuccess callback",g)}i.removePendingData(h)};return Ue._LoadData(l,i,(f,g)=>{if(f.loadAssetContainer){const x=f.loadAssetContainer(i,g,l.rootUrl,u);if(!x)return;i.loadingPluginName=f.name,_(x)}else f.loadAssetContainerAsync?f.loadAssetContainerAsync(i,g,l.rootUrl,d,l.name).then(x=>{i.loadingPluginName=f.name,_(x)}).catch(x=>{u(x.message,x)}):u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},d,u,c,o)}static LoadAssetContainerAsync(e,t="",i=Ie.LastCreatedScene,s=null,n=null){return new Promise((r,o)=>{Ue.LoadAssetContainer(e,t,i,l=>{r(l)},s,(l,h,c)=>{o(c||new Error(h))},n)})}static ImportAnimations(e,t="",i=Ie.LastCreatedScene,s=!0,n=Cs.Clean,r=null,o=null,l=null,h=null,c=null){if(!i){H.Error("No scene available to load animations to");return}if(s){for(const f of i.animatables)f.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(f=>{f.dispose()}),i.getNodes().forEach(f=>{f.animations&&(f.animations=[])})}else switch(n){case Cs.Clean:i.animationGroups.slice().forEach(_=>{_.dispose()});break;case Cs.Stop:i.animationGroups.forEach(_=>{_.stop()});break;case Cs.Sync:i.animationGroups.forEach(_=>{_.reset(),_.restart()});break;case Cs.NoSync:break;default:H.Error("Unknown animation group loading mode value '"+n+"'");return}const u=i.animatables.length,d=_=>{_.mergeAnimationsTo(i,i.animatables.slice(u),r),_.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)};this.LoadAssetContainer(e,t,i,d,l,h,c)}static ImportAnimationsAsync(e,t="",i=Ie.LastCreatedScene,s=!0,n=Cs.Clean,r=null,o=null,l=null,h=null,c=null){return new Promise((u,d)=>{Ue.ImportAnimations(e,t,i,s,n,r,_=>{u(_)},l,(_,f,g)=>{d(g||new Error(f))},c)})}}Ue.NO_LOGGING=0;Ue.MINIMAL_LOGGING=1;Ue.SUMMARY_LOGGING=2;Ue.DETAILED_LOGGING=3;Ue.OnPluginActivatedObservable=new ee;Ue._RegisteredPlugins={};Ue._ShowingLoadingScreen=!1;const Vp="fxaaPixelShader",Gp="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN{const c=this.texelSize;h.setFloat2("texelSize",c.x,c.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\n":null}static _Parse(e,t,i,s){return Se.Parse(()=>new Qr(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}Vt("BABYLON.FxaaPostProcess",Qr);let ys=null;function Jr(a,e,t,i,s="image/png",n=!1){const{height:r,width:o}=Wl(a,e,t);if(!(r&&o)){H.Error("Invalid 'size' parameter !");return}ys||(ys=document.createElement("canvas")),ys.width=o,ys.height=r;const l=ys.getContext("2d"),h=a.getRenderWidth()/a.getRenderHeight();let c=o,u=c/h;u>r&&(u=r,c=u*h);const d=Math.max(0,o-c)/2,_=Math.max(0,r-u)/2;e.getScene().activeCamera!==e?ea(a,e,t,g=>{if(n){const p=new Blob([g]);re.DownloadBlob(p),i&&i("")}else i&&i(g)},s,1,a.getCreationOptions().antialias):a.onEndFrameObservable.addOnce(()=>{const g=a.getRenderingCanvas();l&&g&&l.drawImage(g,d,_,c,u),ys&&(n?(re.EncodeScreenshotCanvasData(ys,void 0,s),i&&i("")):re.EncodeScreenshotCanvasData(ys,i,s))})}function Vl(a,e,t,i="image/png"){return new Promise((s,n)=>{Jr(a,e,t,r=>{typeof r<"u"?s(r):n(new Error("Data is undefined"))},i)})}function Hp(a,e,t,i,s="image/png"){return new Promise(n=>{Jr(a,e,{width:t,height:i},()=>{n()},s,!0)})}function ea(a,e,t,i,s="image/png",n=1,r=!1,o,l=!1,h=!1,c=!0){const{height:u,width:d,finalWidth:_,finalHeight:f}=Wl(a,e,t),g={width:d,height:u};if(!(u&&d)){H.Error("Invalid 'size' parameter !");return}const p={width:a.getRenderWidth(),height:a.getRenderHeight()};a.setSize(d,u);const x=e.getScene(),m=new zi("screenShot",g,x,!1,!1,0,!1,se.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);m.renderList=x.meshes.slice(),m.samples=n,m.renderSprites=l,m.activeCamera=e,m.forceLayerMaskCheck=c;const T=()=>{a.onEndFrameObservable.addOnce(()=>{_===d&&f===u?m.readPixels(void 0,void 0,void 0,!1).then(S=>{Yt.DumpData(d,u,S,i,s,o,!0),m.dispose()}):Dd("pass",m.getInternalTexture(),x,void 0,void 0,void 0,_,f).then(S=>{a._readTexturePixels(S,_,f,-1,0,null,!0,!1,0,0).then(b=>{Yt.DumpData(_,f,b,i,s,o,!0),S.dispose()})})}),x.incrementRenderId(),x.resetCachedMaterial(),m.render(!0),x.incrementRenderId(),x.resetCachedMaterial(),a.setSize(p.width,p.height),e.getProjectionMatrix(!0),x.render()};if(r){const S=new Qr("antialiasing",1,x.activeCamera);m.addPostProcess(S),S.getEffect().isReady()?T():S.getEffect().onCompiled=()=>{T()}}else T()}function Gl(a,e,t,i="image/png",s=1,n=!1,r,o=!1,l=!1,h=!0){return new Promise((c,u)=>{ea(a,e,t,d=>{typeof d<"u"?c(d):u(new Error("Data is undefined"))},i,s,n,r,o,l,h)})}function Wl(a,e,t){let i=0,s=0,n=0,r=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?(r=t.finalHeight,n=t.finalWidth):t.finalWidth&&!t.finalHeight?(n=t.finalWidth,r=Math.round(n/a.getAspectRatio(e))):t.finalHeight&&!t.finalWidth?(r=t.finalHeight,n=Math.round(r*a.getAspectRatio(e))):(n=s,r=i)}else isNaN(t)||(i=t,s=t,n=t,r=t);return s&&(s=Math.floor(s)),i&&(i=Math.floor(i)),n&&(n=Math.floor(n)),r&&(r=Math.floor(r)),{height:i|0,width:s|0,finalWidth:n|0,finalHeight:r|0}}const Xp={CreateScreenshot:Jr,CreateScreenshotAsync:Vl,CreateScreenshotWithResizeAsync:Hp,CreateScreenshotUsingRenderTarget:ea,CreateScreenshotUsingRenderTargetAsync:Gl},Kp=()=>{re.CreateScreenshot=Jr,re.CreateScreenshotAsync=Vl,re.CreateScreenshotUsingRenderTarget=ea,re.CreateScreenshotUsingRenderTargetAsync=Gl};Kp();O._instancedMeshFactory=(a,e)=>{const t=new I0(a,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class I0 extends ei{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&&re.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&&re.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&&re.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&&re.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||H.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||H.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!==be.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new N);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,G.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(G.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;e(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;s1&&(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 C=0;C4&&(d.push(A.MatricesIndicesExtraKind),d.push(A.MatricesWeightsExtraKind));const C=e.skeleton;u.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),_.addCPUSkinningFallback(0,e),C.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 "+(C.bones.length+1)),this._options.uniforms.indexOf("mBones")===-1&&this._options.uniforms.push("mBones"))}else u.push("#define NUM_BONE_INFLUENCERS 0");let m=0;const T=e?e.morphTargetManager:null;if(T){const C=T.supportsUVs&&u.indexOf("#define UV1")!==-1,R=T.supportsTangents&&u.indexOf("#define TANGENT")!==-1,w=T.supportsNormals&&u.indexOf("#define NORMAL")!==-1;m=T.numInfluencers,C&&u.push("#define MORPHTARGETS_UV"),R&&u.push("#define MORPHTARGETS_TANGENT"),w&&u.push("#define MORPHTARGETS_NORMAL"),m>0&&u.push("#define MORPHTARGETS"),T.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 "+m);for(let D=0;D0&&(g=g.slice(),g.push("morphTargetInfluences"),g.push("morphTargetTextureInfo"),g.push("morphTargetTextureIndices"))}else u.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const C=e.bakedVertexAnimationManager;C&&C.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")),we.PrepareAttributesForBakedVertexAnimation(d,e,u)}for(const C in this._textures)if(!this._textures[C].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&u.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(S0(g),Nl(this,h,u)),this.customShaderNameResolve&&(g=g.slice(),p=p.slice(),x=x.slice(),f=this.customShaderNameResolve(f,g,p,x,u,d));const S=l?i._getDrawWrapper():this._drawWrapper,b=(s=S==null?void 0:S.effect)!==null&&s!==void 0?s:null,y=(n=S==null?void 0:S.defines)!==null&&n!==void 0?n:null,E=u.join("\n");let P=b;return y!==E&&(P=c.createEffect(f,{attributes:d,uniformsNames:g,uniformBuffersNames:p,samplers:x,defines:E,fallbacks:_,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage},c),l?i.setEffect(P,E,this._materialContext):S&&S.setEffect(P,E),this._onEffectCreatedObservable&&(Aa.effect=P,Aa.subMesh=(r=i!=null?i:e==null?void 0:e.subMeshes[0])!==null&&r!==void 0?r:null,this._onEffectCreatedObservable.notifyObservers(Aa))),P._wasPreviouslyUsingInstances=!!t,!((o=!(P!=null&&P.isReady()))!==null&&o!==void 0)||o?!1:(b!==P&&h.resetCachedMaterial(),P._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t!=null?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 n;const r=s&&this._storeEffectOnSubMeshes,o=i!=null?i:r?s.effect:this.getEffect();if(!o)return;this._activeEffect=o,this.bindOnlyWorldMatrix(e,i);const l=this._options.uniformBuffers;let h=!1;if(o&&l&&l.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let u=0;u0&&we.BindMorphTargetParameters(t,o);const d=t.bakedVertexAnimationManager;d&&d.isEnabled&&((n=t.bakedVertexAnimationManager)===null||n===void 0||n.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 us(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach(i=>{const 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 n=this._textureArrays[s];for(let r=0;rnew us(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);let n;e.stencil&&s.stencil.parse(e.stencil,t,i);for(n in e.textures)s.setTexture(n,se.Parse(e.textures[n],t,i));for(n in e.textureArrays){const r=e.textureArrays[n],o=new Array;for(let l=0;l(h%3===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>he.FromArray(o));s.setColor3Array(n,r)}for(n in e.colors4)s.setColor4(n,q.FromArray(e.colors4[n]));for(n in e.colors4Arrays){const r=e.colors4Arrays[n].reduce((o,l,h)=>(h%4===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>q.FromArray(o));s.setColor4Array(n,r)}for(n in e.vectors2)s.setVector2(n,fe.FromArray(e.vectors2[n]));for(n in e.vectors3)s.setVector3(n,v.FromArray(e.vectors3[n]));for(n in e.vectors4)s.setVector4(n,Ye.FromArray(e.vectors4[n]));for(n in e.quaternions)s.setQuaternion(n,ue.FromArray(e.quaternions[n]));for(n in e.matrices)s.setMatrix(n,N.FromArray(e.matrices[n]));for(n in e.matrixArray)s._matrixArrays[n]=new Float32Array(e.matrixArray[n]);for(n in e.matrices3x3)s.setMatrix3x3(n,e.matrices3x3[n]);for(n in e.matrices2x2)s.setMatrix2x2(n,e.matrices2x2[n]);for(n in e.vectors2Arrays)s.setArray2(n,e.vectors2Arrays[n]);for(n in e.vectors3Arrays)s.setArray3(n,e.vectors3Arrays[n]);for(n in e.vectors4Arrays)s.setArray4(n,e.vectors4Arrays[n]);for(n in e.quaternionsArrays)s.setArray4(n,e.quaternionsArrays[n]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise((n,r)=>{const o=new Jt;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),h=this.Parse(l,i||Ie.LastCreatedScene,s);e&&(h.name=e),n(h)}else r("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((s,n)=>{const r=new Jt;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){const o=JSON.parse(JSON.parse(r.responseText).jsonPayload),l=JSON.parse(o.shaderMaterial),h=this.Parse(l,t||Ie.LastCreatedScene,i);h.snippetId=e,s(h)}else n("Unable to load the snippet "+e)}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}}us.SnippetUrl="https://snippet.babylonjs.com";us.CreateFromSnippetAsync=us.ParseFromSnippetAsync;Vt("BABYLON.ShaderMaterial",us);const Yp="colorPixelShader",qp="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}";te.ShadersStore[Yp]=qp;const jp="colorVertexShader",$p="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";te.ShadersStore[jp]=$p;O._LinesMeshParser=(a,e)=>Ls.Parse(a,e);class Ls extends O{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,s=null,n,r,o,l){super(e,t,i,s,n),this.useVertexColor=r,this.useVertexAlpha=o,this.color=new he(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 h=[],c={attributes:[A.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:h,useClipPlane:null};o===!1?c.needAlphaBlending=!1:c.defines.push("#define VERTEXALPHA"),r?(c.defines.push("#define VERTEXCOLOR"),c.attributes.push(A.ColorKind)):(c.uniforms.push("color"),this._color4=new q),l?this.material=l:(this.material=new us("colorShader",this.getScene(),"color",c,!1),this.material.doNotSerialize=!0)}isReady(){return this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage)?super.isReady():!1}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=j.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._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,i),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:s,g:n,b:r}=this.color;this._color4.set(s,n,r,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(j.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(j.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 Ls(e,this.getScene(),t,this,i)}createInstance(e){const t=new zl(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 Ls(e.name,t);return i.color=he.FromArray(e.color),i.alpha=e.alpha,i}}class zl extends I0{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}const Zp="linePixelShader",Qp="#include\nuniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";te.ShadersStore[Zp]=Qp;const Jp="lineVertexShader",eg="#include\n#include\nattribute vec3 position;\nattribute vec4 normal;\nuniform mat4 viewProjection;\nuniform float width;\nuniform float aspectRatio;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 worldViewProjection=viewProjection*finalWorld;\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";te.ShadersStore[Jp]=eg;ei.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this};ei.prototype.enableEdgesRendering=function(a=.95,e=!1,t){return this.disableEdgesRendering(),this._edgesRenderer=new ta(this,a,e,!0,t),this};Object.defineProperty(ei.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0});Ls.prototype.enableEdgesRendering=function(a=.95,e=!1){return this.disableEdgesRendering(),this._edgesRenderer=new ig(this,a,e),this};zl.prototype.enableEdgesRendering=function(a=.95,e=!1){return Ls.prototype.enableEdgesRendering.apply(this,arguments),this};class tg{constructor(){this.edges=new Array,this.edgesConnectedCount=0}}class ta{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 us("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,n){var r;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 qt(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=n!=null?n:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Ns(e.getEngine())),this._prepareRessources(),s&&(!((r=n==null?void 0:n.useAlternateEdgeFinder)!==null&&r!==void 0)||r?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=ta._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[A.PositionKind];e&&e._rebuild(),e=this._buffers[A.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[A.PositionKind];t&&(t.dispose(),this._buffers[A.PositionKind]=null),t=this._buffers[A.NormalKind],t&&(t.dispose(),this._buffers[A.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,n){return e===i&&t===s||e===s&&t===i?0:e===s&&t===n||e===n&&t===s?1:e===n&&t===i||e===i&&t===n?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,n){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(n,1e-10)||e.equalsWithEpsilon(n,1e-10)&&t.equalsWithEpsilon(s,1e-10)?1:e.equalsWithEpsilon(n,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(n,1e-10)?2:-1}_checkEdge(e,t,i,s,n){let r;t===void 0?r=!0:r=v.Dot(i[e],i[t]){R>=0&&C.push(R);for(let w=0;w=e[0].length&&e[1].length>=e[2].length?r=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(r=2);for(let P=0;P<3;++P)P===r?e[P].sort((C,R)=>C[1]R[1]?1:0):e[P].sort((C,R)=>C[1]>R[1]?-1:C[1]=r+1;--P)n(e[P%3],l,P!==r+2?s[i[t+(P+1)%3]]:-1);const c=l.length,u=0,d=0;i.push(s[i[t+r]],o[0],l[0]),i.push(s[i[t+(r+1)%3]],l[c-1],o[h-1]);const _=h<=c,f=_?h:c,g=_?c:h,p=_?h-1:c-1,x=_?0:1;let m=h+c-2,T=_?u:d,S=_?d:u;const b=_?o:l,y=_?l:o;let E=0;for(;m-- >0;){x?i.push(b[T],y[S]):i.push(y[S],b[T]),E+=f;let P;E>=g&&TE){const w=y;y=E,E=w}const C=y+"_"+E,R=x[C];R?R.done||(v.Dot(S,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 n=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(n=this.customInstances.length,!o.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!o.isFrozen){let l=0;for(let h=0;h=0?c.substring(0,u):c;d=d.toLowerCase();const _=u>=0?c.substring(u+1).trim():"";if(d==="newmtl")l&&this.materials.push(l),e._blockEntityCollection=!!s,l=new ie(_,e),l._parentContainer=s,e._blockEntityCollection=!1;else if(d==="kd"&&l)o=_.split(r,3).map(parseFloat),l.diffuseColor=he.FromArray(o);else if(d==="ka"&&l)o=_.split(r,3).map(parseFloat),l.ambientColor=he.FromArray(o);else if(d==="ks"&&l)o=_.split(r,3).map(parseFloat),l.specularColor=he.FromArray(o);else if(d==="ke"&&l)o=_.split(r,3).map(parseFloat),l.emissiveColor=he.FromArray(o);else if(d==="ns"&&l)l.specularPower=parseFloat(_);else if(d==="d"&&l)l.alpha=parseFloat(_);else if(d==="map_ka"&&l)l.ambientTexture=ki._GetTexture(i,_,e);else if(d==="map_kd"&&l)l.diffuseTexture=ki._GetTexture(i,_,e);else if(d==="map_ks"&&l)l.specularTexture=ki._GetTexture(i,_,e);else if(d!=="map_ns")if(d==="map_bump"&&l){const f=_.split(r),g=f.indexOf("-bm");let p=null;g>=0&&(p=f[g+1],f.splice(g,2)),l.bumpTexture=ki._GetTexture(i,f.join(" "),e),l.bumpTexture&&p!==null&&(l.bumpTexture.level=parseFloat(p))}else d==="map_d"&&l&&(l.opacityTexture=ki._GetTexture(i,_,e))}l&&this.materials.push(l)}static _GetTexture(e,t,i){if(!t)return null;let s=e;if(e==="file:"){let n=t.lastIndexOf("\\");n===-1&&(n=t.lastIndexOf("/")),n>-1?s+=t.substr(n+1):s+=t}else s+=t;return new se(s,i,!1,ki.INVERT_TEXTURE_Y)}}ki.INVERT_TEXTURE_Y=!0;class pt{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new q(.5,.5,.5,1),this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const i=e[t[0]].normals.indexOf(t[1]);return i===-1?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const i=e[t[0]].normals.indexOf(t[1]);return i!=1&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,s,n,r,o){let l;this._loadingOptions.optimizeWithUV?l=this._isInArrayUV(this._tuplePosNorm,[e,i,t]):l=this._isInArray(this._tuplePosNorm,[e,i]),l===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(s),this._wrappedUvsForBabylon.push(n),this._wrappedNormalsForBabylon.push(r),o!==void 0&&this._wrappedColorsForBabylon.push(o),this._tuplePosNorm[e].normals.push(i),this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e].uv.push(t)):this._indicesForBabylon.push(l)}_unwrapData(){for(let e=0;e0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0)}_optimizeNormals(e){const t=e.getVerticesData(A.PositionKind),i=e.getVerticesData(A.NormalKind),s={};if(!t||!i)return;for(let r=0;r=7){const u=parseFloat(c[4]),d=parseFloat(c[5]),_=parseFloat(c[6]);this._colors.push(new q(u>1?u/255:u,d>1?d/255:d,_>1?_/255:_,c.length===7||c[7]===void 0?1:parseFloat(c[7])))}else this._colors.push(this._grayColor)}else if((c=pt.NormalPattern.exec(h))!==null)this._normals.push(new v(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3])));else if((c=pt.UVPattern.exec(h))!==null)this._uvs.push(new fe(parseFloat(c[1])*this._loadingOptions.UVScaling.x,parseFloat(c[2])*this._loadingOptions.UVScaling.y));else if((c=pt.FacePattern3.exec(h))!==null)this._setDataForCurrentFaceWithPattern3(c[1].trim().split(" "),1);else if((c=pt.FacePattern4.exec(h))!==null)this._setDataForCurrentFaceWithPattern4(c[1].trim().split(" "),1);else if((c=pt.FacePattern5.exec(h))!==null)this._setDataForCurrentFaceWithPattern5(c[1].trim().split(" "),1);else if((c=pt.FacePattern2.exec(h))!==null)this._setDataForCurrentFaceWithPattern2(c[1].trim().split(" "),1);else if((c=pt.FacePattern1.exec(h))!==null)this._setDataForCurrentFaceWithPattern1(c[1].trim().split(" "),1);else if(pt.GroupDescriptor.test(h)||pt.ObjectDescriptor.test(h)){const u={name:h.substring(2).trim(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:this._materialNameFromObj};this._addPreviousObjMesh(),this._meshesFromObj.push(u),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(pt.UseMtlDescriptor.test(h)){if(this._materialNameFromObj=h.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const u={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:this._materialNameFromObj};this._increment++,this._meshesFromObj.push(u),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else pt.MtlLibGroupDescriptor.test(h)?n(h.substring(7).trim()):pt.SmoothDescriptor.test(h)||console.log("Unhandled expression at line : "+h)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let l=null;if(this._indicesForBabylon.length)this._indicesForBabylon.reverse(),this._unwrapData();else{for(const h of this._positions)this._unwrappedPositionsForBabylon.push(h.x,h.y,h.z);if(this._normals.length)for(const h of this._normals)this._unwrappedNormalsForBabylon.push(h.x,h.y,h.z);if(this._uvs.length)for(const h of this._uvs)this._unwrappedUVForBabylon.push(h.x,h.y);if(this._colors.length)for(const h of this._colors)this._unwrappedColorsForBabylon.push(h.r,h.g,h.b,h.a);this._materialNameFromObj||(l=new ie(si.RandomId(),i),l.pointsCloud=!0,this._materialNameFromObj=l.name,this._normals.length||(l.disableLighting=!0,l.emissiveColor=he.White()))}this._meshesFromObj.push({name:si.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:l})}for(let l=0;l{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 rg extends ps{constructor(e){super(),this._wasAddedToScene=!1,e=e||Ie.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,h=i.dependsOn.get(l);if(o instanceof I0){const u=o.sourceMesh;t.has(u.uniqueId)&&(h.add(u.uniqueId),i.dependedBy.get(u.uniqueId).add(l))}const c=i.dependedBy.get(l);for(const u of o.getDescendants()){const d=u.uniqueId;t.has(d)&&(c.add(d),i.dependsOn.get(d).add(l))}}const s=[],n=[];for(const o of e){const l=o.uniqueId;i.dependsOn.get(l).size===0&&(n.push(o),t.delete(l))}const r=n;for(;r.length>0;){const o=r.shift();s.push(o);const l=i.dependedBy.get(o.uniqueId);for(const h of Array.from(l.values())){const c=i.dependsOn.get(h);c.delete(o.uniqueId),c.size===0&&t.get(h)&&(r.push(t.get(h)),t.delete(h))}}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 n of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,n,s)}}_isNodeInContainer(e){return e instanceof O&&this.meshes.indexOf(e)!==-1||e instanceof be&&this.transformNodes.indexOf(e)!==-1||e instanceof Le&&this.lights.indexOf(e)!==-1||e instanceof de&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return H.Warn("Node ".concat(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 H.Warn("Node ".concat(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 H.Warn("Node ".concat(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 H.Warn("Node ".concat(e.name," has a parent that is not in the container.")),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||re.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},n={},r=new ng,o=[],l=[],h={doNotInstantiate:!0,...i},c=(g,p)=>{if(s[g.uniqueId]=p.uniqueId,n[p.uniqueId]=p,e&&(p.name=e(g.name)),p instanceof O){const x=p;if(x.morphTargetManager){const m=g.morphTargetManager;x.morphTargetManager=m.clone();for(let T=0;T{if(c(g,p),g.parent){const x=s[g.parent.uniqueId],m=n[x];m?p.parent=m:p.parent=g.parent}if(p.position.copyFrom(g.position),p.rotation.copyFrom(g.rotation),p.scaling.copyFrom(g.scaling),p.material){const x=p;if(x.material)if(t){const m=g.material;if(l.indexOf(m)===-1){let T=m.clone(e?e(m.name):"Clone of "+m.name);if(l.push(m),s[m.uniqueId]=T.uniqueId,n[T.uniqueId]=T,m.getClassName()==="MultiMaterial"){const S=m;for(const b of S.subMaterials)b&&(T=b.clone(e?e(b.name):"Clone of "+b.name),l.push(b),s[b.uniqueId]=T.uniqueId,n[T.uniqueId]=T);S.subMaterials=S.subMaterials.map(b=>b&&n[s[b.uniqueId]])}}x.getClassName()!=="InstancedMesh"&&(x.material=n[s[m.uniqueId]])}else x.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(x.material)===-1&&this.scene.addMultiMaterial(x.material):this.scene.materials.indexOf(x.material)===-1&&this.scene.addMaterial(x.material)}p.parent===null&&r.rootNodes.push(p)};return _.forEach(g=>{if(g.getClassName()==="InstancedMesh"){const p=g,x=p.sourceMesh,m=s[x.uniqueId],S=(typeof m=="number"?n[m]:x).createInstance(p.name);f(p,S)}else{let p=!0;g.getClassName()==="TransformNode"||g.skeleton||g.getTotalVertices()===0?p=!1:h.doNotInstantiate&&(typeof h.doNotInstantiate=="function"?p=!h.doNotInstantiate(g):p=!h.doNotInstantiate);const x=p?g.createInstance("instance of ".concat(g.name)):g.clone("Clone of ".concat(g.name),null,!0);if(!x)throw new Error("Could not clone or instantiate node on Asset Container ".concat(g.name));f(g,x)}}),this.skeletons.forEach(g=>{if(h.predicate&&!h.predicate(g))return;const p=g.clone(e?e(g.name):"Clone of "+g.name);for(const x of this.meshes)if(x.skeleton===g&&!x.isAnInstance){const m=n[s[x.uniqueId]];if(!m||m.isAnInstance||(m.skeleton=p,o.indexOf(p)!==-1))continue;o.push(p);for(const T of p.bones)T._linkedTransformNode&&(T._linkedTransformNode=n[s[T._linkedTransformNode.uniqueId]])}r.skeletons.push(p)}),this.animationGroups.forEach(g=>{if(h.predicate&&!h.predicate(g))return;const p=g.clone(e?e(g.name):"Clone of "+g.name,x=>n[s[x.uniqueId]]||x);r.animationGroups.push(p)}),r}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||re.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){this.cameras.forEach(t=>{e&&!e(t)||this.scene.addCamera(t)}),this.lights.forEach(t=>{e&&!e(t)||this.scene.addLight(t)}),this.meshes.forEach(t=>{e&&!e(t)||this.scene.addMesh(t)}),this.skeletons.forEach(t=>{e&&!e(t)||this.scene.addSkeleton(t)}),this.animations.forEach(t=>{e&&!e(t)||this.scene.addAnimation(t)}),this.animationGroups.forEach(t=>{e&&!e(t)||this.scene.addAnimationGroup(t)}),this.multiMaterials.forEach(t=>{e&&!e(t)||this.scene.addMultiMaterial(t)}),this.materials.forEach(t=>{e&&!e(t)||this.scene.addMaterial(t)}),this.morphTargetManagers.forEach(t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)}),this.geometries.forEach(t=>{e&&!e(t)||this.scene.addGeometry(t)}),this.transformNodes.forEach(t=>{e&&!e(t)||this.scene.addTransformNode(t)}),this.actionManagers.forEach(t=>{e&&!e(t)||this.scene.addActionManager(t)}),this.textures.forEach(t=>{e&&!e(t)||this.scene.addTexture(t)}),this.reflectionProbes.forEach(t=>{e&&!e(t)||this.scene.addReflectionProbe(t)})}removeAllFromScene(){this._isValidHierarchy()||re.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 n=!0;if(i){for(const r of i)if(s===r){n=!1;break}}n&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new sg);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 O("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=Ie.LastCreatedScene,t,i=null){if(!e)return H.Error("No scene available to merge animations to"),[];const s=i||(o=>{let l=null;const h=o.animations.length?o.animations[0].targetProperty:"",c=o.name.split(".").join("").split("_primitive")[0];switch(h){case"position":case"rotationQuaternion":l=e.getTransformNodeByName(o.name)||e.getTransformNodeByName(c);break;case"influence":l=e.getMorphTargetByName(o.name)||e.getMorphTargetByName(c);break;default:l=e.getNodeByName(o.name)||e.getNodeByName(c)}return l});this.getNodes().forEach(o=>{const l=s(o);if(l!==null){for(const h of o.animations){const c=l.animations.filter(u=>u.targetProperty===h.targetProperty);for(const u of c){const d=l.animations.indexOf(u,0);d>-1&&l.animations.splice(d,1)}}l.animations=l.animations.concat(o.animations)}});const r=new Array;return this.animationGroups.slice().forEach(o=>{r.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))}),r}}class St{static get INVERT_TEXTURE_Y(){return ki.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){ki.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||St._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:St.COMPUTE_NORMALS,optimizeNormals:St.OPTIMIZE_NORMALS,importVertexColors:St.IMPORT_VERTEX_COLORS,invertY:St.INVERT_Y,invertTextureY:St.INVERT_TEXTURE_Y,UVScaling:St.UV_SCALING,materialLoadingFailsSilently:St.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:St.OPTIMIZE_WITH_UV,skipMaterials:St.SKIP_MATERIALS}}_loadMTL(e,t,i,s){const n=t+e;re.LoadFile(n,i,void 0,void 0,!1,(r,o)=>{s(n,o)})}createPlugin(){return new St(St._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,s){return this._parseSolid(e,t,i,s).then(n=>({meshes:n,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[]}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then(()=>{})}loadAssetContainerAsync(e,t,i){const s=new rg(e);return this._assetContainer=s,this.importMeshAsync(null,e,t,i).then(n=>(n.meshes.forEach(r=>s.meshes.push(r)),n.meshes.forEach(r=>{const o=r.material;o&&s.materials.indexOf(o)==-1&&(s.materials.push(o),o.getActiveTextures().forEach(h=>{s.textures.indexOf(h)==-1&&s.textures.push(h)}))}),this._assetContainer=null,s)).catch(n=>{throw this._assetContainer=null,n})}_parseSolid(e,t,i,s){let n="";const r=new ki,o=new Array,l=[];new pt(o,l,this._loadingOptions).parse(e,i,t,this._assetContainer,u=>{n=u});const c=[];return n!==""&&!this._loadingOptions.skipMaterials&&c.push(new Promise((u,d)=>{this._loadMTL(n,s,_=>{try{r.parseMTL(t,_,s,this._assetContainer);for(let f=0;f-1;)p.push(x),g=x+1;if(x===-1&&p.length===0)r.materials[f].dispose();else for(let m=0;m{re.Warn("Error downloading MTL file: '".concat(n,"'")),this._loadingOptions.materialLoadingFailsSilently?u():d(f)})})),Promise.all(c).then(()=>l)}}St.OPTIMIZE_WITH_UV=!0;St.INVERT_Y=!1;St.IMPORT_VERTEX_COLORS=!1;St.COMPUTE_NORMALS=!1;St.OPTIMIZE_NORMALS=!1;St.UV_SCALING=new fe(1,1);St.SKIP_MATERIALS=!1;St.MATERIAL_LOADING_FAILS_SILENTLY=!0;Ue&&Ue.RegisterPlugin(new St);class We{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new We(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=We._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),n=We._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let r=0,o=Number.MAX_VALUE,l,h,c,u;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xn.x)return!1}else if(l=1/this.direction.x,h=(s.x-this.origin.x)*l,c=(n.x-this.origin.x)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),r=Math.max(h,r),o=Math.min(c,o),r>o)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yn.y)return!1}else if(l=1/this.direction.y,h=(s.y-this.origin.y)*l,c=(n.y-this.origin.y)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),r=Math.max(h,r),o=Math.min(c,o),r>o)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zn.z)return!1}else if(l=1/this.direction.z,h=(s.z-this.origin.z)*l,c=(n.z-this.origin.z)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),r=Math.max(h,r),o=Math.min(c,o),r>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,n=e.center.z-this.origin.z,r=i*i+s*s+n*n,o=e.radius+t,l=o*o;if(r<=l)return!0;const h=i*this.direction.x+s*this.direction.y+n*this.direction.z;return h<0?!1:r-h*h<=l}intersectsTriangle(e,t,i){const s=We._TmpVector3[0],n=We._TmpVector3[1],r=We._TmpVector3[2],o=We._TmpVector3[3],l=We._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,n),v.CrossToRef(this.direction,n,r);const h=v.Dot(s,r);if(h===0)return null;const c=1/h;this.origin.subtractToRef(e,o);const u=v.Dot(o,r)*c;if(u<0||u>1)return null;v.CrossToRef(o,s,l);const d=v.Dot(this.direction,l)*c;if(d<0||u+d>1)return null;const _=v.Dot(n,l)*c;return _>this.length?null:new Va(1-u-d,u,_)}intersectsPlane(e){let t;const i=v.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{const s=v.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 v(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 v(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 v(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t){const i=G.Matrix[0];return e.getWorldMatrix().invertToRef(i),this._tmpRay?We.TransformToRef(this,i,this._tmpRay):this._tmpRay=We.Transform(this,i),e.intersects(this._tmpRay,t)}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,n=G.Vector3[0],r=G.Vector3[1],o=G.Vector3[2],l=G.Vector3[3];t.subtractToRef(e,n),this.direction.scaleToRef(We._Rayl,o),s.addToRef(o,r),e.subtractToRef(s,l);const h=v.Dot(n,n),c=v.Dot(n,o),u=v.Dot(o,o),d=v.Dot(n,l),_=v.Dot(o,l),f=h*u-c*c;let g,p=f,x,m=f;fp&&(g=p,x=_+c,m=u)),x<0?(x=0,-d<0?g=0:-d>h?g=p:(g=-d,p=h)):x>m&&(x=m,-d+c<0?g=0:-d+c>h?g=p:(g=-d+c,p=h));const T=Math.abs(g)0&&S<=this.length&&E.lengthSquared()=a.distance?null:h};Me.prototype._internalPick=function(a,e,t,i,s){let n=null;const r=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let r=0;r(this._tempPickingRay||(this._tempPickingRay=We.Zero()),this.createPickingRayToRef(a,e,r,this._tempPickingRay,s||null),this._tempPickingRay),t,i,!0);return n&&(n.ray=this.createPickingRay(a,e,N.Identity(),s||null)),n};Object.defineProperty(Me.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1});Me.prototype.pick=function(a,e,t,i,s,n,r=!1){const o=this._internalPick((l,h)=>(this._tempPickingRay||(this._tempPickingRay=We.Zero()),this.createPickingRayToRef(a,e,l,this._tempPickingRay,s||null,!1,h),this._tempPickingRay),t,i,!1,n);return o&&(o.ray=this.createPickingRay(a,e,N.Identity(),s||null)),o};Me.prototype.pickWithRay=function(a,e,t,i){const s=this._internalPick(n=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=N.Identity()),n.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=We.Zero()),We.TransformToRef(a,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t,!1,i);return s&&(s.ray=a),s};Me.prototype.multiPick=function(a,e,t,i,s){return this._internalMultiPick(n=>this.createPickingRay(a,e,n,i||null),t,s)};Me.prototype.multiPickWithRay=function(a,e,t){return this._internalMultiPick(i=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=N.Identity()),i.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=We.Zero()),We.TransformToRef(a,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t)};de.prototype.getForwardRay=function(a=100,e,t){return this.getForwardRayToRef(new We(v.Zero(),v.Zero(),a),a,e,t)};de.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),G.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),v.TransformNormalToRef(G.Vector3[2],t,G.Vector3[3]),v.NormalizeToRef(G.Vector3[3],a.direction),a};pe.prototype.setAlphaMode=function(a,e=!1){if(this._alphaMode===a&&(a===0&&!this._alphaState.alphaBlend||a!==0&&this._alphaState.alphaBlend)){if(!e){const t=a===0;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}return}switch(a){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0;break}e||(this.setDepthWrite(a===Y.ALPHA_DISABLE),this._cacheRenderPipeline.setDepthWriteEnabled(a===Y.ALPHA_DISABLE)),this._alphaMode=a,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};pe.prototype.setAlphaEquation=function(a){Y.prototype.setAlphaEquation.call(this,a),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};class bn{constructor(e,t,i,s=""){var n,r;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new ee,this.onErrorObservable=new ee,this.onBindObservable=new ee,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=at.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=bn._UniqueIdSeed++,this.defines=(n=t.defines)!==null&&n!==void 0?n:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=(r=t.entryPoint)!==null&&r!==void 0?r:"main",this._shaderStore=te.GetShadersStore(this._shaderLanguage),this._shaderRepository=te.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=te.GetIncludesShadersStore(this._shaderLanguage);let o;const l=Pt()?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 h={defines:this.defines.split("\n"),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","",c=>{Qi.Initialize(h),Qi.PreProcess(c,h,u=>{this._rawComputeSourceCode=c,t.processFinalCode&&(u=t.processFinalCode(u));const d=Qi.Finalize(u,"",h);this._useFinalCode(d.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+"\n"+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 r=Xr(e);s(r);return}if(e.substr(0,7)==="source:"){s(e.substr(7));return}if(e.substr(0,7)==="base64:"){const r=window.atob(e.substr(7));s(r);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 n;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?n=e:n=this._shaderRepository+e,this._engine._loadFile(n+"."+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 n=t.match(i);if(n&&n.length===2){const r=parseInt(n[1]),o=e.split("\n",-1);o.length>=r&&(s="Offending line [".concat(r,"] in compute code: ").concat(o[r-1]))}}return[e,s]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,H.Error("Unable to compile compute effect:"),H.Error("Defines:\r\n"+this.defines),bn.LogShaderCodeOnCompilationError){let s=null,n=null;!((i=this._pipelineContext)===null||i===void 0)&&i._getComputeShaderCode()&&([n,s]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),n&&(H.Error("Compute code:"),H.Error(n))),s&&H.Error(s)}H.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){te.GetShadersStore(at.WGSL)["".concat(e,"ComputeShader")]=t}}bn._UniqueIdSeed=0;bn.LogShaderCodeOnCompilationError=!0;var Bi;(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"})(Bi||(Bi={}));Ee.prototype.createComputeEffect=function(a,e){throw new Error("createComputeEffect: This engine does not support compute shaders!")};Ee.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")};Ee.prototype.createComputeContext=function(){};Ee.prototype.computeDispatch=function(a,e,t,i,s,n,r){throw new Error("computeDispatch: This engine does not support compute shaders!")};Ee.prototype.areAllComputeEffectsReady=function(){return!0};Ee.prototype.releaseComputeEffects=function(){};Ee.prototype._prepareComputePipelineContext=function(a,e,t,i,s){};Ee.prototype._rebuildComputeEffects=function(){};Ee.prototype._executeWhenComputeStateIsCompiled=function(a,e){e()};Ee.prototype._releaseComputeEffect=function(a){};Ee.prototype._deleteComputePipelineContext=function(a){};class ia{getBindGroups(e,t,i){if(!i)throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(this._bindGroups.length===0){const s=this._bindGroupEntries.length>0;for(const n in e){const r=e[n],o=i[n],l=o.group,h=o.binding,c=r.type,u=r.object;let d=r.indexInGroupEntries,_=this._bindGroupEntries[l];switch(_||(_=this._bindGroupEntries[l]=[]),c){case Bi.Sampler:{const f=u;d!==void 0&&s?_[d].resource=this._cacheSampler.getSampler(f):(r.indexInGroupEntries=_.length,_.push({binding:h,resource:this._cacheSampler.getSampler(f)}));break}case Bi.Texture:case Bi.TextureWithoutSampler:{const f=u,g=f._texture._hardwareTexture;d!==void 0&&s?(c===Bi.Texture&&(_[d++].resource=this._cacheSampler.getSampler(f._texture)),_[d].resource=g.view):(r.indexInGroupEntries=_.length,c===Bi.Texture&&_.push({binding:h-1,resource:this._cacheSampler.getSampler(f._texture)}),_.push({binding:h,resource:g.view}));break}case Bi.StorageTexture:{const f=u,g=f._texture._hardwareTexture;g.textureAdditionalUsages&it.StorageBinding||H.Error("computeDispatch: The texture (name=".concat(f.name,", uniqueId=").concat(f.uniqueId,") is not a storage texture!"),50),d!==void 0&&s?_[d].resource=g.viewForWriting:(r.indexInGroupEntries=_.length,_.push({binding:h,resource:g.viewForWriting}));break}case Bi.UniformBuffer:case Bi.StorageBuffer:{const g=(c===Bi.UniformBuffer,u).getBuffer(),p=g.underlyingResource;d!==void 0&&s?(_[d].resource.buffer=p,_[d].resource.size=g.capacity):(r.indexInGroupEntries=_.length,_.push({binding:h,resource:{buffer:p,offset:0,size:g.capacity}}));break}}}for(let n=0;n{this.computeDispatch(a,e,t,i,s,n,r)});return}const o=a._pipelineContext,l=e;o.computePipeline||(o.computePipeline=this._device.createComputePipeline({layout:Wn.Auto,compute:o.stage}));const c=this._renderTargetEncoder.beginComputePass();c.setPipeline(o.computePipeline);const u=l.getBindGroups(t,o.computePipeline,r);for(let d=0;d{const g=f,p=g[0].width,x=p;this._setCubeMapTextureParams(_,!i),_.format=r!=null?r:-1;const m=this._textureHelper.createGPUTextureForInternalTexture(_,p,x);this._textureHelper.updateCubeTextures(g,m.underlyingResource,p,x,m.format,!1,!1,0,0),i||this._generateMipmaps(_,this._uploadEncoder),_.isReady=!0,_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear(),s&&s()},!!d)};pe.prototype._setCubeMapTextureParams=function(a,e,t){a.samplingMode=e?3:2,a._cachedWrapU=0,a._cachedWrapV=0,t&&(a._maxLodLevel=t)};pe.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]))};pe.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]))};pe.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]))};pe.prototype._debugFlushPendingCommands=function(){for(let a=0;a{e==null||e.removePendingData(d),h&&g&&h(g.status+" "+g.statusText,p)},f=g=>{const p=d.width,x=r(g);if(!x)return;const m=[0,2,4,1,3,5];if(o){const T=i===4,S=o(x),b=d._hardwareTexture,y=[0,1,2,3,4,5];for(let E=0;E>E,C=[];for(let R=0;R<6;R++){let w=S[E][y[R]];T&&(w=nr(w,P,P,s)),C.push(new Uint8Array(w.buffer,w.byteOffset,w.byteLength))}this._textureHelper.updateCubeTextures(C,b.underlyingResource,P,P,b.format,u,!1,0,0)}}else{const T=[];for(let S=0;S<6;S++)T.push(x[m[S]]);this.updateRawCubeTexture(d,T,i,s,u)}d.isReady=!0,e==null||e.removePendingData(d),l&&l()};return this._loadFile(a,g=>{f(g)},void 0,e==null?void 0:e.offlineProvider,!0,_),d};pe.prototype.createRawTexture3D=function(a,e,t,i,s,n,r,o,l=null,h=0,c=0){const u=ze.Raw3D,d=new Dt(this,u);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=s,d.type=h,d.generateMipMaps=n,d.samplingMode=o,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,void 0,c),this.updateRawTexture3D(d,a,s,r,l,h),this._internalTexturesCache.push(d),d};pe.prototype.updateRawTexture3D=function(a,e,t,i,s=null,n=0){if(this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.invertY=i,a._compression=s),e){const r=a._hardwareTexture;t===4&&(e=nr(e,a.width,a.height,n));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,a,a.width,a.height,a.depth,r.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};pe.prototype.createRawTexture2DArray=function(a,e,t,i,s,n,r,o,l=null,h=0,c=0){const u=ze.Raw2DArray,d=new Dt(this,u);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=s,d.type=h,d.generateMipMaps=n,d.samplingMode=o,d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,i,c),this.updateRawTexture2DArray(d,a,s,r,l,h),this._internalTexturesCache.push(d),d};pe.prototype.updateRawTexture2DArray=function(a,e,t,i,s=null,n=0){if(this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.invertY=i,a._compression=s),e){const r=a._hardwareTexture;t===4&&(e=nr(e,a.width,a.height,n));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,a,a.width,a.height,a.depth,r.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};function nr(a,e,t,i){let s,n=1;i===1?s=new Float32Array(e*t*4):i===2?(s=new Uint16Array(e*t*4),n=15360):i===7?s=new Uint32Array(e*t*4):s=new Uint8Array(e*t*4);for(let r=0;r0,a.depth=l,a.isReady=!0,a.samples=n,a.generateMipMaps=!1,a.samplingMode=i?2:1,a.type=1,a._comparisonFunction=s,a._cachedWrapU=0,a._cachedWrapV=0};pe.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};pe.prototype.createRenderTargetCubeTexture=function(a,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,a),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer;const s=new Dt(this,ze.RenderTarget);return s.width=a,s.height=a,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=i.samples,s.generateMipMaps=i.generateMipMaps,s.samplingMode=i.samplingMode,s.type=i.type,s.format=i.format,this._internalTexturesCache.push(s),t.setTextures(s),(t._generateDepthBuffer||t._generateStencilBuffer)&&t.createDepthStencilTexture(0,i.samplingMode===void 0||i.samplingMode===2||i.samplingMode===2||i.samplingMode===3||i.samplingMode===3||i.samplingMode===5||i.samplingMode===6||i.samplingMode===7||i.samplingMode===11,t._generateStencilBuffer,t.samples),e&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),e&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!1),t};wt.prototype.setTextureSampler=function(a,e){this._engine.setTextureSampler(a,e)};pe.prototype.setTextureSampler=function(a,e){var t;(t=this._currentMaterialContext)===null||t===void 0||t.setSampler(a,e)};wt.prototype.setStorageBuffer=function(a,e){this._engine.setStorageBuffer(a,e)};pe.prototype.createStorageBuffer=function(a,e){return this._createBuffer(a,e|32)};pe.prototype.updateStorageBuffer=function(a,e,t,i){const s=a;t===void 0&&(t=0);let n;i===void 0?(e instanceof Array?n=new Float32Array(e):e instanceof ArrayBuffer?n=new Uint8Array(e):n=e,i=n.byteLength):e instanceof Array?n=new Float32Array(e):e instanceof ArrayBuffer?n=new Uint8Array(e):n=e,this._bufferManager.setSubData(s,t,n,0,i)};pe.prototype.readFromStorageBuffer=function(a,e,t,i){t=t||a.capacity;const s=this._bufferManager.createRawBuffer(t,Je.MapRead|Je.CopyDst);return this._renderTargetEncoder.copyBufferToBuffer(a.underlyingResource,e!=null?e:0,s,0,t),new Promise((n,r)=>{this.onEndFrameObservable.addOnce(()=>{s.mapAsync(Xs.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 h=l.constructor;l=new h(l.buffer),l.set(new h(o))}s.unmap(),this._bufferManager.releaseBuffer(s),n(l)},o=>r(o))})})};pe.prototype.setStorageBuffer=function(a,e){var t,i;(t=this._currentDrawContext)===null||t===void 0||t.setBuffer(a,(i=e==null?void 0:e.getBuffer())!==null&&i!==void 0?i:null)};pe.prototype.createUniformBuffer=function(a){let e;return a instanceof Array?e=new Float32Array(a):e=a,this._bufferManager.createBuffer(e,Je.Uniform|Je.CopyDst)};pe.prototype.createDynamicUniformBuffer=function(a){return this.createUniformBuffer(a)};pe.prototype.updateUniformBuffer=function(a,e,t,i){t===void 0&&(t=0);const s=a;let n;i===void 0?(e instanceof Float32Array?n=e:n=new Float32Array(e),i=n.byteLength):e instanceof Float32Array?n=e:n=new Float32Array(e),this._bufferManager.setSubData(s,t,n,0,i)};pe.prototype.bindUniformBufferBase=function(a,e,t){this._currentDrawContext.setBuffer(t,a)};pe.prototype.bindUniformBlock=function(){};function hg(a){return!!(a&&a.underlyingResource!==void 0)}pe.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)),hg(e)?(this._textureHelper.copyVideoToTexture(e,a,s.format,!t),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder),a.isReady=!0):e&&this.createImageBitmap(e).then(n=>{this._textureHelper.updateTexture(n,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})};var cg={value:()=>{}};function Hl(){for(var a=0,e=arguments.length,t={},i;a=0&&(i=t.slice(s+1),t=t.slice(0,s)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:i}})}Tr.prototype=Hl.prototype={constructor:Tr,on:function(a,e){var t=this._,i=ug(a+"",t),s,n=-1,r=i.length;if(arguments.length<2){for(;++n0)for(var t=new Array(s),i=0,s,n;i=0&&(e=a.slice(0,t))!=="xmlns"&&(a=a.slice(t+1)),Fo.hasOwnProperty(e)?{space:Fo[e],local:a}:a}function fg(a){return function(){var e=this.ownerDocument,t=this.namespaceURI;return t===Wa&&e.documentElement.namespaceURI===Wa?e.createElement(a):e.createElementNS(t,a)}}function _g(a){return function(){return this.ownerDocument.createElementNS(a.space,a.local)}}function M0(a){var e=sa(a);return(e.local?_g:fg)(e)}function pg(){}function P0(a){return a==null?pg:function(){return this.querySelector(a)}}function gg(a){typeof a!="function"&&(a=P0(a));for(var e=this._groups,t=e.length,i=new Array(t),s=0;s=T&&(T=m+1);!(b=p[T])&&++T=0;)(r=i[s])&&(n&&r.compareDocumentPosition(n)^4&&n.parentNode.insertBefore(r,n),n=r);return this}function Gg(a){a||(a=Wg);function e(u,d){return u&&d?a(u.__data__,d.__data__):!u-!d}for(var t=this._groups,i=t.length,s=new Array(i),n=0;ne?1:a>=e?0:NaN}function zg(){var a=arguments[0];return arguments[0]=this,a.apply(null,arguments),this}function Hg(){return Array.from(this)}function Xg(){for(var a=this._groups,e=0,t=a.length;e1?this.each((e==null?i1:typeof e=="function"?n1:s1)(a,e,t==null?"":t)):yn(this.node(),a)}function yn(a,e){return a.style.getPropertyValue(e)||jl(a).getComputedStyle(a,null).getPropertyValue(e)}function a1(a){return function(){delete this[a]}}function o1(a,e){return function(){this[a]=e}}function l1(a,e){return function(){var t=e.apply(this,arguments);t==null?delete this[a]:this[a]=t}}function h1(a,e){return arguments.length>1?this.each((e==null?a1:typeof e=="function"?l1:o1)(a,e)):this.node()[a]}function $l(a){return a.trim().split(/^|\s+/)}function w0(a){return a.classList||new Zl(a)}function Zl(a){this._node=a,this._names=$l(a.getAttribute("class")||"")}Zl.prototype={add:function(a){var e=this._names.indexOf(a);e<0&&(this._names.push(a),this._node.setAttribute("class",this._names.join(" ")))},remove:function(a){var e=this._names.indexOf(a);e>=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(a){return this._names.indexOf(a)>=0}};function Ql(a,e){for(var t=w0(a),i=-1,s=e.length;++i=0&&(t=e.slice(i+1),e=e.slice(0,i)),{type:e,name:t}})}function N1(a){return function(){var e=this.__on;if(e){for(var t=0,i=-1,s=e.length,n;t>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):t===8?pr(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):t===4?pr(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=Y1.exec(a))?new gi(e[1],e[2],e[3],1):(e=q1.exec(a))?new gi(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=j1.exec(a))?pr(e[1],e[2],e[3],e[4]):(e=$1.exec(a))?pr(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=Z1.exec(a))?Vo(e[1],e[2]/100,e[3]/100,1):(e=Q1.exec(a))?Vo(e[1],e[2]/100,e[3]/100,e[4]):Oo.hasOwnProperty(a)?No(Oo[a]):a==="transparent"?new gi(NaN,NaN,NaN,0):null}function No(a){return new gi(a>>16&255,a>>8&255,a&255,1)}function pr(a,e,t,i){return i<=0&&(a=e=t=NaN),new gi(a,e,t,i)}function tm(a){return a instanceof ar||(a=jn(a)),a?(a=a.rgb(),new gi(a.r,a.g,a.b,a.opacity)):new gi}function za(a,e,t,i){return arguments.length===1?tm(a):new gi(a,e,t,i==null?1:i)}function gi(a,e,t,i){this.r=+a,this.g=+e,this.b=+t,this.opacity=+i}D0(gi,za,sh(ar,{brighter(a){return a=a==null?Br:Math.pow(Br,a),new gi(this.r*a,this.g*a,this.b*a,this.opacity)},darker(a){return a=a==null?Yn:Math.pow(Yn,a),new gi(this.r*a,this.g*a,this.b*a,this.opacity)},rgb(){return this},clamp(){return new gi(js(this.r),js(this.g),js(this.b),Nr(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Uo,formatHex:Uo,formatHex8:im,formatRgb:ko,toString:ko}));function Uo(){return"#".concat(Hs(this.r)).concat(Hs(this.g)).concat(Hs(this.b))}function im(){return"#".concat(Hs(this.r)).concat(Hs(this.g)).concat(Hs(this.b)).concat(Hs((isNaN(this.opacity)?1:this.opacity)*255))}function ko(){const a=Nr(this.opacity);return"".concat(a===1?"rgb(":"rgba(").concat(js(this.r),", ").concat(js(this.g),", ").concat(js(this.b)).concat(a===1?")":", ".concat(a,")"))}function Nr(a){return isNaN(a)?1:Math.max(0,Math.min(1,a))}function js(a){return Math.max(0,Math.min(255,Math.round(a)||0))}function Hs(a){return a=js(a),(a<16?"0":"")+a.toString(16)}function Vo(a,e,t,i){return i<=0?a=e=t=NaN:t<=0||t>=1?a=e=NaN:e<=0&&(a=NaN),new Vi(a,e,t,i)}function nh(a){if(a instanceof Vi)return new Vi(a.h,a.s,a.l,a.opacity);if(a instanceof ar||(a=jn(a)),!a)return new Vi;if(a instanceof Vi)return a;a=a.rgb();var e=a.r/255,t=a.g/255,i=a.b/255,s=Math.min(e,t,i),n=Math.max(e,t,i),r=NaN,o=n-s,l=(n+s)/2;return o?(e===n?r=(t-i)/o+(t0&&l<1?0:r,new Vi(r,o,l,a.opacity)}function sm(a,e,t,i){return arguments.length===1?nh(a):new Vi(a,e,t,i==null?1:i)}function Vi(a,e,t,i){this.h=+a,this.s=+e,this.l=+t,this.opacity=+i}D0(Vi,sm,sh(ar,{brighter(a){return a=a==null?Br:Math.pow(Br,a),new Vi(this.h,this.s,this.l*a,this.opacity)},darker(a){return a=a==null?Yn:Math.pow(Yn,a),new Vi(this.h,this.s,this.l*a,this.opacity)},rgb(){var a=this.h%360+(this.h<0)*360,e=isNaN(a)||isNaN(this.s)?0:this.s,t=this.l,i=t+(t<.5?t:1-t)*e,s=2*t-i;return new gi(Ea(a>=240?a-240:a+120,s,i),Ea(a,s,i),Ea(a<120?a+240:a-120,s,i),this.opacity)},clamp(){return new Vi(Go(this.h),gr(this.s),gr(this.l),Nr(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const a=Nr(this.opacity);return"".concat(a===1?"hsl(":"hsla(").concat(Go(this.h),", ").concat(gr(this.s)*100,"%, ").concat(gr(this.l)*100,"%").concat(a===1?")":", ".concat(a,")"))}}));function Go(a){return a=(a||0)%360,a<0?a+360:a}function gr(a){return Math.max(0,Math.min(1,a||0))}function Ea(a,e,t){return(a<60?e+(t-e)*a/60:a<180?t:a<240?e+(t-e)*(240-a)/60:e)*255}const rh=a=>()=>a;function nm(a,e){return function(t){return a+t*e}}function rm(a,e,t){return a=Math.pow(a,t),e=Math.pow(e,t)-a,t=1/t,function(i){return Math.pow(a+i*e,t)}}function am(a){return(a=+a)==1?ah:function(e,t){return t-e?rm(e,t,a):rh(isNaN(e)?t:e)}}function ah(a,e){var t=e-a;return t?nm(a,t):rh(isNaN(a)?e:a)}const Wo=function a(e){var t=am(e);function i(s,n){var r=t((s=za(s)).r,(n=za(n)).r),o=t(s.g,n.g),l=t(s.b,n.b),h=ah(s.opacity,n.opacity);return function(c){return s.r=r(c),s.g=o(c),s.b=l(c),s.opacity=h(c),s+""}}return i.gamma=a,i}(1);function Rs(a,e){return a=+a,e=+e,function(t){return a*(1-t)+e*t}}var Ha=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ca=new RegExp(Ha.source,"g");function om(a){return function(){return a}}function lm(a){return function(e){return a(e)+""}}function hm(a,e){var t=Ha.lastIndex=Ca.lastIndex=0,i,s,n,r=-1,o=[],l=[];for(a=a+"",e=e+"";(i=Ha.exec(a))&&(s=Ca.exec(e));)(n=s.index)>t&&(n=e.slice(t,n),o[r]?o[r]+=n:o[++r]=n),(i=i[0])===(s=s[0])?o[r]?o[r]+=s:o[++r]=s:(o[++r]=null,l.push({i:r,x:Rs(i,s)})),t=Ca.lastIndex;return t180?c+=360:c-h>180&&(h+=360),d.push({i:u.push(s(u)+"rotate(",null,i)-2,x:Rs(h,c)})):c&&u.push(s(u)+"rotate("+c+i)}function o(h,c,u,d){h!==c?d.push({i:u.push(s(u)+"skewX(",null,i)-2,x:Rs(h,c)}):c&&u.push(s(u)+"skewX("+c+i)}function l(h,c,u,d,_,f){if(h!==u||c!==d){var g=_.push(s(_)+"scale(",null,",",null,")");f.push({i:g-4,x:Rs(h,u)},{i:g-2,x:Rs(c,d)})}else(u!==1||d!==1)&&_.push(s(_)+"scale("+u+","+d+")")}return function(h,c){var u=[],d=[];return h=a(h),c=a(c),n(h.translateX,h.translateY,c.translateX,c.translateY,u,d),r(h.rotate,c.rotate,u,d),o(h.skewX,c.skewX,u,d),l(h.scaleX,h.scaleY,c.scaleX,c.scaleY,u,d),h=c=null,function(_){for(var f=-1,g=d.length,p;++f=0&&a._call.call(void 0,e),a=a._next;--Tn}function Ho(){Zs=(kr=$n.now())+na,Tn=In=0;try{pm()}finally{Tn=0,mm(),Zs=0}}function gm(){var a=$n.now(),e=a-kr;e>hh&&(na-=e,kr=a)}function mm(){for(var a,e=Ur,t,i=1/0;e;)e._call?(i>e._time&&(i=e._time),a=e,e=e._next):(t=e._next,e._next=null,e=a?a._next=t:Ur=t);Mn=a,Ka(i)}function Ka(a){if(!Tn){In&&(In=clearTimeout(In));var e=a-Zs;e>24?(a<1/0&&(In=setTimeout(Ho,a-$n.now()-na)),Rn&&(Rn=clearInterval(Rn))):(Rn||(kr=$n.now(),Rn=setInterval(gm,hh)),Tn=1,ch(Ho))}}function Xo(a,e,t){var i=new Vr;return e=e==null?0:+e,i.restart(s=>{i.stop(),a(s+e)},e,t),i}var vm=Hl("start","end","cancel","interrupt"),xm=[],dh=0,Ko=1,Ya=2,Sr=3,Yo=4,qa=5,Ar=6;function ra(a,e,t,i,s,n){var r=a.__transition;if(!r)a.__transition={};else if(t in r)return;bm(a,t,{name:e,index:i,group:s,on:vm,tween:xm,time:n.time,delay:n.delay,duration:n.duration,ease:n.ease,timer:null,state:dh})}function O0(a,e){var t=Yi(a,e);if(t.state>dh)throw new Error("too late; already scheduled");return t}function es(a,e){var t=Yi(a,e);if(t.state>Sr)throw new Error("too late; already running");return t}function Yi(a,e){var t=a.__transition;if(!t||!(t=t[e]))throw new Error("transition not found");return t}function bm(a,e,t){var i=a.__transition,s;i[e]=t,t.timer=uh(n,0,t.time);function n(h){t.state=Ko,t.timer.restart(r,t.delay,t.time),t.delay<=h&&r(h-t.delay)}function r(h){var c,u,d,_;if(t.state!==Ko)return l();for(c in i)if(_=i[c],_.name===t.name){if(_.state===Sr)return Xo(r);_.state===Yo?(_.state=Ar,_.timer.stop(),_.on.call("interrupt",a,a.__data__,_.index,_.group),delete i[c]):+cYa&&i.state=0&&(e=e.slice(0,t)),!e||e==="start"})}function Zm(a,e,t){var i,s,n=$m(e)?O0:es;return function(){var r=n(this,a),o=r.on;o!==i&&(s=(i=o).copy()).on(e,t),r.on=s}}function Qm(a,e){var t=this._id;return arguments.length<2?Yi(this.node(),t).on.on(a):this.each(Zm(t,a,e))}function Jm(a){return function(){var e=this.parentNode;for(var t in this.__transition)if(+t!==a)return;e&&e.removeChild(this)}}function ev(){return this.on("end.remove",Jm(this._id))}function tv(a){var e=this._name,t=this._id;typeof a!="function"&&(a=P0(a));for(var i=this._groups,s=i.length,n=new Array(s),r=0;rn?n:Math.floor(r);const o=a.sideOrientation===0?0:a.sideOrientation||J.DEFAULTSIDE,l=a.uvs,h=a.colors,c=[],u=[],d=[],_=[],f=[],g=[],p=[],x=[];let m;const T=[],S=[];let b,y,E;if(e.length<2){const Ce=[],le=[];for(y=0;y0&&(D=R[E].subtract(R[E-1]).length(),W=D+p[b],f[b].push(W),p[b]=W),E++;i&&(E--,c.push(R[0].x,R[0].y,R[0].z),D=R[E].subtract(R[0]).length(),W=D+p[b],f[b].push(W),p[b]=W),T[b]=w+C,S[b]=P,P+=w+C}let L,z,K=null,ae=null;for(y=0;y{let f=i[0].length;const g=o;let p=0;const x=g._originalBuilderSideOrientation===O.DOUBLESIDE?2:1;for(let m=1;m<=x;++m)for(let T=0;TQs(a,{pathArray:e,closeArray:t,closePath:i,offset:s,updatable:r,sideOrientation:o,instance:l},n);function mh(a){const e=new Array,t=new Array,i=new Array,s=new Array,n=a.radius||.5,r=a.tessellation||64,o=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,l=a.sideOrientation===0?0:a.sideOrientation||J.DEFAULTSIDE;e.push(0,0,0),s.push(.5,.5);const h=Math.PI*2*o,c=o===1?h/r:h/(r-1);let u=0;for(let f=0;fvh(a,{radius:e,tessellation:t,sideOrientation:n,updatable:s},i);function xh(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 n=[];const r=a.width||a.size||1,o=a.height||a.size||1,l=a.depth||a.size||1,h=a.wrap||!1;let c=a.topBaseAt===void 0?1:a.topBaseAt,u=a.bottomBaseAt===void 0?0:a.bottomBaseAt;c=(c+4)%4,u=(u+4)%4;const d=[2,0,3,1],_=[2,0,1,3];let f=d[c],g=_[u],p=[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(h){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],p=[-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 E=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],P=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const C=[17,18,19,16],R=[22,23,20,21];for(;f>0;)E.unshift(E.pop()),C.unshift(C.pop()),f--;for(;g>0;)P.unshift(P.pop()),R.unshift(R.pop()),g--;E=E.flat(),P=P.flat(),p=p.concat(E).concat(P),t.push(C[0],C[2],C[3],C[0],C[1],C[2]),t.push(R[0],R[2],R[3],R[0],R[1],R[2])}const x=[r/2,o/2,l/2];n=p.reduce((E,P,C)=>E.concat(P*x[C%3]),[]);const m=a.sideOrientation===0?0:a.sideOrientation||J.DEFAULTSIDE,T=a.faceUV||new Array(6),S=a.faceColors,b=[];for(let E=0;E<6;E++)T[E]===void 0&&(T[E]=new Ye(0,0,1,1)),S&&S[E]===void 0&&(S[E]=new q(1,1,1,1));for(let E=0;E<6;E++)if(s.push(T[E].z,Ne.UseOpenGLOrientationForUV?1-T[E].w:T[E].w),s.push(T[E].x,Ne.UseOpenGLOrientationForUV?1-T[E].w:T[E].w),s.push(T[E].x,Ne.UseOpenGLOrientationForUV?1-T[E].y:T[E].y),s.push(T[E].z,Ne.UseOpenGLOrientationForUV?1-T[E].y:T[E].y),S)for(let P=0;P<4;P++)b.push(S[E].r,S[E].g,S[E].b,S[E].a);J._ComputeSides(m,n,t,i,s,a.frontUVs,a.backUVs);const y=new J;if(y.indices=t,y.positions=n,y.normals=i,y.uvs=s,S){const E=m===J.DOUBLESIDE?b.concat(b):b;y.colors=E}return y}function bh(a,e={},t=null){const i=new O(a,t);return e.sideOrientation=O._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,xh(e).applyToMesh(i,e.updatable),i}J.CreateBox=xh;O.CreateBox=(a,e,t=null,i,s)=>bh(a,{size:e,sideOrientation:s,updatable:i},t);function Un(a){const e=a.pattern||O.NO_FLIP,t=a.tileWidth||a.tileSize||1,i=a.tileHeight||a.tileSize||1,s=a.alignHorizontal||0,n=a.alignVertical||0,r=a.width||a.size||1,o=Math.floor(r/t);let l=r-o*t;const h=a.height||a.size||1,c=Math.floor(h/i);let u=h-c*i;const d=t*o/2,_=i*c/2;let f=0,g=0,p=0,x=0,m=0,T=0;if(l>0||u>0){switch(p=-d,x=-_,m=d,T=_,s){case O.CENTER:l/=2,p-=l,m+=l;break;case O.LEFT:m+=l,f=-l/2;break;case O.RIGHT:p-=l,f=l/2;break}switch(n){case O.CENTER:u/=2,x-=u,T+=u;break;case O.BOTTOM:T+=u,g=-u/2;break;case O.TOP:x-=u,g=u/2;break}}const S=[],b=[],y=[];y[0]=[0,0,1,0,1,1,0,1],y[1]=[0,0,1,0,1,1,0,1],(e===O.ROTATE_TILE||e===O.ROTATE_ROW)&&(y[1]=[1,1,0,1,0,0,1,0]),(e===O.FLIP_TILE||e===O.FLIP_ROW)&&(y[1]=[1,0,0,0,0,1,1,1]),(e===O.FLIP_N_ROTATE_TILE||e===O.FLIP_N_ROTATE_ROW)&&(y[1]=[0,1,1,1,1,0,0,0]);let E=[];const P=[],C=[];let R=0;for(let L=0;L0||u>0){const L=u>0&&(n===O.CENTER||n===O.TOP),z=u>0&&(n===O.CENTER||n===O.BOTTOM),K=l>0&&(s===O.CENTER||s===O.RIGHT),ae=l>0&&(s===O.CENTER||s===O.LEFT);let $=[],U,V,M,k;if(L&&K&&(S.push(p+f,x+g,0),S.push(-d+f,x+g,0),S.push(-d+f,x+u+g,0),S.push(p+f,x+u+g,0),C.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,U=1-l/t,V=1-u/i,M=1,k=1,$=[U,V,M,V,M,k,U,k],e===O.ROTATE_ROW&&($=[1-U,1-V,1-M,1-V,1-M,1-k,1-U,1-k]),e===O.FLIP_ROW&&($=[1-U,V,1-M,V,1-M,k,1-U,k]),e===O.FLIP_N_ROTATE_ROW&&($=[U,1-V,M,1-V,M,1-k,U,1-k]),E=E.concat($),P.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)),L&&ae&&(S.push(d+f,x+g,0),S.push(m+f,x+g,0),S.push(m+f,x+u+g,0),S.push(d+f,x+u+g,0),C.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,U=0,V=1-u/i,M=l/t,k=1,$=[U,V,M,V,M,k,U,k],(e===O.ROTATE_ROW||e===O.ROTATE_TILE&&o%2===0)&&($=[1-U,1-V,1-M,1-V,1-M,1-k,1-U,1-k]),(e===O.FLIP_ROW||e===O.FLIP_TILE&&o%2===0)&&($=[1-U,V,1-M,V,1-M,k,1-U,k]),(e===O.FLIP_N_ROTATE_ROW||e===O.FLIP_N_ROTATE_TILE&&o%2===0)&&($=[U,1-V,M,1-V,M,1-k,U,1-k]),E=E.concat($),P.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)),z&&K&&(S.push(p+f,_+g,0),S.push(-d+f,_+g,0),S.push(-d+f,T+g,0),S.push(p+f,T+g,0),C.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,U=1-l/t,V=0,M=1,k=u/i,$=[U,V,M,V,M,k,U,k],(e===O.ROTATE_ROW&&c%2===1||e===O.ROTATE_TILE&&c%1===0)&&($=[1-U,1-V,1-M,1-V,1-M,1-k,1-U,1-k]),(e===O.FLIP_ROW&&c%2===1||e===O.FLIP_TILE&&c%2===0)&&($=[1-U,V,1-M,V,1-M,k,1-U,k]),(e===O.FLIP_N_ROTATE_ROW&&c%2===1||e===O.FLIP_N_ROTATE_TILE&&c%2===0)&&($=[U,1-V,M,1-V,M,1-k,U,1-k]),E=E.concat($),P.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)),z&&ae&&(S.push(d+f,_+g,0),S.push(m+f,_+g,0),S.push(m+f,T+g,0),S.push(d+f,T+g,0),C.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,U=0,V=0,M=l/t,k=u/i,$=[U,V,M,V,M,k,U,k],(e===O.ROTATE_ROW&&c%2===1||e===O.ROTATE_TILE&&(c+o)%2===1)&&($=[1-U,1-V,1-M,1-V,1-M,1-k,1-U,1-k]),(e===O.FLIP_ROW&&c%2===1||e===O.FLIP_TILE&&(c+o)%2===1)&&($=[1-U,V,1-M,V,1-M,k,1-U,k]),(e===O.FLIP_N_ROTATE_ROW&&c%2===1||e===O.FLIP_N_ROTATE_TILE&&(c+o)%2===1)&&($=[U,1-V,M,1-V,M,1-k,U,1-k]),E=E.concat($),P.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)),L){const X=[];U=0,V=1-u/i,M=1,k=1,X[0]=[U,V,M,V,M,k,U,k],X[1]=[U,V,M,V,M,k,U,k],(e===O.ROTATE_TILE||e===O.ROTATE_ROW)&&(X[1]=[1-U,1-V,1-M,1-V,1-M,1-k,1-U,1-k]),(e===O.FLIP_TILE||e===O.FLIP_ROW)&&(X[1]=[1-U,V,1-M,V,1-M,k,1-U,k]),(e===O.FLIP_N_ROTATE_TILE||e===O.FLIP_N_ROTATE_ROW)&&(X[1]=[U,1-V,M,1-V,M,1-k,U,1-k]);for(let Q=0;QX+w)),w+=E[M].length,i)for(let X=0;X<4;X++)y.push(i[M].r,i[M].g,i[M].b,i[M].a)}const D=new v(0,0,g),W=N.RotationY(Math.PI);m=E[0].map(M=>v.TransformNormal(M,W).add(D)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[]),T=P[0].map(M=>v.TransformNormal(M,W)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[]),m=m.concat(E[1].map(M=>M.subtract(D)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[])),T=T.concat(P[1].map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[]));const L=new v(_,0,0),z=N.RotationY(-Math.PI/2);m=m.concat(E[2].map(M=>v.TransformNormal(M,z).add(L)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[])),T=T.concat(P[2].map(M=>v.TransformNormal(M,z)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[]));const K=N.RotationY(Math.PI/2);m=m.concat(E[3].map(M=>v.TransformNormal(M,K).subtract(L)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[])),T=T.concat(P[3].map(M=>v.TransformNormal(M,K)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[]));const ae=new v(0,f,0),$=N.RotationX(Math.PI/2);m=m.concat(E[4].map(M=>v.TransformNormal(M,$).add(ae)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[])),T=T.concat(P[4].map(M=>v.TransformNormal(M,$)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[]));const U=N.RotationX(-Math.PI/2);m=m.concat(E[5].map(M=>v.TransformNormal(M,U).subtract(ae)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[])),T=T.concat(P[5].map(M=>v.TransformNormal(M,U)).map(M=>[M.x,M.y,M.z]).reduce((M,k)=>M.concat(k),[])),J._ComputeSides(d,m,b,T,S);const V=new J;if(V.indices=b,V.positions=m,V.normals=T,V.uvs=S,i){const M=d===J.DOUBLESIDE?y.concat(y):y;V.colors=M}return V}function Rv(a,e,t=null){const i=new O(a,t);return e.sideOrientation=O._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,yh(e).applyToMesh(i,e.updatable),i}J.CreateTiledBox=yh;function Th(a){const e=a.segments||32,t=a.diameterX||a.diameter||1,i=a.diameterY||a.diameter||1,s=a.diameterZ||a.diameter||1,n=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,r=a.slice&&a.slice<=0?1:a.slice||1,o=a.sideOrientation===0?0:a.sideOrientation||J.DEFAULTSIDE,l=!!a.dedupTopBottomIndices,h=new v(t/2,i/2,s/2),c=2+e,u=2*c,d=[],_=[],f=[],g=[];for(let x=0;x<=c;x++){const m=x/c,T=m*Math.PI*r;for(let S=0;S<=u;S++){const b=S/u,y=b*Math.PI*2*n,E=N.RotationZ(-T),P=N.RotationY(y),C=v.TransformCoordinates(v.Up(),E),R=v.TransformCoordinates(C,P),w=R.multiply(h),D=R.divide(h).normalize();_.push(w.x,w.y,w.z),f.push(D.x,D.y,D.z),g.push(b,Ne.UseOpenGLOrientationForUV?1-m:m)}if(x>0){const S=_.length/3;for(let b=S-2*(u+1);b+u+21&&(d.push(b),d.push(b+1),d.push(b+u+1)),(xSh(a,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:n,updatable:s},i);function Ah(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,n=a.subdivisions||1,r=!!a.hasRings,o=!!a.enclose,l=a.cap===0?0:a.cap||O.CAP_ALL,h=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,c=a.sideOrientation===0?0:a.sideOrientation||J.DEFAULTSIDE,u=a.faceUV||new Array(3),d=a.faceColors,_=h!==1&&o?2:0,f=r?n:1,g=2+(1+_)*f;let p;for(p=0;p{const Pe=Te?t/2:i/2;if(Pe===0)return;let De,nt,Ce;const le=Te?u[g-1]:u[0];let Fe=null;d&&(Fe=Te?d[g-1]:d[0]);const ke=m.length/3,Xe=Te?e/2:-e/2,tt=new v(0,Xe,0);m.push(tt.x,tt.y,tt.z),T.push(0,Te?1:-1,0);const Gt=le.y+(le.w-le.y)*.5;S.push(le.x+(le.z-le.x)*.5,Ne.UseOpenGLOrientationForUV?1-Gt:Gt),Fe&&b.push(Fe.r,Fe.g,Fe.b,Fe.a);const Rt=new fe(.5,.5);for(Ce=0;Ce<=s;Ce++){De=Math.PI*2*Ce*h/s;const di=Math.cos(-De),ti=Math.sin(-De);nt=new v(di*Pe,Xe,ti*Pe);const Wt=new fe(di*Rt.x+.5,ti*Rt.y+.5);m.push(nt.x,nt.y,nt.z),T.push(0,Te?1:-1,0);const Ft=le.y+(le.w-le.y)*Wt.y;S.push(le.x+(le.z-le.x)*Wt.x,Ne.UseOpenGLOrientationForUV?1-Ft:Ft),Fe&&b.push(Fe.r,Fe.g,Fe.b,Fe.a)}for(Ce=0;Ce((r===void 0||!(r instanceof Me))&&(r!==void 0&&(l=o||O.DEFAULTSIDE,o=r),r=n,n=1),Eh(a,{height:e,diameterTop:t,diameterBottom:i,tessellation:s,subdivisions:n,sideOrientation:l,updatable:o},r));function Ch(a){const e=[],t=[],i=[],s=[],n=a.diameter||1,r=a.thickness||.5,o=a.tessellation||16,l=a.sideOrientation===0?0:a.sideOrientation||J.DEFAULTSIDE,h=o+1;for(let u=0;u<=o;u++){const d=u/o,_=u*Math.PI*2/o-Math.PI/2,f=N.Translation(n/2,0,0).multiply(N.RotationY(_));for(let g=0;g<=o;g++){const p=1-g/o,x=g*Math.PI*2/o+Math.PI,m=Math.cos(x),T=Math.sin(x);let S=new v(m,T,0),b=S.scale(r/2);const y=new fe(d,p);b=v.TransformCoordinates(b,f),S=v.TransformNormal(S,f),t.push(b.x,b.y,b.z),i.push(S.x,S.y,S.z),s.push(y.x,Ne.UseOpenGLOrientationForUV?1-y.y:y.y);const E=(u+1)%h,P=(g+1)%h;e.push(u*h+g),e.push(u*h+P),e.push(E*h+g),e.push(u*h+P),e.push(E*h+P),e.push(E*h+g)}}J._ComputeSides(l,t,e,i,s,a.frontUVs,a.backUVs);const c=new J;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Rh(a,e={},t){const i=new O(a,t);return e.sideOrientation=O._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Ch(e).applyToMesh(i,e.updatable),i}J.CreateTorus=Ch;O.CreateTorus=(a,e,t,i,s,n,r)=>Rh(a,{diameter:e,thickness:t,tessellation:i,sideOrientation:r,updatable:n},s);function Ih(a){const e=new Array,t=new Array,i=new Array,s=new Array,n=a.radius||2,r=a.tube||.5,o=a.radialSegments||32,l=a.tubularSegments||32,h=a.p||2,c=a.q||3,u=a.sideOrientation===0?0:a.sideOrientation||J.DEFAULTSIDE,d=p=>{const x=Math.cos(p),m=Math.sin(p),T=c/h*p,S=Math.cos(T),b=n*(2+S)*.5*x,y=n*(2+S)*m*.5,E=n*Math.sin(T)*.5;return new v(b,y,E)};let _,f;for(_=0;_<=o;_++){const x=_%o/o*2*h*Math.PI,m=d(x),T=d(x+.01),S=T.subtract(m);let b=T.add(m);const y=v.Cross(S,b);for(b=v.Cross(y,S),y.normalize(),b.normalize(),f=0;fMh(a,{radius:e,tube:t,radialSegments:i,tubularSegments:s,p:n,q:r,sideOrientation:h,updatable:l},o);function Ph(a){const e=[],t=[],i=a.lines,s=a.colors,n=[];let r=0;for(let l=0;l0&&(e.push(r-1),e.push(r)),r++}}const o=new J;return o.indices=e,o.positions=t,s&&(o.colors=n),o}function wh(a){const e=a.dashSize||3,t=a.gapSize||1,i=a.dashNb||200,s=a.points,n=new Array,r=new Array,o=v.Zero();let l=0,h=0,c=0,u=0,d=0,_=0,f=0;for(f=0;f{const u=v.Zero(),d=c.length/6;let _=0,f=0,g=0,p=0,x=0,m=0,T=0,S=0;for(T=0;TFh(a,{points:e,updatable:i,instance:s},t);O.CreateDashedLines=(a,e,t,i,s,n=null,r,o)=>Oh(a,{points:e,dashSize:t,gapSize:i,dashNb:s,updatable:r,instance:o},n);class Iv extends fe{constructor(e,t){super(e.x,e.y),this.index=t}}class Ra{constructor(){this.elements=new Array}add(e){const t=new Array;return e.forEach(i=>{const s=new Iv(i,this.elements.length);t.push(s),this.elements.push(s)}),t}computeBounds(){const e=new fe(this.elements[0].x,this.elements[0].y),t=new fe(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 Mv{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){this._points=new Ra,this._outlinepoints=new Ra,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||Ie.LastCreatedScene;let n;t instanceof r0?n=t.getPoints():n=t,this._addToepoint(n),this._points.add(n),this._outlinepoints.add(n),typeof this.bjsEarcut>"u"&&H.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new Ra;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 O(this._name,this._scene),n=this.buildVertexData(t,i);return s.setVerticesData(A.PositionKind,n.positions,e),s.setVerticesData(A.NormalKind,n.normals,e),s.setVerticesData(A.UVKind,n.uvs,e),s.setIndices(n.indices),s}buildVertexData(e=0,t=2){const i=new J,s=new Array,n=new Array,r=new Array,o=this._points.computeBounds();this._points.elements.forEach(c=>{s.push(0,1,0),n.push(c.x,0,c.y),r.push((c.x-o.min.x)/o.width,(c.y-o.min.y)/o.height)});const l=new Array,h=this.bjsEarcut(this._epoints,this._eholes,2);for(let c=0;c0){const c=n.length/3;this._points.elements.forEach(d=>{s.push(0,-1,0),n.push(d.x,-e,d.y),r.push(1-(d.x-o.min.x)/o.width,1-(d.y-o.min.y)/o.height)});const u=l.length;for(let d=0;d{this._addSide(n,s,r,l,o,d,e,!0,t)})}return i.indices=l,i.positions=n,i.normals=s,i.uvs=r,i}_addSide(e,t,i,s,n,r,o,l,h){let c=e.length/3,u=0;for(let d=0;dh?Eh?PB0(a,{shape:e,holes:i,updatable:s,sideOrientation:n},t,r);O.ExtrudePolygon=(a,e,t,i,s,n,r,o=earcut)=>Bh(a,{shape:e,holes:s,depth:t,updatable:n,sideOrientation:r},i,o);function Nh(a,e,t=null){const i=e.path,s=e.shape,n=e.scale||1,r=e.rotation||0,o=e.cap===0?0:e.cap||O.NO_CAP,l=e.updatable,h=O._GetDefaultSideOrientation(e.sideOrientation),c=e.instance||null,u=e.invertUV||!1,d=e.closeShape||!1,_=e.closePath||!1;return kh(a,s,i,n,r,null,null,_,d,o,!1,t,!!l,h,c,u,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function Uh(a,e,t=null){const i=e.path,s=e.shape,n=e.scaleFunction||(()=>1),r=e.rotationFunction||(()=>0),o=e.closePath||e.ribbonCloseArray||!1,l=e.closeShape||e.ribbonClosePath||!1,h=e.cap===0?0:e.cap||O.NO_CAP,c=e.updatable,u=e.firstNormal||null,d=e.adjustFrame||!1,_=O._GetDefaultSideOrientation(e.sideOrientation),f=e.instance,g=e.invertUV||!1;return kh(a,s,i,null,null,n,r,o,l,h,!0,t,!!c,_,f||null,g,e.frontUVs||null,e.backUVs||null,u,d)}function kh(a,e,t,i,s,n,r,o,l,h,c,u,d,_,f,g,p,x,m,T){const S=(C,R,w,D,W,L,z,K,ae,$,U)=>{const V=w.getTangents(),M=w.getNormals(),k=w.getBinormals(),X=w.getDistances();if(U){for(let le=0;le0){let Fe=V[le-1];v.Dot(Fe,V[le])<0&&V[le].scaleInPlace(-1),Fe=M[le-1],v.Dot(Fe,M[le])<0&&M[le].scaleInPlace(-1),Fe=k[le-1],v.Dot(Fe,k[le])<0&&k[le].scaleInPlace(-1)}}let Q=0;const ge=()=>W!==null?W:1,Te=$&&K?K:()=>L!==null?L:0,Pe=$&&z?z:ge;let De=ae===O.NO_CAP||ae===O.CAP_END?0:2;const nt=G.Matrix[0];for(let le=0;le{const Fe=Array(),ke=v.Zero();let Xe;for(Xe=0;Xe3?0:h,y=S(e,t,b,E,i,s,n,r,h,c,T);const P=Qs(a,{pathArray:y,closeArray:o,closePath:l,updatable:d,sideOrientation:_,invertUV:g,frontUVs:p||void 0,backUVs:x||void 0},u);return P._creationDataStorage.pathArray=y,P._creationDataStorage.path3D=b,P._creationDataStorage.cap=h,P}O.ExtrudeShape=(a,e,t,i,s,n,r=null,o,l,h)=>{const c={shape:e,path:t,scale:i,rotation:s,cap:n===0?0:n||O.NO_CAP,sideOrientation:l,instance:h,updatable:o};return Nh(a,c,r)};O.ExtrudeShapeCustom=(a,e,t,i,s,n,r,o,l,h,c,u)=>{const d={shape:e,path:t,scaleFunction:i,rotationFunction:s,ribbonCloseArray:n,ribbonClosePath:r,cap:o===0?0:o||O.NO_CAP,sideOrientation:c,instance:u,updatable:h};return Uh(a,d,l)};function Vh(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,n=e.shape,r=e.radius||1,o=e.tessellation||64,l=e.clip||0,h=e.updatable,c=O._GetDefaultSideOrientation(e.sideOrientation),u=e.cap||O.NO_CAP,d=Math.PI*2,_=new Array,f=e.invertUV||!1;let g=0,p=0;const x=d/o*i;let m,T;for(g=0;g<=o-l;g++){for(T=[],(u==O.CAP_START||u==O.CAP_ALL)&&(T.push(new v(0,n[0].y,0)),T.push(new v(Math.cos(g*x)*n[0].x*r,n[0].y,Math.sin(g*x)*n[0].x*r))),p=0;pVh(a,{shape:e,radius:t,tessellation:i,sideOrientation:r,updatable:n},s);function Gh(a){const e=[],t=[],i=[],s=[],n=a.width||a.size||1,r=a.height||a.size||1,o=a.sideOrientation===0?0:a.sideOrientation||J.DEFAULTSIDE,l=n/2,h=r/2;t.push(-l,-h,0),i.push(0,0,-1),s.push(0,Ne.UseOpenGLOrientationForUV?1:0),t.push(l,-h,0),i.push(0,0,-1),s.push(1,Ne.UseOpenGLOrientationForUV?1:0),t.push(l,h,0),i.push(0,0,-1),s.push(1,Ne.UseOpenGLOrientationForUV?0:1),t.push(-l,h,0),i.push(0,0,-1),s.push(0,Ne.UseOpenGLOrientationForUV?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),J._ComputeSides(o,t,e,i,s,a.frontUVs,a.backUVs);const c=new J;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Wh(a,e={},t=null){const i=new O(a,t);return e.sideOrientation=O._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Gh(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}J.CreatePlane=Gh;O.CreatePlane=(a,e,t,i,s)=>Wh(a,{size:e,width:e,height:e,sideOrientation:s,updatable:i},t);O._GroundMeshParser=(a,e)=>or.Parse(a,e);class or extends O{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=G.Matrix[5];i.invertToRef(s);const n=G.Vector3[8];if(v.TransformCoordinatesFromFloatsToRef(e,0,t,s,n),e=n.x,t=n.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 r=this._getFacetAt(e,t),o=-(r.x*e+r.z*t+r.w)/r.y;return v.TransformCoordinatesFromFloatsToRef(0,o,0,i,n),n.y}getNormalAtCoordinates(e,t){const i=new v(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),n=G.Matrix[5];s.invertToRef(n);const r=G.Vector3[8];if(v.TransformCoordinatesFromFloatsToRef(e,0,t,n,r),e=r.x,t=r.z,ethis._maxX||tthis._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return v.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),n=this._heightQuads[s*this._subdivisionsX+i];let r;return ta.maxHeight){h=!0;const u=a.maxHeight;a.maxHeight=a.minHeight,a.minHeight=u}for(n=0;n<=a.subdivisions;n++)for(r=0;r<=a.subdivisions;r++){const u=new v(r*a.width/a.subdivisions-a.width/2,0,(a.subdivisions-n)*a.height/a.subdivisions-a.height/2),d=(u.x+a.width/2)/a.width*(a.bufferWidth-1)|0,_=(1-(u.z+a.height/2)/a.height)*(a.bufferHeight-1)|0,f=(d+_*a.bufferWidth)*4;let g=a.buffer[f]/255,p=a.buffer[f+1]/255,x=a.buffer[f+2]/255;const m=a.buffer[f+3]/255;h&&(g=1-g,p=1-p,x=1-x);const T=g*o.r+p*o.g+x*o.b;m>=l?u.y=a.minHeight+(a.maxHeight-a.minHeight)*T:u.y=a.minHeight-Ge,t.push(u.x,u.y,u.z),i.push(0,0,0),s.push(r/a.subdivisions,1-n/a.subdivisions)}for(n=0;n=a.minHeight,p=t[d*3+1]>=a.minHeight,x=t[_*3+1]>=a.minHeight;g&&p&&x&&(e.push(u),e.push(d),e.push(_)),t[f*3+1]>=a.minHeight&&g&&x&&(e.push(f),e.push(u),e.push(_))}J.ComputeNormals(t,e,i);const c=new J;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Kh(a,e={},t){const i=new or(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,zh(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function Yh(a,e,t=null){const i=new O(a,t);return Hh(e).applyToMesh(i,e.updatable),i}function qh(a,e,t={},i=null){const s=t.width||10,n=t.height||10,r=t.subdivisions||1,o=t.minHeight||0,l=t.maxHeight||1,h=t.colorFilter||new he(.3,.59,.11),c=t.alphaFilter||0,u=t.updatable,d=t.onReady;i=i||Ie.LastCreatedScene;const _=new or(a,i);_._subdivisionsX=r,_._subdivisionsY=r,_._width=s,_._height=n,_._maxX=_._width/2,_._maxZ=_._height/2,_._minX=-_._maxX,_._minZ=-_._maxZ,_._setReady(!1);const f=g=>{const p=g.width,x=g.height;if(i.isDisposed)return;const m=i==null?void 0:i.getEngine().resizeImageBitmap(g,p,x);Xh({width:s,height:n,subdivisions:r,minHeight:o,maxHeight:l,colorFilter:h,buffer:m,bufferWidth:p,bufferHeight:x,alphaFilter:c}).applyToMesh(_,u),d&&d(_),_._setReady(!0)};return re.LoadImage(e,f,()=>{},i.offlineProvider),_}J.CreateGround=zh;J.CreateTiledGround=Hh;J.CreateGroundFromHeightMap=Xh;O.CreateGround=(a,e,t,i,s,n)=>Kh(a,{width:e,height:t,subdivisions:i,updatable:n},s);O.CreateTiledGround=(a,e,t,i,s,n,r,o,l)=>Yh(a,{xmin:e,zmin:t,xmax:i,zmax:s,subdivisions:n,precision:r,updatable:l},o);O.CreateGroundFromHeightMap=(a,e,t,i,s,n,r,o,l,h,c)=>qh(a,e,{width:t,height:i,subdivisions:s,minHeight:n,maxHeight:r,updatable:l,onReady:h,alphaFilter:c},o);function jh(a,e,t=null){const i=e.path;let s=e.instance,n=1;e.radius!==void 0?n=e.radius:s&&(n=s._creationDataStorage.radius);const r=e.tessellation||64,o=e.radiusFunction||null;let l=e.cap||O.NO_CAP;const h=e.invertUV||!1,c=e.updatable,u=O._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const d=(x,m,T,S,b,y,E,P)=>{const C=m.getTangents(),R=m.getNormals(),w=m.getDistances(),W=Math.PI*2/b*P,z=y||(()=>S);let K,ae,$,U;const V=G.Matrix[0];let M=E===O.NO_CAP||E===O.CAP_END?0:2;for(let X=0;X{const ge=Array();for(let ye=0;ye3?0:l,f=d(i,_,g,n,r,o,l,e.arc);const p=Qs(a,{pathArray:f,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return p._creationDataStorage.pathArray=f,p._creationDataStorage.path3D=_,p._creationDataStorage.tessellation=r,p._creationDataStorage.cap=l,p._creationDataStorage.arc=e.arc,p._creationDataStorage.radius=n,p}O.CreateTube=(a,e,t,i,s,n,r,o,l,h)=>jh(a,{path:e,radius:t,tessellation:i,radiusFunction:s,arc:1,cap:n,updatable:o,sideOrientation:l,instance:h},r);function $h(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,n=a.sizeY||i||1,r=a.sizeZ||i||1,o=a.custom||e[t],l=o.face.length,h=a.faceUV||new Array(l),c=a.faceColors,u=a.flat===void 0?!0:a.flat,d=a.sideOrientation===0?0:a.sideOrientation||J.DEFAULTSIDE,_=new Array,f=new Array,g=new Array,p=new Array,x=new Array;let m=0,T=0;const S=new Array;let b=0,y=0,E,P,C,R,w,D;if(u)for(y=0;yN0(a,e,t);function Zh(a){const e=a.sideOrientation||J.DEFAULTSIDE,t=a.radius||1,i=a.flat===void 0?!0:a.flat,s=a.subdivisions||4,n=a.radiusX||t,r=a.radiusY||t,o=a.radiusZ||t,l=(1+Math.sqrt(5))/2,h=[-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],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],_=138/1024,f=239/1024,g=60/1024,p=26/1024,x=-40/1024,m=20/1024,T=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],S=new Array,b=new Array,y=new Array,E=new Array;let P=0;const C=new Array(3),R=new Array(3);let w;for(w=0;w<3;w++)C[w]=v.Zero(),R[w]=fe.Zero();for(let W=0;W<20;W++){for(w=0;w<3;w++){const z=c[3*W+w];C[w].copyFromFloats(h[3*u[z]],h[3*u[z]+1],h[3*u[z]+2]),C[w].normalize(),R[w].copyFromFloats(d[2*z]*_+g+T[W]*x,d[2*z+1]*f+p+T[W]*m)}const L=(z,K,ae,$)=>{const U=v.Lerp(C[0],C[2],K/s),V=v.Lerp(C[1],C[2],K/s),M=s===K?C[2]:v.Lerp(U,V,z/(s-K));M.normalize();let k;if(i){const ye=v.Lerp(C[0],C[2],$/s),Te=v.Lerp(C[1],C[2],$/s);k=v.Lerp(ye,Te,ae/(s-$))}else k=new v(M.x,M.y,M.z);k.x/=n,k.y/=r,k.z/=o,k.normalize();const X=fe.Lerp(R[0],R[2],K/s),Q=fe.Lerp(R[1],R[2],K/s),ge=s===K?R[2]:fe.Lerp(X,Q,z/(s-K));b.push(M.x*n,M.y*r,M.z*o),y.push(k.x,k.y,k.z),E.push(ge.x,Ne.UseOpenGLOrientationForUV?1-ge.y:ge.y),S.push(P),P++};for(let z=0;zQh(a,e,t);const Pv=new v(1,0,0),wv=new v(-1,0,0),Dv=new v(0,1,0),Fv=new v(0,-1,0),Ov=new v(0,0,1),Lv=new v(0,0,-1);class Gr{constructor(e=v.Zero(),t=v.Up(),i=fe.Zero(),s=0,n=0,r=null,o=null,l=null,h=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=n,this.localPositionOverride=r,this.localNormalOverride=o,this.matrixIndicesOverride=l,this.matrixWeightsOverride=h}clone(){var e,t,i,s;return new Gr(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 Jh(a,e,t){const i=!!e.skeleton,s=t.localMode||i,n=e.overrideMaterialSideOrientation!==null&&e.overrideMaterialSideOrientation!==void 0,r=e.getIndices(),o=i?e.getPositionData(!0,!0):e.getVerticesData(A.PositionKind),l=i?e.getNormalsData(!0,!0):e.getVerticesData(A.NormalKind),h=s?i?e.getVerticesData(A.PositionKind):o:null,c=s?i?e.getVerticesData(A.NormalKind):l:null,u=e.getVerticesData(A.UVKind),d=i?e.getVerticesData(A.MatricesIndicesKind):null,_=i?e.getVerticesData(A.MatricesWeightsKind):null,f=i?e.getVerticesData(A.MatricesIndicesExtraKind):null,g=i?e.getVerticesData(A.MatricesWeightsExtraKind):null,p=t.position||v.Zero();let x=t.normal||v.Up();const m=t.size||v.One(),T=t.angle||0;if(!x){const $=new v(0,0,1),U=e.getScene().activeCamera,V=v.TransformCoordinates($,U.getWorldMatrix());x=U.globalPosition.subtract(V)}const S=-Math.atan2(x.z,x.x)-Math.PI/2,b=Math.sqrt(x.x*x.x+x.z*x.z),y=Math.atan2(x.y,b),E=N.RotationYawPitchRoll(S,y,T).multiply(N.Translation(p.x,p.y,p.z)),P=N.Invert(E),R=e.getWorldMatrix().multiply(P),w=new J;w.indices=[],w.positions=[],w.normals=[],w.uvs=[],w.matricesIndices=i?[]:null,w.matricesWeights=i?[]:null,w.matricesIndicesExtra=f?[]:null,w.matricesWeightsExtra=g?[]:null;let D=0;const W=$=>{const U=new Gr;if(!r||!o||!l)return U;const V=r[$];if(U.vertexIdx=V*3,U.vertexIdxForBones=V*4,U.position=new v(o[V*3],o[V*3+1],o[V*3+2]),v.TransformCoordinatesToRef(U.position,R,U.position),U.normal=new v(l[V*3],l[V*3+1],l[V*3+2]),v.TransformNormalToRef(U.normal,R,U.normal),t.captureUVS&&u){const M=u[V*2+1];U.uv=new fe(u[V*2],Ne.UseOpenGLOrientationForUV?1-M:M)}return U},L=[0,0,0,0],z=($,U)=>{if($.length===0)return $;const V=.5*Math.abs(v.Dot(m,U)),M=(Q,ge,ye,Te)=>{for(let Pe=0;Pe{var ye,Te,Pe,De,nt,Ce,le,Fe,ke,Xe,tt,Gt,Rt,di,ti,Wt;const Ft=v.GetClipFactor(Q.position,ge.position,U,V);let ms=L,Ot=L;if(d&&_){const An=Q.matrixIndicesOverride?0:Q.vertexIdxForBones,_a=(ye=Q.matrixIndicesOverride)!==null&&ye!==void 0?ye:d,W0=(Te=Q.matrixWeightsOverride)!==null&&Te!==void 0?Te:_,pa=ge.matrixIndicesOverride?0:ge.vertexIdxForBones,z0=(Pe=ge.matrixIndicesOverride)!==null&&Pe!==void 0?Pe:d,H0=(De=ge.matrixWeightsOverride)!==null&&De!==void 0?De:_;ms=[0,0,0,0],Ot=[0,0,0,0];let Us=0;for(let Fi=0;Fi<4;++Fi)if(W0[An+Fi]>0){const En=M(z0,_a[An+Fi],pa,4);ms[Us]=_a[An+Fi],Ot[Us]=me.Lerp(W0[An+Fi],En>=0?H0[En]:0,Ft),Us++}for(let Fi=0;Fi<4&&Us<4;++Fi){const En=z0[pa+Fi];M(_a,En,An,4)===-1&&(ms[Us]=En,Ot[Us]=me.Lerp(0,H0[pa+Fi],Ft),Us++)}const lr=Ot[0]+Ot[1]+Ot[2]+Ot[3];Ot[0]/=lr,Ot[1]/=lr,Ot[2]/=lr,Ot[3]/=lr}const ai=Q.localPositionOverride?Q.localPositionOverride[0]:(nt=h==null?void 0:h[Q.vertexIdx])!==null&&nt!==void 0?nt:0,Ai=Q.localPositionOverride?Q.localPositionOverride[1]:(Ce=h==null?void 0:h[Q.vertexIdx+1])!==null&&Ce!==void 0?Ce:0,$t=Q.localPositionOverride?Q.localPositionOverride[2]:(le=h==null?void 0:h[Q.vertexIdx+2])!==null&&le!==void 0?le:0,fi=ge.localPositionOverride?ge.localPositionOverride[0]:(Fe=h==null?void 0:h[ge.vertexIdx])!==null&&Fe!==void 0?Fe:0,vs=ge.localPositionOverride?ge.localPositionOverride[1]:(ke=h==null?void 0:h[ge.vertexIdx+1])!==null&&ke!==void 0?ke:0,ha=ge.localPositionOverride?ge.localPositionOverride[2]:(Xe=h==null?void 0:h[ge.vertexIdx+2])!==null&&Xe!==void 0?Xe:0,k0=Q.localNormalOverride?Q.localNormalOverride[0]:(tt=c==null?void 0:c[Q.vertexIdx])!==null&&tt!==void 0?tt:0,V0=Q.localNormalOverride?Q.localNormalOverride[1]:(Gt=c==null?void 0:c[Q.vertexIdx+1])!==null&&Gt!==void 0?Gt:0,G0=Q.localNormalOverride?Q.localNormalOverride[2]:(Rt=c==null?void 0:c[Q.vertexIdx+2])!==null&&Rt!==void 0?Rt:0,oc=ge.localNormalOverride?ge.localNormalOverride[0]:(di=c==null?void 0:c[ge.vertexIdx])!==null&&di!==void 0?di:0,lc=ge.localNormalOverride?ge.localNormalOverride[1]:(ti=c==null?void 0:c[ge.vertexIdx+1])!==null&&ti!==void 0?ti:0,hc=ge.localNormalOverride?ge.localNormalOverride[2]:(Wt=c==null?void 0:c[ge.vertexIdx+2])!==null&&Wt!==void 0?Wt:0,ca=k0+(oc-k0)*Ft,ua=V0+(lc-V0)*Ft,da=G0+(hc-G0)*Ft,fa=Math.sqrt(ca*ca+ua*ua+da*da);return new Gr(v.Lerp(Q.position,ge.position,Ft),v.Lerp(Q.normal,ge.normal,Ft).normalize(),fe.Lerp(Q.uv,ge.uv,Ft),-1,-1,h?[ai+(fi-ai)*Ft,Ai+(vs-Ai)*Ft,$t+(ha-$t)*Ft]:null,c?[ca/fa,ua/fa,da/fa]:null,ms,Ot)};let X=null;$.length>3&&(X=new Array);for(let Q=0;Q<$.length;Q+=3){let ge=0,ye=null,Te=null,Pe=null,De=null;const nt=v.Dot($[Q].position,U)-V,Ce=v.Dot($[Q+1].position,U)-V,le=v.Dot($[Q+2].position,U)-V,Fe=nt>0,ke=Ce>0,Xe=le>0;switch(ge=(Fe?1:0)+(ke?1:0)+(Xe?1:0),ge){case 0:$.length>3?(X.push($[Q]),X.push($[Q+1]),X.push($[Q+2])):X=$;break;case 1:if(X=X!=null?X:new Array,Fe&&(ye=$[Q+1],Te=$[Q+2],Pe=k($[Q],ye),De=k($[Q],Te)),ke){ye=$[Q],Te=$[Q+2],Pe=k($[Q+1],ye),De=k($[Q+1],Te),X.push(Pe),X.push(Te.clone()),X.push(ye.clone()),X.push(Te.clone()),X.push(Pe.clone()),X.push(De);break}Xe&&(ye=$[Q],Te=$[Q+1],Pe=k($[Q+2],ye),De=k($[Q+2],Te)),ye&&Te&&Pe&&De&&(X.push(ye.clone()),X.push(Te.clone()),X.push(Pe),X.push(De),X.push(Pe.clone()),X.push(Te.clone()));break;case 2:X=X!=null?X:new Array,Fe||(ye=$[Q].clone(),Te=k(ye,$[Q+1]),Pe=k(ye,$[Q+2]),X.push(ye),X.push(Te),X.push(Pe)),ke||(ye=$[Q+1].clone(),Te=k(ye,$[Q+2]),Pe=k(ye,$[Q]),X.push(ye),X.push(Te),X.push(Pe)),Xe||(ye=$[Q+2].clone(),Te=k(ye,$[Q]),Pe=k(ye,$[Q+1]),X.push(ye),X.push(Te),X.push(Pe));break}}return X},K=new Array(3);for(let $=0;$Jh(a,e,{position:t,normal:i,size:s,angle:n});function ec(a={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(a.subdivisions?a.subdivisions:2,1),t=Math.max(a.tessellation?a.tessellation:16,3),i=Math.max(a.height?a.height:1,0),s=Math.max(a.radius?a.radius:.25,0),n=Math.max(a.capSubdivisions?a.capSubdivisions:6,1),r=t,o=e,l=Math.max(a.radiusTop?a.radiusTop:s,0),h=Math.max(a.radiusBottom?a.radiusBottom:s,0),c=i-(l+h),u=0,d=2*Math.PI,_=Math.max(a.topCapSubdivisions?a.topCapSubdivisions:n,1),f=Math.max(a.bottomCapSubdivisions?a.bottomCapSubdivisions:n,1),g=Math.acos((h-l)/i);let p=[];const x=[],m=[],T=[];let S=0;const b=[],y=c*.5,E=Math.PI*.5;let P,C;const R=v.Zero(),w=v.Zero(),D=Math.cos(g),W=Math.sin(g),L=new fe(l*W,y+l*D).subtract(new fe(h*W,-y+h*D)).length(),z=l*g+L+h*(E-g);let K=0;for(C=0;C<=_;C++){const V=[],M=E-g*(C/_);K+=l*g/_;const k=Math.cos(M),X=Math.sin(M),Q=k*l;for(P=0;P<=r;P++){const ge=P/r,ye=ge*d+u,Te=Math.sin(ye),Pe=Math.cos(ye);w.x=Q*Te,w.y=y+X*l,w.z=Q*Pe,x.push(w.x,w.y,w.z),R.set(k*Te,X,k*Pe),m.push(R.x,R.y,R.z),T.push(ge,Ne.UseOpenGLOrientationForUV?K/z:1-K/z),V.push(S),S++}b.push(V)}const ae=i-l-h+D*l-D*h,$=W*(h-l)/ae;for(C=1;C<=o;C++){const V=[];K+=L/o;const M=W*(C*(h-l)/o+l);for(P=0;P<=r;P++){const k=P/r,X=k*d+u,Q=Math.sin(X),ge=Math.cos(X);w.x=M*Q,w.y=y+D*l-C*ae/o,w.z=M*ge,x.push(w.x,w.y,w.z),R.set(Q,$,ge).normalize(),m.push(R.x,R.y,R.z),T.push(k,Ne.UseOpenGLOrientationForUV?K/z:1-K/z),V.push(S),S++}b.push(V)}for(C=1;C<=f;C++){const V=[],M=E-g-(Math.PI-g)*(C/f);K+=h*g/f;const k=Math.cos(M),X=Math.sin(M),Q=k*h;for(P=0;P<=r;P++){const ge=P/r,ye=ge*d+u,Te=Math.sin(ye),Pe=Math.cos(ye);w.x=Q*Te,w.y=-y+X*h,w.z=Q*Pe,x.push(w.x,w.y,w.z),R.set(k*Te,X,k*Pe),m.push(R.x,R.y,R.z),T.push(ge,Ne.UseOpenGLOrientationForUV?K/z:1-K/z),V.push(S),S++}b.push(V)}for(P=0;Ptc(a,e,t);J.CreateCapsule=ec;class ut{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&H.Warn("x is not an integer, floor(x) used"),t!==Math.floor(t)&&H.Warn("y is not an integer, floor(y) used")}clone(){return new ut(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)&&H.Warn("m not an integer only floor(m) used"),t!==Math.floor(t)&&H.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)&&H.Warn("m is not an integer, floor(m) used"),t!==Math.floor(t)&&H.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=v.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 ut(0,0)}}class ic{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new ja("icosahedron","Regular",[[0,xt,-1],[-xt,1,0],[-1,0,-xt],[1,0,-xt],[xt,1,0],[0,xt,1],[-1,0,xt],[-xt,-1,0],[0,-xt,-1],[xt,-1,0],[1,0,xt],[0,-xt,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 n=i,r=1,o=0;s!==0&&(n=me.HCF(i,s)),r=i/n,o=s/n;let l,h,c,u,d;const _=ut.Zero(),f=new ut(i,s),g=new ut(-s,i+s),p=ut.Zero(),x=ut.Zero(),m=ut.Zero();let T=[],S,b,y,E;const P=[],C=this.vertByDist,R=(w,D,W,L)=>{S=w+"|"+W,b=D+"|"+L,S in t||b in t?S in t&&!(b in t)?t[b]=t[S]:b in t&&!(S in t)&&(t[S]=t[b]):(t[S]=e,t[b]=e,e++),C[W][0]>2?P[t[S]]=[-C[W][0],C[W][1],t[S]]:P[t[S]]=[T[C[W][0]],C[W][1],t[S]]};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 w=0;w<20;w++){if(T=this.IDATA.face[w],c=T[2],u=T[1],d=T[0],y=_.x+"|"+_.y,S=w+"|"+y,S in t||(t[S]=c,P[c]=[T[C[y][0]],C[y][1]]),y=f.x+"|"+f.y,S=w+"|"+y,S in t||(t[S]=u,P[u]=[T[C[y][0]],C[y][1]]),y=g.x+"|"+g.y,S=w+"|"+y,S in t||(t[S]=d,P[d]=[T[C[y][0]],C[y][1]]),l=this.IDATA.edgematch[w][0],h=this.IDATA.edgematch[w][1],h==="B")for(let D=1;D2?P[t[S]]=[-C[y][0],C[y][1],t[S]]:P[t[S]]=[T[C[y][0]],C[y][1],t[S]])}this.closestTo=P,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=me.HCF(e,t),y=e/b,E=t/b;for(let C=1;Cb.x-y.x),i.sort((b,y)=>b.y-y.y);const o=new Array(e+t+1),l=new Array(e+t+1);for(let b=0;b{const E=b.clone();return y==="A"&&E.rotateNeg120(e,t),y==="B"&&E.rotate120(e,t),E.x<0?E.y:E.x+E.y},_=[],f=[],g=[],p=[],x={},m=[];let T=-1,S=-1;for(let b=0;bb[2]-y[2]),m.sort((b,y)=>b[3]-y[3]),m.sort((b,y)=>b[1]-y[1]),m.sort((b,y)=>b[0]-y[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[r][1]>0&&t[i[r][0]].push([r,i[r][1]]):t[12].push([r,i[r][0]]);const s=[];for(let r=0;r<12;r++)s[r]=r;let n=12;for(let r=0;r<12;r++){t[r].sort((o,l)=>o[1]-l[1]);for(let o=0;or[3]-o[3]);for(let r=0;r0;)n=t[l],this.face[n].indexOf(o)>-1?(r=(this.face[n].indexOf(o)+1)%3,o=this.face[n][r],i.push(o),s.push(n),t.splice(l,1),l=0):l++;return this.adjacentFaces.push(i),s}toGoldbergPolyhedronData(){const e=new ja("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let h=0;h{s=0,n=0,r=0,o=this.face[c];for(let u=0;u<3;u++)l=this.vertex[o[u]],s+=l[0],n+=l[1],r+=l[2];e.vertex[c]=[s/3,n/3,r/3]});return e}static BuildGeodesicData(e){const t=new aa("Geodesic-m-n","Geodesic",[[0,xt,-1],[-xt,1,0],[-1,0,-xt],[1,0,-xt],[xt,1,0],[0,xt,1],[-1,0,xt],[-xt,-1,0],[0,-xt,-1],[xt,-1,0],[1,0,xt],[0,-xt,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let s=0;si){const h=s;s=i,i=h,H.Warn("n > m therefore m and n swapped")}const n=new ic;n.build(i,s);const o={custom:aa.BuildGeodesicData(n),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 N0(a,o,t)}O._GoldbergMeshParser=(a,e)=>oa.Parse(a,e);class oa extends O{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&&(H.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(H.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(H.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),h.push(u,d);for(let _=0;_<6;_++)u=r.x+o*Math.cos(l+_*Math.PI/3),d=r.y+o*Math.sin(l+_*Math.PI/3),u<0&&(u=0),u>1&&(u=1),c.push(u,d);for(let _=s;_q.FromArray(n)),i.faceCenters=i.faceCenters.map(n=>v.FromArray(n)),i.faceZaxis=i.faceZaxis.map(n=>v.FromArray(n)),i.faceXaxis=i.faceXaxis.map(n=>v.FromArray(n)),i.faceYaxis=i.faceYaxis.map(n=>v.FromArray(n));const s=new oa(e.name,t);return s.goldbergData=i,s}}function Nv(a,e){const t=a.size,i=a.sizeX||t||1,s=a.sizeY||t||1,n=a.sizeZ||t||1,r=a.sideOrientation===0?0:a.sideOrientation||J.DEFAULTSIDE,o=new Array,l=new Array,h=new Array,c=new Array;let u=1/0,d=-1/0,_=1/0,f=-1/0;for(let x=0;xo){const f=l;l=o,o=f,H.Warn("n > m therefore m and n swapped")}const h=new ic;h.build(o,l);const c=aa.BuildGeodesicData(h),u=c.toGoldbergPolyhedronData(),d=new oa(a,t);e.sideOrientation=O._GetDefaultSideOrientation(e.sideOrientation),d._originalBuilderSideOrientation=e.sideOrientation,Nv(e,u).applyToMesh(d,e.updatable),d.goldbergData.nbSharedFaces=c.sharedNodes,d.goldbergData.nbUnsharedFaces=c.poleNodes,d.goldbergData.adjacentFaces=c.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let f=0;f=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};O.prototype.thinInstanceSetAttributeAt=function(a,e,t,i=!0){return a===A.ColorKind&&(a=A.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(O.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});O.prototype._thinInstanceCreateMatrixBuffer=function(a,e,t=!1){a===A.ColorKind&&(a=A.ColorInstanceKind);const i=new zn(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};O.prototype.thinInstanceSetBuffer=function(a,e,t=0,i=!1){var s,n,r;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"?((n=this._thinInstanceDataStorage.previousMatrixBuffer)===null||n===void 0||n.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=e,e!==null&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",e,i))):(a===A.ColorKind&&(a=A.ColorInstanceKind),e===null?!((r=this._userThinInstanceBuffersStorage)===null||r===void 0)&&r.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 A(this.getEngine(),e,a,!i,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[a])))};O.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===A.ColorKind&&(a=A.ColorInstanceKind),!((i=this._userThinInstanceBuffersStorage)===null||i===void 0)&&i.vertexBuffers[a]&&this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(this._userThinInstanceBuffersStorage.data[a],0))};O.prototype.thinInstancePartialBufferUpdate=function(a,e,t){var i;a==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(e,t):(a===A.ColorKind&&(a=A.ColorInstanceKind),!((i=this._userThinInstanceBuffersStorage)===null||i===void 0)&&i.vertexBuffers[a]&&this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(e,t))};O.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;e{this._outputTexture?_.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):_.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,n,r){this._updateParameters(n,r)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let n=[],r=[],o=0;for(let p=0;p0)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 Se.Parse(()=>new Bs(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,s)}}F([B("kernel")],Bs.prototype,"_kernel",void 0);F([B("packedFloat")],Bs.prototype,"_packedFloat",void 0);F([Al()],Bs.prototype,"direction",void 0);Vt("BABYLON.BlurPostProcess",Bs);const Qv="glowMapGenerationPixelShader",Jv="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\nuniform sampler2D opacitySampler;\nuniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a{if((i||t===0)&&e.subMeshes)for(let s=0;s{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let n;const r=this._scene.getEngine();if(s.length){for(r.setColorWrite(!1),n=0;n{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 n=this._scene.getEngine(),r=e.getMesh(),o=(s=r._internalAbstractMeshDataInfo._materialForRenderPass)===null||s===void 0?void 0:s[n.currentRenderPassId];if(o)return o.isReadyForSubMesh(r,e,t);const l=e.getMaterial();if(!l)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return l.isReadyForSubMesh(e.getMesh(),e,t);const h=[],c=[A.PositionKind];let u=!1,d=!1;if(l){const T=l.needAlphaTesting(),S=l.getAlphaTestTexture(),b=S&&S.hasAlpha&&(l.useAlphaFromDiffuseTexture||l._useAlphaFromAlbedoTexture);S&&(T||b)&&(h.push("#define DIFFUSE"),r.isVerticesDataPresent(A.UV2Kind)&&S.coordinatesIndex===1?(h.push("#define DIFFUSEUV2"),d=!0):r.isVerticesDataPresent(A.UVKind)&&(h.push("#define DIFFUSEUV1"),u=!0),T&&(h.push("#define ALPHATEST"),h.push("#define ALPHATESTVALUE 0.4")),S.gammaSpace||h.push("#define DIFFUSE_ISLINEAR"));const y=l.opacityTexture;y&&(h.push("#define OPACITY"),r.isVerticesDataPresent(A.UV2Kind)&&y.coordinatesIndex===1?(h.push("#define OPACITYUV2"),d=!0):r.isVerticesDataPresent(A.UVKind)&&(h.push("#define OPACITYUV1"),u=!0))}i&&(h.push("#define EMISSIVE"),r.isVerticesDataPresent(A.UV2Kind)&&i.coordinatesIndex===1?(h.push("#define EMISSIVEUV2"),d=!0):r.isVerticesDataPresent(A.UVKind)&&(h.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||h.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(A.ColorKind)&&r.hasVertexAlpha&&l.transparencyMode!==j.MATERIAL_OPAQUE&&(c.push(A.ColorKind),h.push("#define VERTEXALPHA")),u&&(c.push(A.UVKind),h.push("#define UV1")),d&&(c.push(A.UV2Kind),h.push("#define UV2"));const _=new R0;if(r.useBones&&r.computeBonesUsingShaders){c.push(A.MatricesIndicesKind),c.push(A.MatricesWeightsKind),r.numBoneInfluencers>4&&(c.push(A.MatricesIndicesExtraKind),c.push(A.MatricesWeightsExtraKind)),h.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const T=r.skeleton;T&&T.isUsingTextureForMatrices?h.push("#define BONETEXTURE"):h.push("#define BonesPerMesh "+(T?T.bones.length+1:0)),r.numBoneInfluencers>0&&_.addCPUSkinningFallback(0,r)}else h.push("#define NUM_BONE_INFLUENCERS 0");const f=r.morphTargetManager;let g=0;f&&f.numInfluencers>0&&(h.push("#define MORPHTARGETS"),g=f.numInfluencers,h.push("#define NUM_MORPH_INFLUENCERS "+g),f.isUsingTextureForTargets&&h.push("#define MORPHTARGETS_TEXTURE"),we.PrepareAttributesForMorphTargetsInfluencers(c,r,g)),t&&(h.push("#define INSTANCES"),we.PushAttributesForInstances(c),e.getRenderingMesh().hasThinInstances&&h.push("#define THIN_INSTANCES")),Nl(l,this._scene,h),this._addCustomEffectDefines(h);const p=e._getDrawWrapper(void 0,!0),x=p.defines,m=h.join("\n");if(x!==m){const T=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices"];S0(T),p.setEffect(this._engine.createEffect("glowMapGeneration",c,T,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,_,void 0,void 0,{maxSimultaneousMorphTargets:g}),m)}return p.effect.isReady()}render(){for(let r=0;rT.setMatrix("world",b))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[A.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 re.Instantiate(e.customType).Parse(e,t,i)}}Di._SceneComponentInitialization=a=>{throw Ae("EffectLayerSceneComponent")};F([B()],Di.prototype,"name",void 0);F([f0()],Di.prototype,"neutralColor",void 0);F([B()],Di.prototype,"isEnabled",void 0);F([bd()],Di.prototype,"camera",null);F([B()],Di.prototype,"renderingGroupId",null);F([B()],Di.prototype,"disableBoundingBoxesFromEffectLayer",void 0);const i2="glowMapMergePixelShader",s2="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";te.ShadersStore[i2]=s2;const n2="glowMapMergeVertexShader",r2="attribute vec2 position;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";te.ShadersStore[n2]=r2;const a2="glowBlurPostProcessPixelShader",o2="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}";te.ShadersStore[a2]=o2;ps.AddParser(ve.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 n of s){if(!n.hasMesh(e))continue;const r=n._mainTexture;this._engine.currentRenderPassId=r.renderPassId;for(const o of e.subMeshes)if(!n.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===de.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==de.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const n=s._mainTexture;n._shouldRender()&&(this.scene.incrementRenderId(),n.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(ve.NAME_EFFECTLAYER);e||(e=new l2(a),a._addComponent(e))};ps.prototype.getHighlightLayerByName=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()===jt.EffectName)return this.effectLayers[t];return null};class qo extends st{constructor(e,t,i,s,n,r=se.BILINEAR_SAMPLINGMODE,o,l){super(e,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,s,n,r,o,l),this.direction=t,this.kernel=i,this.onApplyObservable.add(h=>{h.setFloat2("screenSize",this.width,this.height),h.setVector2("direction",this.direction),h.setFloat("blurWidth",this.kernel)})}}class jt extends Di{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 ee,this.onAfterBlurObservable=new ee,this._instanceGlowingMeshStencilReference=jt.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=jt.NeutralColor,this._engine.isStencilEnable||H.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return jt.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[A.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?Y.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?Y.GetExponentOfTwo(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new zi("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=se.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=se.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(se.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new er("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,se.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new qo("HighlightLayerHBP",new fe(1,0),this._options.blurHorizontalSize,1,null,se.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new qo("HighlightLayerVBP",new fe(0,1),this._options.blurVerticalSize,1,null,se.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 Bs("HighlightLayerHBP",new fe(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,se.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 Bs("HighlightLayerVBP",new fe(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,se.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 n=null;const r=this._meshes[s.uniqueId];return r&&r.glowEmissiveOnly&&i&&(n=i.emissiveTexture),super._isReady(e,t,n)}_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(j.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(j.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(n=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[n.uniqueId]?this._defaultStencilReference(n):n.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(n=>{this.isEnabled&&this._defaultStencilReference(n)}),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(jt.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=Se.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=Se.Parse(()=>new jt(e.name,t,e.options),e,t,i);let n;for(n=0;nnew ri(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return Se.Parse(()=>new ri(e.name,t),e,t,i)}}F([_s()],ri.prototype,"mainColor",void 0);F([_s()],ri.prototype,"lineColor",void 0);F([B()],ri.prototype,"gridRatio",void 0);F([wi()],ri.prototype,"gridOffset",void 0);F([B()],ri.prototype,"majorUnitFrequency",void 0);F([B()],ri.prototype,"minorUnitVisibility",void 0);F([B()],ri.prototype,"opacity",void 0);F([B()],ri.prototype,"preMultiplyAlpha",void 0);F([B()],ri.prototype,"useMaxLine",void 0);F([Si("opacityTexture")],ri.prototype,"_opacityTexture",void 0);F([je("_markAllSubMeshesAsTexturesDirty")],ri.prototype,"opacityTexture",void 0);Vt("BABYLON.GridMaterial",ri);Ee.prototype.createDynamicTexture=function(a,e,t,i){const s=new Dt(this,ze.Dynamic);return s.baseWidth=a,s.baseHeight=e,t&&(a=this.needPOTTextures?Ee.GetExponentOfTwo(a,this._caps.maxTextureSize):a,e=this.needPOTTextures?Ee.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};Ee.prototype.updateDynamicTexture=function(a,e,t,i=!1,s,n=!1,r=!1){if(!a)return;const o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,a,!0,n);this._unpackFlipY(t===void 0?a.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(a.type),u=this._getInternalFormat(s||a.format),d=this._getRGBABufferInternalSizedFormat(a.type,u);o.texImage2D(l,0,d,u,c,e),a.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),a.isReady=!0};class Zn extends se{constructor(e,t,i=null,s=!1,n=3,r=5,o){super(null,i,!s,o,n,void 0,void 0,void 0,void 0,r),this.name=e,this.wrapU=se.CLAMP_ADDRESSMODE,this.wrapV=se.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,n)):(this._canvas=l.createCanvas(1,1),t.width||t.width===0?this._texture=l.createDynamicTexture(t.width,t.height,s,n):this._texture=l.createDynamicTexture(t,t,s,n));const h=this.getSize();this._canvas.width!==h.width&&(this._canvas.width=h.width),this._canvas.height!==h.height&&(this._canvas.height=h.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,n,r,o,l=!0){const h=this.getSize();if(r&&(this._context.fillStyle=r,this._context.fillRect(0,0,h.width,h.height)),this._context.font=s,t==null){const c=this._context.measureText(e);t=(h.width-c.width)/2}if(i==null){const c=parseInt(s.replace(/\D/g,""));i=h.height/2+c/3.65}this._context.fillStyle=n||"",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 Zn(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()&&H.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Zn._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()}}At.AddNodeConstructor("Light_Type_3",(a,e)=>()=>new Qn(a,v.Zero(),e));class Qn extends Le{constructor(e,t,i){super(e,i),this.groundColor=new he(0,0,0),this.direction=t||v.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=v.Normalize(e.subtract(v.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=v.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=v.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=N.Identity()),this._worldMatrix}getTypeID(){return Le.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}F([_s()],Qn.prototype,"groundColor",void 0);F([wi()],Qn.prototype,"direction",void 0);function yt(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */yt=()=>a;var a={},e=Object.prototype,t=e.hasOwnProperty,i=typeof Symbol=="function"?Symbol:{},s=i.iterator||"@@iterator",n=i.asyncIterator||"@@asyncIterator",r=i.toStringTag||"@@toStringTag";function o(R,w,D){return Object.defineProperty(R,w,{value:D,enumerable:!0,configurable:!0,writable:!0}),R[w]}try{o({},"")}catch{o=(w,D,W)=>w[D]=W}function l(R,w,D,W){var L=w&&w.prototype instanceof u?w:u,z=Object.create(L.prototype),K=new E(W||[]);return z._invoke=((ae,$,U)=>{var V="suspendedStart";return(M,k)=>{if(V==="executing")throw new Error("Generator is already running");if(V==="completed"){if(M==="throw")throw k;return C()}for(U.method=M,U.arg=k;;){var X=U.delegate;if(X){var Q=S(X,U);if(Q){if(Q===c)continue;return Q}}if(U.method==="next")U.sent=U._sent=U.arg;else if(U.method==="throw"){if(V==="suspendedStart")throw V="completed",U.arg;U.dispatchException(U.arg)}else U.method==="return"&&U.abrupt("return",U.arg);V="executing";var ge=h(ae,$,U);if(ge.type==="normal"){if(V=U.done?"completed":"suspendedYield",ge.arg===c)continue;return{value:ge.arg,done:U.done}}ge.type==="throw"&&(V="completed",U.method="throw",U.arg=ge.arg)}}})(R,D,K),z}function h(R,w,D){try{return{type:"normal",arg:R.call(w,D)}}catch(W){return{type:"throw",arg:W}}}a.wrap=l;var c={};function u(){}function d(){}function _(){}var f={};o(f,s,function(){return this});var g=Object.getPrototypeOf,p=g&&g(g(P([])));p&&p!==e&&t.call(p,s)&&(f=p);var x=_.prototype=u.prototype=Object.create(f);function m(R){["next","throw","return"].forEach(function(w){o(R,w,function(D){return this._invoke(w,D)})})}function T(R,w){function D(L,z,K,ae){var $=h(R[L],R,z);if($.type!=="throw"){var U=$.arg,V=U.value;return V&&typeof V=="object"&&t.call(V,"__await")?w.resolve(V.__await).then(M=>{D("next",M,K,ae)},M=>{D("throw",M,K,ae)}):w.resolve(V).then(M=>{U.value=M,K(U)},M=>D("throw",M,K,ae))}ae($.arg)}var W;this._invoke=(L,z)=>{function K(){return new w((ae,$)=>{D(L,z,ae,$)})}return W=W?W.then(K,K):K()}}function S(R,w){var D=R.iterator[w.method];if(D===void 0){if(w.delegate=null,w.method==="throw"){if(R.iterator.return&&(w.method="return",w.arg=void 0,S(R,w),w.method==="throw"))return c;w.method="throw",w.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var W=h(D,R.iterator,w.arg);if(W.type==="throw")return w.method="throw",w.arg=W.arg,w.delegate=null,c;var L=W.arg;return L?L.done?(w[R.resultName]=L.value,w.next=R.nextLoc,w.method!=="return"&&(w.method="next",w.arg=void 0),w.delegate=null,c):L:(w.method="throw",w.arg=new TypeError("iterator result is not an object"),w.delegate=null,c)}function b(R){var w={tryLoc:R[0]};1 in R&&(w.catchLoc=R[1]),2 in R&&(w.finallyLoc=R[2],w.afterLoc=R[3]),this.tryEntries.push(w)}function y(R){var w=R.completion||{};w.type="normal",delete w.arg,R.completion=w}function E(R){this.tryEntries=[{tryLoc:"root"}],R.forEach(b,this),this.reset(!0)}function P(R){if(R){var w=R[s];if(w)return w.call(R);if(typeof R.next=="function")return R;if(!isNaN(R.length)){var D=-1,W=function L(){for(;++D{var w=typeof R=="function"&&R.constructor;return!!w&&(w===d||(w.displayName||w.name)==="GeneratorFunction")},a.mark=R=>(Object.setPrototypeOf?Object.setPrototypeOf(R,_):(R.__proto__=_,o(R,r,"GeneratorFunction")),R.prototype=Object.create(x),R),a.awrap=R=>({__await:R}),m(T.prototype),o(T.prototype,n,function(){return this}),a.AsyncIterator=T,a.async=(R,w,D,W,L)=>{L===void 0&&(L=Promise);var z=new T(l(R,w,D,W),L);return a.isGeneratorFunction(w)?z:z.next().then(K=>K.done?K.value:z.next())},m(x),o(x,r,"Generator"),o(x,s,function(){return this}),o(x,"toString",()=>"[object Generator]"),a.keys=R=>{var w=[];for(var D in R)w.push(D);return w.reverse(),function W(){for(;w.length;){var L=w.pop();if(L in R)return W.value=L,W.done=!1,W}return W.done=!0,W}},a.values=P,E.prototype={constructor:E,reset:function(R){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(y),!R)for(var w in this)w.charAt(0)==="t"&&t.call(this,w)&&!isNaN(+w.slice(1))&&(this[w]=void 0)},stop:function(){this.done=!0;var R=this.tryEntries[0].completion;if(R.type==="throw")throw R.arg;return this.rval},dispatchException:function(R){if(this.done)throw R;var w=this;function D($,U){return z.type="throw",z.arg=R,w.next=$,U&&(w.method="next",w.arg=void 0),!!U}for(var W=this.tryEntries.length-1;W>=0;--W){var L=this.tryEntries[W],z=L.completion;if(L.tryLoc==="root")return D("end");if(L.tryLoc<=this.prev){var K=t.call(L,"catchLoc"),ae=t.call(L,"finallyLoc");if(K&&ae){if(this.prev=0;--D){var W=this.tryEntries[D];if(W.tryLoc<=this.prev&&t.call(W,"finallyLoc")&&this.prev=0;--w){var D=this.tryEntries[w];if(D.finallyLoc===R)return this.complete(D.completion,D.afterLoc),y(D),c}},catch:function(R){for(var w=this.tryEntries.length-1;w>=0;--w){var D=this.tryEntries[w];if(D.tryLoc===R){var W=D.completion;if(W.type==="throw"){var L=W.arg;y(D)}return L}}throw new Error("illegal catch attempt")},delegateYield:function(R,w,D){return this.delegate={iterator:P(R),resultName:w,nextLoc:D},this.method==="next"&&(this.arg=void 0),c}},a}function $a(a){return $a=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?e=>typeof e:e=>e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e,$a(a)}function jo(a,e,t,i,s,n,r){try{var o=a[n](r),l=o.value}catch(h){return void t(h)}o.done?e(l):Promise.resolve(l).then(i,s)}function Zi(a){return function(){var e=this,t=arguments;return new Promise((i,s)=>{var n=a.apply(e,t);function r(l){jo(n,i,s,r,o,"next",l)}function o(l){jo(n,i,s,r,o,"throw",l)}r(void 0)})}}function Et(a,e){if(!(a instanceof e))throw new TypeError("Cannot call a class as a function")}function $o(a,e){for(var t=0;t"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],()=>{})),!0}catch{return!1}}();return function(){var t,i=Wr(a);if(e){var s=Wr(this).constructor;t=Reflect.construct(i,arguments,s)}else t=i.apply(this,arguments);return g2(this,t)}}function Zo(a,e){return function(t){if(Array.isArray(t))return t}(a)||function(t,i){var s=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(s!=null){var n,r,o=[],l=!0,h=!1;try{for(s=s.call(t);!(l=(n=s.next()).done)&&(o.push(n.value),!i||o.length!==i);l=!0);}catch(c){h=!0,r=c}finally{try{l||s.return==null||s.return()}finally{if(h)throw r}}return o}}(a,e)||U0(a,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Qo(a){return function(e){if(Array.isArray(e))return Qa(e)}(a)||function(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}(a)||U0(a)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function U0(a,e){if(a){if(typeof a=="string")return Qa(a,e);var t=Object.prototype.toString.call(a).slice(8,-1);return t==="Object"&&a.constructor&&(t=a.constructor.name),t==="Map"||t==="Set"?Array.from(a):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Qa(a,e):void 0}}function Qa(a,e){(e==null||e>a.length)&&(e=a.length);for(var t=0,i=new Array(e);tsetTimeout(a)).then(()=>Date.now())}var m2=Math.PI/2,v2=new v(2,2,2),Jo=function(){function a(){Et(this,a),this.tool=0,this.start=v.Zero(),this.end=v.Zero(),this.extruding=!1,this.gcodeLineNumber=0,this.gcodeFilePosition=0,this.color=null,this.feedRate=0,this.layerHeight=0,this.isPerimeter=!1}return Ct(a,[{key:"length",value:function(){return v.Distance(this.start,this.end)}},{key:"renderLine",value:function(e){var t=[this.start,this.end],i=ci.CreateLines("lines",t,e);i.enableEdgesRendering(),i.edgesWidth=10,i.edgesColor=new q(1,1,0,1)}},{key:"renderLinev4",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:.4,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;this.layerHeight===0&&(this.layerHeight=this.start.y);var i={},s=this.length()+t,n=this.start.add(this.end).divide(v2),r=this.end.subtract(this.start),o=Math.sqrt(Math.pow(r.x,2)+Math.pow(r.y,2)+Math.pow(r.z,2)),l=Math.atan2(r.z,r.x),h=Math.acos(r.y/o);return i.matrix=N.Compose(new v(s,this.layerHeight,e),ue.FromEulerVector(new v(0,-l,m2-h)),n),i.color=this.color,i.props={gcodeLineNumber:this.gcodeLineNumber,gcodeFilePosition:this.gcodeFilePosition,originalColor:this.color},i}},{key:"renderParticle",value:function(e){e.position.x=this.start.x,e.position.y=this.start.y,e.position.z=this.start.z,e.color=this.color}},{key:"getPoints",value:function(){return{points:[this.start,this.end],colors:[this.color,this.color]}}},{key:"getColor",value:function(){return this.extruding?new q(1,1,1,1):new q(1,0,0,1)}},{key:"getVoxelSegments",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,s=arguments.length>3?arguments[3]:void 0,n=new Array,r=v.Distance(this.start,this.end);if(!(r<.1)){var o=Math.round(100*(r/(e/2)-1))/100,l=Math.atan2(this.end.z-this.start.z,this.end.x-this.start.x);s&&(this.start.y-=e/2,this.end.y-=e/2);var h=this.start.clone(),c=0;n.push(h.clone());var u=e/2*Math.cos(l),d=e/2*Math.sin(l),_=0;for(o!==0&&(_=(this.end.y-this.start.y)/o);ce)for(var f=h.x-i;f<=h.x+i;f+=e)for(var g=h.z-i;gt&&s){for(var p=[],x=0;x5e4||this.currentFilePositionthis.scrubDistance&&e>=t-1e3&&e<=i+1e3}},{key:"getTransparentValue",value:function(){return this.vertexAlpha?this.transparentValue:0}},{key:"canUpdateColor",value:function(){return this.colorMode==rs.Color&&!this.hasMixing}},{key:"forceDraw",value:function(){this.timeStamp=0}}]),a}(),x2=function(a){ts(t,la);var e=is(t);function t(i,s,n,r,o,l){var h;return Et(this,t),(h=e.call(this,i,s,n,r,o)).meshIndex=l!=null?l:0,h.lostInSpace=N.Identity().setTranslation(new v(1e4,1e4,1e4)),h.additiveColor=new q(0,1,0,.8),h}return Ct(t,[{key:"buildBox",value:function(){if(this.solidMat)try{this.solidMat.dispose(),this.solidMat=null}catch{console.warn("nothing to dispose")}if(this.transparentMat)try{this.transparentMat.dispose(),this.transparentMat=null}catch{console.warn("nothing to dispose")}var i=ci.CreateBox("box",{width:1,height:1,depth:1,sideOrientation:O.FRONTSIDE},this.scene);return this.material=new ie("mat",this.scene),this.material.specularColor=this.specularColor,i.material=this.material,this.vertexAlpha&&(i.hasVertexAlpha=!0,i.material.forceDepthWrite=!0,i.material.alpha=.99),i}},{key:"render",value:function(i){for(var s=this,n=new Array(i.length),r=0,o=new Array(i.length),l=0;l.5&&f[L+3]<1){f[L+3]+=.02;var z=10*(f[L+3]-.9);f[L]=s.lerp(s.progressColor.r,n[D].color.r,z),f[L+1]=s.lerp(s.progressColor.g,n[D].color.g,z),f[L+2]=s.lerp(s.progressColor.b,n[D].color.b,z),R=!0}f[L+3]>=1&&!g[D]&&(n[D].color.toArray(f,L),f[L+3]=1,g[D]=!0,R=!0)}}else o[D]<=s.currentFilePosition?(n[D].color.toArray(f,L),n[D].matrix.copyToArray(_,16*D),f[L+3]=1,g[D]=!0):(s.getTransparentValue()===0?s.lostInSpace.copyToArray(_,16*D):n[D].matrix.copyToArray(_,16*D),f[L+3]=s.getTransparentValue(),g[D]=!1)}R&&m.thinInstanceBufferUpdated("color"),w&&(m.thinInstanceBufferUpdated("matrix"),m.thinInstanceRefreshBoundingInfo())};if(i.length!==0){var S=i[0].gcodeFilePosition,b=i.slice(-1)[0].gcodeFilePosition,y=0,E=!1,P=!1;this.timeStamp=Date.now();var C=function(){if(!(s.isLoading||Date.now()-s.timeStamp<200)){if(s.timeStamp=Date.now(),s.doScrub(y,S,b)||s.forceRedraw){E=!0,s.forceRedraw=!1,y=0;for(var R=0;R=S-3e4&&s.currentFilePosition<=b+3e4?(E=!1,P&&m.unfreezeWorldMatrix(),T()):P||(m.freezeWorldMatrix(),P=!0);y=s.currentFilePosition}};this.renderFuncs.push(C),this.scene.registerBeforeRender(C)}}}]),t}(),b2=function(a){ts(t,la);var e=is(t);function t(i,s,n,r,o,l){var h;return Et(this,t),(h=e.call(this,i,s,n,r,o)).meshIndex=l!=null?l:0,h.lostInSpace=N.Identity().setTranslation(new v(1e4,1e4,1e4)),h.additiveColor=new q(0,1,0,.8),h}return Ct(t,[{key:"buildCylinder",value:function(){if(this.solidMat)try{this.solidMat.dispose(),this.solidMat=null}catch{console.warn("nothing to dispose")}if(this.transparentMat)try{this.transparentMat.dispose(),this.transparentMat=null}catch{console.warn("nothing to dispose")}var i=ci.CreateCylinder("box",{height:1,diameter:1},this.scene);return i.locallyTranslate(new v(0,0,0)),i.rotate(new v(0,0,1),Math.PI/2,Nt.WORLD),i.bakeCurrentTransformIntoVertices(),this.material=new ie("mat",this.scene),this.material.specularColor=this.specularColor,i.material=this.material,this.vertexAlpha&&(i.hasVertexAlpha=!0,i.material.forceDepthWrite=!0,i.material.alpha=.99),i}},{key:"render",value:function(i){for(var s=this,n=new Array(i.length),r=0,o=new Array(i.length),l=0;l.5&&f[L+3]<1){f[L+3]+=.02;var z=10*(f[L+3]-.9);f[L]=s.lerp(s.progressColor.r,n[D].color.r,z),f[L+1]=s.lerp(s.progressColor.g,n[D].color.g,z),f[L+2]=s.lerp(s.progressColor.b,n[D].color.b,z)}f[L+3]>=1&&!g[D]&&(n[D].color.toArray(f,L),f[L+3]=1,g[D]=!0,R=!0)}}else o[D]<=s.currentFilePosition?(n[D].color.toArray(f,L),n[D].matrix.copyToArray(_,W),f[L+3]=1,g[D]=!0):(s.getTransparentValue()===0?s.lostInSpace.copyToArray(_,W):n[D].matrix.copyToArray(_,W),f[L+3]=s.getTransparentValue(),g[D]=!1)}R&&m.thinInstanceBufferUpdated("color"),w&&(m.thinInstanceBufferUpdated("matrix"),m.thinInstanceRefreshBoundingInfo())};if(i.length!==0){var S=i[0].gcodeFilePosition,b=i.slice(-1)[0].gcodeFilePosition,y=0,E=!1,P=!1;this.timeStamp=Date.now();var C=function(){if(!(s.isLoading||Date.now()-s.timeStamp<200)){if(s.timeStamp=Date.now(),s.doScrub(y,S,b)||s.forceRedraw){E=!0,s.forceRedraw=!1,y=0;for(var R=0;R=S-3e4&&s.currentFilePosition<=b+3e4?(E=!1,P&&m.unfreezeWorldMatrix(),T()):P||(P=!0,m.freezeWorldMatrix());y=s.currentFilePosition}};this.renderFuncs.push(C),this.scene.registerBeforeRender(C)}}}]),t}(),y2=Ct(function a(e,t){Et(this,a),this.filePosition=e,this.add=t,this.complete=!1}),nc=function(a){ts(i,la);var e,t=is(i);function i(s,n,r,o,l,h,c){var u;return Et(this,i),(u=t.call(this,s,n,r,o,l)).voxelWidth=parseFloat(h),u.voxelHeight=parseFloat(c),u.solidMat,u.transparentMat,u.hasSubtractive=!1,u.lostInSpace=N.Identity().setTranslation(new v(1e4,1e4,1e4)),u.clearColor=new q(1,0,0,0),u.additiveColor=new q(0,1,0,.8),u.subtractiveColor=new q(1,0,0,.8),u}return Ct(i,[{key:"buildBox",value:function(){if(this.solidMat)try{this.solidMat.dispose(),this.solidMat=null}catch{}if(this.transparentMat)try{this.transparentMat.dispose(),this.transparentMat=null}catch{}var s=ci.CreateBox("box",{width:this.voxelWidth,height:this.voxelHeight,depth:this.voxelWidth},this.scene);return s.hasVertexAlpha=!0,s.updateFacetData=!0,this.material=new ie("mat",this.scene),this.material.needDepthPrePass=!0,this.material.forceDepthWrite=!0,this.material.backFaceCulling=!1,s.material=this.material,s}},{key:"render",value:(e=Zi(yt().mark(function s(n){var r,o,l,h,c,u,d,_,f,g,p,x,m,T,S,b,y,E,P,C,R,w=this;return yt().wrap(function(D){for(;;)switch(D.prev=D.next){case 0:for(this.isLoading=!0,r=parseInt(300/this.voxelWidth)+1,o=r,l=parseInt(300/this.voxelHeight)+1,h=new Array(o),c=0;c<=l;c++)h[c]=new Object;u=0,d=new Date,_=0;case 10:if(!(_5e3)){D.next=57;break}return d=new Date,this.loadingProgressCallback(_/n.length,"Generating Voxel Map..."),D.next=57,zr();case 57:m++,D.next=22;break;case 60:_++,D.next=10;break;case 63:this.loadingProgressCallback(_/n.length,"Rendering Voxel..."),C=yt().mark(function W(L){var z,K,ae,$,U,V,M,k,X,Q,ge,ye,Te,Pe,De,nt,Ce,le,Fe,ke,Xe,tt,Gt,Rt,di,ti,Wt,Ft,ms;return yt().wrap(Ot=>{for(;;)switch(Ot.prev=Ot.next){case 0:if(z=[],h[L]!==void 0){Ot.next=3;break}return Ot.abrupt("return","continue");case 3:for(K=999999999999,ae=-999999999999,$=[],U=0,V=Object.entries(h[L]);Uae&&(ae=De.voxelEvents[0].filePosition),(ye=$).push.apply(ye,Qo(De.voxelEvents.map(ai=>ai.filePosition))),De.color.a=1,(nt={matrix:N.Identity(),color:De.color.clone(),voxelEvents:De.voxelEvents,lastDrawnCount:0}).matrix.setTranslation(new v(k*w.voxelWidth,L*w.voxelHeight,Pe*w.voxelWidth)),z.push(nt);for(Ce=0,$=$.sort((ai,Ai)=>ai-Ai),$=Qo(new Set($)),z.length,h[L]=null,(le=w.buildBox()).alphaIndex=L,le.renderingGroupId=1,Fe=new Float32Array(16*z.length),ke=new Float32Array(4*z.length),Xe=0;Xe{for(var ai=!1,Ai=!1,$t=0;$tha.filePositionRt&&vs.filePosition<=w.currentFilePosition&&(fi.lastDrawnCount=0,w.hasSubtractive&&fi.matrix.copyToArray(Fe,16*$t)),ti&&(fi.lastDrawnCount=i.drawDelay),fi.lastDrawnCount=Rt&&vs.filePosition<=w.currentFilePosition&&(fi.lastDrawnCount=0),ti&&(fi.lastDrawnCount=i.drawDelay),fi.lastDrawnCount{if(!(w.isLoading||Date.now()-Ft<200)){if(Ft=Date.now(),w.doScrub(Rt,K,ae)||di||w.forceRedraw){Ce=0,ti=!0,w.forceRedraw=!1;for(var ai=0;ai$t.complete=!1);Gt(),di=!1}else if(Ce<$.length-1&&$[Ce]w.currentFilePosition));Ai++);}else Wt<10&&(Wt++,Gt());Rt=w.currentFilePosition}},w.loadingProgressCallback&&w.loadingProgressCallback(L/u,"Rendering Voxels..."),w.renderFuncs.push(ms),w.scene.registerBeforeRender(ms),!(new Date-d>1e3)){Ot.next=36;break}return d=new Date,Ot.next=36,zr();case 36:case"end":return Ot.stop()}},W,this)}),R=0;case 67:if(!(RU===!1);z<=R;z++){var K=8*z;if(l[z]){if(h[z])continue;s.progressMode||C[K+3]<=.5?(C[K]=s.progressColor.r,C[K+1]=s.progressColor.g,C[K+2]=s.progressColor.b,C[K+3]=.9,C[K+4]=s.progressColor.r,C[K+5]=s.progressColor.g,C[K+6]=s.progressColor.b,C[K+7]=.9):C[K+3]<1?(C[K+3]+=.02,C[K+7]+=.02):C[K+3]>=1&&(C[K]=o[z][0].r,C[K+1]=o[z][0].g,C[K+2]=o[z][0].b,C[K+3]=1,C[K+4]=o[z][1].r,C[K+5]=o[z][1].g,C[K+6]=o[z][1].b,C[K+7]=1,h[z]=!0)}else{if(h[z])continue;C[K+3]===0?(C[K]=1,C[K+1]=0,C[K+2]=0,C[K+3]=.9,C[K+4]=1,C[K+5]=0,C[K+6]=0,C[K+7]=.9):C[K+3]<1?(C[K+3]+=.02,C[K+7]+=.02):(C[K+3]=1e-4,C[K+7]=1e-4,h[z]=!0)}b=z}for(var ae=R;ae=x-3e4&&s.currentFilePosition<=m+3e4&&(S=!1,y());T=s.currentFilePosition}};this.renderFuncs.push(P),this.scene.registerBeforeRender(P)}}]),t}(),en=function(){function a(){Et(this,a),this.feature=null,this.perimeter=!0,this.support=!1,this.missingFeatures=[]}return Ct(a,[{key:"isTypeComment",value:function(e){return!1}},{key:"getFeatureColor",value:function(e){return new Color4(1,1,1,1)}},{key:"isPerimeter",value:function(){return this.perimeter}},{key:"isSupport",value:function(){return this.support}},{key:"processComments",value:function(e,t){}},{key:"reportMissingFeature",value:function(e){this.missingFeatures.includes(e)||(console.error("Missing feature ".concat(e)),this.missingFeatures.push(e))}}]),a}(),T2=function(a){ts(t,en);var e=is(t);function t(){var i;return Et(this,t),(i=e.call(this)).featureList={Perimeter:{color:new q(1,.9,.3,1),perimeter:!1,support:!1},"External perimeter":{color:new q(1,.5,.2,1),perimeter:!0,support:!1},"Internal infill":{color:new q(.59,.19,.16,1),perimeter:!1,support:!1},"Solid infill":{color:new q(.59,.19,.8,1),perimeter:!1,support:!1},"Top solid infill":{color:new q(.95,.25,.25,1),perimeter:!0,support:!1},"Bridge infill":{color:new q(.3,.5,.73,1),perimeter:!1,support:!1},"Gap fill":{color:new q(1,1,1,1),perimeter:!1,support:!1},Skirt:{color:new q(0,.53,.43,1),perimeter:!1,support:!1},"Skirt/Brim":{color:new q(0,.53,.43,1),perimeter:!1,support:!1},"Supported material":{color:new q(0,1,0,1),perimeter:!1,support:!0},"Supported material interface":{color:new q(0,.5,0,1),perimeter:!1,support:!0},Custom:{color:new q(.5,.5,.5,1),perimeter:!1,support:!1},Unknown:{color:new q(.5,.5,.5,1),perimeter:!1,support:!1},"Support material":{color:new q(.5,.5,.5,1),perimeter:!1,support:!0},"Support material interface":{color:new q(.5,.5,.5,1),perimeter:!1,support:!0},"Overhang perimeter":{color:new q(.5,.5,.5,1),perimeter:!0,support:!1},"Wipe tower":{color:new q(.5,.5,.5,1),perimeter:!0,support:!1}},i}return Ct(t,[{key:"isTypeComment",value:function(i){return!!i.trim().startsWith(";TYPE:")&&(this.feature=i.substring(6).trim(),!0)}},{key:"getFeatureColor",value:function(){if(Object.prototype.hasOwnProperty.call(this.featureList,this.feature))try{return this.featureList[this.feature].color}catch{this.reportMissingFeature(this.feature)}return this.featureList.Unknown.color}},{key:"isPerimeter",value:function(){try{return this.featureList[this.feature].perimeter}catch{return this.reportMissingFeature(this.feature),!0}}},{key:"isSupport",value:function(){try{return this.featureList[this.feature].support}catch{return this.reportMissingFeature(this.feature),!1}}},{key:"processComments",value:function(i,s){try{for(var n=i.length-350;n{},this.hasSpindle=!1,this.voxelWidth=1,this.voxelHeight=1,this.forceVoxels=!1,this.renderInstances=new Array,this.meshIndex=0,this.highQualityExtrusion=!1,this.perimeterOnly=!1,this.lastUpdate=Date.now(),this.g1AsExtrusion=!1,this.firstGCodeByte=0,this.lastGCodeByte=0,this.zBelt=!1,this.gantryAngle=45*Math.PI/180,this.hyp=Math.cos(this.gantryAngle),this.adj=Math.tan(this.gantryAngle),this.currentZ=0,this.beltLength=100,this.nozzleStartPosition=new v(0,0,0),this.nozzlePosition=new v(0,0,0),this.nozzleFeedRate=0,this.firmwareRetraction=!1,this.inches=!1,this.fixRadius=!1,this.csysContainers=new Array,this.lastCommand="G0",this.arcPlane="XY",this.workplaceOffsets=[new v(0,0,0),new v(0,0,0)],this.currentWorkplace=0,this.progressMode=!1,this.transparentValue=.25,this.hasMixing=!1,this.renderAnimation=!0}var e,t,i,s,n;return Ct(a,[{key:"doUpdate",value:function(){this.lastUpdate=Date.now()}},{key:"setProgressColor",value:function(r){var o=this;this.progressColor=q.FromHexString(r.padEnd(9,"F")),this.renderInstances.forEach(l=>l.progressColor=o.progressColor)}},{key:"getMaxHeight",value:function(){return this.maxHeight+1}},{key:"getMinHeight",value:function(){return this.minHeight}},{key:"setRenderQualitySettings",value:function(r,o){if(this.forceVoxels)return this.renderVersion=ks.Voxel,this.meshBreakPoint=tl,void(this.lines=new Array(tl));this.lines=new Array(1.5*this.meshBreakPoint),o===void 0&&(o=1);var l=0,h=this.forceWireMode?2:1,c=2;switch(this.refreshTime=5e3,this.everyNthRow=1,this.renderTravels=!0,o){case 1:h=2,this.refreshTime=3e4,l=25e3,c=50,this.renderTravels=!1;break;case 2:h=2,this.refreshTime=3e4,l=5e5,c=10,this.renderTravels=!1;break;case 3:l=1e6,c=3;break;case 4:l=15e6,c=2;break;case 5:l=25e6;break;default:return this.renderVersion=ks.Block,void(this.everyNthRow=1)}for(var u=h;u<4;u++){var d=void 0;switch(u){case 1:d=24;break;case 2:d=2;break;case 3:d=1}for(var _=this.everyNthRow;_<=c;_++)if(this.debug&&console.log("Mode: "+u+" NRow: "+_+" vertexcount: "+r*d/_),r*d/_0&&(f.extruding=!0,this.maxHeight=this.currentPosition.y);break;case"F":if(this.currentFeedRate=Number(x.substring(1)),f.feedRate=this.currentFeedRate,this.currentFeedRate>this.maxFeedRate&&(this.maxFeedRate=this.currentFeedRate),this.currentFeedRate=1?this.maxFeedColor:m<=0?this.minFeedColor:q.Lerp(this.minFeedColor,this.maxFeedColor,m)}}}if(this.zBelt&&(this.beltLength=this.currentPosition.z1&&f.extruding&&(this.currentPosition.y>this.currentZ&&(this.currentRowIdx++,this.currentRowIdx%3==0&&this.currentRowIdx++,this.currentZ=this.currentPosition.y),this.currentRowIdx%this.everyNthRow==0&&this.currentRowIdx>2)))){var T=this.hasSpindle&&c[0]==="G1",S=this.g1AsExtrusion||f.length()>=this.lineLengthTolerance;h&&(this.renderedLines.push(f),f.extruding&&this.lastZExtrusionthis.currentLayerHeight&&!this.isSupport&&g&&(this.previousLayerHeight=this.currentLayerHeight,this.currentLayerHeight=this.currentPosition.y)):this.renderTravels&&!f.extruding&&(f.color=new q(1,0,0,1),this.travels.push(f)),this.zBelt?f.layerHeight=Math.abs(this.currentLayerHeight-this.previousLayerHeight):this.g1AsExtrusion?f.layerHeight=1:f.layerHeight=this.currentLayerHeight-this.previousLayerHeight)}}},{key:"g2g3",value:function(r,o,l,h){var c=this,u=r.split(/(?=[GXYZIJKFRE])/),d=r.indexOf("E")>0||this.g1AsExtrusion,_=u.filter(p=>p==="G2"||p==="G02"),f={position:this.currentPosition.clone(),points:[]};try{f=function(p,x,m,T,S,b,y){for(var E=new v(x.x,x.z,x.y),P=E.clone(),C=0,R=0,w=0,D=p.some(Ft=>Ft.includes("G2")),W=0;W=0)X=Math.sqrt(k/M);else if(k<-.02*Math.pow(w,2)){if(!S)return console.error("G2/G3: Radius too small"),{position:{x:P.x,y:P.z,z:P.y},points:[]};var Q=Math.sqrt(Math.pow(U/2,2)+Math.pow(V/2,2));k=Math.pow(Q,2)-M/4,X=Math.sqrt(k/M)}(D&&w<0||!D&&w>0)&&(X=-X),C=U/2+V*X,R=V/2-U*X}else if(C===0&&R===0)return{position:E.clone(),points:[]};var ge,ye=E[z]===P[z]&&E[K]===P[K],Te=E[z]+C,Pe=E[K]+R,De=Math.sqrt(C*C+R*R),nt=Math.atan2(-R,-C),Ce=Math.atan2(P[K]-Pe,P[z]-Te);ye?ge=2*Math.PI:(ge=D?nt-Ce:Ce-nt)<0&&(ge+=2*Math.PI);var le=De*ge/T;le<1&&(le=1);var Fe=ge/le;Fe*=D?-1:1;for(var ke=new Array,Xe=(P[ae]-E[ae])/le,tt=E[z],Gt=E[K],Rt=E[ae],di=nt,ti=0;ti{var m=new Jo;m.tool=c.currentTool,m.gcodeLineNumber=o,m.gcodeFilePosition=l,m.feedRate=c.currentFeedRate,m.isPerimeter=c.slicer.isPerimeter(),c.g1AsExtrusion?m.layerHeight=1:m.layerHeight=c.currentLayerHeight-c.previousLayerHeight,m.start=g.clone(),m.end=new v(p.x,p.y,p.z),m.extruding=d,m.color=d?c.currentColor.clone():new q(1,0,0,1),c.debug&&(m.color=_?new q(0,1,1,1):new q(1,1,0,1),x===0&&(m.color=new q(0,1,0,1))),g=m.end.clone(),c.debug&&console.log(m),h&&(c.renderedLines.push(m),m.extruding?c.lines[c.linesIndex++]=m:c.travels.push(m))}),this.currentPosition=new v(g.x,g.y,g.z),this.currentPosition.y>this.currentLayerHeight&&!this.isSupport&&(this.previousLayerHeight=this.currentLayerHeight,this.currentLayerHeight=this.currentPosition.y)}},{key:"m567",value:function(r){var o=r.split(/(?=[PE])/),l=[1,1,1];if(this.colorMode!==rs.Feed){for(var h=1;h0&&(this.firstGCodeByte=d),this.lastGCodeByte=d,this.processLine(f,_,d,g)),!(Date.now()-this.timeStamp>10)){p.next=33;break}return this.loadingProgressCallback&&this.loadingProgressCallback(d/o.length,"Loading File..."),p.next=32,zr();case 32:this.timeStamp=p.sent;case 33:this.doUpdate(),p.next=19;break;case 36:if(this.layerDictionary.push(o.length),!this.renderTravels){p.next=40;break}return p.next=40,this.createTravelLines(this.scene);case 40:this.loadingProgressCallback&&this.loadingProgressCallback(1),o={};case 42:case"end":return p.stop()}},r,this)})),function(r,o,l){return n.apply(this,arguments)})},{key:"loadingComplete",value:function(){this.renderInstances.forEach(r=>r.isLoading=!1),this.updateFilePosition(Number.MAX_VALUE-1),this.updateFilePosition(Number.MAX_VALUE)}},{key:"processLine",value:(s=Zi(yt().mark(function r(o,l,h){var c,u,d,_,f,g,p,x,m,T,S,b,y=arguments;return yt().wrap(function(E){for(;;)switch(E.prev=E.next){case 0:if(c=!(y.length>3&&y[3]!==void 0)||y[3],(u=o.indexOf(";"))>-1&&(o=o.substring(0,u-1).trim()),o=o.toUpperCase(),(_=o.match(/[GM]+[0-9.]+/g))===null&&o.match(/[XYZ]+[+-]?[0-9.]+/g)!==null&&(_=this.lastCommand),!_){E.next=61;break}f=0;case 8:if(!(f<_.length)){E.next=59;break}E.t0=_[f],E.next=E.t0==="G0"||E.t0==="G1"||E.t0==="G00"||E.t0==="G01"?12:E.t0==="G2"||E.t0==="G3"||E.t0==="G02"||E.t0==="G03"?14:E.t0==="G10"?16:E.t0==="G11"?18:E.t0==="G17"?20:E.t0==="G18"?22:E.t0==="G19"?24:E.t0==="G20"?26:E.t0==="G28"?28:E.t0==="G53"?31:E.t0==="G54"||E.t0==="G55"||E.t0==="G56"||E.t0==="G57"||E.t0==="G58"||E.t0==="G59"?32:E.t0==="G59.1"||E.t0==="G59.2"||E.t0==="G59.2"?35:E.t0==="G90"?38:E.t0==="G91"?40:E.t0==="G92"?42:E.t0==="S"?43:E.t0==="M3"||E.t0==="M4"?45:E.t0==="M567"?50:E.t0==="M600"?53:55;break;case 12:return this.g0g1(o,l,h,c,_),E.abrupt("break",55);case 14:return this.g2g3(o,l,h,c),E.abrupt("break",55);case 16:return this.firmwareRetraction=!0,E.abrupt("break",55);case 18:return this.firmwareRetraction=!1,E.abrupt("break",55);case 20:return this.arcPlane="XY",E.abrupt("break",55);case 22:return this.arcPlane="XZ",E.abrupt("break",55);case 24:return this.arcPlane="YZ",E.abrupt("break",55);case 26:return this.inches=!0,E.abrupt("break",55);case 28:return(d=o.split(/(?=[GXYZ])/)).length===1||o==="G28 W"?this.currentPosition=new v(this.workplaceOffsets[this.currentWorkplace].x,this.workplaceOffsets[this.currentWorkplace].z,this.workplaceOffsets[this.currentWorkplace].y):(d.some(P=>P.trim()==="X")&&(this.currentPosition.x=this.workplaceOffsets[this.currentWorkplace].x),d.some(P=>P.trim()==="Y")&&(this.currentPosition.z=this.workplaceOffsets[this.currentWorkplace].y),d.some(P=>P.trim()==="Z")&&(this.currentPosition.y=this.workplaceOffsets[this.currentWorkplace].z)),E.abrupt("break",55);case 31:return E.abrupt("break",55);case 32:return this.currentWorkplace=54-Number(_[f].substring(1)),this.currentPosition=this.workplaceOffsets[this.currentWorkplace].clone(),E.abrupt("break",55);case 35:return this.currentWorkplace=10*(58.6-Number(_[f].substring(1))),this.currentPosition=this.workplaceOffsets[this.currentWorkplace].clone(),E.abrupt("break",55);case 38:return this.absolute=!0,E.abrupt("break",55);case 40:return this.absolute=!1,E.abrupt("break",55);case 42:return E.abrupt("break",55);case 43:return this.hasSpindle=!0,E.abrupt("break",55);case 45:return g=o.split(/(?=[SM])/),(p=(p=g.filter(P=>P.startsWith("S")))[0]?Number(p[0].substring(1)):0)>0&&(this.hasSpindle=!0),E.abrupt("break",55);case 50:return this.hasMixing=!0,this.m567(o),E.abrupt("break",55);case 53:try{this.currentTool++,this.currentTool>=this.tools.length&&(this.currentTool=0),this.colorMode!==rs.Feed&&(this.currentColor=this.tools[this.currentTool].color.clone())}catch(P){console.log(P)}return E.abrupt("break",55);case 55:this.lastCommand=_;case 56:f++,E.next=8;break;case 59:E.next=63;break;case 61:o.startsWith("T")&&(x=Number.parseInt(o.substring(1),10),isNaN(x)||(this.currentPosition.z+=10,this.currentTool=x,this.currentTool>=this.tools.length?this.currentTool=this.currentTool%this.tools.length:x<0&&(this.currentTool=0),this.colorMode!==rs.Feed&&((b=Number(o.substring(1))%this.extruderCount)<0&&(b=0),this.currentColor=(m=(T=this.tools[b])===null||T===void 0||(S=T.color)===null||S===void 0?void 0:S.clone())!==null&&m!==void 0?m:new he(1,0,0)))),this.debug&&console.log(o);case 63:if(!(this.linesIndex>=this.meshBreakPoint)){E.next=70;break}return E.next=66,this.createMesh(this.scene);case 66:return E.next=68,zr();case 68:this.doUpdate(),this.meshIndex++;case 70:case"end":return E.stop()}},r,this)})),function(r,o,l){return s.apply(this,arguments)})},{key:"createMesh",value:(i=Zi(yt().mark(function r(o){var l,h,c;return yt().wrap(function(u){for(;;)switch(u.prev=u.next){case 0:if(this.zBelt&&(l=this.lines[this.linesIndex-1].layerHeight,this.lines.forEach(d=>{d.layerHeight=l})),this.renderVersion===ks.Line||this.renderVersion===ks.Point?h=new el(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.meshIndex):this.renderVersion===ks.Block?h=this.highQualityExtrusion?new b2(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.meshIndex):new x2(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.meshIndex):this.renderVersion===ks.Voxel&&(h=new nc(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.voxelWidth,this.voxelHeight)),h.progressColor=this.progressColor,h.vertexAlpha=this.vertexAlpha,h.g1AsExtrusion=this.g1AsExtrusion,h.progressMode=this.progressMode,h.transparentValue=this.transparentValue,h.hasMixing=this.hasMixing,h.colorMode=this.colorMode,h.renderAnimation=this.renderAnimation,this.renderInstances.push(h),!((c=this.lines.slice(0,this.linesIndex-1))!=null&&c.length>0)){u.next=15;break}return u.next=15,h.render(c);case 15:this.linesIndex=0;case 16:case"end":return u.stop()}},r,this)})),function(r){return i.apply(this,arguments)})},{key:"chunk",value:function(r,o){for(var l=[],h=0,c=r.length;hl.updateFilePosition(r));try{rr+5);o++)this.currentLineNumber=this.renderedLines[o].gcodeLineNumber,this.nozzleStartPosition=this.renderedLines[o].start,this.nozzlePosition=this.renderedLines[o].end,this.nozzleFeedRate=this.renderedLines[o].feedRate,this.lastFilePositionIndex=o;this.doUpdate()}},{key:"updateFilePositionIndex",value:function(r){var o=this;r>=this.renderedLines.length||(this.currentLineNumber=this.renderedLines[r].gcodeLineNumber,this.nozzleStartPosition=this.renderedLines[r].start,this.nozzlePosition=this.renderedLines[r].end,this.nozzleFeedRate=this.renderedLines[r].feedRate,this.lastFilePositionIndex=r,this.renderInstances.forEach(l=>l.updateFilePosition(o.renderedLines[r].gcodeFilePosition)),this.doUpdate())}},{key:"doFinalPass",value:function(){var r=this;this.liveTracking=!0,this.gcodeFilePosition=Number.MAX_VALUE,setTimeout(()=>{r.liveTracking=!1},this.refreshTime+200)}},{key:"updateMesh",value:function(){this.renderVersion===1?console.log("Version 1"):this.renderVersion===2&&console.log("Version 2")}},{key:"unregisterEvents",value:function(){for(var r=0;r2&&arguments[2]!==void 0?arguments[2]:Ja.Extruder,h=new vr;h.color=q.FromHexString(r.padEnd(9,"F")),h.updateDarkerValue(),h.diameter=o,h.toolType=l,this.tools.push(h)}},{key:"updateTool",value:function(r,o,l){l{if(l.material!==null&&Object.prototype.hasOwnProperty.call(l.material,"specularColor"))try{l.material.specularColor=o}catch(h){console.error(h)}}),this.scene&&this.scene.render(!0,!0)}},{key:"g1AsExtrusion",value:function(r){this.g1AsExtrusion=r}},{key:"cancel",value:(e=Zi(yt().mark(function r(){return yt().wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.cancelLoad=!0,o.next=3,this.pauseProcessing();case 3:case"end":return o.stop()}},r,this)})),function(){return e.apply(this,arguments)})},{key:"setZBeltAngle",value:function(r){this.gantryAngle=(90-r)*Math.PI/180,this.hyp=Math.cos(this.gantryAngle),this.adj=Math.tan(this.gantryAngle)}},{key:"setTransparencyValue",value:function(r){this.transparentValue=r,this.renderInstances.forEach(o=>{o.transparentValue=r})}},{key:"setRenderAnimation",value:function(r){var o=this;this.renderAnimation=r,this.renderInstances.forEach(l=>l.renderAnimation=o.renderAnimation)}}]),a}(),il=0,P2=1,w2=function(){function a(e){Et(this,a),this.buildVolume={x:{min:0,max:100},y:{min:0,max:100},z:{min:0,max:100}};var t=localStorage.getItem("buildVolume");t!==null&&(this.buildVolume=JSON.parse(t)),this.renderMode=Number.parseInt(localStorage.getItem("renderBedMode"),10),this.renderMode||(this.renderMode=il),this.bedMesh,this.isDelta=!1,this.scene=e,this.registerClipIgnore=()=>{},this.bedLineColor="#0000FF",this.getBedColor()||this.setBedColor("#0000FF"),this.planeMaterial=this.buildGridMaterial(),this.boxMaterial=new ie("bedBoxMaterial",this.scene),this.boxMaterial.alpha=0,this.debug=!1}return Ct(a,[{key:"setRenderMode",value:function(e){this.renderMode=e,localStorage.setItem("renderBedMode",this.renderMode),this.bedMesh&&(this.scene.removeMesh(this.bedMesh),this.bedMesh.dispose(!1,!0)),this.buildBed(),this.scene.render()}},{key:"buildBed",value:function(){if(!(this.renderMode>1||this.debug)){if(this.bedMesh&&this.bedMesh.isDisposed()&&(this.bedMesh=null),this.bedMesh)return this.bedMesh;switch(this.renderMode){case il:this.buildFlatBed();break;case P2:this.buildBox()}return this.bedMesh}}},{key:"setDelta",value:function(e){this.isDelta=e,this.setRenderMode(this.renderMode)}},{key:"buildFlatBed",value:function(){var e=this.getCenter(),t=this.getSize();if(this.isDelta){var i=Math.abs(this.buildVolume.x.max-this.buildVolume.x.min)/2;this.bedMesh=ci.CreateDisc("BuildPlate",{radius:i},this.scene),this.bedMesh.rotationQuaternion=ue.RotationAxis(new v(1,0,0),Math.PI/2),this.bedMesh.material=this.planeMaterial}else{var s=t.x,n=t.y;this.bedMesh=ci.CreatePlane("BuildPlate",{width:s,height:n},this.scene),this.bedMesh.material=this.planeMaterial,this.bedMesh.rotationQuaternion=ue.RotationAxis(new v(1,0,0),Math.PI/2),this.bedMesh.translate(new v(e.x,0,e.y),1,Nt.WORLD)}this.registerClipIgnore(this.bedMesh)}},{key:"getCenter",value:function(){return{x:(this.buildVolume.x.max+this.buildVolume.x.min)/2,y:(this.buildVolume.y.max+this.buildVolume.y.min)/2,z:(this.buildVolume.z.max+this.buildVolume.z.min)/2}}},{key:"getSize",value:function(){return{x:Math.abs(this.buildVolume.x.max-this.buildVolume.x.min),y:Math.abs(this.buildVolume.y.max-this.buildVolume.y.min),z:Math.abs(this.buildVolume.z.max-this.buildVolume.z.min)}}},{key:"buildBox",value:function(){var e=this,t=this.getSize(),i=this.getCenter();if(this.isDelta)this.bedMesh=ci.CreateCylinder("bed",{diameterTop:t.x,diameterBottom:t.x,height:t.z},this.scene),this.bedMesh.position.x=i.x,this.bedMesh.position.y=i.z,this.bedMesh.position.z=i.x,this.bedMesh.alpha=0,this.bedMesh.diffuseColor=new q(0,0,0,0),this.bedMesh.isPickable=!1,this.bedMesh.enableEdgesRendering(void 0,!0),this.bedMesh.renderingGroupId=2,this.scene.setRenderingAutoClearDepthStencil(2,!1,!1,!1),new jt("hl",this.scene,{isStroke:!0,blurTextureSizeRatio:3}).addMesh(this.bedMesh,this.getBedColor4()),this.bedMesh.onBeforeRenderObservable.add(()=>{e.scene.getEngine().setColorWrite(!1)}),this.bedMesh.onAfterRenderObservable.add(()=>{e.scene.getEngine().setColorWrite(!0)}),this.registerClipIgnore(this.bedMesh);else{this.bedMesh=ci.CreateBox("bed",{width:t.x,depth:t.y,height:t.z},this.scene);var s=this.getCenter();this.bedMesh.position.x=s.x-this.buildVolume.x.min,this.bedMesh.position.y=s.z-this.buildVolume.z.min,this.bedMesh.position.z=s.y-this.buildVolume.y.min,this.bedMesh.diffuseColor=new q(0,0,0,0),this.bedMesh.enableEdgesRendering(),this.bedMesh.edgesWidth=100,this.bedMesh.material=this.boxMaterial,this.bedMesh.isPickable=!1,this.bedMesh.edgesColor=this.getBedColor4(),this.registerClipIgnore(this.bedMesh)}}},{key:"setVisibility",value:function(e){this.bedMesh&&this.bedMesh.setEnabled(e)}},{key:"commitBedSize",value:function(){localStorage.setItem("buildVolume",JSON.stringify(this.buildVolume)),this.setRenderMode(this.renderMode)}},{key:"buildGridMaterial",value:function(){var e=new ri("bedMaterial",this.scene);return e.mainColor=new q(0,0,0,0),e.lineColor=he.FromHexString(this.getBedColor()),e.gridRatio=5,e.opacity=.8,e.majorUnitFrequency=10,e.minorUnitVisibility=.6,e.gridOffset=new v(0,0,0),e}},{key:"getBedColor",value:function(){return localStorage.getItem("bedLineColor")}},{key:"setBedColor",value:function(e){localStorage.setItem("bedLineColor",e),this.renderMode>1||this.planeMaterial&&(this.planeMaterial=this.buildGridMaterial(),this.dispose(),this.buildBed(),this.scene.render())}},{key:"getBedColor4",value:function(){return q.FromHexString(this.getBedColor().padEnd(9,"F"))}},{key:"dispose",value:function(){this.bedMesh&&!this.bedMesh.isDisposed&&this.bedMesh.dispose(!1,!0)}}]),a}(),D2=function(){function a(e){Et(this,a),this.scene=e,this.checkerBoard="iVBORw0KGgoAAAANSUhEUgAAAQEAAAEBCAIAAAD3joeqAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAALnSURBVHhe7dZBEYQwFAVBWBtogAv+IhIEsZd4yGG6L/lPwFRl31jqPM/neeZghd98oUoD1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjb7/ueJyscxzHGmIMV9u/75skK7/te1zUHK/gLUacB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA7Rt2x+drw1hSNi5LQAAAABJRU5ErkJggg==",this.xmark="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAADPCAMAAAD1TAyiAAAAkFBMVEX39/eZAAD8//+TAACWAACRAAD4+vr5/PyaAAD39fX18vLy6enr29v18PDm0dG1Y2PewMDYtbWuUFDkzc2jLy+iKSnLlpbRpKS/enrIjo6hJCTbu7u8dHSxWFi4a2vEh4eoOzudEhKdEBDPn5+pQUHq2dmsSUmnODjUqqqhJye0YGCeGRnIk5OrTEy6b2+fHh7/wUBWAAAIiElEQVR4nO2d2ULbOhRF4yNFijNAQiCBMoShhBTo7f//3bUc2kLIIOnsI6ut90v7hLS8ZCVWZJ1Op02bNm3atGnTps0fGGOsizGm6Z4kiiHqDMeT+Wo1vxwPS6IGwI2lqt3qqlf/WPH2DZnpYqnVz3SL5cXUpuWumnucL66Xp1WW14v5UUlWsDlDw0VPaV28i9aqWAyTYRsqJ8fVRdfrXlT/VP9/nvTFOkDDY/UB+Be4uhmSUKMbXRgsis990EqfD0Q6YMvz7cjrZs9Ledm2v7MLVQdG+EFO07udyC7q5UhaNk2KPV3QxSW6A/TQ3Yfs0n0QpTblsTrQgRvsRyhdHWiwln0lSG0Hp3tHWi37dASkpkMX+Y36WIzaDvVBZjeZD2HUXp5r6nMhajPw64C+R7mmC09mMeqK2cNzTX2HoaaJN7MQtRn0PJkr6q+ITy4zCGAWmc2st2dYB2gZ0GIhMJvZR3/PdQcu2a7tKkg0nrqatwM70Otz2yx7gU2Cqe1jcPuaO6/QLFQ0ljrcs2t/wJvBTXiTSGr7GMHMVW0uI0TjqKM8u+ZHnFbpOK5VDHWcZ9f6ijWBxzVaU7MXr2I9V+N7ybjk5ihudNfUJ8wHPZrGMlfUjPFt5/HQheZRc5gLNY5vmv5jNMyjpinjehf6Nf6mpu8c6Io6+r5mea5afo6/qc0Lp2WGa57nKreMmYzXcrRrpucqvXjmzsHVwMPUEa7Znqt2m4SOoeZ7Lopuo9CFvg38GYDGbM88aP4ld9SdEGoIc6HimeOesTYT5JrGgNFVJR6aviJUF/rJ2zXGc1F8Y3w5iX3I2oi3a5RnfR3/OW0fMNC+rlGeC71gfCPjf2D+7IXPbAZjLtSE8UBdgkx7ucYx81bJ6BpHfdrf3xGKXJraljPOuk3sGtm26LO9s1nQr0eHmprx1vvDl713d+V0DzVdYubtOsw1YHrFXf/K9c4RThMgM+dpuk4fdlMXe1wj7+dK9BFzTZI4y2SfssM11DPrm8lb7OG9HiEd2uYa67lQ/D0YZgjt0RbXWM+FmiF+oF5B+6RfNqZWCv4xeP/f5yyPvevVObZXdx+oaQ69pkXB/MnyV7+usdTvXWMnSjdzo3ZLWjD1b9doz2qM2xBgT2So0Z670P2hMq7hnsF7YiVc5+25pvbbH+qbajbL3bML3YBd++++9IqaSmzRBFOHbAP0iAwznhoZKeacqeWY86WWZM6VWpY5T2ppZrf5JjdqeWb4kyY7WvyFsJra9z2WJNGwZ8kD1Bm5TsWck2vcmoEHdSau03muqbNwndJzTZ2B67Se86BO7bmmvgCv3YZmmJ456B3Mv4a5YdcNMTfpWjfG3KDrBpkbc90oc0OuG2ZuwLVuntnrNBAo8/2geWZHndB1xZzHeWAJXWfDnNB1RszJXGfFnMj1xm6V5pPAtdaZMeN3Unxmzs2zC3gP3CfmL8gjqGARpd6zg7jZCFLrL5kyC1Jn69kF+U7Ce+Z8PbuIuM7as4uA68w9u9AEu2uoKJ6yZ+4Yc4Zl1qs0p88yYvpPaNMqd2pTQl/5WEf4GFZuTAn37AJ5LUMqIp5dMnYt5NlF5Upt+kKeXbp5jnCxsb1Olq7N6Ickc5auTf+LLHOGrsU9u2TmOoFnF/WaEXUSzzX1RTbUiTzX1Lm4Tua5ps7DdVLmTKjNwKeEwN9F7X+cPo666fvaDO5TMzfuOqSEAJKacQgVgLkBzzW1VMEPH+ZGPDdK3ZjnBqltc54bo7bD5J9VjVPHH7P+51JXnptPYuoMPLskpc7Cs4u6SUadiWcXwWJsm8xNo75LItfRJUFkksQ1HWXFnMR1dswJXGfILO46S2Zh15ky1+WL/jlmV75IiJoYNZXEo05E9l0hymN86Cb2cVzENU3BR6bNRi9garhrQOmXD+nOCL3cpNGu8Z4Jv0kF/Mkl4Nn9WTP6hqVG/gpgJTyvqbGuu2PYCDfg5+d32yjQrgvU2y2mDzy4v9jY9Ai+rzXqtgbWpXDZ2C5jRmfIP9/lHl3/xow9f/vTRmasa1Ydz9+BlioouvNPncK6ZlcpcKFz6OjbtmHdjDAlquog7urAkvIHssVz3UgJpOaVJK5Dr0DRWz3X1B0cNauC0jr2HtWZnZ5rapxr/vjGVcza47luCOeaU8izDi1ww27/Szc46i63+AjdYjriccw6jJpTh7lOH1ag7fAx6yhq9cCbyWC3tNdx+qZzC6keytxwZUGvi3oep286iK/5mvmrtcV8SnuXTTB0wm+QC42ZvEPKJli+azY04ot3WHkMvuscoEPLY7Af37kTGQC6G1zih+tazXkfWfx7OqasEbNUFffLiZ0xoeNKOfEK+XSZx/1YZkm+2PJVLNcvzG+hzG9k8SW76Dm6Yf6jZcmB5pQpi6fmLyJwCqzzSrNFU6s+k5kzfWtmOTqKK9AFWBiMv6k1uyRIHDViCZheIpkBJUFiRjigUG3V8CxukEHKoES4hqz1d0YxN7UClX4Jdq2vMEVbIw44xpW7CS3adM+eutcpg5lRnl3CCn50p6Af5W1otXdsWaOQ0hfAoyLoJui2Rpdy8neNfaUj6K1w+JHjvq6xm4HNwB9aomwCLXxuMPSrO/bRc4QJHS3vc+Qu/vVi67f/V/eEjtOn8YEzCLREoVo79Dj5QP8QO6LY9vcuK6jlQGKbux08HRpiail47KOhy7tdHVB6RTItG7P/o0OrC6GW32JpdaY+Dzet7mcduXoNNL7fja1u5SstWju90kr/vtG0Vur6siPasDUPxVZsrV6kBtjHGLJHDzdf77RL7/Z6Ni7l26Vy/qQ2prTqai8nJllBEGOJyr5LSWTTnB1r6XH2vVBK1RdbqW7veT6gHGqgiKa61J3H8fzi9fX1YjIedFJd7sZjjF3H/CPAbdq0adOmTZs2bbD5H8lJpKRvNiuNAAAAAElFTkSuQmCC",this.buildObjectMeshes=new Array,this.labels=new Array,this.labelSVGS=new Array,this.baseMaterial=null,this.highlightMaterial=null,this.cancelledMaterial=null,this.cancelledHighlightMaterial=null,this.showCancelObjects=!1,this.objectCallback=null,this.renderFailedCallback=null,this.labelCallback=null,this.registerClipIgnore=null,this.getMaxHeight=null,this.alphaLevel=.5,this.observableControls=null,this.showLabel=localStorage.getItem("showObjectLabels"),this.showLabel===null?this.showLabel=!0:this.showLabel=JSON.parse(this.showLabel),this.rebuildMaterials()}return Ct(a,[{key:"setBuildMaterial",value:function(e,t,i){i||(i=this.alphaLevel);var s=new ie(e,this.scene);return s.diffuseColor=t,s.specularColor=new he(0,0,0),s.alpha=i,s.needAlphaTesting=()=>!0,s.separateCullingPass=!0,s.backFaceCulling=!0,s}},{key:"rebuildMaterials",value:function(){this.baseMaterial=this.setBuildMaterial("BuildObjectBaseMaterial",new q(.1,.5,.1),.25),this.highlightMaterial=this.setBuildMaterial("BuildObjectHighlightMateria",new he(.8,.8,.8)),this.cancelledMaterial=this.setBuildMaterial("BuildObjectHighlightMateria",new he(1,0,0),.4),this.cancelledHighlightMaterial=this.setBuildMaterial("BuildObjectHighlightMateria",new he(1,1,0),.6);var e=se.CreateFromBase64String(this.xmark,"checkerboard",this.scene);this.cancelledMaterial.diffuseTexture=e,this.cancelledHighlightMaterial.diffuseTexture=e}},{key:"loadObjectBoundaries",value:function(e){if(this.rebuildMaterials(),this.buildObjectMeshes.length>0){for(var t=0;twindow.URL.revokeObjectURL(o)),this.buildObjectMeshes=new Array,this.labels=new Array}if(e)for(var i=0;i'+r],{type:"image/svg+xml"}),l=window.URL.createObjectURL(o);this.labelSVGS.push(l);var h=ci.CreatePlane("TextPlane",{width:i,height:8},this.scene);return h.material=new ie("TextPlaneMaterial",this.scene),h.material.backFaceCulling=!1,h.material.specularColor=new he(0,0,0),h.material.diffuseTexture=new se(l,this.scene),h.material.diffuseTexture.hasAlpha=!0,h.billboardMode=7,this.registerClipIgnore(h),h}},{key:"buildObservables",value:function(){var e=this;if(!this.observableControls){var t=0,i=!1,s=0;this.observableControls=this.scene.onPointerObservable.add(n=>{var r=n.pickInfo;switch(n.type){case Re.POINTERDOWN:i=!0,s=Date.now();break;case Re.POINTERUP:if(i=!1,Date.now()-s>200)return;e.handleClick(r);break;case Re.POINTERMOVE:if(i||Date.now()-t<100)return;t=Date.now(),e.handlePointerMove(r)}})}}},{key:"clearObservables",value:function(){this.observableControls&&(this.scene.onPointerObservable.remove(this.observableControls),this.observableControls=null)}},{key:"showObjectSelection",value:function(e){this.showCancelObjects=e,this.buildObjectMeshes.forEach(t=>t.setEnabled(e)),e?this.buildObservables():this.clearObservables()}},{key:"setObjectTexture",value:function(e){e.metadata&&(e.metadata.cancelled?(e.material=this.cancelledMaterial,e.enableEdgesRendering(),e.edgesWidth=15,e.edgesColor=new q(1,0,0,1)):(e.material=this.baseMaterial,e.enableEdgesRendering(),e.edgesWidth=15,e.edgesColor=new q(0,1,0,1)))}},{key:"handleClick",value:function(e){this.showCancelObjects&&e.hit&&e.pickedMesh&&e.pickedMesh.name.includes("OBJECTMESH")&&this.objectCallback&&this.objectCallback(e.pickedMesh.metadata)}},{key:"handlePointerMove",value:function(e){var t=this;this.showCancelObjects&&(this.buildObjectMeshes.forEach(i=>t.setObjectTexture(i)),e.hit&&e.pickedMesh&&e.pickedMesh.name.includes("OBJECTMESH")?(e.pickedMesh.material=e.pickedMesh.metadata.cancelled?this.cancelledHighlightMaterial:this.highlightMaterial,this.labelCallback&&this.labelCallback(e.pickedMesh.metadata.name)):this.labelCallback&&this.labelCallback(""))}},{key:"showLabels",value:function(e){localStorage.setItem("showObjectLabels",e),this.showLabel=e,this.labels.forEach(t=>t.setEnabled(e))}}]),a}(),F2=function(){function a(e){Et(this,a),this.visible=localStorage.getItem("axesVisible"),this.visible===null?this.visible=!0:this.visible=JSON.parse(this.visible),this.scene=e,this.registerClipIgnore=()=>{},this.axesMesh=null,this.axesMeshPosition=null,this.size=50,this.debug=!1}return Ct(a,[{key:"show",value:function(e){localStorage.setItem("axesVisible",e),this.axesMesh&&this.axesMesh.setEnabled(e),this.scene.render()}},{key:"makeTextPlane",value:function(e,t,i){var s=new Zn("DynamicTexture",50,this.scene,!0);s.hasAlpha=!0,s.drawText(e,5,40,"bold 36px Arial",t,"transparent",!0);var n=O.CreatePlane("TextPlane",i,this.scene,!0);return n.material=new ie("TextPlaneMaterial",this.scene),n.material.backFaceCulling=!1,n.material.specularColor=new he(0,0,0),n.material.diffuseTexture=s,n}},{key:"resize",value:function(e){this.size=e,this.axesMesh.dispose(!1,!0),this.render()}},{key:"render",value:function(e){var t=this;if(!this.debug)if(!this.axesMesh||this.axesMesh.isDisposed()){this.axesMesh=new O("axis",this.scene),this.registerClipIgnore(this.axesMesh);var i=O.CreateLines("axisX",[v.Zero(),new v(this.size,0,0),new v(.95*this.size,.05*this.size,0),new v(this.size,0,0),new v(.95*this.size,-.05*this.size,0)],this.scene);i.color=new he(1,0,0),i.parent=this.axesMesh;var s=this.makeTextPlane("X","red",this.size/10);s.billboardMode=7,s.position=new v(.9*this.size,.05*this.size,0),s.parent=this.axesMesh;var n=O.CreateLines("axisZ",[v.Zero(),new v(0,0,this.size),new v(0,-.05*this.size,.95*this.size),new v(0,0,this.size),new v(0,.05*this.size,.95*this.size)],this.scene);n.color=new he(0,1,0),n.parent=this.axesMesh;var r=this.makeTextPlane("Y","green",this.size/10);r.billboardMode=7,r.position=new v(0,.05*this.size,.9*this.size),r.parent=this.axesMesh;var o=O.CreateLines("axisY",[v.Zero(),new v(0,this.size,0),new v(-.05*this.size,.95*this.size,0),new v(0,this.size,0),new v(.05*this.size,.95*this.size,0)],this.scene);o.color=new he(0,0,1),o.parent=this.axesMesh;var l=this.makeTextPlane("Z","blue",this.size/10);l.billboardMode=7,l.position=new v(0,.9*this.size,-.05*this.size),l.parent=this.axesMesh,this.axesMesh.setEnabled(this.visible),this.axesMesh.getChildren().forEach(h=>t.registerClipIgnore(h)),e&&(this.axesMesh.position=e)}else e&&(this.axesMesh.position=e)}},{key:"dispose",value:function(){this.axesMesh&&this.axesMesh.dispose(!1,!0)}}]),a}(),Ze=null;function on(a,e,t){var i=function(s,n,r,o,l,h){var c=arguments.length>6&&arguments[6]!==void 0?arguments[6]:75,u=ih("svg").attr("width",400).attr("height",300);u.append("rect").attr("x",0).attr("y",0).attr("width",400).attr("height",300).attr("fill","#333333"),u.append("text").attr("x",200).attr("y",150).attr("font-family","Roboto").attr("font-size",c+"px").attr("text-anchor","middle").attr("alignment-baseline","middle").attr("fill",o).attr("stroke",r).attr("stroke-width",2).attr("text-rendering","optimizeLegibility").text(n);var d=u.attr("title","test2").attr("version",1.1).attr("xmlns","http://www.w3.org/2000/svg").node(),_='',f=new XMLSerializer().serializeToString(d),g=new Blob([_+f],{type:"image/svg+xml"}),p=window.URL.createObjectURL(g),x=ci.CreatePlane("TextPlane",{width:l,height:h},s);return x.material=new ie("TextPlaneMaterial",s),x.material.backFaceCulling=!1,x.material.specularColor=new he(0,0,0),x.material.diffuseTexture=new se(p,s),x.material.diffuseTexture.hasAlpha=!1,x}(a,e,"white","white",6,6,90);i.name=e,i.lookAt(t),i.position=t.scale(-3),e==="Top"&&i.rotate(Qt.Z,Math.PI/2,Nt.LOCAL),e==="Bottom"&&i.rotate(Qt.Z,-Math.PI/2,Nt.LOCAL),i.metadata={x:Math.sign(t.x),y:Math.sign(t.y),z:Math.sign(t.z)},i.isPickable=!0}function Ts(a,e,t){var i=ci.CreateSphere(e,{diameter:1.1},a),s=v.Zero();s.x=t.x-.25*Math.sign(t.x),s.y=t.y-.1*Math.sign(t.y),s.z=t.z-.25*Math.sign(t.z),i.metadata={x:-1*Math.sign(t.x),y:-1*Math.sign(t.y),z:-1*Math.sign(t.z)},i.position=s,i.isPickable=!0}var e0,wa=null;function Ei(a,e,t){wa||((wa=new ie("edgematerial",a)).diffuseColor=new he(.5,.5,.5));var i=ci.CreateBox(e,{width:.35,height:5.8,depth:.35},a),s=v.Zero();t.y!==0&&(i.rotate(Qt.Z,Math.PI/2,Nt.WORLD),t.x!==0&&i.rotate(Qt.Y,Math.PI/2,Nt.WORLD),i.bakeCurrentTransformIntoVertices()),s.x=t.x-Math.sign(t.x),s.y=t.y-Math.sign(t.y),s.z=t.z-Math.sign(t.z),i.metadata={x:-1*Math.sign(t.x),y:-1*Math.sign(t.y),z:-1*Math.sign(t.z)},i.position=s,i.material=wa}function O2(a,e,t){(Ze=new Me(a)).autoClear=!1;var i=new lt("camera1",5*Math.PI/8,5*Math.PI/8,13,new v(0,0,0),Ze);i.viewport=new mn(.85,.85,.15,.15),i.viewport.toGlobal(200,200),e.afterRender=()=>{Ze.render(),i.alpha=t.alpha,i.beta=t.beta,i.radius=15},new Qn("light1",new v(0,1,0),Ze).intensity=.8,new Qn("light2",new v(-1,-.5,0),Ze).intensity=.8;var s=3.9;Ei(Ze,"FrontLeft",new v(-s,0,-s)),Ei(Ze,"BackLeft",new v(-s,0,s)),Ei(Ze,"BackRight",new v(s,0,s)),Ei(Ze,"FrontRight",new v(s,0,-s)),Ei(Ze,"TopFront",new v(0,s,-s)),Ei(Ze,"TopBack",new v(0,s,s)),Ei(Ze,"TopLeft",new v(-s,s,0)),Ei(Ze,"TopRight",new v(s,s,0)),Ei(Ze,"BottomFront",new v(0,-s,-s)),Ei(Ze,"BottomBack",new v(0,-s,s)),Ei(Ze,"BottomLeft",new v(-s,-s,0)),Ei(Ze,"BottomRight",new v(s,-s,0)),Ts(Ze,"FrontTopLeft",new v(-3,3,-3)),Ts(Ze,"FrontTopRight",new v(3,3,-3)),Ts(Ze,"BackTopLeft",new v(-3,3,3)),Ts(Ze,"BackTopRight",new v(3,3,3)),Ts(Ze,"FrontBottomLeft",new v(-3,-3,-3)),Ts(Ze,"FrontBottomRight",new v(3,-3,-3)),Ts(Ze,"BackBottomLeft",new v(-3,-3,3)),Ts(Ze,"BackBottomRight",new v(3,-3,3)),on(Ze,"Front",new v(0,0,1)),on(Ze,"Right",new v(-1,0,0)),on(Ze,"Back",new v(0,0,-1)),on(Ze,"Left",new v(1,0,0)),on(Ze,"Top",new v(0,-1,0)),on(Ze,"Bottom",new v(0,1,0)),Ze.onPointerDown=(n,r)=>{r.distance>0&&e0&&(e0(r.pickedMesh.metadata),Ze.render(!0))}}var L2=function(){function a(e){Et(this,a),this.visible=!0,this.scene=e,this.workplacePoints=[],this.workplaceMeshes=[],this.registerClipIgnore=()=>{}}return Ct(a,[{key:"setOffsets",value:function(e){this.workplacePoints=e,this.render()}},{key:"makeTextPlane",value:function(e,t,i){var s=new Zn("DynamicTexture",50,this.scene,!0);s.hasAlpha=!0,s.drawText(e,5,40,"bold 36px Arial",t,"transparent",!0);var n=O.CreatePlane("TextPlane",i,this.scene,!0);return n.material=new ie("TextPlaneMaterial",this.scene),n.material.backFaceCulling=!1,n.material.specularColor=new he(0,0,0),n.material.diffuseTexture=s,n}},{key:"render",value:function(){if(this.workplaceMeshes.length>0){for(var e=0;e{},this.simulationStopped=()=>{},this.simLine=v.Zero(),this.isMMS=!1}var e,t,i,s;return Ct(a,[{key:"getMaxHeight",value:function(){return this.maxHeight}},{key:"getMinHeight",value:function(){return this.minHeight}},{key:"setCameraType",value:function(n){this.scene.activeCamera=n?this.orbitCamera:this.flyCamera}},{key:"setZClipPlane",value:function(n,r){this.zTopClipValue=-n,this.zBottomClipValue=r,r>n&&(this.zTopClipValue=r+1),this.scene.clipPlane=new ni(0,1,0,this.zTopClipValue),this.scene.clipPlane2=new ni(0,-1,0,this.zBottomClipValue),this.scene.render()}},{key:"isArcRotateCameraStopped",value:function(n){return n.inertialAlphaOffset===0&&n.inertialBetaOffset===0&&n.inertialRadiusOffset===0&&n.inertialPanningX===0&&n.inertialPanningY===0}},{key:"init",value:(s=Zi(yt().mark(function n(r){var o,l,h=this;return yt().wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return r===void 0&&(r=!1),console.info("GCode Viewer - Sindarius - ".concat("3.7.6"," ")),c.next=4,pe.IsSupportedAsync;case 4:if(!c.sent||!r){c.next=13;break}return console.log("WebGPU Supported"),this.engine=new pe(this.canvas,{doNotHandleContextLost:!0}),c.next=10,this.engine.initAsync();case 10:console.log(this.engine),c.next=15;break;case 13:console.log("WebGPU Not Supported"),this.engine=new Y(this.canvas,!0,{doNotHandleContextLost:!0});case 15:this.engine.enableOfflineSupport=!1,this.scene=new Me(this.engine),this.scene.performancePriority=Wi.BackwardCompatible,this.debug,this.scene.clearColor=he.FromHexString(this.getBackgroundColor()),this.bed=new w2(this.scene),this.bed.registerClipIgnore=u=>{h.registerClipIgnore(u)},o=this.bed.getCenter(),this.orbitCamera=new lt("Camera",Math.PI/2,2.356194,250,new v(o.x,-2,o.y),this.scene),this.orbitCamera.attachControl(!1),this.orbitCamera.invertRotation=!1,this.orbitCamera.attachControl(this.canvas,!1),this.orbitCamera.maxZ=1e5,this.orbitCamera.lowerRadiusLimit=5,this.updateCameraInertiaProperties(),(l=new E0("light2",new v(0,1,-1),this.scene)).diffuse=new he(1,1,1),l.specular=new he(1,1,1),this.engine.runRenderLoop(()=>{if(!document.hidden){if(h.simulation){if(h.pause)return}else if(h.pause||Date.now()-h.gcodeProcessor.lastUpdate>h.renderTimeout&&h.isArcRotateCameraStopped(h.orbitCamera))return;if(h.simulation)try{h.runSimulation(),h.gcodeProcessor.doUpdate()}catch{h.simulation=!1,h.simulationStopped()}h.scene.render(!0),l.position=h.scene.cameras[0].position}}),this.buildObjects=new D2(this.scene),this.buildObjects.getMaxHeight=()=>h.gcodeProcessor.getMaxHeight(),this.buildObjects.registerClipIgnore=u=>{h.registerClipIgnore(u)},this.bed.buildBed(),this.axes=new F2(this.scene),this.axes.registerClipIgnore=u=>{h.registerClipIgnore(u)},this.axes.render(),this.workplace=new L2(this.scene),this.workplace.registerClipIgnore=u=>{h.registerClipIgnore(u)},this.workplace.setOffsets(this.gcodeProcessor.workplaceOffsets),this.workplace.render(),this.resetCamera(),O2(this.engine,this.scene,this.orbitCamera),e0=u=>{h.setCameraPosition(u)},setTimeout(()=>{h.forceRender()},1e3);case 49:case"end":return c.stop()}},n,this)})),function(n){return s.apply(this,arguments)})},{key:"setCameraPosition",value:function(n,r,o){console.log(this.scene.activeCamera.position);var l=Number(n),h=Number(r),c=Number(o);l!==NaN&&h!==NaN&&c!==NaN&&(this.scene.activeCamera.position=new v(Number(n),Number(o),Number(r)),this.forceRender())}},{key:"resize",value:function(){this.engine.resize(),this.scene.render(!0)}},{key:"refreshUI",value:function(){setTimeout(()=>{},0)}},{key:"resetCamera",value:function(){var n=this.bed.getCenter(),r=this.bed.getSize();this.bed.isDelta?(this.scene.activeCamera.radius=n.x,this.scene.activeCamera.target=new v(n.x,-2,n.y),this.scene.activeCamera.position=new v(-r.x,r.z,-r.x)):(this.scene.activeCamera.radius=3*n.x,this.scene.activeCamera.target=new v(n.x,-2,n.y),this.scene.activeCamera.position=new v(-r.x/2,r.z,-r.y/2)),this.scene.render(!0),this.scene.render(!0)}},{key:"lastLoadFailed",value:function(){return!!localStorage&&localStorage.getItem(this.lastLoadKey)==="true"}},{key:"setLoadFlag",value:function(){localStorage&&localStorage.setItem(this.lastLoadKey,"true")}},{key:"clearLoadFlag",value:function(){localStorage&&(localStorage.setItem(this.lastLoadKey,""),localStorage.removeItem(this.lastLoadKey))}},{key:"processFile",value:(i=Zi(yt().mark(function n(r){return yt().wrap(function(o){for(;;)switch(o.prev=o.next){case 0:this.clearScene(),this.refreshUI(),r?(this.fileData=r,this.fileSize=r.length):(this.fileData=0,this.fileSize=0),this.fileDataArray=[];try{this.fileData===null&&this.fileData===""||(this.fileDataArray=this.fileData.split("\n"))}catch{this.fileDataArray=[]}return this.gcodeProcessor.setProgressColor(this.getProgressColor()),this.gcodeProcessor.scene=this.scene,this.lastLoadFailed()&&(console.error("Last rendering failed dropping to SBC quality"),this.updateRenderQuality(1),this.clearLoadFlag()),this.setLoadFlag(),o.next=11,this.gcodeProcessor.processGcodeFile(r,this.renderQuality);case 11:return this.clearLoadFlag(),o.next=14,this.gcodeProcessor.createMesh(this.scene);case 14:this.gcodeProcessor.loadingComplete(),this.maxHeight=this.gcodeProcessor.getMaxHeight(),this.minHeight=this.gcodeProcessor.getMinHeight(),this.toggleTravels(this.travelVisible),this.setCursorVisiblity(this.toolCursorVisible),this.gcodeProcessor.zBelt&&(this.bed.buildVolume.y.min=this.gcodeProcessor.beltLength,this.bed.buildVolume.y.max=0,this.bed.dispose(),this.bed.buildBed());case 20:case"end":return o.stop()}},n,this)})),function(n){return i.apply(this,arguments)})},{key:"toggleTravels",value:function(n){var r,o=function(h,c){var u=typeof Symbol<"u"&&h[Symbol.iterator]||h["@@iterator"];if(!u){if(Array.isArray(h)||(u=U0(h))||c&&h&&typeof h.length=="number"){u&&(h=u);var d=0,_=()=>{};return{s:_,n:()=>d>=h.length?{done:!0}:{done:!1,value:h[d++]},e:x=>{throw x},f:_}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var f,g=!0,p=!1;return{s:()=>{u=u.call(h)},n:()=>{var x=u.next();return g=x.done,x},e:x=>{p=!0,f=x},f:()=>{try{g||u.return==null||u.return()}finally{if(p)throw f}}}}(this.scene.meshes);try{for(o.s();!(r=o.n()).done;){var l=r.value;l.name==="travels"&&(l.isVisible=n)}}catch(h){o.e(h)}finally{o.f()}this.travelVisible=n,this.scene.render(!0)}},{key:"getProgressColor",value:function(){var n=localStorage.getItem("progressColor");return n===null&&(n="#FFFFFF"),n}},{key:"setProgressColor",value:function(n){localStorage.setItem("progressColor",n),this.gcodeProcessor.setProgressColor(n)}},{key:"getBackgroundColor",value:function(){var n=localStorage.getItem("sceneBackgroundColor");return n===null&&(n="#000000"),n}},{key:"setBackgroundColor",value:function(n){this.scene!==null&&this.scene!==void 0&&(n.length>7&&(n=n.substring(0,7)),this.scene.clearColor=he.FromHexString(n),this.scene.render()),localStorage.setItem("sceneBackgroundColor",n)}},{key:"clearScene",value:function(n){this.fileData&&n&&(this.fileData=""),this.gcodeProcessor.unregisterEvents();for(var r=this.scene.meshes.length-1;r>=0;r--){var o=this.scene.meshes[r];o&&this.debug&&console.log("Disposing ".concat(o.name)),this.scene.removeMesh(o),o&&typeof o.dispose=="function"&&o.dispose(!1,!0)}for(var l=this.scene.materials.length-1;l>=0;l--){var h=this.scene.materials[l];h.name==="solidMaterial"&&(h&&this.debug&&console.log("Disposing ".concat(h.name)),this.scene.removeMaterial(h),h&&typeof h.dispose=="function"&&h.dispose(!1,!0))}this.toolCursor&&(this.toolCursor.dispose(!1,!0),this.toolCursor=void 0),this.buildtoolCursor(),this.bed.buildBed(),this.axes.render(),this.workplace.render()}},{key:"reload",value:(t=Zi(yt().mark(function n(){return yt().wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return this.clearScene(),r.next=3,this.processFile(this.fileData);case 3:case"end":return r.stop()}},n,this)})),function(){return t.apply(this,arguments)})},{key:"getRenderMode",value:function(){return this.gcodeProcessor.renderMode}},{key:"setCursorVisiblity",value:function(n){this.scene!==void 0&&(this.toolCursor===void 0&&this.buildtoolCursor(),this.toolCursorMesh.isVisible=n,this.toolCursorVisible=n,this.scene.render())}},{key:"updateToolPosition",value:function(n){var r=0,o=0,l=0;if(this.buildtoolCursor(),n instanceof v)r=n.x,o=n.z,l=n.y;else for(var h=0;h{r.scene.clipPlane=null,r.scene.clipPlane2=null}),n.onAfterRenderObservable.add(()=>{r.scene.clipPlane=new ni(0,1,0,r.zTopClipValue),r.scene.clipPlane2=new ni(0,-1,0,r.zBottomClipValue)}))}},{key:"updateCameraInertiaProperties",value:function(){this.cameraInertia?(this.orbitCamera.speed=2,this.orbitCamera.inertia=.9,this.orbitCamera.panningInertia=.9,this.orbitCamera.inputs.attached.keyboard.angularSpeed=.005,this.orbitCamera.inputs.attached.keyboard.zoomingSensibility=2,this.orbitCamera.inputs.attached.keyboard.panningSensibility=2,this.orbitCamera.angularSensibilityX=1e3,this.orbitCamera.angularSensibilityY=1e3,this.orbitCamera.panningSensibility=10,this.orbitCamera.wheelPrecision=1):(this.orbitCamera.speed=500,this.orbitCamera.inertia=0,this.orbitCamera.panningInertia=0,this.orbitCamera.inputs.attached.keyboard.angularSpeed=.05,this.orbitCamera.inputs.attached.keyboard.zoomingSensibility=.5,this.orbitCamera.inputs.attached.keyboard.panningSensibility=.5,this.orbitCamera.angularSensibilityX=200,this.orbitCamera.angularSensibilityY=200,this.orbitCamera.panningSensibility=2,this.orbitCamera.wheelPrecision=.25)}},{key:"setCameraInertia",value:function(n){this.cameraInertia=n,localStorage.setItem("cameraInertia",n),this.updateCameraInertiaProperties()}},{key:"forceRender",value:function(){this.scene&&this.scene.render(!0)}},{key:"getLayers",value:function(){return this.gcodeProcessor.layerDictionary}},{key:"getGCodeLine",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:5;try{var r=Math.max(0,this.gcodeProcessor.currentLineNumber-n),o=Math.min(this.gcodeProcessor.currentLineNumber,this.fileDataArray.length-1);return this.fileDataArray.slice(r,o).join("\r\n").trim()}catch{return""}}},{key:"getGCodeLineNumber",value:function(){return this.gcodeProcessor.currentLineNumber}},{key:"goToGCodeLine",value:function(n){}},{key:"simulateToolPosition",value:function(){this.updateToolPosition(this.gcodeProcessor.nozzlePosition)}},{key:"setZBelt",value:function(n,r){this.gcodeProcessor.zBelt=n,n&&(this.gcodeProcessor.setZBeltAngle(r),this.toolCursorMesh.rotate(Qt.X,Math.PI/2-r*Math.PI/180,Nt.LOCAL))}},{key:"setWorkplaceVisiblity",value:function(n){this.workplace.visible=n,this.workplace.setOffsets(this.gcodeProcessor.workplaceOffsets),this.workplace.render(),this.scene.render()}},{key:"startSimulation",value:function(){this.gcodeProcessor.lastFilePositionIndex>=this.gcodeProcessor.renderedLines.length-1&&this.gcodeProcessor.updateFilePositionIndex(1),this.simulation=!0,this.gcodeProcessor.doUpdate()}},{key:"stopSimulation",value:function(){this.simulation=!1,this.simulationStopped()}},{key:"clamp",value:function(n,r,o){return Math.min(Math.max(n,r),o)}},{key:"runSimulation",value:function(){if(this.gcodeProcessor.renderedLines.length!==0){if(this.gcodeProcessor.lastFilePositionIndex>=this.gcodeProcessor.renderedLines.length-1&&(this.simulation=!1,this.simulationStopped()),this.simulationCurrentLine!=this.gcodeProcessor.renderedLines[this.gcodeProcessor.lastFilePositionIndex]){this.simulationCurrentLine=this.gcodeProcessor.renderedLines[this.gcodeProcessor.lastFilePositionIndex],this.updateToolPosition(this.simulationCurrentLine.start),this.simulationLastUpdate=0;var n=this.isMMS?this.simulationCurrentLine.feedRate:this.simulationCurrentLine.feedRate/60;this.simulationTimeToMove=this.simulationCurrentLine.length()/n*1e3,this.simulationUpdatePosition(this.simulationCurrentLine.gcodeFilePosition)}this.simLine=this.simulationCurrentLine.start.clone(),this.simulationLastUpdate+=this.engine.getDeltaTime()*this.simulationMultiplier*this.scene.getAnimationRatio();var r=this.clamp(this.simulationLastUpdate/this.simulationTimeToMove,0,1);if(v.LerpToRef(this.simulationCurrentLine.start,this.simulationCurrentLine.end,r,this.simLine),this.updateToolPosition(this.simLine),this.simulationLastUpdate>=this.simulationTimeToMove||this.simulationTimeToMove==1/0||this.simulationTimeToMove==0){var o=this.simulationMultiplier>10?this.simulationMultiplier:1,l=this.scene.getAnimationRatio();l>3&&(o+=~~l),this.gcodeProcessor.updateFilePositionIndex(this.gcodeProcessor.lastFilePositionIndex+o)}}}},{key:"getCameraPosition",value:function(){return this.scene.cameras[0].position}},{key:"getCameraTarget",value:function(){return this.scene.cameras[0].target}},{key:"setCameraTarget",value:function(n,r,o){var l=Number(n),h=Number(r),c=Number(o);l!==NaN&&h!==NaN&&c!==NaN&&(this.scene.activeCamera.target=new v(Number(n),Number(o),Number(r)),this.forceRender())}},{key:"createScreenshot",value:(e=Zi(yt().mark(function n(){var r,o,l,h,c=arguments;return yt().wrap(function(u){for(;;)switch(u.prev=u.next){case 0:return r=c.length>0&&c[0]!==void 0?c[0]:1920,o=c.length>1&&c[1]!==void 0?c[1]:1080,l=this.scene.clearColor,this.scene.clearColor=new q(0,0,0,0),this.displayViewBox(!1),this.gcodeProcessor.forceRender(),this.gcodeProcessor.doUpdate(),this.scene.render(!0,!0),this.scene.onAfterRenderObservable.addOnce(()=>{}),u.next=13,Xp.CreateScreenshotAsync(this.engine,this.scene.activeCamera,{width:r,height:o});case 13:return h=u.sent,this.scene.clearColor=l,u.abrupt("return",h);case 16:case"end":return u.stop()}},n,this)})),function(){return e.apply(this,arguments)})},{key:"displayViewBox",value:function(n){(function(r){Ze.meshes.forEach(o=>{o.setEnabled(r)})})(n)}}]),a}(),N2=Object.defineProperty,U2=Object.getOwnPropertyDescriptor,tn=(a,e,t,i)=>{for(var s=i>1?void 0:i?U2(e,t):e,n=a.length-1,r;n>=0;n--)(r=a[n])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&N2(e,t,s),s};let fs=class extends Ec{constructor(){super(...arguments),this.view=void 0}mounted(){this.view=new Nc({doc:this.document,extensions:[Uc,kc.readOnly.of(!0)],parent:this.$refs.view})}mouseUp(){if(this.view){let a=this.view.state.doc.lineAt(this.view.state.selection.ranges[0].from);this.$emit("update:currentline",a.to),this.view.contentDOM.blur(),this.$emit("got-focus")}}keyPress(){if(this.view){let a=this.view.state.doc.lineAt(this.view.state.selection.ranges[0].from);this.$emit("update:currentline",a.to),this.$emit("got-focus")}}documentUpdated(){this.view&&this.shown&&this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:this.document}})}currentlineUpdated(a){if(this.view&&this.shown){let e=this.view.state.doc.lineAt(a);this.view.dispatch({selection:{anchor:e.from,head:e.from},scrollIntoView:!0})}}};tn([Vc("currentline")],fs.prototype,"currentLineNumber",2);tn([Hr({type:String,default:""})],fs.prototype,"document",2);tn([Hr({type:Boolean,default:!1})],fs.prototype,"isSimulating",2);tn([Hr({type:Boolean,default:!1})],fs.prototype,"shown",2);tn([ot("document")],fs.prototype,"documentUpdated",1);tn([ot("currentLineNumber")],fs.prototype,"currentlineUpdated",1);fs=tn([i0({})],fs);var k2=function(){var a=this,e=a.$createElement,t=a._self._c||e;return t("div",{ref:"view",staticClass:"codeview",on:{mouseup:a.mouseUp,keydown:a.keyPress}})},V2=[];const sl={};var G2=s0(fs,k2,V2,!1,W2,"7831183a",null,null);function W2(a){for(let e in sl)this[e]=sl[e]}const rc=function(){return G2.exports}();var z2=Object.defineProperty,H2=Object.getOwnPropertyDescriptor,et=(a,e,t,i)=>{for(var s=i>1?void 0:i?H2(e,t):e,n=a.length-1,r;n>=0;n--)(r=a[n])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&z2(e,t,s),s};let Z=null,qe=class extends al(ol){constructor(){super(...arguments),this.mdiReloadAlert=dc,this.mdiCameraRetake=fc,this.mdiToggleSwitch=_c,this.mdiToggleSwitchOffOutline=pc,this.mdiClose=gc,this.mdiCog=mc,this.mdiVideo3d=vc,this.mdiPlay=xc,this.mdiPause=bc,this.mdiFastForward=yc,this.mdiBroom=Tc,this.mdiSelectionRemove=Sc,this.formatFilesize=Ac,this.isBusy=!1,this.loading=!1,this.loadingPercent=0,this.tracking=!1,this.loadedFile=null,this.reloadRequired=!1,this.fileSize=0,this.renderQuality=this.renderQualities[2],this.scrubPosition=0,this.scrubPlaying=!1,this.scrubSpeed=1,this.scrubInterval=void 0,this.scrubFileSize=0,this.downloadSnackbar={status:!1,filename:"",percent:0,speed:0,total:0,cancelTokenSource:{},lastProgress:{time:0,loaded:0}},this.excludeObject={bool:!1,name:""},this.fileData="",this.colorModes=[{text:"Extruder",value:0},{text:"Feed Rate",value:1},{text:"Feature",value:2}]}get renderQualities(){return[{label:this.$t("GCodeViewer.Low"),value:2},{label:this.$t("GCodeViewer.Medium"),value:3},{label:this.$t("GCodeViewer.High"),value:4},{label:this.$t("GCodeViewer.Ultra"),value:5},{label:this.$t("GCodeViewer.Max"),value:6}]}async mounted(){var e,t,i,s;this.loadedFile=(t=(e=this.$store.state.gcodeviewer)==null?void 0:e.loadedFileBackup)!=null?t:null,Z=(s=(i=this.$store.state.gcodeviewer)==null?void 0:i.viewerBackup)!=null?s:null,await this.init(),this.loadedFile!==null&&(this.scrubFileSize=Z.fileSize),Z&&(this.fileData=Z.fileData)}beforeDestroy(){Z&&(Z.gcodeProcessor.loadingProgressCallback=null,this.$store.dispatch("gcodeviewer/setLoadedFileBackup",this.loadedFile),this.$store.dispatch("gcodeviewer/setViewerBackup",Z)),this.scrubPlaying=!1,this.scrubInterval&&(clearInterval(this.scrubInterval),this.scrubInterval=void 0)}handleResize(){this.$nextTick(()=>{Z==null||Z.resize()})}get panelTitle(){let e=this.$t("GCodeViewer.Title").toString();return this.loadedFile&&(e+=": ".concat(this.loadedFile)),e}get filePosition(){return this.printerIsPrinting?this.$store.state.printer.virtual_sdcard.file_position:0}get sdCardFilePath(){var e,t;return(t=(e=this.$store.state.printer.print_stats)==null?void 0:e.filename)!=null?t:""}get livePosition(){var e,t;return(t=(e=this.$store.state.printer.motion_report)==null?void 0:e.live_position)!=null?t:[0,0,0,0]}get gcodeOffset(){var e,t,i;return(i=(t=(e=this.$store.state.printer)==null?void 0:e.gcode_move)==null?void 0:t.homing_origin)!=null?i:[0,0,0]}get currentPosition(){return[this.livePosition[0]-this.gcodeOffset[0],this.livePosition[1]-this.gcodeOffset[1],this.livePosition[2]-this.gcodeOffset[2],this.livePosition[3]]}get showTrackingButton(){return this.printerIsPrinting&&this.sdCardFilePath===this.loadedFile}get printing_objects(){var e,t;return(t=(e=this.$store.state.printer.exclude_object)==null?void 0:e.objects)!=null?t:[]}printing_objectsChanged(){this.refreshPrintingObjects()}get excluded_objects(){var e,t;return(t=(e=this.$store.state.printer.exclude_object)==null?void 0:e.excluded_objects)!=null?t:[]}excluded_objectsChanged(){this.refreshPrintingObjects()}get nozzle_diameter(){var e,t,i,s;return(s=(i=(t=(e=this.$store.state.printer.configfile)==null?void 0:e.settings)==null?void 0:t.extruder)==null?void 0:i.nozzle_diameter)!=null?s:.4}async init(){var t,i,s,n,r;let e=(i=(t=this.$store.state.gcodeviewer)==null?void 0:t.canvasBackup)!=null?i:null;e===null?(e=document.createElement("canvas"),e.className="viewer",this.$refs.viewerCanvasContainer.appendChild(e),await this.$store.dispatch("gcodeviewer/setCanvasBackup",e)):(this.$refs.viewerCanvasContainer.appendChild(e),Z!=null&&Z.gcodeProcessor&&Z.gcodeProcessor.updateFilePosition(Z==null?void 0:Z.fileSize)),Z===null&&await this.viewerInit(e),this.registerProgressCallback(),(s=this.$route.query)!=null&&s.filename&&this.loadedFile!==((r=(n=this.$route.query)==null?void 0:n.filename)==null?void 0:r.toString())&&(await this.sleep(1e3),await this.loadFile(this.$route.query.filename.toString()))}async viewerInit(e){Z=new B2(e),await Z.init(),Z.setBackgroundColor(this.backgroundColor),Z.bed.setBedColor(this.gridColor),Z.setCursorVisiblity(this.showCursor),Z.setZClipPlane(1e6,-1e6),Z.axes.show(this.showAxes),Z.bed.setDelta(this.kinematics.includes("delta")),this.bedMaxSize!==null&&(Z.bed.buildVolume.x.max=this.bedMaxSize[0],Z.bed.buildVolume.y.max=this.bedMaxSize[1],Z.bed.buildVolume.z.max=this.bedMaxSize[2]),this.bedMinSize!==null&&(Z.bed.buildVolume.x.min=this.bedMinSize[0],Z.bed.buildVolume.y.min=this.bedMinSize[1],Z.bed.buildVolume.z.min=this.bedMinSize[2]),Z.gcodeProcessor.useHighQualityExtrusion(this.hdRendering),Z.gcodeProcessor.updateForceWireMode(this.forceLineRendering||this.cncMode),Z.gcodeProcessor.setAlpha(this.transparency),Z.gcodeProcessor.setVoxelMode(this.voxelMode),Z.gcodeProcessor.voxelWidth=this.voxelWidth,Z.gcodeProcessor.voxelHeight=this.voxelHeight,Z.gcodeProcessor.useSpecularColor(this.specularLighting),Z.gcodeProcessor.setLiveTracking(!1),Z.gcodeProcessor.g1AsExtrusion=this.cncMode,Z.buildObjects.objectCallback=this.objectCallback,this.loadToolColors(this.extruderColors),Z.lastLoadFailed()&&(this.renderQuality=this.renderQualities[0],Z.updateRenderQuality(1),Z.clearLoadFlag())}registerProgressCallback(){Z&&(Z.gcodeProcessor.loadingProgressCallback=e=>{this.loadingPercent=Math.ceil(e*100),this.loading=this.loadingPercent<=99})}async cancelRendering(){Z&&(Z.gcodeProcessor.cancelLoad=!0,await this.sleep(1e3))}clearLoadedFile(){Z&&(this.scrubPlaying=!1,this.scrubFileSize=0,Z.clearScene(!0),this.loadedFile=null,this.tracking=!1)}chooseFile(){this.isBusy||this.fileInput.click()}finishLoad(){this.loading=!1,Z.setCursorVisiblity(this.showCursor),this.refreshPrintingObjects(),this.scrubFileSize=Z.fileSize,Z.gcodeProcessor.updateFilePosition(Z.fileSize)}refreshPrintingObjects(){let e=[];this.loadedFile===this.sdCardFilePath&&this.printing_objects.length&&this.printing_objects.forEach(t=>{const i=t.polygon.map(n=>n[0]),s=t.polygon.map(n=>n[1]);e.push({cancelled:this.excluded_objects.includes(t.name),name:t.name,x:[Math.min(...i),Math.max(...i)],y:[Math.min(...s),Math.max(...s)]})}),Z.buildObjects.loadObjectBoundaries(e),Z.buildObjects.showObjectSelection(this.showObjectSelection)}async fileSelected(e){var i,s;const t=new FileReader;t.addEventListener("load",async n=>{if(!n||!n.target)return;const r=n.target.result;typeof r=="string"&&(this.fileSize=r.length,await Z.processFile(r),this.fileData=Z.fileData),this.finishLoad()}),this.tracking=!1,(i=e.target.files)!=null&&i.length&&(this.loadedFile=(s=e==null?void 0:e.target)==null?void 0:s.files[0].name,t.readAsText(e.target.files[0])),e.target.value=""}async loadFile(e){this.downloadSnackbar.status=!0,this.downloadSnackbar.speed=0,this.downloadSnackbar.lastProgress.time=0,this.downloadSnackbar.filename=e.startsWith("gcodes/")?e.slice(7):e;const t=X0.CancelToken;this.downloadSnackbar.cancelTokenSource=t.source();const i=await X0.get(this.apiUrl+"/server/files/"+encodeURI(e),{cancelToken:this.downloadSnackbar.cancelTokenSource.token,responseType:"blob",onDownloadProgress:s=>{if(this.downloadSnackbar.percent=s.loaded*100/s.total,this.downloadSnackbar.lastProgress.time){const n=s.timeStamp-this.downloadSnackbar.lastProgress.time,r=s.loaded-this.downloadSnackbar.lastProgress.loaded;(n>1e3||this.downloadSnackbar.speed===0)&&(this.downloadSnackbar.speed=r/(n/1e3),this.downloadSnackbar.lastProgress.time=s.timeStamp,this.downloadSnackbar.lastProgress.loaded=s.loaded)}else this.downloadSnackbar.lastProgress.time=s.timeStamp;this.downloadSnackbar.total=s.total}}).then(s=>s.data.text()).catch(s=>{window.console.error(s.message)});this.downloadSnackbar.status=!1,this.loadedFile=this.downloadSnackbar.filename,Z.updateRenderQuality(this.renderQuality.value),await Z.processFile(i),this.fileData=Z.fileData,this.loadingPercent=100,this.finishLoad(),this.scrubFileSize=Z.fileSize}cancelDownload(){this.downloadSnackbar.cancelTokenSource.cancel("User canceled download gcode file")}async sleep(e){await new Promise(t=>setTimeout(t,e))}async loadCurrentFile(){await this.loadFile("gcodes/"+this.sdCardFilePath),this.loadedFile=this.sdCardFilePath}async reloadViewer(){this.loading&&(Z.gcodeProcessor.cancelLoad=!0,await this.sleep(1e3)),this.reloadRequired=!1,this.loading=!0,this.loadingPercent=0,await Z.reload(),this.fileData=Z.fileData,this.loadingPercent=100,this.finishLoad()}resetCamera(){Z.resetCamera()}setReloadRequiredFlag(){this.loadedFile&&this.loadedFile!=""&&(this.reloadRequired=!0)}async renderQualityChanged(e){Z&&Z.renderQuality!==e&&(Z.updateRenderQuality(e),await this.reloadViewer())}currentPositionChanged(e){if(Z){const t=[{axes:"X",position:e[0]},{axes:"Y",position:e[1]},{axes:"Z",position:e[2]}];Z.updateToolPosition(t)}}filePositionChanged(e){if(!Z)return;const t=350;e>0&&this.printerIsPrinting&&this.tracking&&e>t?(Z.gcodeProcessor.updateFilePosition(e-t),this.scrubPosition=e-t):Z.gcodeProcessor.updateFilePosition(Z.fileSize)}async trackingChanged(e){Z&&(e?(this.scrubPlaying=!1,Z.gcodeProcessor.updateFilePosition(0),Z==null||Z.forceRender()):(Z.gcodeProcessor.setLiveTracking(!1),await this.reloadViewer()))}printerIsPrintingChanged(){this.tracking=!1}get showCursor(){var e;return(e=this.$store.state.gui.gcodeViewer.showCursor)!=null?e:!1}set showCursor(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.showCursor",value:e})}showCursorChanged(e){Z==null||Z.setCursorVisiblity(e)}get showTravelMoves(){var e;return(e=this.$store.state.gui.gcodeViewer.showTravelMoves)!=null?e:!1}set showTravelMoves(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.showTravelMoves",value:e})}get showGCode(){var e;return(e=this.$store.state.gui.gcodeViewer.showGCode)!=null?e:!1}set showGCode(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.showGCode",value:e}),e&&Z&&(this.fileData=Z.fileData),this.handleResize()}showTravelMovesChanged(e){Z==null||Z.toggleTravels(e)}get showObjectSelection(){var e;return(e=this.$store.state.gui.gcodeViewer.showObjectSelection)!=null?e:!1}set showObjectSelection(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.showObjectSelection",value:e})}showObjectSelectionChanged(e){Z==null||Z.buildObjects.showObjectSelection(e)}get hdRendering(){return this.$store.state.gui.gcodeViewer.hdRendering}set hdRendering(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.hdRendering",value:e})}async hdRenderingChanged(e){Z&&(Z.gcodeProcessor.useHighQualityExtrusion(e),await this.reloadViewer())}get forceLineRendering(){return this.$store.state.gui.gcodeViewer.forceLineRendering}set forceLineRendering(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.forceLineRendering",value:e})}async forceLineRenderingChanged(e){Z&&(Z.gcodeProcessor.updateForceWireMode(e||this.cncMode),await this.reloadViewer())}get transparency(){return this.$store.state.gui.gcodeViewer.transparency}set transparency(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.transparency",value:e})}async transparencyChanged(e){Z&&(Z.gcodeProcessor.setAlpha(e),await this.reloadViewer())}get voxelMode(){return this.$store.state.gui.gcodeViewer.voxelMode}set voxelMode(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.voxelMode",value:e})}async voxelModeChanged(e){Z&&(Z.gcodeProcessor.setVoxelMode(e),Z.gcodeProcessor.voxelWidth=this.voxelWidth,Z.gcodeProcessor.voxelHeight=this.voxelHeight,await this.reloadViewer())}get voxelWidth(){var e;return(e=this.$store.state.gui.gcodeViewer.voxelWidth)!=null?e:1}set voxelWidth(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.voxelWidth",value:e})}get voxelHeight(){var e;return(e=this.$store.state.gui.gcodeViewer.voxelHeight)!=null?e:1}set voxelHeight(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.voxelHeight",value:e})}get specularLighting(){return this.$store.state.gui.gcodeViewer.specularLighting}set specularLighting(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.specularLighting",value:e})}async specularLightingChanged(e){Z&&Z.gcodeProcessor.useSpecularColor(e)}get cncMode(){return this.$store.state.gui.gcodeViewer.cncMode}set cncMode(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.cncMode",value:e}),Z.gcodeProcessor.g1AsExtrusion=e,Z.gcodeProcessor.updateForceWireMode(this.forceLineRendering||e),this.reloadViewer()}get extruderColors(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.extruderColors)!=null?t:!1}loadToolColors(e){Z&&e.length&&(Z.gcodeProcessor.resetTools(),e.forEach(t=>{Z.gcodeProcessor.addTool(t,this.nozzle_diameter)}),this.setReloadRequiredFlag())}extruderColorsChanged(e){Z&&e&&e.length&&(this.loadToolColors(e),this.setReloadRequiredFlag())}get colorMode(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.colorMode)!=null?t:2}set colorMode(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.colorMode",value:e}),Z&&Z.gcodeProcessor.colorMode!==e&&(Z.gcodeProcessor.setColorMode(e),this.reloadViewer())}get backgroundColor(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.backgroundColor)!=null?t:"#121212"}backgroundColorChanged(e){Z&&Z.setBackgroundColor(e)}get gridColor(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.gridColor)!=null?t:"#B3B3B3"}gridColorChanged(e){Z&&Z.bed.setBedColor(e)}get showAxes(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.showAxes)!=null?t:!0}showAxesChanged(e){Z&&Z.axes.show(e)}get minFeed(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.minFeed)!=null?t:20}minFeedChanged(e){Z&&Z.gcodeProcessor.updateColorRate(e*60,this.maxFeed*60)}get maxFeed(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.maxFeed)!=null?t:100}maxFeedChanged(e){Z&&Z.gcodeProcessor.updateColorRate(this.minFeed*60,e*60)}get minFeedColor(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.minFeedColor)!=null?t:"#0000FF"}minFeedColorUpdated(e){Z&&(Z.gcodeProcessor.updateMinFeedColor(e),this.setReloadRequiredFlag())}get maxFeedColor(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.maxFeedColor)!=null?t:"#FF0000"}maxFeedColorUpdated(e){Z&&(Z.gcodeProcessor.updateMaxFeedColor(e),this.setReloadRequiredFlag())}get kinematics(){var e,t,i,s,n,r,o,l;return(l=(o=(i=(t=(e=this.$store.state.printer.configfile)==null?void 0:e.settings)==null?void 0:t.printer)==null?void 0:i.kinematics)!=null?o:(r=(n=(s=this.$store.state.gui)==null?void 0:s.gcodeViewer)==null?void 0:n.klipperCache)==null?void 0:r.kinematics)!=null?l:""}get bedMaxSize(){var e,t,i,s,n,r;return(r=(n=(e=this.$store.state.printer.toolhead)==null?void 0:e.axis_maximum)!=null?n:(s=(i=(t=this.$store.state.gui)==null?void 0:t.gcodeViewer)==null?void 0:i.klipperCache)==null?void 0:s.axis_maximum)!=null?r:null}get bedMinSize(){var e,t,i,s,n,r;return(r=(n=(e=this.$store.state.printer.toolhead)==null?void 0:e.axis_minimum)!=null?n:(s=(i=(t=this.$store.state.gui)==null?void 0:t.gcodeViewer)==null?void 0:i.klipperCache)==null?void 0:s.axis_minimum)!=null?r:null}kinematicsChanged(e){Z&&e&&Z.bed.setDelta(e.includes("delta"))}bedMinSizeChanged(e){Z&&e&&(Z.bed.buildVolume.x.min=e[0],Z.bed.buildVolume.y.min=e[1],Z.bed.buildVolume.z.min=e[2])}bedMaxSizeChanged(e){e&&Z&&(Z.bed.buildVolume.x.max=e[0],Z.bed.buildVolume.y.max=e[1],Z.bed.buildVolume.z.max=e[2])}get progressColor(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.progressColor)!=null?t:"#FFFFFF"}progressColorChanged(e){Z==null||Z.setProgressColor(e)}scrubPlayingChanged(e){e?(this.scrubInterval&&(clearInterval(this.scrubInterval),this.scrubInterval=void 0),this.scrubPlaying=!0,this.scrubPosition>=this.scrubFileSize&&(this.scrubPosition=0),Z.gcodeProcessor.updateFilePosition(this.scrubPosition-3e4),this.scrubInterval=setInterval(()=>{this.scrubPosition+=100*this.scrubSpeed,Z.gcodeProcessor.updateFilePosition(this.scrubPosition),Z.simulateToolPosition(),(this.tracking||this.scrubPosition>=this.scrubFileSize)&&(this.scrubPlaying=!1)},200)):(this.scrubInterval&&clearInterval(this.scrubInterval),this.scrubPlaying=!1,this.scrubInterval=void 0)}get showScrubber(){return!this.tracking&&this.scrubFileSize>0}updateScrubPosition(e){this.tracking||(Z.gcodeProcessor.updateFilePosition(e),Z.simulateToolPosition())}fastForward(){this.scrubPosition=this.scrubFileSize,Z.gcodeProcessor.updateFilePosition(this.scrubPosition)}objectCallback(e){var t;(e==null?void 0:e.cancelled)===!1&&(this.excludeObject.name=(t=e.name)!=null?t:"UNKNOWN",this.excludeObject.bool=!0)}cancelObject(){this.$socket.emit("printer.gcode.script",{script:"EXCLUDE_OBJECT NAME="+this.excludeObject.name}),this.excludeObject.bool=!1}};et([Hr({type:String,default:"",required:!1})],qe.prototype,"filename",2);et([cl("fileInput")],qe.prototype,"fileInput",2);et([cl("viewerCanvasContainer")],qe.prototype,"viewerCanvasContainer",2);et([ll(200)],qe.prototype,"handleResize",1);et([ot("printing_objects")],qe.prototype,"printing_objectsChanged",1);et([ot("excluded_objects")],qe.prototype,"excluded_objectsChanged",1);et([ot("renderQuality")],qe.prototype,"renderQualityChanged",1);et([ot("currentPosition")],qe.prototype,"currentPositionChanged",1);et([ot("filePosition")],qe.prototype,"filePositionChanged",1);et([ot("tracking")],qe.prototype,"trackingChanged",1);et([ot("printerIsPrinting")],qe.prototype,"printerIsPrintingChanged",1);et([ot("showCursor")],qe.prototype,"showCursorChanged",1);et([ot("showTravelMoves")],qe.prototype,"showTravelMovesChanged",1);et([ot("showObjectSelection")],qe.prototype,"showObjectSelectionChanged",1);et([ot("hdRendering")],qe.prototype,"hdRenderingChanged",1);et([ot("forceLineRendering")],qe.prototype,"forceLineRenderingChanged",1);et([ot("transparency")],qe.prototype,"transparencyChanged",1);et([ot("voxelMode")],qe.prototype,"voxelModeChanged",1);et([ot("specularLighting")],qe.prototype,"specularLightingChanged",1);et([ot("extruderColors")],qe.prototype,"extruderColorsChanged",1);et([ot("backgroundColor")],qe.prototype,"backgroundColorChanged",1);et([ot("gridColor")],qe.prototype,"gridColorChanged",1);et([ot("showAxes")],qe.prototype,"showAxesChanged",1);et([ot("minFeed")],qe.prototype,"minFeedChanged",1);et([ot("maxFeed")],qe.prototype,"maxFeedChanged",1);et([ot("minFeedColor")],qe.prototype,"minFeedColorUpdated",1);et([ot("maxFeedColor")],qe.prototype,"maxFeedColorUpdated",1);et([ot("kinematics")],qe.prototype,"kinematicsChanged",1);et([ot("bedMinSize",{deep:!0})],qe.prototype,"bedMinSizeChanged",1);et([ot("bedMaxSize",{deep:!0})],qe.prototype,"bedMaxSizeChanged",1);et([ot("progressColor")],qe.prototype,"progressColorChanged",1);et([ot("scrubPlaying")],qe.prototype,"scrubPlayingChanged",1);et([ll(200),ot("scrubPosition")],qe.prototype,"updateScrubPosition",1);qe=et([i0({components:{Panel:hl,CodeStream:rc}})],qe);var X2=function(){var a=this,e=a.$createElement,t=a._self._c||e;return t("div",[t(hl,{attrs:{title:a.panelTitle,icon:a.mdiVideo3d,"card-class":"gcode-viewer-panel","margin-bottom":!1},scopedSlots:a._u([{key:"buttons",fn:function(){return[t(zt,{directives:[{name:"show",rawName:"v-show",value:a.reloadRequired,expression:"reloadRequired"}],staticClass:"ml-3",attrs:{icon:a.$vuetify.breakpoint.xs,text:a.$vuetify.breakpoint.smAndUp,tile:"",color:"info"},on:{click:a.reloadViewer}},[t("span",{staticClass:"d-none d-sm-block"},[a._v(a._s(a.$t("GCodeViewer.ReloadRequired")))]),t(Oi,{staticClass:"d-sm-none"},[a._v(a._s(a.mdiReloadAlert))])],1),t(zt,{attrs:{icon:"",tile:""},on:{click:a.resetCamera}},[t(Oi,[a._v(a._s(a.mdiCameraRetake))])],1)]},proxy:!0}])},[t(K0,[t(hr,{class:a.showScrubber?"withScrubber":""},[t(xs,{attrs:{cols:a.showGCode?8:12}},[t("div",{ref:"viewerCanvasContainer"})]),t(xs,{directives:[{name:"show",rawName:"v-show",value:a.showGCode,expression:"showGCode"}],attrs:{cols:"4"}},[t("div",{staticClass:"viewer"},[t(rc,{ref:"gcodestream",attrs:{shown:a.showGCode,currentline:a.scrubPosition,document:a.fileData,"is-simulating":!a.printerIsPrinting},on:{"update:currentline":function(i){a.scrubPosition=i}}})],1)])],1),t(hr,{directives:[{name:"show",rawName:"v-show",value:a.showScrubber,expression:"showScrubber"}],staticClass:"scrubber"},[t(xs,{staticClass:"pt-0"},[t(Cc,{attrs:{hint:a.scrubPosition+"/"+a.scrubFileSize,max:a.scrubFileSize,dense:"",min:"0","persistent-hint":""},model:{value:a.scrubPosition,callback:function(i){a.scrubPosition=i},expression:"scrubPosition"}})],1),t(xs,{staticClass:"col-auto pt-0 text-center"},[t(zt,{staticClass:"px-2 minwidth-0",attrs:{color:"primary"},on:{click:function(i){a.scrubPlaying=!a.scrubPlaying}}},[a.scrubPlaying?t(Oi,[a._v(a._s(a.mdiPause))]):t(Oi,[a._v(a._s(a.mdiPlay))])],1),t(zt,{staticClass:"px-2 minwidth-0 mx-3",attrs:{color:"primary"},on:{click:a.fastForward}},[t(Oi,[a._v(a._s(a.mdiFastForward))])],1),t(Rc,{staticClass:"mt-3 mt-sm-0",attrs:{dense:"",mandatory:"",rounded:""},model:{value:a.scrubSpeed,callback:function(i){a.scrubSpeed=i},expression:"scrubSpeed"}},[t(zt,{attrs:{value:1}},[a._v("1x")]),t(zt,{attrs:{value:2}},[a._v("2x")]),t(zt,{attrs:{value:5}},[a._v("5x")]),t(zt,{attrs:{value:10}},[a._v("10x")]),t(zt,{attrs:{value:20}},[a._v("20x")])],1)],1)],1),t(hr,{staticClass:"mt-0 d-flex align-top"},[t(xs,[t(hr,[t(xs,{staticClass:"d-flex align-content-space-around justify-center flex-wrap flex-md-nowrap col-12 col-md-4",attrs:{"order-md":"2"}},[a.loadedFile===null?[a.sdCardFilePath!==""&&a.sdCardFilePath!==a.loadedFile?t(zt,{staticClass:"mr-3",on:{click:a.loadCurrentFile}},[a._v(" "+a._s(a.$t("GCodeViewer.LoadCurrentFile"))+" ")]):a._e(),t(zt,{on:{click:a.chooseFile}},[a._v(a._s(a.$t("GCodeViewer.LoadLocal")))])]:[a.showTrackingButton?t(zt,{staticClass:"mr-3",on:{click:function(i){a.tracking=!a.tracking}}},[t(Oi,{staticClass:"mr-2",domProps:{innerHTML:a._s(a.tracking?a.mdiToggleSwitch:a.mdiToggleSwitchOffOutline)}}),a._v(" "+a._s(a.$t("GCodeViewer.Tracking"))+" ")],1):a._e(),t(zt,{on:{click:a.clearLoadedFile}},[t(Oi,{attrs:{left:""}},[a._v(a._s(a.mdiBroom))]),a._v(" "+a._s(a.$t("GCodeViewer.ClearLoadedFile"))+" ")],1)]],2),t(xs,{staticClass:"col-12 col-sm-6 col-md-4"},[t(Y0,{attrs:{items:a.colorModes,label:a.$t("GCodeViewer.ColorMode"),"item-text":"text",dense:"","hide-details":"",outlined:""},model:{value:a.colorMode,callback:function(i){a.colorMode=i},expression:"colorMode"}})],1),t(xs,{staticClass:"col-12 col-sm-6 col-md-4 d-flex",attrs:{"order-md":"3"}},[t(Y0,{attrs:{items:a.renderQualities,label:a.$t("GCodeViewer.RenderQuality"),"item-text":"label",dense:"","hide-details":"",outlined:""},model:{value:a.renderQuality,callback:function(i){a.renderQuality=i},expression:"renderQuality"}}),t(Ic,{attrs:{"offset-y":!0,"offset-x":!0,top:"","close-on-content-click":!1,title:a.$t("Files.SetupCurrentList")},scopedSlots:a._u([{key:"activator",fn:function(i){var s=i.on,n=i.attrs;return[t(zt,a._g(a._b({staticClass:"minwidth-0 px-2 ml-3"},"v-btn",n,!1),s),[t(Oi,[a._v(a._s(a.mdiCog))])],1)]}}])},[t(Mc,[t(qi,{staticClass:"minHeight36"},[t(ji,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.ShowToolhead")},model:{value:a.showCursor,callback:function(i){a.showCursor=i},expression:"showCursor"}})],1),t(qi,{staticClass:"minHeight36"},[t(ji,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.ShowTravelMoves")},model:{value:a.showTravelMoves,callback:function(i){a.showTravelMoves=i},expression:"showTravelMoves"}})],1),t(qi,{staticClass:"minHeight36"},[t(ji,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.ShowGCode")},model:{value:a.showGCode,callback:function(i){a.showGCode=i},expression:"showGCode"}})],1),a.loadedFile===a.sdCardFilePath&&a.printing_objects.length?t(qi,{staticClass:"minHeight36"},[t(ji,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.ShowObjectSelection")},model:{value:a.showObjectSelection,callback:function(i){a.showObjectSelection=i},expression:"showObjectSelection"}})],1):a._e(),t(Pc),t(qi,{staticClass:"minHeight36"},[t(ji,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.HDRendering")},model:{value:a.hdRendering,callback:function(i){a.hdRendering=i},expression:"hdRendering"}})],1),t(qi,{staticClass:"minHeight36"},[t(ji,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.ForceLineRendering")},model:{value:a.forceLineRendering,callback:function(i){a.forceLineRendering=i},expression:"forceLineRendering"}})],1),t(qi,{staticClass:"minHeight36"},[t(ji,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.Transparency")},model:{value:a.transparency,callback:function(i){a.transparency=i},expression:"transparency"}})],1),t(qi,{staticClass:"minHeight36"},[t(ji,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.VoxelMode")},model:{value:a.voxelMode,callback:function(i){a.voxelMode=i},expression:"voxelMode"}})],1),t(qi,{staticClass:"minHeight36"},[t(ji,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.SpecularLighting")},model:{value:a.specularLighting,callback:function(i){a.specularLighting=i},expression:"specularLighting"}})],1),t(qi,{staticClass:"minHeight36"},[t(ji,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.CNCMode")},model:{value:a.cncMode,callback:function(i){a.cncMode=i},expression:"cncMode"}})],1)],1)],1)],1)],1)],1)],1),t("input",{ref:"fileInput",attrs:{accept:".g,.gcode,.gc,.gco,.nc,.ngc,.tap",hidden:"",multiple:"",type:"file"},on:{change:a.fileSelected}})],1),t("resize-observer",{on:{notify:a.handleResize}})],1),t(q0,{attrs:{timeout:-1,value:!0,fixed:"",right:"",bottom:""},scopedSlots:a._u([{key:"action",fn:function(i){var s=i.attrs;return[t(zt,a._b({staticStyle:{"min-width":"auto"},attrs:{color:"red",text:""},on:{click:function(n){return a.cancelRendering()}}},"v-btn",s,!1),[t(Oi,{staticClass:"0"},[a._v(a._s(a.mdiClose))])],1)]}}]),model:{value:a.loading,callback:function(i){a.loading=i},expression:"loading"}},[t("div",[a._v(" "+a._s(a.$t("GCodeViewer.Rendering"))+" - "+a._s(a.loadingPercent)+"% "),t("br"),t("strong",[a._v(a._s(a.loadedFile))])]),t(ga,{staticClass:"mt-2",attrs:{value:a.loadingPercent}})],1),t(q0,{attrs:{timeout:-1,value:!0,fixed:"",right:"",bottom:""},scopedSlots:a._u([{key:"action",fn:function(i){var s=i.attrs;return[t(zt,a._b({staticStyle:{"min-width":"auto"},attrs:{color:"red",text:""},on:{click:a.cancelDownload}},"v-btn",s,!1),[t(Oi,{staticClass:"0"},[a._v(a._s(a.mdiClose))])],1)]}}]),model:{value:a.downloadSnackbar.status,callback:function(i){a.$set(a.downloadSnackbar,"status",i)},expression:"downloadSnackbar.status"}},[a.downloadSnackbar.total>0?[t("div",[a._v(" "+a._s(a.$t("GCodeViewer.Downloading"))+" - "+a._s(Math.round(a.downloadSnackbar.percent))+" % @ "+a._s(a.formatFilesize(Math.round(a.downloadSnackbar.speed)))+"/s "),t("br"),t("strong",[a._v(a._s(a.downloadSnackbar.filename))])]),t(ga,{staticClass:"mt-2",attrs:{value:a.downloadSnackbar.percent}})]:[t("div",[a._v(" "+a._s(a.$t("GCodeViewer.Downloading"))+" "),t("br"),t("strong",[a._v(a._s(a.downloadSnackbar.filename))])]),t(ga,{staticClass:"mt-2",attrs:{indeterminate:""}})]],2),t(wc,{attrs:{"max-width":"400"},model:{value:a.excludeObject.bool,callback:function(i){a.$set(a.excludeObject,"bool",i)},expression:"excludeObject.bool"}},[t(Dc,[t(Fc,{attrs:{flat:"",dense:""}},[t(Oc,[t("span",{staticClass:"subheading"},[t(Oi,{attrs:{left:""}},[a._v(a._s(a.mdiSelectionRemove))]),a._v(" "+a._s(a.$t("Panels.StatusPanel.ExcludeObject.ExcludeObjectHeadline"))+" ")],1)])],1),t(K0,{staticClass:"mt-3"},[a._v(" "+a._s(a.$t("Panels.StatusPanel.ExcludeObject.ExcludeObjectText",{name:a.excludeObject.name}))+" ")]),t(Lc,[t(Bc),t(zt,{attrs:{text:""},on:{click:function(i){a.excludeObject.bool=!1}}},[a._v(" "+a._s(a.$t("Panels.StatusPanel.ExcludeObject.Cancel"))+" ")]),t(zt,{attrs:{color:"primary",text:""},on:{click:a.cancelObject}},[a._v(" "+a._s(a.$t("Panels.StatusPanel.ExcludeObject.ExcludeObject"))+" ")])],1)],1)],1)],1)},K2=[];const nl={};var Y2=s0(qe,X2,K2,!1,q2,"0de79293",null,null);function q2(a){for(let e in nl)this[e]=nl[e]}const ac=function(){return Y2.exports}();var j2=Object.defineProperty,$2=Object.getOwnPropertyDescriptor,Z2=(a,e,t,i)=>{for(var s=i>1?void 0:i?$2(e,t):e,n=a.length-1,r;n>=0;n--)(r=a[n])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&j2(e,t,s),s};let t0=class extends al(ol){};t0=Z2([i0({components:{Viewer:ac}})],t0);var Q2=function(){var a=this,e=a.$createElement,t=a._self._c||e;return t(ac)},J2=[];const rl={};var ex=s0(t0,Q2,J2,!1,tx,null,null,null);function tx(a){for(let e in rl)this[e]=rl[e]}const lx=function(){return ex.exports}();export{lx as default};