const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ddsTextureLoader-7rBWB6fI.js","assets/dds-C4nWUSlI.js","assets/cubemapToSphericalPolynomial-DI79UW0r.js","assets/vuetify-Ce4WN_Dg.js","assets/overlayscrollbars-CiKU261J.js","assets/overlayscrollbars-BJn_P54_.css","assets/vuetify-BSwS9o2d.css","assets/index-Bku7SJna.js","assets/echarts-DzoUeqWp.js","assets/index-DdkGOISd.css","assets/codemirror-ZSHHXwGs.js","assets/basisTextureLoader-C2AKop91.js","assets/envTextureLoader-0a1UyQXk.js","assets/hdrTextureLoader-CbSWrxkf.js","assets/ktxTextureLoader-DFWsW27H.js","assets/tgaTextureLoader-CGo25llH.js","assets/exrTextureLoader-CpwykM8r.js","assets/postprocess.vertex-DvFhjUjz.js","assets/pass.fragment-CM2j9WLA.js","assets/pass.fragment-BkcfUm5b.js","assets/default.vertex-Caa9iT2n.js","assets/mainUVVaryingDeclaration-Byysp88Q.js","assets/bonesVertex-B72aYlMi.js","assets/clipPlaneVertex-L9tMAQxe.js","assets/vertexColorMixing-D-DdWwxQ.js","assets/morphTargetsVertex-B2hbMuPn.js","assets/logDepthDeclaration-QTuRqmDC.js","assets/logDepthVertex-SrVRb0bM.js","assets/default.fragment-DzWBfowK.js","assets/clipPlaneFragment-ef4zNzcj.js","assets/fogFragment-BYUe2MTZ.js","assets/logDepthFragment-CVSnEUp_.js","assets/default.vertex-B3P8Ow0L.js","assets/mainUVVaryingDeclaration-DltpozJN.js","assets/meshUboDeclaration-BEPmj8E0.js","assets/helperFunctions-CmftqOHQ.js","assets/bakedVertexAnimation-jXsepPDt.js","assets/morphTargetsVertex-Dur5DJ01.js","assets/vertexColorMixing-CVYhb6uZ.js","assets/default.fragment-BQ0cgw4g.js","assets/fxaa.fragment-CKBSH8ak.js","assets/fxaa.vertex-pl3gzfER.js","assets/fxaa.fragment-CQ-OctB5.js","assets/fxaa.vertex-D11BDiUg.js","assets/color.vertex-Ccg8Ge1R.js","assets/color.fragment-DNkpzaOC.js","assets/color.vertex-BL9BK6Le.js","assets/color.fragment-BjUREcw_.js","assets/line.vertex-ChOZncX4.js","assets/line.fragment-azBhzxfj.js","assets/line.vertex-DNyxgHBi.js","assets/line.fragment-thDij4Gq.js","assets/kernelBlur.fragment-BJnJE4Wi.js","assets/kernelBlurVaryingDeclaration-DuItmes5.js","assets/kernelBlur.vertex-SB8k7aXt.js","assets/kernelBlur.fragment-CAduVWsS.js","assets/kernelBlurVaryingDeclaration-DOqeMSlf.js","assets/kernelBlur.vertex-Dciph_cp.js","assets/glowMapGeneration.vertex-O7p-xSBA.js","assets/glowMapGeneration.fragment-CfLBq-Y2.js","assets/glowMapGeneration.vertex-BcKlBU7O.js","assets/glowMapGeneration.fragment-C2VnGqtj.js","assets/glowBlurPostProcess.fragment-D0h3Yhq8.js","assets/glowBlurPostProcess.fragment-BmYiq-YF.js","assets/glowMapMerge.fragment-z1wsxOL6.js","assets/glowMapMerge.vertex-BOpN3rPY.js","assets/glowMapMerge.fragment-C9pBmOul.js","assets/glowMapMerge.vertex-CYvG5BDv.js"])))=>i.map(i=>d[i]); import{V as pf,f as Bt,c as Ri,i as Ro,m as sr,n as ds,S as gf,Y as mf,P as Io,D as vf,E as bf,y as Bi,q as Li,j as xf,w as Eo,k as da,h as yf,_ as Tf,a as Af,b as Rf,p as If,d as Ef}from"./vuetify-Ce4WN_Dg.js";import{k as Cf,l as Sf,P as Vr,W as nt,C as a0,n as o0,o as Oe,m as El,B as Cl,p as Mf,q as Pf,r as wf,s as Df,t as Ff,u as Of,v as Bf,w as Lf,x as Nf,y as Uf,z as kf,A as Vf,D as Gf,E as Co,F as zf,R as Sl,G as Ml,_ as Pl}from"./index-Bku7SJna.js";import{E as Wf,b as Hf,a as Kf}from"./codemirror-ZSHHXwGs.js";function Xf(a,e){return e===void 0&&(e={}),function(t,i){Cf(e,t,i),Sf(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)}}var Yf=Object.defineProperty,qf=Object.getOwnPropertyDescriptor,Ws=(a,e,t,i)=>{for(var s=i>1?void 0:i?qf(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&&Yf(e,t,s),s};let ns=class extends pf{constructor(){super(...arguments),this.view=void 0}mounted(){this.view=new Wf({doc:this.document,extensions:[Hf,Kf.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})}}};Ws([Xf("currentline")],ns.prototype,"currentLineNumber",2);Ws([Vr({type:String,default:""})],ns.prototype,"document",2);Ws([Vr({type:Boolean,default:!1})],ns.prototype,"isSimulating",2);Ws([Vr({type:Boolean,default:!1})],ns.prototype,"shown",2);Ws([nt("document")],ns.prototype,"documentUpdated",1);Ws([nt("currentLineNumber")],ns.prototype,"currentlineUpdated",1);ns=Ws([a0({})],ns);var jf=function(){var e=this,t=e._self._c;return e._self._setupProxy,t("div",{ref:"view",staticClass:"codeview",on:{mouseup:e.mouseUp,keydown:e.keyPress}})},$f=[],Zf=o0(ns,jf,$f,!1,null,"083209f9");const wl=Zf.exports,Qf=typeof WeakRef<"u";class Jf{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 ed{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class Z{static FromPromise(e,t){const i=new Z;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 Jf(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,n=!1){if(!e)return null;const r=new ed(e,t,s);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);const o=Qf?new WeakRef(this):{deref:()=>this};return r._remove=()=>{const h=o.deref();h&&h._remove(r)},r}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return e?(e._remove=null,this._observers.indexOf(e)!==-1?(this._deferUnregister(e),!0):!1):!1}removeCallback(e,t){for(let i=0;i{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return i!==-1?(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0):!1}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,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(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new Z;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 td{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 So;(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"})(So||(So={}));function Mo(a){return a===13||a===14||a===15||a===16||a===17||a===18||a===19}function id(a){switch(a){case 13:case 17:case 18:case 14:case 16:return 1;case 15:return 5;case 19:return 0}return 0}function br(a){return a===13||a===17||a===18||a===19}class ft extends td{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 Z,this.onErrorObservable=new Z,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=0,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._creationFlags=0,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._premulAlpha=!1,this._dynamicTextureSource=null,this._autoMSAAManagement=!1,this._engine=e,this._source=t,this._uniqueId=ft._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 t,i;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const s=this.onRebuildCallback(this),n=r=>{r._swapAndDie(this,!1),this.isReady=s.isReady};s.isAsync?s.proxy.then(n):n(s.proxy);return}let e;switch(this.source){case 2:break;case 1:e=this._engine.createTexture((t=this._originalUrl)!=null?t:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,s=>{s._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 3:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case 10:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 11:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 4:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case 7:e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null);return;case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,(i=this._originalFormat)!=null?i:this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,s=>{s&&s._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),e._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){var n;(n=this._hardwareTexture)==null||n.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);s!==-1&&i.splice(s,1),s=i.indexOf(e),s===-1&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._references===0&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}ft._Counter=0;class Ee{static get LastCreatedEngine(){return this.Instances.length===0?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}Ee.Instances=[];Ee.OnEnginesDisposedObservable=new Z;Ee._LastCreatedScene=null;Ee.UseFallbackTexture=!0;Ee.FallbackTexture="";class sd{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return this.program?this.isParallelCompiled?this.engine._isRenderingStateCompiled(this):!0:!1}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,s,n,r,o,h){const l=this.engine;if(l.supportsUniformBuffers)for(const f in t)e.bindUniformBlock(f,t[f]);this.engine.getUniforms(this,i).forEach((f,d)=>{s[i[d]]=f}),this._uniforms=s;let u;for(u=0;u{r[f]=d});for(const f of l.getAttributes(this,o))h.push(f)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||s.length!==2)return s=[t,i],this._valueCache[e]=s,!0;let 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.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,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}}const Po={};function ye(a,e=!1){if(!(e&&Po[a]))return Po[a]=!0,"".concat(a," needs to be imported before as it contains a side-effect required by your code.")}function St(){return typeof window<"u"}function Qs(){return typeof navigator<"u"}function En(){return typeof document<"u"}function h0(a){let e="",t=a.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}const xr={};function Dl(a,e,t=""){return t+(e?e+"\n":"")+a}function Fl(a,e,t,i,s,n,r){const o=r||xr.loadFile;if(o)return o(a,e,t,i,s,n);throw ye("FileTools")}function Ol(a,e,t,i){if(a){e?a.IS_NDC_HALF_ZRANGE="":delete a.IS_NDC_HALF_ZRANGE,t?a.USE_REVERSE_DEPTHBUFFER="":delete a.USE_REVERSE_DEPTHBUFFER,i?a.USE_EXACT_SRGB_CONVERSIONS="":delete a.USE_EXACT_SRGB_CONVERSIONS;return}else{let s="";return e&&(s+="#define IS_NDC_HALF_ZRANGE"),t&&(s&&(s+="\n"),s+="#define USE_REVERSE_DEPTHBUFFER"),i&&(s&&(s+="\n"),s+="#define USE_EXACT_SRGB_CONVERSIONS"),s}}function Pa(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}const wa=new WeakMap,nd={_webGLVersion:2,cachedPipelines:{}};function ii(a){let e=wa.get(a);if(!e){if(!a)return nd;e={_webGLVersion:a.TEXTURE_BINDING_3D?2:1,_context:a,parallelShaderCompile:a.getExtension("KHR_parallel_shader_compile")||void 0,cachedPipelines:{}},wa.set(a,e)}return e}function rd(a){wa.delete(a)}function Bl(a,e,t,i,s,n){var l;const r=ii(i);n||(n=(l=r._createShaderProgramInjection)!=null?l:l0);const o=Da(e,"vertex",i,r._contextWasLost),h=Da(t,"fragment",i,r._contextWasLost);return n(a,o,h,i,s,r.validateShaderPrograms)}function Ll(a,e,t,i,s,n=null,r){var u;const o=ii(s);r||(r=(u=o._createShaderProgramInjection)!=null?u:l0);const h=o._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",l=wo(e,"vertex",i,h,s,o._contextWasLost),c=wo(t,"fragment",i,h,s,o._contextWasLost);return r(a,l,c,s,n,o.validateShaderPrograms)}function ad(a,e){const t=new sd,i=ii(a);return i.parallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}function l0(a,e,t,i,s=null,n){const r=i.createProgram();if(a.program=r,!r)throw new Error("Unable to create program");return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),a.context=i,a.vertexShader=e,a.fragmentShader=t,a.isParallelCompiled||c0(a,i,n),r}function od(a,e,t){const i=a;if(i._isDisposed)return!1;const s=ii(e);return e.getProgramParameter(i.program,s.parallelShaderCompile.COMPLETION_STATUS_KHR)?(c0(i,e,t),!0):!1}function c0(a,e,t){const i=a.context,s=a.vertexShader,n=a.fragmentShader,r=a.program;if(!i.getProgramParameter(r,i.LINK_STATUS)){if(!e.getShaderParameter(s,e.COMPILE_STATUS)){const l=e.getShaderInfoLog(s);if(l)throw a.vertexCompilationError=l,new Error("VERTEX SHADER "+l)}if(!e.getShaderParameter(n,e.COMPILE_STATUS)){const l=e.getShaderInfoLog(n);if(l)throw a.fragmentCompilationError=l,new Error("FRAGMENT SHADER "+l)}const h=i.getProgramInfoLog(r);if(h)throw a.programLinkError=h,new Error(h)}if(t&&(i.validateProgram(r),!i.getProgramParameter(r,i.VALIDATE_STATUS))){const l=i.getProgramInfoLog(r);if(l)throw a.programValidationError=l,new Error(l)}i.deleteShader(s),i.deleteShader(n),a.vertexShader=void 0,a.fragmentShader=void 0,a.onCompiled&&(a.onCompiled(),a.onCompiled=void 0)}function hd(a,e,t,i,s,n,r,o,h,l="",c,u,f){var p,g;const d=ii(a.context);u||(u=(p=d.createRawShaderProgramInjection)!=null?p:Bl),f||(f=(g=d.createShaderProgramInjection)!=null?g:Ll);const _=a;i?_.program=u(_,e,t,_.context,h):_.program=f(_,e,t,o,_.context,h),_.program.__SPECTOR_rebuildProgram=r,c()}function wo(a,e,t,i,s,n){return Da(Dl(a,t,i),e,s,n)}function Da(a,e,t,i){const s=t.createShader(e==="vertex"?t.VERTEX_SHADER:t.FRAGMENT_SHADER);if(!s){let n=t.NO_ERROR,r=t.NO_ERROR;for(;(r=t.getError())!==t.NO_ERROR;)n=r;throw new Error("Something went wrong while creating a gl ".concat(e," shader object. gl error=").concat(n,", gl isContextLost=").concat(t.isContextLost(),", _contextWasLost=").concat(i))}return t.shaderSource(s,a),t.compileShader(s),s}function ld(a,e){e.useProgram(a)}function cd(a,e){const t=a;if(!t.isParallelCompiled){e(a);return}const i=t.onCompiled;t.onCompiled=()=>{i==null||i(),e(a)}}function Nl(a){return a.getPipelineContext===void 0}class U{static _CheckLimit(e,t){let i=U._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},U._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var n;const i=U._LogLimitOutputs[e];if(!i||!U.MessageLimitReached)return;const s=this._Levels[t];i.current===i.limit&&U[s.name](U.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,(n=s.name)!=null?n:""))}static _AddLogEntry(e){U._LogCache=e+U._LogCache,U.OnNewCacheEntry&&U.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){const s=Array.isArray(t)?t[0]:t;if(i!==void 0&&!U._CheckLimit(s,i))return;const n=U._FormatMessage(s),r=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];r.logFunc&&r.logFunc("BJS - "+n,...o);const h="
").concat(n,"

");U._AddLogEntry(h),U._GenerateLimitMessage(s,e)}static get LogCache(){return U._LogCache}static ClearLogCache(){U._LogCache="",U._LogLimitOutputs={},U.errorsCount=0}static set LogLevels(e){U.Log=U._LogDisabled,U.Warn=U._LogDisabled,U.Error=U._LogDisabled,[U.MessageLogLevel,U.WarningLogLevel,U.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];U[i.name]=U._LogEnabled.bind(U,t)}})}}U.NoneLogLevel=0;U.MessageLogLevel=1;U.WarningLogLevel=2;U.ErrorLogLevel=4;U.AllLogLevel=7;U.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";U._LogCache="";U._LogLimitOutputs={};U._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];U.errorsCount=0;U.Log=U._LogEnabled.bind(U,U.MessageLogLevel);U.Warn=U._LogEnabled.bind(U,U.WarningLogLevel);U.Error=U._LogEnabled.bind(U,U.ErrorLogLevel);class ud{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,s,n){if(n.drawBuffersExtensionDisabled){const r=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(r,"")}return e}}const fd=/(flat\s)?\s*varying\s*.*/;class dd{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return fd.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,n=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(n,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){const r=e.search(/layout *\(location *= *0\) *out/g)!==-1;e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/void\s+?main\s*\(/g,(s||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(t.indexOf("#define MULTIVIEW")!==-1)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class pn{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=pn._Counter++}}pn._Counter=0;class Pn extends pn{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}function wn(a){let e=1;do e*=2;while(ea-t?t:e}function kl(a){return a--,a|=a>>1,a|=a>>2,a|=a>>4,a|=a>>8,a|=a>>16,a++,a}function u0(a){return a=a|a>>1,a=a|a>>2,a=a|a>>4,a=a|a>>8,a=a|a>>16,a-(a>>1)}function fi(a,e,t=2){let i;switch(t){case 1:i=u0(a);break;case 2:i=Ul(a);break;case 3:default:i=kl(a);break}return Math.min(i,e)}class Me{static GetShadersRepository(e=0){return e===0?Me.ShadersRepository:Me.ShadersRepositoryWGSL}static GetShadersStore(e=0){return e===0?Me.ShadersStore:Me.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return e===0?Me.IncludesShadersStore:Me.IncludesShadersStoreWGSL}}Me.ShadersRepository="src/Shaders/";Me.ShadersStore={};Me.IncludesShadersStore={};Me.ShadersRepositoryWGSL="src/ShadersWGSL/";Me.ShadersStoreWGSL={};Me.IncludesShadersStoreWGSL={};const _d="attribute",pd="varying";class Hn{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var s,n,r,o,h,l,c;let i="";if(this.line){let u=this.line;const f=t.processor;if(f){f.lineProcessor&&(u=f.lineProcessor(u,t.isFragment,t.processingContext));const d=(n=(s=t.processor)==null?void 0:s.attributeKeywordName)!=null?n:_d,_=t.isFragment&&((r=t.processor)!=null&&r.varyingFragmentKeywordName)?(o=t.processor)==null?void 0:o.varyingFragmentKeywordName:!t.isFragment&&((h=t.processor)!=null&&h.varyingVertexKeywordName)?(l=t.processor)==null?void 0:l.varyingVertexKeywordName:pd;!t.isFragment&&f.attributeProcessor&&this.line.startsWith(d)?u=f.attributeProcessor(this.line,e,t.processingContext):f.varyingProcessor&&((c=f.varyingCheck)!=null&&c.call(f,this.line,t.isFragment)||!f.varyingCheck&&this.line.startsWith(_))?u=f.varyingProcessor(this.line,t.isFragment,e,t.processingContext):f.uniformProcessor&&f.uniformRegexp&&f.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=f.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):f.uniformBufferProcessor&&f.uniformBufferRegexp&&f.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=f.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):f.textureProcessor&&f.textureRegexp&&f.textureRegexp.test(this.line)?u=f.textureProcessor(this.line,t.isFragment,e,t.processingContext):(f.uniformProcessor||f.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?f.uniformProcessor&&(u=f.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):f.uniformBufferProcessor&&(u=f.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&this.line.indexOf("}")!==-1&&(t.lookForClosingBracketForUniformBuffer=!1,f.endOfUniformBufferProcessor&&(u=f.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=u+"\n"}return this.children.forEach(u=>{i+=u.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class gd{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{const n=t.split(";");for(let r=0;r{c=c.trim(),c!==""&&(i.push(c),c="")},r=u=>{sct._Stack[s],h=()=>s===-1?"!!INVALID EXPRESSION!!":ct._Stack[s--];let l=0,c="";for(;l1){for(n();s!==-1&&ct._OperatorPriority[o()]>=ct._OperatorPriority[f];)i.push(h());r(f),l++}else c+=u;l++}for(n();s!==-1;)o()==="("?h():i.push(h());return ct._InfixToPostfixCache.size>=ct.InfixToPostfixCacheLimitSize&&ct.ClearCache(),ct._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(ct._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t":i=s>n;break;case"<":i=s=":i=s>=n;break;case"==":i=s===n;break;case"!=":i=s!==n;break}return i}}const yd=/defined\s*?\((.+?)\)/g,pa=/defined\s*?\[(.+?)\]/g,Td=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Ad=/__decl__/,Do=/light\{X\}.(\w*)/g,Fo=/\{X\}/g,nr=[],Rd=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function f0(a){a.processor&&a.processor.initializeShaders&&a.processor.initializeShaders(a.processingContext)}function Tr(a,e,t,i){var s;(s=e.processor)!=null&&s.preProcessShaderCode&&(a=e.processor.preProcessShaderCode(a,e.isFragment)),Dn(a,e,n=>{e.processCodeAfterIncludes&&(n=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",n,e.defines));const r=Sd(n,e,i);t(r,n)})}function Id(a,e,t,i){var s;(s=e.processor)!=null&&s.preProcessShaderCode&&(a=e.processor.preProcessShaderCode(a,e.isFragment)),Dn(a,e,n=>{e.processCodeAfterIncludes&&(n=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",n,e.defines));const r=Md(n,e,i);t(r,n)})}function d0(a,e,t){return!t.processor||!t.processor.finalizeShaders?{vertexCode:a,fragmentCode:e}:t.processor.finalizeShaders(a,e,t.processingContext)}function Ed(a,e){var i;if((i=e.processor)!=null&&i.noPrecision)return a;const t=e.shouldUseHighPrecisionShader;return a.indexOf("precision highp float")===-1?t?a="precision highp float;\n"+a:a="precision mediump float;\n"+a:t||(a=a.replace("precision highp float","precision mediump float")),a}function ga(a){const t=/defined\((.+)\)/.exec(a);if(t&&t.length)return new yr(t[1].trim(),a[0]==="!");const i=["==","!=",">=","<=","<",">"];let s="",n=0;for(s of i)if(n=a.indexOf(s),n>-1)break;if(n===-1)return new yr(a);const r=a.substring(0,n).trim(),o=a.substring(n+s.length).trim();return new xd(r,s,o)}function Cd(a){a=a.replace(yd,"defined[$1]");const e=ct.infixToPostfix(a),t=[];for(const s of e)if(s!=="||"&&s!=="&&")t.push(s);else if(t.length>=2){let n=t[t.length-1],r=t[t.length-2];t.length-=2;const o=s=="&&"?new bd:new vd;typeof n=="string"&&(n=n.replace(pa,"defined($1)")),typeof r=="string"&&(r=r.replace(pa,"defined($1)")),o.leftOperand=typeof r=="string"?ga(r):r,o.rightOperand=typeof n=="string"?ga(n):n,t.push(o)}let i=t[t.length-1];return typeof i=="string"&&(i=i.replace(pa,"defined($1)")),typeof i=="string"?ga(i):i}function dr(a,e){const t=new md,i=a.substring(0,e);let s=a.substring(e);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),i==="#ifdef"?t.testExpression=new yr(s):i==="#ifndef"?t.testExpression=new yr(s,!0):t.testExpression=Cd(s),t}function ma(a,e,t){let i=a.currentLine;for(;Oa(a,t);){i=a.currentLine;const s=i.substring(0,5).toLowerCase();if(s==="#else"){const n=new Hn;e.children.push(n),Oa(a,n);return}else if(s==="#elif"){const n=dr(i,5);e.children.push(n),t=n}}}function Oa(a,e){for(;a.canRead;){a.lineIndex++;const t=a.currentLine;if(t.indexOf("#")>=0){const s=Rd.exec(t);if(s&&s.length){switch(s[0]){case"#ifdef":{const r=new _a;e.children.push(r);const o=dr(t,6);r.children.push(o),ma(a,r,o);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const r=new _a;e.children.push(r);const o=dr(t,7);r.children.push(o),ma(a,r,o);break}case"#if":{const r=new _a,o=dr(t,3);e.children.push(r),r.children.push(o),ma(a,r,o);break}}continue}}const i=new Hn;if(i.line=t,e.children.push(i),t[0]==="#"&&t[1]==="d"){const s=t.replace(";","").split(" ");i.additionalDefineKey=s[1],s.length===3&&(i.additionalDefineValue=s[2])}}return!1}function Vl(a,e,t){const i=new Hn,s=new gd;return s.lineIndex=-1,s.lines=a.split("\n"),Oa(s,i),i.process(e,t)}function Gl(a,e){var s;const t=a.defines,i={};for(const n of t){const o=n.replace("#define","").replace(";","").trim().split(" ");i[o[0]]=o.length>1?o[1]:""}return((s=a.processor)==null?void 0:s.shaderLanguage)===0&&(i.GL_ES="true"),i.__VERSION__=a.version,i[a.platformName]="true",Ol(i,e==null?void 0:e.isNDCHalfZRange,e==null?void 0:e.useReverseDepthBuffer,e==null?void 0:e.useExactSrgbConversions),i}function Sd(a,e,t){let i=Ed(a,e);if(!e.processor||e.processor.shaderLanguage===0&&i.indexOf("#version 3")!==-1&&(i=i.replace("#version 300 es",""),!e.processor.parseGLES3))return i;const s=e.defines,n=Gl(e,t);return e.processor.preProcessor&&(i=e.processor.preProcessor(i,s,n,e.isFragment,e.processingContext)),i=Vl(i,n,e),e.processor.postProcessor&&(i=e.processor.postProcessor(i,s,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{})),t!=null&&t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function Md(a,e,t){var r,o;let i=a;const s=e.defines,n=Gl(e,t);return(r=e.processor)!=null&&r.preProcessor&&(i=e.processor.preProcessor(i,s,n,e.isFragment,e.processingContext)),i=Vl(i,n,e),(o=e.processor)!=null&&o.postProcessor&&(i=e.processor.postProcessor(i,s,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{})),t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function Dn(a,e,t){nr.length=0;let i;for(;(i=Td.exec(a))!==null;)nr.push(i);let s=String(a),n=[a],r=!1;for(const o of nr){let h=o[1];if(h.indexOf("__decl__")!==-1&&(h=h.replace(Ad,""),e.supportsUniformBuffers&&(h=h.replace("Vertex","Ubo").replace("Fragment","Ubo")),h=h+"Declaration"),e.includesShadersStore[h]){let l=e.includesShadersStore[h];if(o[2]){const u=o[3].split(",");for(let f=0;fb+"{X}")),l+=p.replace(Fo,g.toString())+"\n"}else e.supportsUniformBuffers||(l=l.replace(Do,(f,d)=>d+"{X}")),l=l.replace(Fo,u)}const c=[];for(const u of n){const f=u.split(o[0]);for(let d=0;d=0||l.indexOf("#include <")>=0}else{const l=e.shadersRepository+"ShadersInclude/"+h+".fx";zl.loadFile(l,c=>{e.includesShadersStore[h]=c,Dn(n.join(""),e,t)});return}}nr.length=0,s=n.join(""),r?Dn(s.toString(),e,t):t(s)}const zl={loadFile:(a,e,t,i,s,n)=>{throw ye("FileTools")}};function Pd(a,e){return ii(e).cachedPipelines[a]}function _0(a){const e=a._name,t=a.context;if(e&&t){const i=ii(t),s=i.cachedPipelines[e];s==null||s.dispose(),delete i.cachedPipelines[e]}}function wd(a,e,t,i,s,n,r){let o,h;const l=St()?n==null?void 0:n.getHostDocument():null;typeof e=="string"?o=e:e.vertexSource?o="source:"+e.vertexSource:e.vertexElement?o=(l==null?void 0:l.getElementById(e.vertexElement))||e.vertexElement:o=e.vertex||e,typeof e=="string"?h=e:e.fragmentSource?h="source:"+e.fragmentSource:e.fragmentElement?h=(l==null?void 0:l.getElementById(e.fragmentElement))||e.fragmentElement:h=e.fragment||e;const c=[void 0,void 0],u=()=>{if(c[0]&&c[1]){a.isFragment=!0;const[f,d]=c;Tr(d,a,(_,p)=>{r&&(r._fragmentSourceCodeBeforeMigration=p),t&&(_=t("fragment",_));const g=d0(f,_,a);a=null;const m=Dd(g.vertexCode,g.fragmentCode,e,s);i==null||i(m.vertexSourceCode,m.fragmentSourceCode)},n)}};Oo(o,"Vertex","",f=>{f0(a),Tr(f,a,(d,_)=>{r&&(r._rawVertexSourceCode=f,r._vertexSourceCodeBeforeMigration=_),t&&(d=t("vertex",d)),c[0]=d,u()},n)},s),Oo(h,"Fragment","Pixel",f=>{r&&(r._rawFragmentSourceCode=f),c[1]=f,u()},s)}function Oo(a,e,t,i,s,n){if(typeof HTMLElement<"u"&&a instanceof HTMLElement){const h=h0(a);i(h);return}if(a.substring(0,7)==="source:"){i(a.substring(7));return}if(a.substring(0,7)==="base64:"){const h=window.atob(a.substring(7));i(h);return}const r=Me.GetShadersStore(s);if(r[a+e+"Shader"]){i(r[a+e+"Shader"]);return}if(t&&r[a+t+"Shader"]){i(r[a+t+"Shader"]);return}let o;if(a[0]==="."||a[0]==="/"||a.indexOf("http")>-1?o=a:o=Me.GetShadersRepository(s)+a,n=n||Fl,!n)throw new Error("loadFileInjection is not defined");n(o+"."+e.toLowerCase()+".fx",i)}function Dd(a,e,t,i){if(t){const s=t.vertexElement||t.vertex||t.spectorName||t,n=t.fragmentElement||t.fragment||t.spectorName||t;return{vertexSourceCode:(i===1?"//":"")+"#define SHADER_NAME vertex:"+s+"\n"+a,fragmentSourceCode:(i===1?"//":"")+"#define SHADER_NAME fragment:"+n+"\n"+e}}else return{vertexSourceCode:a,fragmentSourceCode:e}}const Fd=(a,e,t,i)=>{try{const s=a.existingPipelineContext||e(a.shaderProcessingContext);if(s._name=a.name,a.name&&a.context){const n=ii(a.context);n.cachedPipelines[a.name]=s}return t(s,a.vertex,a.fragment,!!a.createAsRaw,"","",a.rebuildRebind,a.defines,a.transformFeedbackVaryings,"",()=>{i(s,()=>{var n;(n=a.onRenderingStateCompiled)==null||n.call(a,s)})}),s}catch(s){throw U.Error("Error compiling effect"),s}},Od=(a,e,t,i=16,s=1e3)=>{const n=setInterval(()=>{try{a()&&(clearInterval(n),e())}catch(r){clearInterval(n),t==null||t(r)}s-=i,s<0&&(clearInterval(n),t==null||t())},i)};class Et{static get ShadersRepository(){return Me.ShadersRepository}static set ShadersRepository(e){Me.ShadersRepository=e}get isDisposed(){return this._isDisposed}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new Z),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,n,r=null,o=null,h=null,l=null,c,u="",f=0,d){var g,m,b,I;this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new Z,this.onErrorObservable=new Z,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=u;const _=this._key.replace(/\r/g,"").replace(/\n/g,"|");let p;if(t.attributes){const T=t;if(this._engine=i,this._attributesNames=T.attributes,this._uniformsNames=T.uniformsNames.concat(T.samplers),this._samplerList=T.samplers.slice(),this.defines=T.defines,this.onError=T.onError,this.onCompiled=T.onCompiled,this._fallbacks=T.fallbacks,this._indexParameters=T.indexParameters,this._transformFeedbackVaryings=T.transformFeedbackVaryings||null,this._multiTarget=!!T.multiTarget,this._shaderLanguage=(g=T.shaderLanguage)!=null?g:0,T.uniformBuffersNames){this._uniformBuffersNamesList=T.uniformBuffersNames.slice();for(let x=0;x{this._vertexSourceCode=r,this._fragmentSourceCode=o,this._prepareEffect(t)},this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return this._engine.isDisposed||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)&&this._checkIsReady(null)}_checkIsReady(e){Od(()=>this._isReadyInternal()||this._isDisposed,()=>{},t=>{this._processCompilationErrors(t,e)})}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:(t=(e=this._pipelineContext)==null?void 0:e._getVertexShaderCode())!=null?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:(t=(e=this._pipelineContext)==null?void 0:e._getFragmentShaderCode())!=null?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!!(this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(n,r)=>{s&&s(r)},this.onCompiled=()=>{var r,o;const n=this.getEngine().scenes;if(n)for(let h=0;hthis._rebuildProgram(h,l,c,u),defines:s,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:o._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:h=>{t&&!e&&this._engine._deletePipelineContext(t),h&&this._onRenderingStateCompiled(h)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let n=null;if(t&&e){const r=t.match(s);if(r&&r.length===2){const o=parseInt(r[1]),h=e.split("\n",-1);h.length>=o&&(n="Offending line [".concat(o,"] in ").concat(i?"fragment":"vertex"," code: ").concat(h[o-1]))}}return[e,n]}_processCompilationErrors(e,t=null){var r,o,h;this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(U.Error("Unable to compile effect:"),U.Error("Uniforms: "+this._uniformsNames.map(function(l){return" "+l})),U.Error("Attributes: "+i.map(function(l){return" "+l})),U.Error("Defines:\n"+this.defines),Et.LogShaderCodeOnCompilationError){let l=null,c=null,u=null;(r=this._pipelineContext)!=null&&r._getVertexShaderCode()&&([u,l]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),u&&(U.Error("Vertex code:"),U.Error(u))),(o=this._pipelineContext)!=null&&o._getFragmentShaderCode()&&([u,c]=this._getShaderCodeAndErrorLine((h=this._pipelineContext)==null?void 0:h._getFragmentShaderCode(),this._compilationError,!0),u&&(U.Error("Fragment code:"),U.Error(u))),l&&U.Error(l),c&&U.Error(c)}U.Error("Error: "+this._compilationError);const n=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,n()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,U.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,n(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||n())}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)}setTextureArray(e,t){const i=e+"Ex";if(this._samplerList.indexOf(i+"0")===-1){const s=this._samplerList.indexOf(e);for(let r=1;r0||this._isDisposed)&&(this._pipelineContext&&_0(this._pipelineContext),this._engine._releaseEffect(this),this.clearCodeCache(),this._isDisposed=!0)}static RegisterShader(e,t,i,s=0){t&&(Me.GetShadersStore(s)["".concat(e,"PixelShader")]=t),i&&(Me.GetShadersStore(s)["".concat(e,"VertexShader")]=i)}static ResetCache(){Et._BaseCache={}}}Et.LogShaderCodeOnCompilationError=!0;Et.AutomaticallyClearCodeCache=!1;Et._UniqueIdSeed=0;Et._BaseCache={};Et.ShadersStore=Me.ShadersStore;Et.IncludesShadersStore=Me.IncludesShadersStore;class Dt{static SetMatrixPrecision(e){if(Dt.MatrixTrackPrecisionChange=!1,e&&!Dt.MatrixUse64Bits&&Dt.MatrixTrackedMatrices)for(let t=0;tOe(()=>import("./ddsTextureLoader-7rBWB6fI.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])).then(i=>new i._DDSTextureLoader)),a.endsWith(".basis")&&_s(".basis",()=>Oe(()=>import("./basisTextureLoader-C2AKop91.js"),__vite__mapDeps([11,3,4,5,6,7,8,9,10])).then(i=>new i._BasisTextureLoader)),a.endsWith(".env")&&_s(".env",()=>Oe(()=>import("./envTextureLoader-0a1UyQXk.js"),__vite__mapDeps([12,7,3,4,5,6,8,9,2,10])).then(i=>new i._ENVTextureLoader)),a.endsWith(".hdr")&&_s(".hdr",()=>Oe(()=>import("./hdrTextureLoader-CbSWrxkf.js"),__vite__mapDeps([13,3,4,5,6,7,8,9,10])).then(i=>new i._HDRTextureLoader)),(a.endsWith(".ktx")||a.endsWith(".ktx2"))&&(_s(".ktx",()=>Oe(()=>import("./ktxTextureLoader-DFWsW27H.js"),__vite__mapDeps([14,3,4,5,6,7,8,9,10])).then(i=>new i._KTXTextureLoader)),_s(".ktx2",()=>Oe(()=>import("./ktxTextureLoader-DFWsW27H.js"),__vite__mapDeps([14,3,4,5,6,7,8,9,10])).then(i=>new i._KTXTextureLoader))),a.endsWith(".tga")&&_s(".tga",()=>Oe(()=>import("./tgaTextureLoader-CGo25llH.js"),__vite__mapDeps([15,3,4,5,6,7,8,9,10])).then(i=>new i._TGATextureLoader)),a.endsWith(".exr")&&_s(".exr",()=>Oe(()=>import("./exrTextureLoader-CpwykM8r.js"),__vite__mapDeps([16,3,4,5,6,7,8,9,10])).then(i=>new i._ExrTextureLoader)));const t=Ar.get(a);return t?Promise.resolve(t(e)):null}function Kl(a,e){if(St()){const{requestAnimationFrame:t}=e||window;if(typeof t=="function")return t(a)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(a);return setTimeout(a,16)}class ae{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e){this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS;return}else{let t="";return this.isNDCHalfZRange&&(t+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(t&&(t+="\n"),t+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(t&&(t+="\n"),t+="#define USE_EXACT_SRGB_CONVERSIONS"),t}}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}Et.ResetCache()}_rebuildGraphicsResources(){var e;this.wipeCaches(!0),this._rebuildEffects(),(e=this._rebuildComputeEffects)==null||e.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){U.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout(async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=n,this._flagContextRestored()},0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}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 activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._frameHandler!==0){const e=this._frameHandler;if(this._frameHandler=0,St()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if(typeof t=="function")return t(e)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(y).toLowerCase():"");R.indexOf("?")>-1&&(R=R.split("?")[0]);const C=Nd(R,_);s&&s.addPendingData(T),T.url=e,T.generateMipMaps=!t,T.samplingMode=n,T.invertY=i,T._useSRGBBuffer=this._getUseSRGBBuffer(!!g,t),this._doNotHandleContextLost||(T._buffer=c);let S=null;r&&!u&&(S=T.onLoadedObservable.add(r)),u||this._internalTexturesCache.push(T);const w=(P,G)=>{s&&s.removePendingData(T),e===x?(S&&T.onLoadedObservable.remove(S),Ee.UseFallbackTexture&&e!==Ee.FallbackTexture&&this._createTextureBase(Ee.FallbackTexture,t,T.invertY,s,n,null,o,h,l,c,T),P=(P||"Unknown error")+(Ee.UseFallbackTexture?" - Fallback texture was used":""),T.onErrorObservable.notifyObservers({message:P,exception:G}),o&&o(P,G)):(U.Warn("Failed to load ".concat(e,", falling back to ").concat(x)),this._createTextureBase(x,t,T.invertY,s,n,r,o,h,l,c,T,f,d,_,p,g))};if(C){const P=async G=>{(await C).loadData(G,T,(W,K,ce,$,z,k)=>{k?w("TextureLoader failed to load data"):h(T,R,s,{width:W,height:K},T.invertY,!ce,$,()=>(z(),!1),n)},p)};c?c instanceof ArrayBuffer?P(new Uint8Array(c)):ArrayBuffer.isView(c)?P(c):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,G=>P(new Uint8Array(G)),void 0,s?s.offlineProvider:void 0,!0,(G,L)=>{w("Unable to load "+(G&&G.responseURL,L))})}else{const P=G=>{b&&!this._doNotHandleContextLost&&(T._buffer=G),h(T,R,s,G,T.invertY,t,!1,l,n)};!m||I?c&&(typeof c.decoding=="string"||c.close)?P(c):ae._FileToolsLoadImage(e||"",P,w,s?s.offlineProvider:null,_,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof c=="string"||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?ae._FileToolsLoadImage(c,P,w,s?s.offlineProvider:null,_,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):c&&P(c)}return T}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:En()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@7.37.0"}static get Version(){return"7.37.0"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){var r,o,h,l,c,u,f,d,_,p,g;this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new Wl,this._stencilStateComposer=new Hl,this._stencilState=new ss,this._alphaState=new Bd,this._alphaMode=1,this._alphaEquation=0,this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this.onCanvasBlurObservable=new Z,this.onCanvasFocusObservable=new Z,this.onNewSceneAddedObservable=new Z,this.onResizeObservable=new Z,this.onCanvasPointerOutObservable=new Z,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new Z,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new Z,this.onAfterShaderCompilationObservable=new Z,this.onBeginFrameObservable=new Z,this.onEndFrameObservable=new Z,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new Z,this.onContextRestoredObservable=new Z,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new Z,Ee.Instances.push(this),this.startTime=bi.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,Dt.SetMatrixPrecision(!!t.useHighPrecisionMatrix),Qs()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i!=null?i:!1,t.antialias=e!=null?e:t.antialias,t.deterministicLockstep=(r=t.deterministicLockstep)!=null?r:!1,t.lockstepMaxSteps=(o=t.lockstepMaxSteps)!=null?o:4,t.timeStep=(h=t.timeStep)!=null?h:1/60,t.audioEngine=(l=t.audioEngine)!=null?l:!0,t.stencil=(c=t.stencil)!=null?c:!0,this._audioContext=(f=(u=t.audioEngineOptions)==null?void 0:u.audioContext)!=null?f:null,this._audioDestination=(_=(d=t.audioEngineOptions)==null?void 0:d.audioDestination)!=null?_:null,this.premultipliedAlpha=(p=t.premultipliedAlpha)!=null?p:!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=(g=t.useExactSrgbConversions)!=null?g:!1;const s=St()&&window.devicePixelRatio||1,n=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(n,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const s=St()&&window.devicePixelRatio||1,n=this._lastDevicePixelRatio/s;this._lastDevicePixelRatio=s,this._hardwareScalingLevel*=n}if(St()&&En())if(this._renderingCanvas){const s=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||s.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||s.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas||(e=e|0,t=t|0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t))return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let s=0;s{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&En()&&"ontouchend"in document},this._checkForMobile(),St()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){var t;(t=this._drawCalls)==null||t.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}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 ae._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,n,r){throw ye("FileTools")}_loadFile(e,t,i,s,n,r){const o=Fl(e,t,i,s,n,r);return this._activeRequests.push(o),o.onCompleteObservable.add(()=>{const h=this._activeRequests.indexOf(o);h!==-1&&this._activeRequests.splice(h,1)}),o}static _FileToolsLoadFile(e,t,i,s,n,r){if(xr.loadFile)return xr.loadFile(e,t,i,s,n,r);throw ye("FileTools")}dispose(){var t;for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();(t=this.releaseComputeEffects)==null||t.call(this),Et.ResetCache();for(const i of this._activeRequests)i.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),St()&&window.removeEventListener("resize",this._checkForMobile);const e=Ee.Instances.indexOf(this);e>=0&&Ee.Instances.splice(e,1),Ee.Instances.length||(Ee.OnEnginesDisposedObservable.notifyObservers(this),Ee.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw ye("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,s){if(i=i||{},super(t!=null?t:i.antialias,i,s),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,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._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let n=null;if(e.getContext){if(n=e,this._renderingCanvas=n,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const h=navigator.userAgent;for(const l of we.ExceptionList){const c=l.key,u=l.targets;if(new RegExp(c).test(h)){if(l.capture&&l.captureConstraint){const d=l.capture,_=l.captureConstraint,g=new RegExp(d).exec(h);if(g&&g.length>0&&parseInt(g[g.length-1])>=_)continue}for(const d of u)switch(d){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1;break}}}}if(this._doNotHandleContextLost||(this._onContextLost=h=>{h.preventDefault(),this._contextWasLost=!0,U.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},n.addEventListener("webglcontextlost",this._onContextLost,!1),n.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=n.getContext("webgl2",i)||n.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(!n)throw new Error("The provided canvas is null or undefined.");try{this._gl=n.getContext("webgl",i)||n.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 h=this._gl.getContextAttributes();h&&(i.stencil=h.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 h=0;h1?new dd:new ud;const r="Babylon.js v".concat(we.Version);U.Log(r+" - ".concat(this.description)),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",r);const o=ii(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){var t;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||this._gl.getExtension("OES_standard_derivatives")!==null,maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:this._webGLVersion!==1,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1,textureNorm16:!!this._gl.getExtension("EXT_texture_norm16")},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(e!=null&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=((t=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))!=null?t: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.textureNorm16&&(this._gl.R16_EXT=33322,this._gl.RG16_EXT=33324,this._gl.RGB16_EXT=32852,this._gl.RGBA16_EXT=32859,this._gl.R16_SNORM_EXT=36760,this._gl.RG16_SNORM_EXT=36761,this._gl.RGB16_SNORM_EXT=36762,this._gl.RGBA16_SNORM_EXT=36763),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),this._caps.maxDrawBuffers=this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS);else{const i=this._gl.getExtension("WEBGL_draw_buffers");if(i!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=i.drawBuffersWEBGL.bind(i),this._caps.maxDrawBuffers=this._gl.getParameter(i.MAX_DRAW_BUFFERS_WEBGL),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let s=0;s<16;s++)this._gl["COLOR_ATTACHMENT"+s+"_WEBGL"]=i["COLOR_ATTACHMENT"+s+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const i=this._gl.getExtension("WEBGL_depth_texture");i!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=i.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const i=this._gl.getExtension("OES_vertex_array_object");i!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=i.createVertexArrayOES.bind(i),this._gl.bindVertexArray=i.bindVertexArrayOES.bind(i),this._gl.deleteVertexArray=i.deleteVertexArrayOES.bind(i))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const i=this._gl.getExtension("ANGLE_instanced_arrays");i!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=i.drawArraysInstancedANGLE.bind(i),this._gl.drawElementsInstanced=i.drawElementsInstancedANGLE.bind(i),this._gl.vertexAttribDivisor=i.vertexAttribDivisorANGLE.bind(i)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const i=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),s=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);i&&s&&(this._caps.highPrecisionShaderSupported=i.precision!==0&&s.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const i=this._gl.getExtension("EXT_blend_minmax");i!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=i.MAX_EXT,this._gl.MIN=i.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const i=this._gl.getExtension("EXT_sRGB");i!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:i.SRGB_EXT,SRGB8:i.SRGB_ALPHA_EXT,SRGB8_ALPHA8:i.SRGB_ALPHA_EXT})}if(this._creationOptions){const i=this._creationOptions.forceSRGBBufferSupportState;i!==void 0&&(this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&i)}}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let i=0;i"u",supportRenderAndCopyToLodForFloatTextures:this._webGLVersion!==1,supportDepthStencilTexture:this._webGLVersion!==1,supportShadowSamplers:this._webGLVersion!==1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:this._webGLVersion!==1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:this._webGLVersion!==1,basisNeedsPOT:this._webGLVersion===1,support3DTextures:this._webGLVersion!==1,needTypeSuffixInShaderConstants:this._webGLVersion!==1,supportMSAA:this._webGLVersion!==1,supportSSAO2:this._webGLVersion!==1,supportIBLShadows:this._webGLVersion!==1,supportExtendedTextureFormats:this._webGLVersion!==1,supportSwitchCaseInShader:this._webGLVersion!==1,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);const e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}extractDriverInfo(){const e=this.getGlInfo();return e&&e.renderer?e.renderer:""}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}clear(e,t,i,s=!1){var o,h;const n=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=n;let r=0;if(t&&e){let l=!0;if(this._currentRenderTarget){const c=(o=this._currentRenderTarget.texture)==null?void 0:o.format;if(c===8||c===9||c===10||c===11){const u=(h=this._currentRenderTarget.texture)==null?void 0:h.type;u===7||u===5?(we._TempClearColorUint32[0]=e.r*255,we._TempClearColorUint32[1]=e.g*255,we._TempClearColorUint32[2]=e.b*255,we._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,we._TempClearColorUint32),l=!1):(we._TempClearColorInt32[0]=e.r*255,we._TempClearColorInt32[1]=e.g*255,we._TempClearColorInt32[2]=e.b*255,we._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,we._TempClearColorInt32),l=!1)}}l&&(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))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,i,s,n,r=0,o=0){var u,f,d,_,p,g;const h=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(h._framebuffer);const l=this._gl;e.isMulti||(e.is2DArray||e.is3D?(l.framebufferTextureLayer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,(u=e.texture._hardwareTexture)==null?void 0:u.underlyingResource,r,o),h._currentLOD=r):e.isCube?l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+t,(f=e.texture._hardwareTexture)==null?void 0:f.underlyingResource,r):h._currentLOD!==r&&(l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,(d=e.texture._hardwareTexture)==null?void 0:d.underlyingResource,r),h._currentLOD=r));const c=e._depthStencilTexture;if(c){e.is3D&&(e.texture.width!==c.width||e.texture.height!==c.height||e.texture.depth!==c.depth)&&U.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment");const m=e._depthStencilTextureWithStencil?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?l.framebufferTextureLayer(l.FRAMEBUFFER,m,(_=c._hardwareTexture)==null?void 0:_.underlyingResource,r,o):e.isCube?l.framebufferTexture2D(l.FRAMEBUFFER,m,l.TEXTURE_CUBE_MAP_POSITIVE_X+t,(p=c._hardwareTexture)==null?void 0:p.underlyingResource,r):l.framebufferTexture2D(l.FRAMEBUFFER,m,l.TEXTURE_2D,(g=c._hardwareTexture)==null?void 0:g.underlyingResource,r)}h._MSAAFramebuffer&&this._bindUnboundFramebuffer(h._MSAAFramebuffer),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 c,u;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const h=(u=(c=this.cullBackFaces)!=null?c:n)==null||u?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(o);const l=s?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==l||i)&&(this._depthCullingState.frontFace=l),this._stencilStateComposer.stencilMaterial=r}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return this._currentFramebuffer===null}generateMipmaps(e){const t=this._getTextureTarget(e);this._bindTextureDirectly(t,e,!0),this._gl.generateMipmap(t),this._bindTextureDirectly(t,null)}unBindFramebuffer(e,t=!1,i){const s=e;this._currentRenderTarget=null,s.disableAutomaticMSAAResolve||(e.isMulti?this.resolveMultiFramebuffer(e):this.resolveFramebuffer(e)),t||(e.isMulti?this.generateMipMapsMultiFramebuffer(e):this.generateMipMapsFramebuffer(e)),i&&(s._MSAAFramebuffer&&this._bindUnboundFramebuffer(s._framebuffer),i()),this._bindUnboundFramebuffer(null)}generateMipMapsFramebuffer(e){var t;!e.isMulti&&((t=e.texture)!=null&&t.generateMipMaps)&&!e.isCube&&this.generateMipmaps(e.texture)}resolveFramebuffer(e){const t=e,i=this._gl;if(!t._MSAAFramebuffer||t.isMulti)return;let s=t.resolveMSAAColors?i.COLOR_BUFFER_BIT:0;s|=t._generateDepthBuffer&&t.resolveMSAADepth?i.DEPTH_BUFFER_BIT:0,s|=t._generateStencilBuffer&&t.resolveMSAAStencil?i.STENCIL_BUFFER_BIT:0,i.bindFramebuffer(i.READ_FRAMEBUFFER,t._MSAAFramebuffer),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),i.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s,i.NEAREST)}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,t,i){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 Pn(i);return this.bindArrayBuffer(s),typeof e!="number"?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),s.capacity=e.length*4):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),s.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),s.capacity=e),this._resetVertexBufferBinding(),s.references=1,s}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){const s=this._gl.createBuffer(),n=new Pn(s);if(!s)throw new Error("Unable to create index buffer");this.bindIndexBuffer(n);const r=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),n.references=1,n.is32Bits=r.BYTES_PER_ELEMENT===4,n}_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 h=this._currentBufferPointers[t];if(!h)return;let l=!1;h.active?(h.buffer!==e&&(h.buffer=e,l=!0),h.size!==i&&(h.size=i,l=!0),h.type!==s&&(h.type=s,l=!0),h.normalized!==n&&(h.normalized=n,l=!0),h.stride!==r&&(h.stride=r,l=!0),h.offset!==o&&(h.offset=o,l=!0)):(l=!0,h.active=!0,h.index=t,h.size=i,h.type=s,h.normalized=n,h.stride=r,h.offset=o,h.buffer=e),(l||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 h=null;if(i&&(h=i[o]),h||(h=e[o]),!h)continue;this._gl.enableVertexAttribArray(r),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[r]=!0);const l=h.getBuffer();l&&(this._vertexAttribPointer(l,r,h.getSize(),h.type,h.normalized,h.byteStride,h.byteOffset),h.getIsInstanced()&&(this._gl.vertexAttribDivisor(r,h.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(l))))}}}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 h=0;h=0&&(this._gl.enableVertexAttribArray(l),this._vertexAttribArraysEnabled[l]=!0,this._vertexAttribPointer(e,l,i[h],this._gl.FLOAT,!1,s,o)),o+=i[h]*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||this.isWebGPU)),(o===1&&!this._caps.textureFloatLinearFiltering||o===2&&!this._caps.textureHalfFloatLinearFiltering)&&(h=1),o===1&&!this._caps.textureFloat&&(o=0,U.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const p=Mo(l),g=br(l),m=this._gl,b=new ft(this,s),I=e.width||e,T=e.height||e,x=e.depth||0,y=e.layers||0,R=this._getSamplingParameters(h,(n||r)&&!p),E=y!==0?m.TEXTURE_2D_ARRAY:x!==0?m.TEXTURE_3D:m.TEXTURE_2D,C=p?this._getInternalFormatFromDepthTextureFormat(l,!0,g):this._getRGBABufferInternalSizedFormat(o,l,c),S=p?g?m.DEPTH_STENCIL:m.DEPTH_COMPONENT:this._getInternalFormat(l),w=p?this._getWebGLTextureTypeFromDepthTextureFormat(l):this._getWebGLTextureType(o);if(this._bindTextureDirectly(E,b),y!==0?(b.is2DArray=!0,m.texImage3D(E,0,C,I,T,y,0,S,w,null)):x!==0?(b.is3D=!0,m.texImage3D(E,0,C,I,T,x,0,S,w,null)):m.texImage2D(E,0,C,I,T,0,S,w,null),m.texParameteri(E,m.TEXTURE_MAG_FILTER,R.mag),m.texParameteri(E,m.TEXTURE_MIN_FILTER,R.min),m.texParameteri(E,m.TEXTURE_WRAP_S,m.CLAMP_TO_EDGE),m.texParameteri(E,m.TEXTURE_WRAP_T,m.CLAMP_TO_EDGE),p&&this.webGLVersion>1&&(_===0?(m.texParameteri(E,m.TEXTURE_COMPARE_FUNC,515),m.texParameteri(E,m.TEXTURE_COMPARE_MODE,m.NONE)):(m.texParameteri(E,m.TEXTURE_COMPARE_FUNC,_),m.texParameteri(E,m.TEXTURE_COMPARE_MODE,m.COMPARE_REF_TO_TEXTURE))),(n||r)&&this._gl.generateMipmap(E),this._bindTextureDirectly(E,null),b._useSRGBBuffer=c,b.baseWidth=I,b.baseHeight=T,b.width=I,b.height=T,b.depth=y||x,b.isReady=!0,b.samples=u,b.generateMipMaps=n,b.samplingMode=h,b.type=o,b.format=l,b.label=f,b.comparisonFunction=_,this._internalTexturesCache.push(b),d){let G=null;if(Mo(b.format)?G=this._setupFramebufferDepthAttachments(br(b.format),b.format!==19,b.width,b.height,u,b.format,!0):G=this._createRenderBuffer(b.width,b.height,u,-1,this._getRGBABufferInternalSizedFormat(b.type,b.format,b._useSRGBBuffer),-1),!G)throw new Error("Unable to create render buffer");b._autoMSAAManagement=!0;let L=b._hardwareTexture;L||(L=b._hardwareTexture=this._createHardwareTexture()),L.addMSAARenderBuffer(G)}return b}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,n=3,r=null,o=null,h=null,l=null,c=null,u=null,f,d,_,p){return this._createTextureBase(e,t,i,s,n,r,o,(...g)=>this._prepareWebGLTexture(...g,c),(g,m,b,I,T,x)=>{const y=this._gl,R=b.width===g&&b.height===m;T._creationFlags=_!=null?_:0;const E=this._getTexImageParametersForCreateTexture(T.format,T._useSRGBBuffer);if(R)return y.texImage2D(y.TEXTURE_2D,0,E.internalFormat,E.format,E.type,b),!1;const C=this._caps.maxTextureSize;if(b.width>C||b.height>C||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=g,this._workingCanvas.height=m,this._workingContext.drawImage(b,0,0,b.width,b.height,0,0,g,m),y.texImage2D(y.TEXTURE_2D,0,E.internalFormat,E.format,E.type,this._workingCanvas),T.width=g,T.height=m),!1;{const S=new ft(this,2);this._bindTextureDirectly(y.TEXTURE_2D,S,!0),y.texImage2D(y.TEXTURE_2D,0,E.internalFormat,E.format,E.type,b),this._rescaleTexture(S,T,s,E.format,()=>{this._releaseTexture(S),this._bindTextureDirectly(y.TEXTURE_2D,T,!0),x()})}return!0},h,l,c,u,f,d,p)}_getTexImageParametersForCreateTexture(e,t){let i,s;return this.webGLVersion===1?(i=this._getInternalFormat(e,t),s=i):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,s,n){}_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)}_uploadCompressedDataToTextureDirectly(e,t,i,s,n,r=0,o=0){const h=this._gl;let l=h.TEXTURE_2D;if(e.isCube&&(l=h.TEXTURE_CUBE_MAP_POSITIVE_X+r),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=h.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=h.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=h.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=h.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=h.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=h.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=h.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}this._gl.compressedTexImage2D(l,o,t,i,s,0,n)}_uploadDataToTextureDirectly(e,t,i=0,s=0,n,r=!1){const o=this._gl,h=this._getWebGLTextureType(e.type),l=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 f=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=r?e.width:Math.pow(2,Math.max(f-s,0)),p=r?e.height:Math.pow(2,Math.max(d-s,0));o.texImage2D(u,s,c,_,p,0,l,h,t)}updateTextureData(e,t,i,s,n,r,o=0,h=0,l=!1){const c=this._gl,u=this._getWebGLTextureType(e.type),f=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=c.TEXTURE_2D,_=c.TEXTURE_2D;e.isCube&&(_=c.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),c.texSubImage2D(_,h,i,s,n,r,f,u,t),l&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,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,h,l,c){const u=this.getCaps().maxTextureSize,f=Math.min(u,this.needPOTTextures?fi(s.width,u):s.width),d=Math.min(u,this.needPOTTextures?fi(s.height,u):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=f,e.height=d,e.isReady=!0,e.type=e.type!==-1?e.type:0,e.format=e.format!==-1?e.format:c!=null?c:t===".jpg"&&!e._useSRGBBuffer?4:5,!h(f,d,s,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,r,o,l)})&&this._prepareWebGLTextureContinuation(e,i,r,o,l)}}_getInternalFormatFromDepthTextureFormat(e,t,i){const s=this._gl;if(!t)return s.STENCIL_INDEX8;let r=i?s.DEPTH_STENCIL:s.DEPTH_COMPONENT;return this.webGLVersion>1?e===15?r=s.DEPTH_COMPONENT16:e===16?r=s.DEPTH_COMPONENT24:e===17||e===13?r=i?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24:e===14?r=s.DEPTH_COMPONENT32F:e===18&&(r=i?s.DEPTH32F_STENCIL8:s.DEPTH_COMPONENT32F):r=s.DEPTH_COMPONENT16,r}_getWebGLTextureTypeFromDepthTextureFormat(e){const t=this._gl;let i=t.UNSIGNED_INT;return e===15?i=t.UNSIGNED_SHORT:e===17||e===13?i=t.UNSIGNED_INT_24_8:e===14?i=t.FLOAT:e===18?i=t.FLOAT_32_UNSIGNED_INT_24_8_REV:e===19&&(i=t.UNSIGNED_BYTE),i}_setupFramebufferDepthAttachments(e,t,i,s,n=1,r,o=!1){const h=this._gl;r=r!=null?r:e?13:14;const l=this._getInternalFormatFromDepthTextureFormat(r,t,e);return e&&t?this._createRenderBuffer(i,s,n,h.DEPTH_STENCIL,l,o?-1:h.DEPTH_STENCIL_ATTACHMENT):t?this._createRenderBuffer(i,s,n,l,l,o?-1:h.DEPTH_ATTACHMENT):e?this._createRenderBuffer(i,s,n,l,l,o?-1:h.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,n,r,o=!0){const l=this._gl.createRenderbuffer();return this._updateRenderBuffer(l,e,t,i,s,n,r,o)}_updateRenderBuffer(e,t,i,s,n,r,o,h=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),s>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,r,t,i):l.renderbufferStorage(l.RENDERBUFFER,n,t,i),o!==-1&&l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),h&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);t!==-1&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e==null||e.release()}_setProgram(e){this._currentProgram!==e&&(ld(e,this._gl),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&&r&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw U.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,(l=(h=t==null?void 0:t._hardwareTexture)==null?void 0:h.underlyingResource)!=null?l:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(n=!0,this._activateCurrentTexture());return r&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),n}_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;const l=t.getInternalTexture();l&&(l._associatedChannel=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 h=this._getTextureTarget(r);if(o&&this._bindTextureDirectly(h,r,i),r&&!r.isMultiview){if(r.isCube&&r._cachedCoordinatesMode!==t.coordinatesMode){r._cachedCoordinatesMode=t.coordinatesMode;const l=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=l,t.wrapV=l}r._cachedWrapU!==t.wrapU&&(r._cachedWrapU=t.wrapU,this._setTextureParameterInteger(h,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),r)),r._cachedWrapV!==t.wrapV&&(r._cachedWrapV=t.wrapV,this._setTextureParameterInteger(h,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),r)),r.is3D&&r._cachedWrapR!==t.wrapR&&(r._cachedWrapR=t.wrapR,this._setTextureParameterInteger(h,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),r)),this._setAnisotropicLevel(h,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(){const e=Object.keys(this._compiledEffects);for(const t of e)this._compiledEffects[t].dispose(!0);this._compiledEffects={}}dispose(){var e;St()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&((e=this._gl.getExtension("WEBGL_lose_context"))==null||e.loseContext()),rd(this._gl)}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,h=t.UNSIGNED_BYTE,l=new Uint8Array(4);t.readPixels(0,0,1,1,o,h,l),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._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:case 33322:case 36760:i=this._gl.RED;break;case 7:case 33324:case 36761:i=this._gl.RG;break;case 4:case 32852:case 36762:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:case 32859:case 36763:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;break}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER;break}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(this._webGLVersion===1){if(t!==void 0)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 36760:return this._gl.R16_SNORM_EXT;case 36761:return this._gl.RG16_SNORM_EXT;case 36762:return this._gl.RGB16_SNORM_EXT;case 36763:return this._gl.RGBA16_SNORM_EXT;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 33322:return this._gl.R16_EXT;case 33324:return this._gl.RG16_EXT;case 32852:return this._gl.RGB16_EXT;case 32859:return this._gl.RGBA16_EXT;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;case 11:return this._gl.RGBA16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;case 11:return this._gl.RGBA32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;case 11:return this._gl.RGBA32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;case 5:return this._gl.RGBA32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;case 5:return this._gl.RGBA16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,s,n=!0,r=!0){const o=n?4:3,h=n?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(s*i*o);return r&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,h,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(this._HasMajorPerformanceCaveat!==null)return!this._HasMajorPerformanceCaveat;if(this._IsSupported===null)try{const e=ae._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=ae._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}}we._TempClearColorUint32=new Uint32Array(4);we._TempClearColorInt32=new Int32Array(4);we.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}];we._ConcatenateShader=Dl;we._IsSupported=null;we._HasMajorPerformanceCaveat=null;const kd=Object.freeze(Object.defineProperty({__proto__:null,ThinEngine:we},Symbol.toStringTag,{value:"Module"}));class Yl{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Vd(e)}sampleFrame(e=bi.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 Vd{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}}we.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};we.prototype.updateRawTexture=function(a,e,t,i,s=null,n=0,r=!1){if(!a)return;const o=this._getRGBABufferInternalSizedFormat(n,t,r),h=this._getInternalFormat(t),l=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,a,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.type=n,a.invertY=i,a._compression=s),a.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],a.width,a.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,a.width,a.height,0,h,l,e),a.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),a.isReady=!0};we.prototype.createRawTexture=function(a,e,t,i,s,n,r,o=null,h=0,l=0,c=!1){const u=new ft(this,3);u.baseWidth=e,u.baseHeight=t,u.width=e,u.height=t,u.format=i,u.generateMipMaps=s,u.samplingMode=r,u.invertY=n,u._compression=o,u.type=h,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this._doNotHandleContextLost||(u._bufferView=a),this.updateRawTexture(u,a,i,n,o,h,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const f=this._getSamplingParameters(r,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,f.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,f.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u};we.prototype.createRawCubeTexture=function(a,e,t,i,s,n,r,o=null){const h=this._gl,l=new ft(this,8);l.isCube=!0,l.format=t,l.type=i,this._doNotHandleContextLost||(l._bufferViewArray=a);const c=this._getWebGLTextureType(i);let u=this._getInternalFormat(t);u===h.RGB&&(u=h.RGBA),c===h.FLOAT&&!this._caps.textureFloatLinearFiltering?(s=!1,r=1,U.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):c===this._gl.HALF_FLOAT_OES&&!this._caps.textureHalfFloatLinearFiltering?(s=!1,r=1,U.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):c===h.FLOAT&&!this._caps.textureFloatRender?(s=!1,U.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):c===h.HALF_FLOAT&&!this._caps.colorBufferFloat&&(s=!1,U.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));const f=e,d=f;if(l.width=f,l.height=d,l.invertY=n,l._compression=o,!this.needPOTTextures||wn(l.width)&&wn(l.height)||(s=!1),a)this.updateRawCubeTexture(l,a,t,i,n,o);else{const g=this._getRGBABufferInternalSizedFormat(i),m=0;this._bindTextureDirectly(h.TEXTURE_CUBE_MAP,l,!0);for(let b=0;b<6;b++)o?h.compressedTexImage2D(h.TEXTURE_CUBE_MAP_POSITIVE_X+b,m,this.getCaps().s3tc[o],l.width,l.height,0,void 0):h.texImage2D(h.TEXTURE_CUBE_MAP_POSITIVE_X+b,m,g,l.width,l.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,l,!0),a&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const p=this._getSamplingParameters(r,s);return h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_MAG_FILTER,p.mag),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_MIN_FILTER,p.min),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this._bindTextureDirectly(h.TEXTURE_CUBE_MAP,null),l.generateMipMaps=s,l.samplingMode=r,l.isReady=!0,l};we.prototype.updateRawCubeTexture=function(a,e,t,i,s,n=null,r=0){a._bufferViewArray=e,a.format=t,a.type=i,a.invertY=s,a._compression=n;const o=this._gl,h=this._getWebGLTextureType(i);let l=this._getInternalFormat(t);const c=this._getRGBABufferInternalSizedFormat(i);let u=!1;l===o.RGB&&(l=o.RGBA,u=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,a,!0),this._unpackFlipY(s===void 0?!0:!!s),a.width%4!==0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let d=0;d<6;d++){let _=e[d];n?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+d,r,this.getCaps().s3tc[n],a.width,a.height,0,_):(u&&(_=ql(_,a.width,a.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+d,r,c,a.width,a.height,0,l,h,_))}(!this.needPOTTextures||wn(a.width)&&wn(a.height))&&a.generateMipMaps&&r===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),a.isReady=!0};we.prototype.createRawCubeTextureFromUrl=function(a,e,t,i,s,n,r,o,h=null,l=null,c=3,u=!1){const f=this._gl,d=this.createRawCubeTexture(null,t,i,s,!n,u,c,null);e==null||e.addPendingData(d),d.url=a,d.isReady=!1,this._internalTexturesCache.push(d);const _=(g,m)=>{e==null||e.removePendingData(d),l&&g&&l(g.status+" "+g.statusText,m)},p=g=>{const m=d.width,b=r(g);if(b){if(o){const I=this._getWebGLTextureType(s);let T=this._getInternalFormat(i);const x=this._getRGBABufferInternalSizedFormat(s);let y=!1;T===f.RGB&&(T=f.RGBA,y=!0),this._bindTextureDirectly(f.TEXTURE_CUBE_MAP,d,!0),this._unpackFlipY(!1);const R=o(b);for(let E=0;E>E;for(let S=0;S<6;S++){let w=R[E][S];y&&(w=ql(w,C,C,s)),f.texImage2D(S,E,x,C,C,0,T,I,w)}}this._bindTextureDirectly(f.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(d,b,i,s,u);d.isReady=!0,e==null||e.removePendingData(d),d.onLoadedObservable.notifyObservers(d),d.onLoadedObservable.clear(),h&&h()}};return this._loadFile(a,g=>{p(g)},void 0,e==null?void 0:e.offlineProvider,!0,_),d};function ql(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;r-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+i,(f=a._hardwareTexture)==null?void 0:f.underlyingResource,s):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,(d=a._hardwareTexture)==null?void 0:d.underlyingResource,s);let u=a.type!==void 0?this._getWebGLTextureType(a.type):c.UNSIGNED_BYTE;if(o)n||(n=Pa(a.type,4*e*t));else switch(u){case c.UNSIGNED_BYTE:n||(n=new Uint8Array(4*e*t)),u=c.UNSIGNED_BYTE;break;default:n||(n=new Float32Array(4*e*t)),u=c.FLOAT;break}return r&&this.flushFramebuffer(),c.readPixels(h,l,e,t,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n};we.prototype._readTexturePixels=function(a,e,t,i=-1,s=0,n=null,r=!0,o=!1,h=0,l=0){return Promise.resolve(this._readTexturePixelsSync(a,e,t,i,s,n,r,o,h,l))};we.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()};we.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()};we.prototype._createDepthStencilCubeTexture=function(a,e){const t=new ft(this,12);if(t.isCube=!0,this.webGLVersion===1)return U.Error("Depth cube texture is not supported by WebGL 1."),t;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e},s=this._gl;this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,t,!0),this._setupDepthStencilTexture(t,a,i.bilinearFiltering,i.comparisonFunction);for(let n=0;n<6;n++)i.generateStencil?s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,s.DEPTH24_STENCIL8,a,a,0,s.DEPTH_STENCIL,s.UNSIGNED_INT_24_8,null):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,s.DEPTH_COMPONENT24,a,a,0,s.DEPTH_COMPONENT,s.UNSIGNED_INT,null);return this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(t),t};we.prototype._setCubeMapTextureParams=function(a,e,t){const i=this._gl;i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MIN_FILTER,e?i.LINEAR_MIPMAP_LINEAR:i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),a.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),a._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};we.prototype.createCubeTexture=function(a,e,t,i,s=null,n=null,r,o=null,h=!1,l=0,c=0,u=null,f,d=!1,_=null){const p=this._gl;return this.createCubeTextureBase(a,e,t,!!i,s,n,r,o,h,l,c,u,g=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,g,!0),(g,m)=>{const b=this.needPOTTextures?fi(m[0].width,this._caps.maxCubemapTextureSize):m[0].width,I=b,T=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,g,!0),this._unpackFlipY(!1);const x=r?this._getInternalFormat(r,g._useSRGBBuffer):g._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA;let y=r?this._getInternalFormat(r):p.RGBA;g._useSRGBBuffer&&this.webGLVersion===1&&(y=x);for(let R=0;R0}get is3D(){return this.depth>0}get size(){return this.width}get width(){var e;return(e=this._size.width)!=null?e:this._size}get height(){var e;return(e=this._size.height)!=null?e:this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){var e,t;return(t=(e=this._textures)==null?void 0:e[0])!=null?t:null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}getBaseArrayLayer(e){var n,r,o,h;if(!this._textures)return-1;const t=this._textures[e],i=(r=(n=this._layerIndices)==null?void 0:n[e])!=null?r:0,s=(h=(o=this._faceIndices)==null?void 0:o[e])!=null?h:0;return t.isCube?i*6+s:t.is3D?0:i}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}resolveMSAATextures(){this.isMulti?this._engine.resolveMultiFramebuffer(this):this._engine.resolveFramebuffer(this)}generateMipMaps(){this._engine._currentRenderTarget===this&&this._engine.unBindFramebuffer(this,!0),this.isMulti?this._engine.generateMipMapsMultiFramebuffer(this):this._engine.generateMipMapsFramebuffer(this)}constructor(e,t,i,s,n){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.disableAutomaticMSAAResolve=!1,this.resolveMSAAColors=!0,this.resolveMSAADepth=!1,this.resolveMSAAStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=n}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),t!==void 0&&t>=0&&(this._layerIndices[e]=t),i!==void 0&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,n=14,r){var o;return(o=this._depthStencilTexture)==null||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=r,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.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var t,i,s,n,r,o,h,l;let e=null;if(this._isMulti){const c=this.textures;if(c&&c.length>0){let u=!1,f=c.length,d=-1;const _=c[c.length-1]._source;(_===14||_===12)&&(u=!0,d=c[c.length-1].format,f--);const p=[],g=[],m=[],b=[],I=[],T=[],x=[],y={};for(let C=0;C1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const _=this._context;l=_["COLOR_ATTACHMENT"+t],e.is2DArray||e.is3D?(i=(u=i!=null?i:(c=this.layerIndices)==null?void 0:c[t])!=null?u:0,_.framebufferTextureLayer(_.FRAMEBUFFER,l,n.underlyingResource,s,i)):e.isCube?(i=(d=i!=null?i:(f=this.faceIndices)==null?void 0:f[t])!=null?d:0,_.framebufferTexture2D(_.FRAMEBUFFER,l,_.TEXTURE_CUBE_MAP_POSITIVE_X+i,n.underlyingResource,s)):_.framebufferTexture2D(_.FRAMEBUFFER,l,_.TEXTURE_2D,n.underlyingResource,s)}else{const _=this._context;l=_["COLOR_ATTACHMENT"+t+"_WEBGL"];const p=i!==void 0?_.TEXTURE_CUBE_MAP_POSITIVE_X+i:_.TEXTURE_2D;_.framebufferTexture2D(_.FRAMEBUFFER,l,p,n.underlyingResource,s)}if(e._autoMSAAManagement&&this._MSAAFramebuffer){const _=this._context;o._bindUnboundFramebuffer(this._MSAAFramebuffer),_.framebufferRenderbuffer(_.FRAMEBUFFER,l,_.RENDERBUFFER,n.getMSAARenderBuffer())}o._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var s,n;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=(n=(s=this._attachments)==null?void 0:s.length)!=null?n:this.textures.length;for(let r=0;r1){const m=r._hardwareTexture.getMSAARenderBuffer(0);t._MSAAFramebuffer=d.createFramebuffer(),this._bindUnboundFramebuffer(t._MSAAFramebuffer),d.framebufferRenderbuffer(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.RENDERBUFFER,m),this._bindUnboundFramebuffer(null)}return t};we.prototype._createDepthStencilTexture=function(a,e,t){var d;const i=this._gl,s=a.layers||0,n=a.depth||0;let r=i.TEXTURE_2D;s!==0?r=i.TEXTURE_2D_ARRAY:n!==0&&(r=i.TEXTURE_3D);const o=new ft(this,12);if(o.label=e.label,!this._caps.depthTextureExtension)return U.Error("Depth texture is not supported by your browser or hardware."),o;const h={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e};if(this._bindTextureDirectly(r,o,!0),this._setupDepthStencilTexture(o,a,h.comparisonFunction===0?!1:h.bilinearFiltering,h.comparisonFunction,h.samples),h.depthTextureFormat!==void 0){if(h.depthTextureFormat!==15&&h.depthTextureFormat!==16&&h.depthTextureFormat!==17&&h.depthTextureFormat!==13&&h.depthTextureFormat!==14&&h.depthTextureFormat!==18)return U.Error("Depth texture ".concat(h.depthTextureFormat," format is not supported.")),o;o.format=h.depthTextureFormat}else o.format=h.generateStencil?13:16;const l=o.format===17||o.format===13||o.format===18,c=this._getWebGLTextureTypeFromDepthTextureFormat(o.format),u=l?i.DEPTH_STENCIL:i.DEPTH_COMPONENT,f=this._getInternalFormatFromDepthTextureFormat(o.format,!0,l);return o.is2DArray?i.texImage3D(r,0,f,o.width,o.height,s,0,u,c,null):o.is3D?i.texImage3D(r,0,f,o.width,o.height,n,0,u,c,null):i.texImage2D(r,0,f,o.width,o.height,0,u,c,null),this._bindTextureDirectly(r,null),this._internalTexturesCache.push(o),t._depthStencilBuffer&&(i.deleteRenderbuffer(t._depthStencilBuffer),t._depthStencilBuffer=null),this._bindUnboundFramebuffer((d=t._MSAAFramebuffer)!=null?d:t._framebuffer),t._generateStencilBuffer=l,t._depthStencilTextureWithStencil=l,t._depthStencilBuffer=this._setupFramebufferDepthAttachments(t._generateStencilBuffer,t._generateDepthBuffer,t.width,t.height,t.samples,o.format),this._bindUnboundFramebuffer(null),o};we.prototype.updateRenderTargetTextureSampleCount=function(a,e){var n,r;if(this.webGLVersion<2||!a)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=(n=a.texture)==null?void 0:n._hardwareTexture;if(i==null||i.releaseMSAARenderBuffers(),a.texture&&e>1&&typeof t.renderbufferStorageMultisample=="function"){const o=t.createFramebuffer();if(!o)throw new Error("Unable to create multi sampled framebuffer");a._MSAAFramebuffer=o,this._bindUnboundFramebuffer(a._MSAAFramebuffer);const h=this._createRenderBuffer(a.texture.width,a.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(a.texture.type,a.texture.format,a.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!h)throw new Error("Unable to create multi sampled framebuffer");i==null||i.addMSAARenderBuffer(h)}this._bindUnboundFramebuffer((r=a._MSAAFramebuffer)!=null?r:a._framebuffer),a.texture&&(a.texture.samples=e),a._samples=e;const s=a._depthStencilTexture?a._depthStencilTexture.format:void 0;return a._depthStencilBuffer=this._setupFramebufferDepthAttachments(a._generateStencilBuffer,a._generateDepthBuffer,a.width,a.height,e,s),this._bindUnboundFramebuffer(null),e};we.prototype._setupDepthStencilTexture=function(a,e,t,i,s=1){var f,d;const n=(f=e.width)!=null?f:e,r=(d=e.height)!=null?d:e,o=e.layers||0,h=e.depth||0;a.baseWidth=n,a.baseHeight=r,a.width=n,a.height=r,a.is2DArray=o>0,a.depth=o||h,a.isReady=!0,a.samples=s,a.generateMipMaps=!1,a.samplingMode=t?2:1,a.type=0,a._comparisonFunction=i;const l=this._gl,c=this._getTextureTarget(a),u=this._getSamplingParameters(a.samplingMode,!1);l.texParameteri(c,l.TEXTURE_MAG_FILTER,u.mag),l.texParameteri(c,l.TEXTURE_MIN_FILTER,u.min),l.texParameteri(c,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(c,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this.webGLVersion>1&&(i===0?(l.texParameteri(c,l.TEXTURE_COMPARE_FUNC,515),l.texParameteri(c,l.TEXTURE_COMPARE_MODE,l.NONE)):(l.texParameteri(c,l.TEXTURE_COMPARE_FUNC,i),l.texParameteri(c,l.TEXTURE_COMPARE_MODE,l.COMPARE_REF_TO_TEXTURE)))};we.prototype.setDepthStencilTexture=function(a,e,t,i){a!==void 0&&(e&&(this._boundUniforms[a]=e),!t||!t.depthStencilTexture?this._setTexture(a,null,void 0,void 0,i):this._setTexture(a,t,!1,!0,i))};we.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 ft(this,5);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,U.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 h=0;h<6;h++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+h,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 zd=1/2.2,Wd=2.2,yt=(1+Math.sqrt(5))/2,Le=.001;function zi(a,e){const t=[];for(let i=0;i{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 Kd=["push","splice","pop","shift","unshift"];function Ql(a,e){const t=Kd.map(i=>Hd(a,i,e));return()=>{t.forEach(i=>{i==null||i()})}}const Jl={};function vt(a,e){Jl[a]=e}function ys(a){return Jl[a]}function lt(a,e,t=1401298e-51){return Math.abs(a-e)<=t}function gt(a,e){return a===e?a:Math.random()*(e-a)+a}function Rr(a,e,t){return a+(e-a)*t}function Xd(a,e,t,i,s){const n=s*s,r=s*n,o=2*r-3*n+1,h=-2*r+3*n,l=r-2*n+s,c=r-n;return a*o+t*h+e*l+i*c}function ht(a,e=0,t=1){return Math.min(t,Math.max(e,a))}function Yd(a){return a-=Math.PI*2*Math.floor((a+Math.PI)/(Math.PI*2)),a}function Ui(a){const e=a.toString(16);return a<=15?("0"+e).toUpperCase():e.toUpperCase()}function ec(a){if(Math.log2)return Math.floor(Math.log2(a));if(a<0)return NaN;if(a===0)return-1/0;let e=0;if(a<1){for(;a<1;)e++,a=a*2;e=-e}else if(a>1)for(;a>1;)e++,a=Math.floor(a/2);return e}function Ba(a,e){const t=a%e;return t===0?e:Ba(e,t)}const $t=a=>parseInt(a.toString().replace(/\W/g,""));class oe{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=$t(this.x),t=$t(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 oe.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new oe(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new oe(this.x+e.x,this.y+e.y)}subtract(e){return new oe(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 oe(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 oe(this.x*e,this.y*t)}divide(e){return new oe(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new oe(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new oe(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new oe(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=Le){return e&<(this.x,e.x,t)&<(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new oe(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new oe(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),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 this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new oe;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new oe(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new oe(0,0)}static One(){return new oe(1,1)}static Random(e=0,t=1){return new oe(gt(e,t),gt(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(gt(e,t),gt(e,t))}static get ZeroReadOnly(){return oe._ZeroReadOnly}static FromArray(e,t=0){return new oe(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,n){const r=n*n,o=n*r,h=.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),l=.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 oe(h,l)}static ClampToRef(e,t,i,s){return s.x=ht(e.x,t.x,i.x),s.y=ht(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=ht(e.x,t.x,i.x),n=ht(e.y,t.y,i.y);return new oe(s,n)}static Hermite(e,t,i,s,n){const r=n*n,o=n*r,h=2*o-3*r+1,l=-2*o+3*r,c=o-2*r+n,u=o-r,f=e.x*h+i.x*l+t.x*c+s.x*u,d=e.y*h+i.y*l+t.y*c+s.y*u;return new oe(f,d)}static Hermite1stDerivative(e,t,i,s,n){return this.Hermite1stDerivativeToRef(e,t,i,s,n,new oe)}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}static Lerp(e,t,i){return oe.LerpToRef(e,t,i,new oe)}static LerpToRef(e,t,i,s){return s.x=e.x+(t.x-e.x)*i,s.y=e.y+(t.y-e.y)*i,s}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return oe.NormalizeToRef(e,new oe)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new oe(i,s)}static Transform(e,t){return oe.TransformToRef(e,t,new oe)}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,h=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*r;return o>0&&h>0&&o+h<2*n*r}static Distance(e,t){return Math.sqrt(oe.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){return oe.CenterToRef(e,t,new oe)}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=oe.DistanceSquared(t,i);if(s===0)return oe.Distance(e,t);const n=i.subtract(t),r=Math.max(0,Math.min(1,oe.Dot(e.subtract(t),n)/s)),o=t.add(n.multiplyByFloats(r,r));return oe.Distance(e,o)}}oe._V8PerformanceHack=new oe(.5,.5);oe._ZeroReadOnly=oe.Zero();Object.defineProperties(oe.prototype,{dimension:{value:[2]},rank:{value:1}});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=$t(this._x),t=$t(this._y),i=$t(this._z);let s=e;return s=s*397^t,s=s*397^i,s}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return v.FromArrayToRef(e,t,this),this}toQuaternion(){return re.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new v(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._isDirty=!0,t}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new v(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 v(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s._x=this._x-e,s._y=this._y-t,s._z=this._z-i,s._isDirty=!0,s}negate(){return new v(-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._x=this._x*-1,e._y=this._y*-1,e._z=this._z*-1,e._isDirty=!0,e}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new v(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}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=this._x,s=this._y,n=this._z,r=e._x,o=e._y,h=e._z,l=e._w,c=2*(o*n-h*s),u=2*(h*i-r*n),f=2*(r*s-o*i);return t._x=i+l*c+o*f-h*u,t._y=s+l*u+h*c-r*f,t._z=n+l*f+r*u-o*c,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new v)}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._isDirty=!0,t}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new v)}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)<1e-10)i.setAll(1/0);else{const h=-(v.Dot(t,s)+n)/o,l=r.scaleInPlace(h);t.addToRef(l,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=Le){return e&<(this._x,e._x,t)&<(this._y,e._y,t)&<(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t._x=this._x*e._x,t._y=this._y*e._y,t._z=this._z*e._z,t._isDirty=!0,t}multiplyByFloats(e,t,i){return new v(this._x*e,this._y*t,this._z*i)}divide(e){return new v(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t._x=this._x/e._x,t._y=this._y/e._y,t._z=this._z/e._z,t._isDirty=!0,t}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!lt(t,i,e))return!0;const s=Math.abs(this._z);return!lt(t,s,e)||!lt(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}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new v(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new v(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;const t=_e.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(_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){return v.CrossToRef(this,e,new v)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new v)}normalizeToRef(e){const t=this.length();return t===0||t===1?(e._x=this._x,e._y=this._y,e._z=this._z,e._isDirty=!0,e):this.scaleToRef(1/t,e)}clone(){return new v(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),r=v.Dot(t,i);return(n-s)/(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=ht(r,-1,1);const o=Math.acos(r),h=_e.Vector3[3];return v.CrossToRef(s,n,h),v.Dot(h,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],h=_e.Vector3[4];s.normalize(),n.normalize(),r.normalize(),v.CrossToRef(r,s,o),v.CrossToRef(o,r,h);const l=Math.atan2(v.Dot(n,o),v.Dot(n,h));return Yd(l)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=N.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=ht(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 h=r.length();r.normalizeFromLength(h);const l=v.Dot(n,r);let c,u;if(l<1-Le){const f=Math.acos(l),d=1/Math.sin(f);c=Math.sin((1-i)*f)*d,u=Math.sin(i*f)*d}else c=1-i,u=i;return n.scaleInPlace(c),r.scaleInPlace(u),s.copyFrom(n).addInPlace(r),s.scaleInPlace(Rr(o,h,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 get OneReadOnly(){return v._OneReadOnly}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(gt(e,t),gt(e,t),gt(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(gt(e,t),gt(e,t),gt(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],h=e*r[1]+t*r[5]+i*r[9]+r[13],l=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=h*c,n._z=l*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,h=.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),l=.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 v(h,l,c)}static Clamp(e,t,i){const s=new v;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&&S<0?(P.copyFrom(r),G=t,L=i):S>0&&w<0?(P.copyFrom(h),G=i,L=s):(P.copyFrom(o).scaleInPlace(-1),G=s,L=t);const W=_e.Vector3[9],K=_e.Vector3[4];if(G.subtractToRef(b,y),L.subtractToRef(b,W),v.CrossToRef(y,W,K),!(v.Dot(K,l)<0))return n.copyFrom(b),Math.abs(p*g);const $=_e.Vector3[5];v.CrossToRef(P,K,$),$.normalize();const z=_e.Vector3[9];z.copyFrom(G).subtractInPlace(b);const k=z.length();if(kthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,s){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(s,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new Pe(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new Pe(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new Pe)}normalizeToRef(e){const t=this.length();return t===0||t===1?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)}toVector3(){return new v(this.x,this.y,this.z)}clone(){return new Pe(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}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new Pe(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 Pe.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 Pe(0,0,0,0)}static One(){return new Pe(1,1,1,1)}static Random(e=0,t=1){return new Pe(gt(e,t),gt(e,t),gt(e,t),gt(e,t))}static RandomToRef(e=0,t=1,i){return i.x=gt(e,t),i.y=gt(e,t),i.z=gt(e,t),i.w=gt(e,t),i}static Clamp(e,t,i){return Pe.ClampToRef(e,t,i,new Pe)}static ClampToRef(e,t,i,s){return s.x=ht(e.x,t.x,i.x),s.y=ht(e.y,t.y,i.y),s.z=ht(e.z,t.z,i.z),s.w=ht(e.w,t.w,i.w),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return Pe._ZeroReadOnly}static Normalize(e){return Pe.NormalizeToRef(e,new Pe)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new Pe;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new Pe;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(Pe.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 Pe.CenterToRef(e,t,new Pe)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return Pe.TransformCoordinatesToRef(e,t,new Pe)}static TransformCoordinatesToRef(e,t,i){return Pe.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],h=e*r[1]+t*r[5]+i*r[9]+r[13],l=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=h,n.z=l,n.w=c,n}static TransformNormal(e,t){return Pe.TransformNormalToRef(e,t,new Pe)}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 Pe(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}Pe._V8PerformanceHack=new Pe(.5,.5,.5,.5);Pe._ZeroReadOnly=Pe.Zero();Object.defineProperties(Pe.prototype,{dimension:{value:[4]},rank:{value:1}});class re{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=$t(this._x),t=$t(this._y),i=$t(this._z),s=$t(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}fromArray(e,t=0){return re.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=Le){return e&<(this._x,e._x,t)&<(this._y,e._y,t)&<(this._z,e._z,t)&<(this._w,e._w,t)}clone(){return new re(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)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new re(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new re)}subtractFromFloatsToRef(e,t,i,s,n){return n._x=this._x-e,n._y=this._y-t,n._z=this._z-i,n._w=this._w-s,n._isDirty=!0,n}subtract(e){return new re(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 re(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 re(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)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new re)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new re(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return t==0||t==1||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return e==0||e==1?this:(this.scaleInPlace(1/e),this)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new re(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=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<-.4999999)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 h=n*n,l=t*t,c=i*i,u=s*s;e._z=Math.atan2(2*(i*s+t*n),-l-c+u+h),e._x=Math.asin(-2*r),e._y=Math.atan2(2*(t*i+s*n),l-c-u+h),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){const t=this._z,i=this._x,s=this._y,n=this._w,r=Math.sqrt(i*i+s*s),o=Math.sqrt(t*t+n*n),h=2*Math.atan2(r,o),l=2*Math.atan2(t,n),c=2*Math.atan2(s,i),u=(l+c)/2,f=(l-c)/2;return e.set(f,h,u),e}toRotationMatrix(e){return O.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return re.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new re;return re.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],n=i[4],r=i[8],o=i[1],h=i[5],l=i[9],c=i[2],u=i[6],f=i[10],d=s+h+f;let _;return d>0?(_=.5/Math.sqrt(d+1),t._w=.25/_,t._x=(u-l)*_,t._y=(r-c)*_,t._z=(o-n)*_,t._isDirty=!0):s>h&&s>f?(_=2*Math.sqrt(1+s-h-f),t._w=(u-l)/_,t._x=.25*_,t._y=(n+o)/_,t._z=(r+c)/_,t._isDirty=!0):h>f?(_=2*Math.sqrt(1+h-s-f),t._w=(r-c)/_,t._x=(n+o)/_,t._y=.25*_,t._z=(l+u)/_,t._isDirty=!0):(_=2*Math.sqrt(1+f-s-h),t._w=(o-n)/_,t._x=(r+c)/_,t._y=(l+u)/_,t._z=.25*_,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=re.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,n){let r=s===0?1:i/s;return r=ht(r,0,1),re.SlerpToRef(e,t,r,n),n}static Zero(){return new re(0,0,0,0)}static Inverse(e){return new re(-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 re(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 re.RotationAxisToRef(e,t,new re)}static RotationAxisToRef(e,t,i){i._w=Math.cos(t/2);const s=Math.sin(t/2)/e.length();return 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 re(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,n){return n.copyFromFloats(e,t,i,s),n}static FromEulerAngles(e,t,i){const s=new re;return re.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return re.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new re;return re.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return re.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=Le){const n=v.Dot(e,t)+1;return nMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(v.CrossToRef(e,t,N.Vector3[0]),i.set(N.Vector3[0].x,N.Vector3[0].y,N.Vector3[0].z,n)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new re;return re.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const n=i*.5,r=t*.5,o=e*.5,h=Math.sin(n),l=Math.cos(n),c=Math.sin(r),u=Math.cos(r),f=Math.sin(o),d=Math.cos(o);return s._x=d*c*l+f*u*h,s._y=f*u*l-d*c*h,s._z=d*u*h-f*c*l,s._w=d*u*l+f*c*h,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new re;return re.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 re(0,0,0,0);return re.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const n=_e.Matrix[0];return e=e.normalizeToRef(_e.Vector3[0]),t=t.normalizeToRef(_e.Vector3[1]),i=i.normalizeToRef(_e.Vector3[2]),O.FromXYZAxesToRef(e,t,i,n),re.FromRotationMatrixToRef(n,s),s}static FromLookDirectionLH(e,t){const i=new re;return re.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=_e.Matrix[0];return O.LookDirectionLHToRef(e,t,s),re.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new re;return re.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=_e.Matrix[0];return O.LookDirectionRHToRef(e,t,s),re.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=re.Identity();return re.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,h=!1;if(o<0&&(h=!0,o=-o),o>.999999)r=1-i,n=h?-i:i;else{const l=Math.acos(o),c=1/Math.sin(l);r=Math.sin((1-i)*l)*c,n=h?-Math.sin(i*l)*c:Math.sin(i*l)*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,h=2*o-3*r+1,l=-2*o+3*r,c=o-2*r+n,u=o-r,f=e._x*h+i._x*l+t._x*c+s._x*u,d=e._y*h+i._y*l+t._y*c+s._y*u,_=e._z*h+i._z*l+t._z*c+s._z*u,p=e._w*h+i._w*l+t._w*c+s._w*u;return new re(f,d,_,p)}static Hermite1stDerivative(e,t,i,s,n){const r=new re;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}static Normalize(e){const t=re.Zero();return re.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new re;return re.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(ht(e.x,t.x,i.x),ht(e.y,t.y,i.y),ht(e.z,t.z,i.z),ht(e.w,t.w,i.w))}static Random(e=0,t=1){return new re(gt(e,t),gt(e,t),gt(e,t),gt(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(gt(e,t),gt(e,t),gt(e,t),gt(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(re.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 re.CenterToRef(e,t,re.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)}}re._V8PerformanceHack=new re(.5,.5,.5,.5);Object.defineProperties(re.prototype,{dimension:{value:[4]},rank:{value:1}});class O{static get Use64Bits(){return Dt.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=O._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,Dt.MatrixTrackPrecisionChange&&Dt.MatrixTrackedMatrices.push(this),this._m=new Dt.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],h=e[6],l=e[7],c=e[8],u=e[9],f=e[10],d=e[11],_=e[12],p=e[13],g=e[14],m=e[15],b=f*m-g*d,I=u*m-p*d,T=u*g-p*f,x=c*m-_*d,y=c*g-f*_,R=c*p-_*u,E=+(o*b-h*I+l*T),C=-(r*b-h*x+l*y),S=+(r*I-o*x+l*R),w=-(r*T-o*y+h*R);return t*E+i*C+s*S+n*w}toString(){return"{".concat(this.m[0],", ").concat(this.m[1],", ").concat(this.m[2],", ").concat(this.m[3],"\n").concat(this.m[4],", ").concat(this.m[5],", ").concat(this.m[6],", ").concat(this.m[7],"\n").concat(this.m[8],", ").concat(this.m[9],", ").concat(this.m[10],", ").concat(this.m[11],"\n").concat(this.m[12],", ").concat(this.m[13],", ").concat(this.m[14],", ").concat(this.m[15],"}")}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return O.FromArrayToRef(e,t,this)}copyFromFloats(...e){return O.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return O.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 O;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;return t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[3],t[4]+=i[4],t[5]+=i[5],t[6]+=i[6],t[7]+=i[7],t[8]+=i[8],t[9]+=i[9],t[10]+=i[10],t[11]+=i[11],t[12]+=i[12],t[13]+=i[13],t[14]+=i[14],t[15]+=i[15],this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]+=i[s];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]-=i[s];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,n=t._m;for(let r=0;r<16;r++)n[r]=i[r]-s[r];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]-=i[s];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new O)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,n=e;for(let r=0;r<16;r++)s[r]=i[r]-n[r];return t.markAsUpdated(),t}invertToRef(e){if(this._isIdentity===!0)return O.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],n=t[2],r=t[3],o=t[4],h=t[5],l=t[6],c=t[7],u=t[8],f=t[9],d=t[10],_=t[11],p=t[12],g=t[13],m=t[14],b=t[15],I=d*b-m*_,T=f*b-g*_,x=f*m-g*d,y=u*b-p*_,R=u*m-d*p,E=u*g-p*f,C=+(h*I-l*T+c*x),S=-(o*I-l*y+c*R),w=+(o*T-h*y+c*E),P=-(o*x-h*R+l*E),G=i*C+s*S+n*w+r*P;if(G===0)return e.copyFrom(this),e;const L=1/G,W=l*b-m*c,K=h*b-g*c,ce=h*m-g*l,$=o*b-p*c,z=o*m-p*l,k=o*g-p*h,M=l*_-d*c,V=h*_-f*c,q=h*d-f*l,he=o*_-u*c,pe=o*d-u*l,se=o*f-u*h,ue=-(s*I-n*T+r*x),me=+(i*I-n*y+r*R),ne=-(i*T-s*y+r*E),Ie=+(i*x-s*R+n*E),Se=+(s*W-n*K+r*ce),Q=-(i*W-n*$+r*z),be=+(i*K-s*$+r*k),Be=-(i*ce-s*z+n*k),ze=-(s*M-n*V+r*q),Ke=+(i*M-n*he+r*pe),Rt=-(i*V-s*he+r*se),Ct=+(i*q-s*pe+n*se);return O.FromValuesToRef(C*L,ue*L,Se*L,ze*L,S*L,me*L,Q*L,Ke*L,w*L,ne*L,be*L,Rt*L,P*L,Ie*L,Be*L,Ct*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 O.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new O;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]*=i[s];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,n=e;for(let r=0;r<16;r++)s[r]=i[r]*n[r];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,n=e.m,r=s[0],o=s[1],h=s[2],l=s[3],c=s[4],u=s[5],f=s[6],d=s[7],_=s[8],p=s[9],g=s[10],m=s[11],b=s[12],I=s[13],T=s[14],x=s[15],y=n[0],R=n[1],E=n[2],C=n[3],S=n[4],w=n[5],P=n[6],G=n[7],L=n[8],W=n[9],K=n[10],ce=n[11],$=n[12],z=n[13],k=n[14],M=n[15];return t[i]=r*y+o*S+h*L+l*$,t[i+1]=r*R+o*w+h*W+l*z,t[i+2]=r*E+o*P+h*K+l*k,t[i+3]=r*C+o*G+h*ce+l*M,t[i+4]=c*y+u*S+f*L+d*$,t[i+5]=c*R+u*w+f*W+d*z,t[i+6]=c*E+u*P+f*K+d*k,t[i+7]=c*C+u*G+f*ce+d*M,t[i+8]=_*y+p*S+g*L+m*$,t[i+9]=_*R+p*w+g*W+m*z,t[i+10]=_*E+p*P+g*K+m*k,t[i+11]=_*C+p*G+g*ce+m*M,t[i+12]=b*y+I*S+T*L+x*$,t[i+13]=b*R+I*w+T*W+x*z,t[i+14]=b*E+I*P+T*K+x*k,t[i+15]=b*C+I*G+T*ce+x*M,this}divide(e){return this.divideToRef(e,new O)}divideToRef(e,t){const i=this._m,s=e.m,n=t._m;for(let r=0;r<16;r++)n[r]=i[r]/s[r];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]/=i[s];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],i[s]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],i[s]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new O)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=-t[s];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,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]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let n=0;n<16;n++)if(!lt(i[n],s[n],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new O)}floorToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=Math.floor(t[s]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new O)}fractToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=t[s]-Math.floor(t[s]);return e.markAsUpdated(),e}clone(){const e=new O;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=$t(this._m[0]);for(let t=1;t<16;t++)e=e*397^$t(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new re,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,n=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const r=this._m;if(i&&i.copyFromFloats(r[12],r[13],r[14]),e=e||_e.Vector3[0],e.x=Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]),e.y=Math.sqrt(r[4]*r[4]+r[5]*r[5]+r[6]*r[6]),e.z=Math.sqrt(r[8]*r[8]+r[9]*r[9]+r[10]*r[10]),s){const o=(n?s.absoluteScaling.x:s.scaling.x)<0?-1:1,h=(n?s.absoluteScaling.y:s.scaling.y)<0?-1:1,l=(n?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=o,e.y*=h,e.z*=l}else this.determinant()<=0&&(e.y*=-1);if(e._x===0||e._y===0||e._z===0)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const o=1/e._x,h=1/e._y,l=1/e._z;O.FromValuesToRef(r[0]*o,r[1]*o,r[2]*o,0,r[4]*h,r[5]*h,r[6]*h,0,r[8]*l,r[9]*l,r[10]*l,0,0,0,0,1,_e.Matrix[0]),re.FromRotationMatrixToRef(_e.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new Pe(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 O;return O.TransposeToRef(this,e),e}transposeToRef(e){return O.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 O;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=_e.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return O.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 O;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=_e.Vector3[0];if(!this.decompose(t))return O.IdentityToRef(e),e;const i=this._m,s=1/t._x,n=1/t._y,r=1/t._z;return O.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 O;return O.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){return s._m[0]=e[0+t]*i,s._m[1]=e[1+t]*i,s._m[2]=e[2+t]*i,s._m[3]=e[3+t]*i,s._m[4]=e[4+t]*i,s._m[5]=e[5+t]*i,s._m[6]=e[6+t]*i,s._m[7]=e[7+t]*i,s._m[8]=e[8+t]*i,s._m[9]=e[9+t]*i,s._m[10]=e[10+t]*i,s._m[11]=e[11+t]*i,s._m[12]=e[12+t]*i,s._m[13]=e[13+t]*i,s._m[14]=e[14+t]*i,s._m[15]=e[15+t]*i,s.markAsUpdated(),s}static get IdentityReadOnly(){return O._IdentityReadOnly}static FromValuesToRef(e,t,i,s,n,r,o,h,l,c,u,f,d,_,p,g,m){const b=m._m;b[0]=e,b[1]=t,b[2]=i,b[3]=s,b[4]=n,b[5]=r,b[6]=o,b[7]=h,b[8]=l,b[9]=c,b[10]=u,b[11]=f,b[12]=d,b[13]=_,b[14]=p,b[15]=g,m.markAsUpdated()}static FromValues(e,t,i,s,n,r,o,h,l,c,u,f,d,_,p,g){const m=new O,b=m._m;return b[0]=e,b[1]=t,b[2]=i,b[3]=s,b[4]=n,b[5]=r,b[6]=o,b[7]=h,b[8]=l,b[9]=c,b[10]=u,b[11]=f,b[12]=d,b[13]=_,b[14]=p,b[15]=g,m.markAsUpdated(),m}static Compose(e,t,i){const s=new O;return O.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const n=s._m,r=t._x,o=t._y,h=t._z,l=t._w,c=r+r,u=o+o,f=h+h,d=r*c,_=r*u,p=r*f,g=o*u,m=o*f,b=h*f,I=l*c,T=l*u,x=l*f,y=e._x,R=e._y,E=e._z;return n[0]=(1-(g+b))*y,n[1]=(_+x)*y,n[2]=(p-T)*y,n[3]=0,n[4]=(_-x)*R,n[5]=(1-(d+b))*R,n[6]=(m+I)*R,n[7]=0,n[8]=(p+T)*E,n[9]=(m-I)*E,n[10]=(1-(d+g))*E,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=O.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 O.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=O.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 O;return O.RotationXToRef(e,t),t}static Invert(e){const t=new O;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return O.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 O;return O.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return O.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 O;return O.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return O.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 O;return O.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),n=Math.cos(-t),r=1-n;e=e.normalizeToRef(_e.Vector3[0]);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,s=!1){const n=v.Dot(t,e),r=i._m;if(n<-1+Le)r[0]=-1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=s?1:-1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=s?-1:1,r[11]=0;else{const o=v.Cross(t,e),h=1/(1+n);r[0]=o._x*o._x*h+n,r[1]=o._y*o._x*h-o._z,r[2]=o._z*o._x*h+o._y,r[3]=0,r[4]=o._x*o._y*h+o._z,r[5]=o._y*o._y*h+n,r[6]=o._z*o._y*h-o._x,r[7]=0,r[8]=o._x*o._z*h-o._y,r[9]=o._y*o._z*h+o._x,r[10]=o._z*o._z*h+n,r[11]=0}return r[12]=0,r[13]=0,r[14]=0,r[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new O;return O.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return re.RotationYawPitchRollToRef(e,t,i,_e.Quaternion[0]),_e.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new O;return O.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return O.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 O;return O.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return O.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 O;return O.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const n=s._m,r=e.m,o=t.m;for(let h=0;h<16;h++)n[h]=r[h]*(1-i)+o[h]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new O;return O.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 h=_e.Vector3[2],l=_e.Quaternion[1],c=_e.Vector3[3];t.decompose(h,l,c);const u=_e.Vector3[4];v.LerpToRef(n,h,i,u);const f=_e.Quaternion[2];re.SlerpToRef(r,l,i,f);const d=_e.Vector3[5];return v.LerpToRef(o,c,i,d),O.ComposeToRef(u,f,d,s),s}static LookAtLH(e,t,i){const s=new O;return O.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 h=n.lengthSquared();h===0?n.x=1:n.normalizeFromLength(Math.sqrt(h)),v.CrossToRef(o,n,r),r.normalize();const l=-v.Dot(n,e),c=-v.Dot(r,e),u=-v.Dot(o,e);return O.FromValuesToRef(n._x,r._x,o._x,0,n._y,r._y,o._y,0,n._z,r._z,o._z,0,l,c,u,1,s),s}static LookAtRH(e,t,i){const s=new O;return O.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 h=n.lengthSquared();h===0?n.x=1:n.normalizeFromLength(Math.sqrt(h)),v.CrossToRef(o,n,r),r.normalize();const l=-v.Dot(n,e),c=-v.Dot(r,e),u=-v.Dot(o,e);return O.FromValuesToRef(n._x,r._x,o._x,0,n._y,r._y,o._y,0,n._z,r._z,o._z,0,l,c,u,1,s),s}static LookDirectionLH(e,t){const i=new O;return O.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),O.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 O;return O.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=_e.Vector3[2];return v.CrossToRef(t,e,s),O.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 O;return O.OrthoLHToRef(e,t,i,s,r,n),r}static OrthoLHToRef(e,t,i,s,n,r){const o=i,h=s,l=2/e,c=2/t,u=2/(h-o),f=-(h+o)/(h-o);return O.FromValuesToRef(l,0,0,0,0,c,0,0,0,0,u,0,0,0,f,1,n),r&&n.multiplyToRef(Cs,n),n._updateIdentityStatus(l===1&&c===1&&u===1&&f===0),n}static OrthoOffCenterLH(e,t,i,s,n,r,o){const h=new O;return O.OrthoOffCenterLHToRef(e,t,i,s,n,r,h,o),h}static OrthoOffCenterLHToRef(e,t,i,s,n,r,o,h){const l=n,c=r,u=2/(t-e),f=2/(s-i),d=2/(c-l),_=-(c+l)/(c-l),p=(e+t)/(e-t),g=(s+i)/(i-s);return O.FromValuesToRef(u,0,0,0,0,f,0,0,0,0,d,0,p,g,_,1,o),h&&o.multiplyToRef(Cs,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,s,n,r,o,h,l,c,u){const f=-o*Math.cos(h),d=-o*Math.sin(h);return O.TranslationToRef(0,0,-l,_e.Matrix[1]),O.FromValuesToRef(1,0,0,0,0,1,0,0,f,d,1,0,0,0,0,1,_e.Matrix[0]),_e.Matrix[1].multiplyToRef(_e.Matrix[0],_e.Matrix[0]),O.TranslationToRef(0,0,l,_e.Matrix[1]),_e.Matrix[0].multiplyToRef(_e.Matrix[1],_e.Matrix[0]),O.OrthoOffCenterLHToRef(e,t,i,s,n,r,c,u),_e.Matrix[0].multiplyToRef(c,c),c}static OrthoOffCenterRH(e,t,i,s,n,r,o){const h=new O;return O.OrthoOffCenterRHToRef(e,t,i,s,n,r,h,o),h}static OrthoOffCenterRHToRef(e,t,i,s,n,r,o,h){return O.OrthoOffCenterLHToRef(e,t,i,s,n,r,o,h),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,s,n,r,o,h,l,c,u){const f=o*Math.cos(h),d=o*Math.sin(h);return O.TranslationToRef(0,0,l,_e.Matrix[1]),O.FromValuesToRef(1,0,0,0,0,1,0,0,f,d,1,0,0,0,0,1,_e.Matrix[0]),_e.Matrix[1].multiplyToRef(_e.Matrix[0],_e.Matrix[0]),O.TranslationToRef(0,0,-l,_e.Matrix[1]),_e.Matrix[0].multiplyToRef(_e.Matrix[1],_e.Matrix[0]),O.OrthoOffCenterRHToRef(e,t,i,s,n,r,c,u),_e.Matrix[0].multiplyToRef(c,c),c}static PerspectiveLH(e,t,i,s,n,r=0){const o=new O,h=i,l=s,c=2*h/e,u=2*h/t,f=(l+h)/(l-h),d=-2*l*h/(l-h),_=Math.tan(r);return O.FromValuesToRef(c,0,0,0,0,u,0,_,0,0,f,1,0,0,d,0,o),n&&o.multiplyToRef(Cs,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,n,r=0,o=!1){const h=new O;return O.PerspectiveFovLHToRef(e,t,i,s,h,!0,n,r,o),h}static PerspectiveFovLHToRef(e,t,i,s,n,r=!0,o,h=0,l=!1){const c=i,u=s,f=1/Math.tan(e*.5),d=r?f/t:f,_=r?f:f*t,p=l&&c===0?-1:u!==0?(u+c)/(u-c):1,g=l&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,m=Math.tan(h);return O.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,p,1,0,0,g,0,n),o&&n.multiplyToRef(Cs,n),n._updateIdentityStatus(!1),n}static PerspectiveFovReverseLHToRef(e,t,i,s,n,r=!0,o,h=0){const l=1/Math.tan(e*.5),c=r?l/t:l,u=r?l:l*t,f=Math.tan(h);return O.FromValuesToRef(c,0,0,0,0,u,0,f,0,0,-i,1,0,0,1,0,n),o&&n.multiplyToRef(Cs,n),n._updateIdentityStatus(!1),n}static PerspectiveFovRH(e,t,i,s,n,r=0,o=!1){const h=new O;return O.PerspectiveFovRHToRef(e,t,i,s,h,!0,n,r,o),h}static PerspectiveFovRHToRef(e,t,i,s,n,r=!0,o,h=0,l=!1){const c=i,u=s,f=1/Math.tan(e*.5),d=r?f/t:f,_=r?f:f*t,p=l&&c===0?1:u!==0?-(u+c)/(u-c):-1,g=l&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,m=Math.tan(h);return O.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,p,-1,0,0,g,0,n),o&&n.multiplyToRef(Cs,n),n._updateIdentityStatus(!1),n}static PerspectiveFovReverseRHToRef(e,t,i,s,n,r=!0,o,h=0){const l=1/Math.tan(e*.5),c=r?l/t:l,u=r?l:l*t,f=Math.tan(h);return O.FromValuesToRef(c,0,0,0,0,u,0,f,0,0,-i,-1,0,0,-1,0,n),o&&n.multiplyToRef(Cs,n),n._updateIdentityStatus(!1),n}static GetFinalMatrix(e,t,i,s,n,r){const o=e.width,h=e.height,l=e.x,c=e.y,u=O.FromValues(o/2,0,0,0,0,-h/2,0,0,0,0,r-n,0,l+o/2,h/2+c,n,1),f=new O;return t.multiplyToRef(i,f),f.multiplyToRef(s,f),f.multiplyToRef(u,f)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return Dt.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 Dt.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new O;return O.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],n=i[4],r=i[8],o=i[12],h=i[1],l=i[5],c=i[9],u=i[13],f=i[2],d=i[6],_=i[10],p=i[14],g=i[3],m=i[7],b=i[11],I=i[15],T=t._m;return T[0]=s,T[1]=n,T[2]=r,T[3]=o,T[4]=h,T[5]=l,T[6]=c,T[7]=u,T[8]=f,T[9]=d,T[10]=_,T[11]=p,T[12]=g,T[13]=m,T[14]=b,T[15]=I,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new O;return O.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,h=-2*n;return O.FromValuesToRef(r*i+1,o*i,h*i,0,r*s,o*s+1,h*s,0,r*n,o*n,h*n+1,0,r*e.d,o*e.d,h*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return O.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,h=e._z*e._x,l=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*(h-l),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*(h+l),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}}O._UpdateFlagSeed=0;O._IdentityReadOnly=O.Identity();Object.defineProperties(O.prototype,{dimension:{value:[4,4]},rank:{value:2}});class _e{}_e.Vector3=Rs(11,v.Zero);_e.Matrix=Rs(2,O.Identity);_e.Quaternion=Rs(3,re.Zero);class N{}N.Vector2=Rs(3,oe.Zero);N.Vector3=Rs(13,v.Zero);N.Vector4=Rs(3,Pe.Zero);N.Quaternion=Rs(3,re.Zero);N.Matrix=Rs(8,O.Identity);vt("BABYLON.Vector2",oe);vt("BABYLON.Vector3",v);vt("BABYLON.Vector4",Pe);vt("BABYLON.Matrix",O);const Cs=O.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);var ci;(function(a){a[a.LOCAL=0]="LOCAL",a[a.WORLD=1]="WORLD",a[a.BONE=2]="BONE"})(ci||(ci={}));class Gt{}Gt.X=new v(1,0,0);Gt.Y=new v(0,1,0);Gt.Z=new v(0,0,1);var Bo;(function(a){a[a.X=0]="X",a[a.Y=1]="Y",a[a.Z=2]="Z"})(Bo||(Bo={}));function tn(a){return Math.pow(a,Wd)}function sn(a){return a<=.04045?.0773993808*a:Math.pow(.947867299*(a+.055),2.4)}function nn(a){return Math.pow(a,zd)}function rn(a){return a<=.0031308?12.92*a:1.055*Math.pow(a,.41666)-.055}class de{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 de.FromArrayToRef(e,t,this),this}toColor4(e=1){return new H(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 de(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new de(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=Le){return lt(this.r,e.r,t)&<(this.g,e.g,t)&<(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new de(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=ht(this.r,e,t),i.g=ht(this.g,e,t),i.b=ht(this.b,e,t),i}add(e){return new de(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new de(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new de(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s}clone(){return new de(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+Ui(e)+Ui(t)+Ui(i)}fromHexString(e){return e.substring(0,1)!=="#"||e.length!==7?this:(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,this)}toHSV(){return this.toHSVToRef(new de)}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,h=0;const l=n,c=n-r;return n!==0&&(h=c/n),n!=r&&(n==t?(o=(i-s)/c,i=0&&r<=1?(h=n,l=o):r>=1&&r<=2?(h=o,l=n):r>=2&&r<=3?(l=n,c=o):r>=3&&r<=4?(l=o,c=n):r>=4&&r<=5?(h=o,c=n):r>=5&&r<=6&&(h=n,c=o);const u=i-n;return s.r=h+u,s.g=l+u,s.b=c+u,s}static FromHSV(e,t,i){const s=new de(0,0,0);return de.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){return new de(0,0,0).fromHexString(e)}static FromArray(e,t=0){return new de(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 de(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new de(0,0,0);return de.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,h=2*o-3*r+1,l=-2*o+3*r,c=o-2*r+n,u=o-r,f=e.r*h+i.r*l+t.r*c+s.r*u,d=e.g*h+i.g*l+t.g*c+s.g*u,_=e.b*h+i.b*l+t.b*c+s.b*u;return new de(f,d,_)}static Hermite1stDerivative(e,t,i,s,n){const r=de.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 de(1,0,0)}static Green(){return new de(0,1,0)}static Blue(){return new de(0,0,1)}static Black(){return new de(0,0,0)}static get BlackReadOnly(){return de._BlackReadOnly}static White(){return new de(1,1,1)}static Purple(){return new de(.5,0,.5)}static Magenta(){return new de(1,0,1)}static Yellow(){return new de(1,1,0)}static Gray(){return new de(.5,.5,.5)}static Teal(){return new de(0,1,1)}static Random(){return new de(Math.random(),Math.random(),Math.random())}}de._V8PerformanceHack=new de(.5,.5,.5);de._BlackReadOnly=de.Black();Object.defineProperties(de.prototype,{dimension:{value:[3]},rank:{value:1}});class H{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new H(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new H(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,s){return new H(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,n){return n.r=this.r-e,n.g=this.g-t,n.b=this.b-i,n.a=this.a-s,n}scale(e){return new H(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=ht(this.r,e,t),i.g=ht(this.g,e,t),i.b=ht(this.b,e,t),i.a=ht(this.a,e,t),i}multiply(e){return new H(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,s){return new H(this.r*e,this.g*t,this.b*i,this.a*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=Le){return lt(this.r,e.r,t)&<(this.g,e.g,t)&<(this.b,e.b,t)&<(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}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 H().copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,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)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(this.r*255),i=Math.round(this.g*255),s=Math.round(this.b*255);if(e)return"#"+Ui(t)+Ui(i)+Ui(s);const n=Math.round(this.a*255);return"#"+Ui(t)+Ui(i)+Ui(s)+Ui(n)}fromHexString(e){return e.substring(0,1)!=="#"||e.length!==9&&e.length!==7?this:(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,e.length===9&&(this.a=parseInt(e.substring(7,9),16)/255),this)}toLinearSpace(e=!1){const t=new H;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=sn(this.r),e.g=sn(this.g),e.b=sn(this.b)):(e.r=tn(this.r),e.g=tn(this.g),e.b=tn(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new H;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=rn(this.r),e.g=rn(this.g),e.b=rn(this.b)):(e.r=nn(this.r),e.g=nn(this.g),e.b=nn(this.b)),e.a=this.a,this}static FromHexString(e){return e.substring(0,1)!=="#"||e.length!==9&&e.length!==7?new H(0,0,0,0):new H(0,0,0,1).fromHexString(e)}static Lerp(e,t,i){return H.LerpToRef(e,t,i,new H)}static LerpToRef(e,t,i,s){return 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,s}static Hermite(e,t,i,s,n){const r=n*n,o=n*r,h=2*o-3*r+1,l=-2*o+3*r,c=o-2*r+n,u=o-r,f=e.r*h+i.r*l+t.r*c+s.r*u,d=e.g*h+i.g*l+t.g*c+s.g*u,_=e.b*h+i.b*l+t.b*c+s.b*u,p=e.a*h+i.a*l+t.a*c+s.a*u;return new H(f,d,_,p)}static Hermite1stDerivative(e,t,i,s,n){const r=new H;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 H(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new H(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 H(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let s=0;snew H(0,0,0,0));vt("BABYLON.Color3",de);vt("BABYLON.Color4",H);class Xt{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 Xt(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=Xt._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,n=this.normal.y,r=this.normal.z,o=this.d,h=s*i[0]+n*i[1]+r*i[2]+o*i[3],l=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 Xt(h,l,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,h=i.y-e.y,l=i.z-e.z,c=n*l-r*h,u=r*o-s*l,f=s*h-n*o,d=Math.sqrt(c*c+u*u+f*f);let _;return d!==0?_=1/d:_=0,this.normal.x=c*_,this.normal.y=u*_,this.normal.z=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 Xt(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Xt(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Xt(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return v.Dot(i,t)+s}}Xt._TmpMatrix=O.Identity();class mi{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new Xt(0,0,0,0));return mi.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){mi.GetNearPlaneToRef(e,t[0]),mi.GetFarPlaneToRef(e,t[1]),mi.GetLeftPlaneToRef(e,t[2]),mi.GetRightPlaneToRef(e,t[3]),mi.GetTopPlaneToRef(e,t[4]),mi.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 Lo;(function(a){a[a.CW=0]="CW",a[a.CCW=1]="CCW"})(Lo||(Lo={}));class ki{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 ki(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new ki(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=ht(s,-1,1);const n=Math.acos(s);return new ki(n)}static FromRadians(e){return new ki(e)}static FromDegrees(e){return new ki(e*Math.PI/180)}}class qd{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 oe((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=ki.BetweenTwoPoints(this.centerPoint,this.startPoint);const h=this.startAngle.degrees();let l=ki.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=ki.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-h>180&&(l-=360),l-h<-180&&(l+=360),c-l>180&&(c-=360),c-l<-180&&(c+=360),this.orientation=l-h<0?0:1,this.angle=ki.FromDegrees(this.orientation===0?h-c:c-h)}}class Gr{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new oe(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new oe(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 oe(e,t),h=new oe(i,s),l=new qd(r,o,h);let c=l.angle.radians()/n;l.orientation===0&&(c*=-1);let u=l.startAngle.radians()+c;for(let f=0;f(1-h)*(1-h)*l+2*h*(1-h)*c+h*h*u,o=this._points[this._points.length-1];for(let h=0;h<=n;h++){const l=h/n,c=r(l,o.x,e,i),u=r(l,o.y,t,s);this.addLineTo(c,u)}return this}addBezierCurveTo(e,t,i,s,n,r,o=36){if(this.closed)return this;const h=(c,u,f,d,_)=>(1-c)*(1-c)*(1-c)*u+3*c*(1-c)*(1-c)*f+3*c*c*(1-c)*d+c*c*c*_,l=this._points[this._points.length-1];for(let c=0;c<=o;c++){const u=c/o,f=h(u,l.x,e,i,n),d=h(u,l.y,t,s,r);this.addLineTo(f,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,n=0;nNumber.EPSILON){if(l<0&&(r=this._points[n],h=-h,o=this._points[s],l=-l),e.yo.y)continue;if(e.y===r.y&&e.x===r.x)return!0;{const c=l*(e.x-r.x)-h*(e.y-r.y);if(c===0)return!0;if(c<0)continue;t=!t}}else{if(e.y!==r.y)continue;if(o.x<=e.x&&e.x<=r.x||r.x<=e.x&&e.x<=o.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s1)return oe.Zero();const t=e*this.length();let i=0;for(let s=0;s=i&&t<=l){const c=h.normalize(),u=t-i;return new oe(r.x+c.x*u,r.y+c.y*u)}i=l}return oe.Zero()}static StartingAt(e,t){return new Gr(e,t)}}class Fn{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:O.Identity()};for(let n=0;nt){const l=e;e=t,t=l}const i=this.getCurve(),s=this.getPointAt(e);let n=this.getPreviousPointIndexAt(e);const r=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,h=[];return e!==0&&(n++,h.push(s)),h.push(...i.slice(n,o)),(t!==1||e===1)&&h.push(r),new Fn(h,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;lt(Math.abs(e.y)/s,1,Le)?lt(Math.abs(e.x)/s,1,Le)?lt(Math.abs(e.z)/s,1,Le)?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 h=1;ho){const u=(r-o)/l,f=s.subtract(n),d=n.add(f.scaleInPlace(u));return this._setPointAtData(e,1-u,d,h-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=O.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(),h=this._binormals[t].clone(),l=re.RotationQuaternionFromAxis(s,n,i),c=re.RotationQuaternionFromAxis(o,h,r);re.Slerp(l,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class hi{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 hi(this.width*e,this.height*t)}clone(){return new hi(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 hi(0,0)}add(e){return new hi(this.width+e.width,this.height+e.height)}subtract(e){return new hi(this.width-e.width,this.height-e.height)}scale(e){return new hi(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,n=e.height+(t.height-e.height)*i;return new hi(s,n)}}class on{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new on(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 on(this.x,this.y,this.width,this.height)}}const Ni=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],jd=[()=>1,a=>a.y,a=>a.z,a=>a.x,a=>a.x*a.y,a=>a.y*a.z,a=>3*a.z*a.z-1,a=>a.x*a.z,a=>a.x*a.x-a.y*a.y],Zi=(a,e)=>Ni[a]*jd[a](e),Qi=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class Ir{constructor(){this.preScaled=!1,this.l00=v.Zero(),this.l1_1=v.Zero(),this.l10=v.Zero(),this.l11=v.Zero(),this.l2_2=v.Zero(),this.l2_1=v.Zero(),this.l20=v.Zero(),this.l21=v.Zero(),this.l22=v.Zero()}addLight(e,t,i){N.Vector3[0].set(t.r,t.g,t.b);const s=N.Vector3[0],n=N.Vector3[1];s.scaleToRef(i,n),n.scaleToRef(Zi(0,e),N.Vector3[2]),this.l00.addInPlace(N.Vector3[2]),n.scaleToRef(Zi(1,e),N.Vector3[2]),this.l1_1.addInPlace(N.Vector3[2]),n.scaleToRef(Zi(2,e),N.Vector3[2]),this.l10.addInPlace(N.Vector3[2]),n.scaleToRef(Zi(3,e),N.Vector3[2]),this.l11.addInPlace(N.Vector3[2]),n.scaleToRef(Zi(4,e),N.Vector3[2]),this.l2_2.addInPlace(N.Vector3[2]),n.scaleToRef(Zi(5,e),N.Vector3[2]),this.l2_1.addInPlace(N.Vector3[2]),n.scaleToRef(Zi(6,e),N.Vector3[2]),this.l20.addInPlace(N.Vector3[2]),n.scaleToRef(Zi(7,e),N.Vector3[2]),this.l21.addInPlace(N.Vector3[2]),n.scaleToRef(Zi(8,e),N.Vector3[2]),this.l22.addInPlace(N.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(Qi[0]),this.l1_1.scaleInPlace(Qi[1]),this.l10.scaleInPlace(Qi[2]),this.l11.scaleInPlace(Qi[3]),this.l2_2.scaleInPlace(Qi[4]),this.l2_1.scaleInPlace(Qi[5]),this.l20.scaleInPlace(Qi[6]),this.l21.scaleInPlace(Qi[7]),this.l22.scaleInPlace(Qi[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Ni[0]),this.l1_1.scaleInPlace(Ni[1]),this.l10.scaleInPlace(Ni[2]),this.l11.scaleInPlace(Ni[3]),this.l2_2.scaleInPlace(Ni[4]),this.l2_1.scaleInPlace(Ni[5]),this.l20.scaleInPlace(Ni[6]),this.l21.scaleInPlace(Ni[7]),this.l22.scaleInPlace(Ni[8])}updateFromArray(e){return v.FromArrayToRef(e[0],0,this.l00),v.FromArrayToRef(e[1],0,this.l1_1),v.FromArrayToRef(e[2],0,this.l10),v.FromArrayToRef(e[3],0,this.l11),v.FromArrayToRef(e[4],0,this.l2_2),v.FromArrayToRef(e[5],0,this.l2_1),v.FromArrayToRef(e[6],0,this.l20),v.FromArrayToRef(e[7],0,this.l21),v.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return v.FromFloatsToRef(e[0],e[1],e[2],this.l00),v.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),v.FromFloatsToRef(e[6],e[7],e[8],this.l10),v.FromFloatsToRef(e[9],e[10],e[11],this.l11),v.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),v.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),v.FromFloatsToRef(e[18],e[19],e[20],this.l20),v.FromFloatsToRef(e[21],e[22],e[23],this.l21),v.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new Ir().updateFromArray(e)}static FromPolynomial(e){const t=new Ir;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class On{constructor(){this.x=v.Zero(),this.y=v.Zero(),this.z=v.Zero(),this.xx=v.Zero(),this.yy=v.Zero(),this.zz=v.Zero(),this.xy=v.Zero(),this.yz=v.Zero(),this.zx=v.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=Ir.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){N.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=N.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),N.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),N.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(N.Vector3[0]).addInPlace(N.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(N.Vector3[0]).subtractInPlace(N.Vector3[1]),this.zz.copyFrom(e.l00),N.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(N.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return new On().updateFromHarmonics(e)}static FromArray(e){const t=new On;return v.FromArrayToRef(e[0],0,t.x),v.FromArrayToRef(e[1],0,t.y),v.FromArrayToRef(e[2],0,t.z),v.FromArrayToRef(e[3],0,t.xx),v.FromArrayToRef(e[4],0,t.yy),v.FromArrayToRef(e[5],0,t.zz),v.FromArrayToRef(e[6],0,t.yz),v.FromArrayToRef(e[7],0,t.zx),v.FromArrayToRef(e[8],0,t.xy),t}}function D(a,e,t,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(a,e,t,i);else for(var o=a.length-1;o>=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}const rr={},_r={};function $d(a){const e=a.getClassName();return _r[e]||(_r[e]={}),_r[e]}function La(a){const e=a.getClassName();if(rr[e])return rr[e];rr[e]={};const t=rr[e];let i=a,s=e;for(;s;){const n=_r[s];for(const h in n)t[h]=n[h];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 Di(a,e){return(t,i)=>{const s=$d(t);s[i]||(s[i]={type:a,sourceName:e})}}function Zd(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 Zd(a,e)}function B(a){return Di(0,a)}function _i(a){return Di(1,a)}function ls(a){return Di(2,a)}function Kn(a){return Di(3,a)}function tc(a){return Di(4,a)}function yi(a){return Di(5,a)}function ic(a){return Di(6,a)}function Qd(a){return Di(7,a)}function p0(a){return Di(8,a)}function Jd(a){return Di(10,a)}function e_(a){return Di(11,a)}function rs(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=(...h)=>i(...h)?o(...h):s(...h):r=o}return a[e]=r,r(...n)}}rs.filter=function(a){return(e,t,i)=>rs(e,t,i,a)};function g0(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const e=Math.random()*16|0;return(a==="x"?e:e&3|8).toString(16)})}function t_(){return typeof _native<"u"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}class Ft{constructor(){this._xhr=t_(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(Ft.CustomRequestHeaders).length>0||Ft.CustomRequestModifiers.length>0}get requestURL(){return this._requestURL}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in Ft.CustomRequestHeaders){const t=Ft.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return Ft.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){Ft.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of Ft.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;i(this._xhr,t)}t=t.replace("file:http:","http:"),t=t.replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}Ft.CustomRequestHeaders={};Ft.CustomRequestModifiers=new Array;Ft.SkipRequestModificationForBabylonCDN=!0;class Cn{}Cn.FilesToLoad={};class i_{static ExponentialBackoff(e=3,t=500){return(i,s,n)=>s.status!==0||n>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,n)*t}}class hn extends Error{}hn._setPrototypeOf=Object.setPrototypeOf||((a,e)=>(a.__proto__=e,a));const Hs={MeshInvalidPositionsError:0,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class cs extends hn{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",hn._setPrototypeOf(this,cs.prototype)}}const sc=a=>{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,s,n,r,o,h,l,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,h=(s&15)<<2|n>>6,l=n&63,isNaN(s)?h=l=64:isNaN(n)&&(l=64),t+=e.charAt(r)+e.charAt(o)+e.charAt(h)+e.charAt(l);return t},nc=a=>atob(a),s_=a=>{const e=nc(a),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let s=0;s(a=a.replace(/#/gm,"%23"),a),ut={DefaultRetryStrategy:i_.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:a=>a,ScriptBaseUrl:"",ScriptPreprocessUrl:a=>a,CleanUrl:n_},v0=(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)}},b0=(a,e,t,i,s="",n)=>{const r=Ee.LastCreatedEngine;if(typeof HTMLImageElement>"u"&&!(r!=null&&r._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let o,h=!1;a instanceof ArrayBuffer||ArrayBuffer.isView(a)?typeof Blob<"u"&&typeof URL<"u"?(o=URL.createObjectURL(new Blob([a],{type:s})),h=!0):o="data:".concat(s,";base64,")+sc(a):a instanceof Blob?(o=URL.createObjectURL(a),h=!0):(o=ut.CleanUrl(a),o=ut.PreprocessUrl(o));const l=x=>{if(t){const y=o||a.toString();t("Error while trying to load image: ".concat(y.indexOf("http")===0||y.length<=128?y:y.slice(0,128)+"..."),x)}};if(r!=null&&r._features.forceBitmapOverHTMLImageElement)return Ts(o,x=>{r.createImageBitmap(new Blob([x],{type:s}),{premultiplyAlpha:"none",...n}).then(y=>{e(y),h&&URL.revokeObjectURL(o)}).catch(y=>{t&&t("Error while trying to load image: "+a,y)})},void 0,i||void 0,!0,(x,y)=>{l(y)}),null;const c=new Image;v0(o,c);const u=[],f=()=>{u.forEach(x=>{x.target.addEventListener(x.name,x.handler)})},d=()=>{u.forEach(x=>{x.target.removeEventListener(x.name,x.handler)}),u.length=0},_=()=>{d(),e(c),h&&c.src&&URL.revokeObjectURL(c.src)},p=x=>{d(),l(x),h&&c.src&&URL.revokeObjectURL(c.src)},g=x=>{if(x.blockedURI!==c.src||x.disposition==="report")return;d();const y=new Error("CSP violation of policy ".concat(x.effectiveDirective," ").concat(x.blockedURI,". Current policy is ").concat(x.originalPolicy));Ee.UseFallbackTexture=!1,l(y),h&&c.src&&URL.revokeObjectURL(c.src),c.src=""};u.push({target:c,name:"load",handler:_}),u.push({target:c,name:"error",handler:p}),u.push({target:document,name:"securitypolicyviolation",handler:g}),f();const m=o.substring(0,5)==="blob:",b=o.substring(0,5)==="data:",I=()=>{m||b||!Ft.IsCustomRequestAvailable?c.src=o:Ts(o,(x,y,R)=>{const E=!s&&R?R:s,C=new Blob([x],{type:E}),S=URL.createObjectURL(C);h=!0,c.src=S},void 0,i||void 0,!0,(x,y)=>{l(y)})},T=()=>{i&&i.loadImage(o,c)};if(!m&&!b&&i&&i.enableTexturesOffline)i.open(T,I);else{if(o.indexOf("file:")!==-1){const x=decodeURIComponent(o.substring(5).toLowerCase());if(Cn.FilesToLoad[x]&&typeof URL<"u"){try{let y;try{y=URL.createObjectURL(Cn.FilesToLoad[x])}catch{y=URL.createObjectURL(Cn.FilesToLoad[x])}c.src=y,h=!0}catch{c.src=""}return c}}I()}return c},Ln=(a,e,t,i,s)=>{const n=new FileReader,r={onCompleteObservable:new Z,abort:()=>n.abort()};return n.onloadend=()=>r.onCompleteObservable.notifyObservers(r),s&&(n.onerror=()=>{s(new m0("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},Ts=(a,e,t,i,s,n,r)=>{if(a.name)return Ln(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=Cn.FilesToLoad[c];if(u)return Ln(u,e,t,s,n?f=>n(void 0,new Er(f.message,f.file)):void 0)}const{match:h,type:l}=r_(o);if(h){const c={onCompleteObservable:new Z,abort:()=>()=>{}};try{const u=s?T0(o):oc(o);e(u,void 0,l)}catch(u){n?n(void 0,u):U.Error(u.message||"Failed to parse the Data URL")}return Bn.SetImmediate(()=>{c.onCompleteObservable.notifyObservers(c)}),c}return x0(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 Er(c.message,c.request))}:void 0,r)},x0=(a,e,t,i,s,n,r)=>{a=ut.CleanUrl(a),a=ut.PreprocessUrl(a);const o=ut.BaseUrl+a;let h=!1;const l={onCompleteObservable:new Z,abort:()=>h=!0},c=()=>{let u=new Ft,f=null,d;const _=()=>{u&&(t&&u.removeEventListener("progress",t),d&&u.removeEventListener("readystatechange",d),u.removeEventListener("loadend",p))};let p=()=>{_(),l.onCompleteObservable.notifyObservers(l),l.onCompleteObservable.clear(),t=void 0,d=null,p=null,n=void 0,r=void 0,e=void 0};l.abort=()=>{h=!0,p&&p(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),f!==null&&(clearTimeout(f),f=null),u=null};const g=b=>{const I=b.message||"Unknown error";n&&u?n(new Cr(I,u)):U.Error(I)},m=b=>{if(u){if(u.open("GET",o),r)try{r(u)}catch(I){g(I);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),p&&u.addEventListener("loadend",p),d=()=>{if(!(h||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(d&&u.removeEventListener("readystatechange",d),u.status>=200&&u.status<300||u.status===0&&(!St()||ac())){try{e&&e(s?u.response:u.responseText,u)}catch(x){g(x)}return}const I=ut.DefaultRetryStrategy;if(I){const x=I(o,u,b);if(x!==-1){_(),u=new Ft,f=setTimeout(()=>m(b+1),x);return}}const T=new Cr("Error status: "+u.status+" "+u.statusText+" - Unable to load "+o,u);n&&n(T)}},u.addEventListener("readystatechange",d),u.send()}};m(0)};if(i&&i.enableSceneOffline){const u=d=>{d&&d.status>400?n&&n(d):c()},f=()=>{i&&i.loadFile(ut.BaseUrl+a,d=>{!h&&e&&e(d),l.onCompleteObservable.notifyObservers(l)},t?d=>{!h&&t&&t(d)}:void 0,u,s)};i.open(f,u)}else c();return l},ac=()=>typeof location<"u"&&location.protocol==="file:",y0=a=>rc.test(a),r_=a=>{const e=rc.exec(a);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function T0(a){return s_(a.split(",")[1])}const oc=a=>nc(a.split(",")[1]),a_=()=>{ae._FileToolsLoadImage=b0,xr.loadFile=Ts,zl.loadFile=Ts};a_();let bn;const o_=(a,e,t,i,s,n,r,o,h,l)=>{bn={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:h,SetCorsBehavior:l},Object.defineProperty(bn,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(c){t.DefaultRetryStrategy=c}}),Object.defineProperty(bn,"BaseUrl",{get:function(){return t.BaseUrl},set:function(c){t.BaseUrl=c}}),Object.defineProperty(bn,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(c){t.PreprocessUrl=c}}),Object.defineProperty(bn,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(c){t.CorsBehavior=c}})};o_(T0,oc,ut,y0,ac,Ts,b0,Ln,x0,v0);class A0{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=hi.Zero(),this._cachedBaseSize=hi.Zero(),this._initialSamplingMode=2,this._texture=A0._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 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 h=0;h(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}class ke{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>ke.HasTags(e),e.addTags=t=>ke.AddTagsTo(e,t),e.removeTags=t=>ke.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>ke.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){ke._AddTagTo(e,s)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(ke.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!ke.HasTags(e))return;const i=t.split(" ");for(const s in i)ke._RemoveTagFrom(e,i[s])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?ke.HasTags(e):ws.Eval(t,i=>ke.HasTags(e)&&e._tags[i])}}const No=function(a,e,t,i={}){const s=a();ke&&ke.HasTags(e)&&ke.AddTagsTo(s,ke.GetTags(e,!0));const n=La(s),r={};for(const o in n){const h=n[o],l=e[o],c=h.type;if(l!=null&&(o!=="uniqueId"||Ae.AllowLoadingUniqueId))switch(c){case 0:case 6:case 11:s[o]=l;break;case 1:i.cloneTexturesOnlyOnce&&r[l.uniqueId]?s[o]=r[l.uniqueId]:(s[o]=t||l.isRenderTarget?l:l.clone(),r[l.uniqueId]=s[o]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[o]=t?l:l.clone();break}}return s};class Ae{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw ye("ImageProcessingConfiguration")};Ae._FresnelParametersParser=a=>{throw ye("FresnelParameters")};Ae._ColorCurvesParser=a=>{throw ye("ColorCurves")};Ae._TextureParser=(a,e,t)=>{throw ye("Texture")};class st extends A0{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){if(this._texture)this._texture._gammaSpace===null&&(this._texture._gammaSpace=this._gammaSpace);else return this._gammaSpace;return this._texture._gammaSpace&&!this._texture._useSRGBBuffer}set gammaSpace(e){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this))}get isRGBD(){return this._texture!=null&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return this._texture?this._texture._linearSpecularLOD:!1}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=g0()),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=st.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new Z,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?st._IsScene(e)?this._scene=e:this._engine=e:this._scene=Ee.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}getTextureMatrix(){return O.IdentityReadOnly}getReflectionTextureMatrix(){return O.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}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 h=o._getUseSRGBBuffer(!!n,t),l=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=Ae.Serialize(this);return Ae.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"}}st.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;D([B()],st.prototype,"uniqueId",void 0);D([B()],st.prototype,"name",void 0);D([B()],st.prototype,"displayName",void 0);D([B()],st.prototype,"metadata",void 0);D([B("hasAlpha")],st.prototype,"_hasAlpha",void 0);D([B("getAlphaFromRGB")],st.prototype,"_getAlphaFromRGB",void 0);D([B()],st.prototype,"level",void 0);D([B("coordinatesIndex")],st.prototype,"_coordinatesIndex",void 0);D([B()],st.prototype,"optimizeUVAllocation",void 0);D([B("coordinatesMode")],st.prototype,"_coordinatesMode",void 0);D([B()],st.prototype,"wrapU",null);D([B()],st.prototype,"wrapV",null);D([B()],st.prototype,"wrapR",void 0);D([B()],st.prototype,"anisotropicFilteringLevel",void 0);D([B()],st.prototype,"isCube",null);D([B()],st.prototype,"is3D",null);D([B()],st.prototype,"is2DArray",null);D([B()],st.prototype,"gammaSpace",null);D([B()],st.prototype,"invertZ",void 0);D([B()],st.prototype,"lodLevelInAlpha",void 0);D([B()],st.prototype,"lodGenerationOffset",null);D([B()],st.prototype,"lodGenerationScale",null);D([B()],st.prototype,"linearSpecularLOD",null);D([_i()],st.prototype,"irradianceTexture",null);D([B()],st.prototype,"isRenderTarget",void 0);we.prototype.createPrefilteredCubeTexture=function(a,e,t,i,s=null,n=null,r,o=null,h=!0){const l=async c=>{if(!c){s&&s(null);return}const u=c.texture;if(h?c.info.sphericalPolynomial&&(u._sphericalPolynomial=c.info.sphericalPolynomial):u._sphericalPolynomial=new On,u._source=9,this.getCaps().textureLOD){s&&s(u);return}const f=3,d=this._gl,_=c.width;if(!_)return;const{DDSTools:p}=await Oe(async()=>{const{DDSTools:m}=await import("./dds-C4nWUSlI.js");return{DDSTools:m}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10])),g=[];for(let m=0;m{a.onCanvasFocusObservable.notifyObservers(a)},a._onCanvasBlur=()=>{a.onCanvasBlurObservable.notifyObservers(a)},a._onCanvasContextMenu=s=>{a.disableContextMenu&&s.preventDefault()},e.addEventListener("focus",a._onCanvasFocus),e.addEventListener("blur",a._onCanvasBlur),e.addEventListener("contextmenu",a._onCanvasContextMenu),a._onBlur=()=>{a.disablePerformanceMonitorInBackground&&a.performanceMonitor.disable(),a._windowIsBackground=!0},a._onFocus=()=>{a.disablePerformanceMonitorInBackground&&a.performanceMonitor.enable(),a._windowIsBackground=!1},a._onCanvasPointerOut=s=>{document.elementFromPoint(s.clientX,s.clientY)!==e&&a.onCanvasPointerOutObservable.notifyObservers(s)};const i=a.getHostWindow();i&&typeof i.addEventListener=="function"&&(i.addEventListener("blur",a._onBlur),i.addEventListener("focus",a._onFocus)),e.addEventListener("pointerout",a._onCanvasPointerOut),t.doNotHandleTouchAction||h_(e),!ae.audioEngine&&t.audioEngine&&ae.AudioEngineFactory&&(ae.audioEngine=ae.AudioEngineFactory(a.getRenderingCanvas(),a.getAudioContext(),a.getAudioDestination())),En()&&(a._onFullscreenChange=()=>{a.isFullscreen=!!document.fullscreenElement,a.isFullscreen&&a._pointerLockRequested&&e&&R0(e)},document.addEventListener("fullscreenchange",a._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",a._onFullscreenChange,!1),a._onPointerLockChange=()=>{a.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",a._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",a._onPointerLockChange,!1)),a.enableOfflineSupport=ae.OfflineProviderFactory!==void 0,a._deterministicLockstep=!!t.deterministicLockstep,a._lockstepMaxSteps=t.lockstepMaxSteps||0,a._timeStep=t.timeStep||1/60}function lc(a,e){Ee.Instances.length===1&&ae.audioEngine&&(ae.audioEngine.dispose(),ae.audioEngine=null);const t=a.getHostWindow();t&&typeof t.removeEventListener=="function"&&(t.removeEventListener("blur",a._onBlur),t.removeEventListener("focus",a._onFocus)),e&&(e.removeEventListener("focus",a._onCanvasFocus),e.removeEventListener("blur",a._onCanvasBlur),e.removeEventListener("pointerout",a._onCanvasPointerOut),e.removeEventListener("contextmenu",a._onCanvasContextMenu)),En()&&(document.removeEventListener("fullscreenchange",a._onFullscreenChange),document.removeEventListener("mozfullscreenchange",a._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",a._onFullscreenChange),document.removeEventListener("msfullscreenchange",a._onFullscreenChange),document.removeEventListener("pointerlockchange",a._onPointerLockChange),document.removeEventListener("mspointerlockchange",a._onPointerLockChange),document.removeEventListener("mozpointerlockchange",a._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",a._onPointerLockChange))}function cc(a){const e=document.createElement("span");e.textContent="Hg",e.style.font=a;const t=document.createElement("div");t.style.display="inline-block",t.style.width="1px",t.style.height="0px",t.style.verticalAlign="bottom";const i=document.createElement("div");i.style.whiteSpace="nowrap",i.appendChild(e),i.appendChild(t),document.body.appendChild(i);let s=0,n=0;try{n=t.getBoundingClientRect().top-e.getBoundingClientRect().top,t.style.verticalAlign="baseline",s=t.getBoundingClientRect().top-e.getBoundingClientRect().top}finally{document.body.removeChild(i)}return{ascent:s,height:n,descent:n-s}}function uc(a,e,t){return new Promise((s,n)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{a.createImageBitmap(r,t).then(o=>{s(o)})})},r.onerror=()=>{n("Error loading image ".concat(r.src))},r.src=e})}function fc(a,e,t,i){const n=a.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}function dc(a){const e=a.requestFullscreen||a.webkitRequestFullscreen;e&&e.call(a)}function _c(){const a=document;document.exitFullscreen?document.exitFullscreen():a.webkitCancelFullScreen&&a.webkitCancelFullScreen()}function R0(a){if(a.requestPointerLock){const e=a.requestPointerLock();e instanceof Promise?e.then(()=>{a.focus()}).catch(()=>{}):a.focus()}}function pc(){document.exitPointerLock&&document.exitPointerLock()}class ui{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){ui.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){ui.Enabled&&(this._startMonitoringTime=bi.Now)}endMonitoring(e=!0){if(!ui.Enabled)return;e&&this.fetchNewFrame();const t=bi.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=bi.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}ui.Enabled=!0;ae.AudioEngineFactory=(a,e,t)=>new l_(a,e,t);class l_{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new Z,this.onAudioLockedObservable=new Z,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!St())return;typeof window.AudioContext<"u"&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch{}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch{}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if(((e=this._audioContext)==null?void 0:e.state)==="running"){this._hideMuteButton(),this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this));return}this._tryToRun?(t=this._audioContext)==null||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContextOnStateChange(){var e;(e=this._audioContext)==null||e.addEventListener("statechange",()=>{var t;this.unlocked&&((t=this._audioContext)==null?void 0:t.state)!=="running"&&this._resumeAudioContext()},{once:!0,passive:!0,signal:AbortSignal.timeout(3e3)})}_resumeAudioContext(){var e;return(e=this._audioContext)!=null&&e.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,this._audioContext.state==="running"&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,U.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then(()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)}).catch(()=>{this._tryToRun=!1,this.unlocked=!1}))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const t=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",()=>{this._triggerRunningState()},!0),this._muteButton.addEventListener("click",()=>{this.unlock()},!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class le extends we{static get NpmPackage(){return ae.NpmPackage}static get Version(){return ae.Version}static get Instances(){return Ee.Instances}static get LastCreatedEngine(){return Ee.LastCreatedEngine}static get LastCreatedScene(){return Ee.LastCreatedScene}static DefaultLoadingScreenFactory(e){return ae.DefaultLoadingScreenFactory(e)}get _supportsHardwareTextureRescaling(){return!!le._RescalePostProcessFactory}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}constructor(e,t,i,s=!1){if(super(e,t,i,s),this.customAnimationFrameRequester=null,this._performanceMonitor=new Yl,this._drawCalls=new ui,!!e&&(this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext)){const n=e;this._sharedInit(n)}}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),hc(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return fc(this,e,t,i)}_createImageBitmapFromSource(e,t){return uc(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&dc(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&_c()}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)}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)}_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}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return cc(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(this._frameHandler!==0){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&this._frameHandler===0&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&R0(this._renderingCanvas)}exitPointerlock(){pc()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,s,n,r=null){n=n||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,s,n,r);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,s,n=null){const r=s.createProgram();if(e.program=r,!r)throw new Error("Unable to create program");if(s.attachShader(r,t),s.attachShader(r,i),this.webGLVersion>1&&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)})})})}_rescaleTexture(e,t,i,s,n){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const r=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&le._RescalePostProcessFactory&&(this._rescalePostProcess=le._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;const o=()=>{this._rescalePostProcess.onApply=function(c){c._bindTexture("textureSampler",e)};let l=i;l||(l=this.scenes[this.scenes.length-1]),l.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()},h=this._rescalePostProcess.getEffect();h?h.executeWhenCompiled(o):this._rescalePostProcess.onEffectCreatedObservable.addOnce(l=>{l.executeWhenCompiled(o)})}}wrapWebGLTexture(e,t=!1,i=3,s=0,n=0){const r=new Xl(e,this._gl),o=new ft(this,0,!0);return o._hardwareTexture=r,o.baseWidth=s,o.baseHeight=n,o.width=s,o.height=n,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const n=this._gl,r=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),h=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(l,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,h,o,r,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){U.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 Pn(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 h=s.clientWaitSync(e,t,0);if(h==s.WAIT_FAILED){r();return}if(h==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 h=this._gl,l=h.createBuffer();h.bindBuffer(h.PIXEL_PACK_BUFFER,l),h.bufferData(h.PIXEL_PACK_BUFFER,o.byteLength,h.STREAM_READ),h.readPixels(e,t,i,s,n,r,0),h.bindBuffer(h.PIXEL_PACK_BUFFER,null);const c=h.fenceSync(h.SYNC_GPU_COMMANDS_COMPLETE,0);return c?(h.flush(),this._clientWaitAsync(c,0,10).then(()=>(h.deleteSync(c),h.bindBuffer(h.PIXEL_PACK_BUFFER,l),h.getBufferSubData(h.PIXEL_PACK_BUFFER,0,o),h.bindBuffer(h.PIXEL_PACK_BUFFER,null),h.deleteBuffer(l),o))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),lc(this,this._renderingCanvas),super.dispose()}}le.ALPHA_DISABLE=0;le.ALPHA_ADD=1;le.ALPHA_COMBINE=2;le.ALPHA_SUBTRACT=3;le.ALPHA_MULTIPLY=4;le.ALPHA_MAXIMIZED=5;le.ALPHA_ONEONE=6;le.ALPHA_PREMULTIPLIED=7;le.ALPHA_PREMULTIPLIED_PORTERDUFF=8;le.ALPHA_INTERPOLATE=9;le.ALPHA_SCREENMODE=10;le.DELAYLOADSTATE_NONE=0;le.DELAYLOADSTATE_LOADED=1;le.DELAYLOADSTATE_LOADING=2;le.DELAYLOADSTATE_NOTLOADED=4;le.NEVER=512;le.ALWAYS=519;le.LESS=513;le.EQUAL=514;le.LEQUAL=515;le.GREATER=516;le.GEQUAL=518;le.NOTEQUAL=517;le.KEEP=7680;le.REPLACE=7681;le.INCR=7682;le.DECR=7683;le.INVERT=5386;le.INCR_WRAP=34055;le.DECR_WRAP=34056;le.TEXTURE_CLAMP_ADDRESSMODE=0;le.TEXTURE_WRAP_ADDRESSMODE=1;le.TEXTURE_MIRROR_ADDRESSMODE=2;le.TEXTUREFORMAT_ALPHA=0;le.TEXTUREFORMAT_LUMINANCE=1;le.TEXTUREFORMAT_LUMINANCE_ALPHA=2;le.TEXTUREFORMAT_RGB=4;le.TEXTUREFORMAT_RGBA=5;le.TEXTUREFORMAT_RED=6;le.TEXTUREFORMAT_R=6;le.TEXTUREFORMAT_R16_UNORM=33322;le.TEXTUREFORMAT_RG16_UNORM=33324;le.TEXTUREFORMAT_RGB16_UNORM=32852;le.TEXTUREFORMAT_RGBA16_UNORM=32859;le.TEXTUREFORMAT_R16_SNORM=36760;le.TEXTUREFORMAT_RG16_SNORM=36761;le.TEXTUREFORMAT_RGB16_SNORM=36762;le.TEXTUREFORMAT_RGBA16_SNORM=36763;le.TEXTUREFORMAT_RG=7;le.TEXTUREFORMAT_RED_INTEGER=8;le.TEXTUREFORMAT_R_INTEGER=8;le.TEXTUREFORMAT_RG_INTEGER=9;le.TEXTUREFORMAT_RGB_INTEGER=10;le.TEXTUREFORMAT_RGBA_INTEGER=11;le.TEXTURETYPE_UNSIGNED_BYTE=0;le.TEXTURETYPE_UNSIGNED_INT=0;le.TEXTURETYPE_FLOAT=1;le.TEXTURETYPE_HALF_FLOAT=2;le.TEXTURETYPE_BYTE=3;le.TEXTURETYPE_SHORT=4;le.TEXTURETYPE_UNSIGNED_SHORT=5;le.TEXTURETYPE_INT=6;le.TEXTURETYPE_UNSIGNED_INTEGER=7;le.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;le.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;le.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;le.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;le.TEXTURETYPE_UNSIGNED_INT_24_8=12;le.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;le.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;le.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;le.TEXTURE_NEAREST_SAMPLINGMODE=1;le.TEXTURE_BILINEAR_SAMPLINGMODE=2;le.TEXTURE_TRILINEAR_SAMPLINGMODE=3;le.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;le.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;le.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;le.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;le.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;le.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;le.TEXTURE_NEAREST_LINEAR=7;le.TEXTURE_NEAREST_NEAREST=1;le.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;le.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;le.TEXTURE_LINEAR_LINEAR=2;le.TEXTURE_LINEAR_NEAREST=12;le.TEXTURE_EXPLICIT_MODE=0;le.TEXTURE_SPHERICAL_MODE=1;le.TEXTURE_PLANAR_MODE=2;le.TEXTURE_CUBIC_MODE=3;le.TEXTURE_PROJECTION_MODE=4;le.TEXTURE_SKYBOX_MODE=5;le.TEXTURE_INVCUBIC_MODE=6;le.TEXTURE_EQUIRECTANGULAR_MODE=7;le.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;le.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;le.SCALEMODE_FLOOR=1;le.SCALEMODE_NEAREST=2;le.SCALEMODE_CEILING=3;class Ve{static ComputeNumMipmapLevels(e,t){return ec(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case"r8unorm":case"r8uint":case"rg8unorm":case"rg8uint":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8uint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb10a2uint":case"rgb10a2unorm":case"rgb9e5ufloat":case"rg11b10ufloat":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc5-rg-unorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc4-r-unorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-rg11unorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":case"stencil8":return 0;case"r8snorm":case"r8sint":case"rg8snorm":case"rg8sint":case"rgba8snorm":case"rgba8sint":case"bc6h-rgb-float":case"bc5-rg-snorm":case"bc4-r-snorm":case"eac-r11snorm":case"eac-rg11snorm":return 3;case"r16uint":case"r16unorm":case"rg16unorm":case"rgba16unorm":case"rg16uint":case"rgba16uint":case"depth16unorm":return 5;case"r16sint":case"r16snorm":case"rg16snorm":case"rgba16snorm":case"rg16sint":case"rgba16sint":return 4;case"r16float":case"rg16float":case"rgba16float":return 2;case"r32uint":case"rg32uint":case"rgba32uint":return 7;case"r32sint":case"rg32sint":case"rgba32sint":return 7;case"r32float":case"rg32float":case"rgba32float":case"depth32float":case"depth32float-stencil8":case"depth24plus":case"depth24plus-stencil8":return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":return{width:1,height:1,length:1};case"r16uint":case"r16sint":case"r16unorm":case"rg16unorm":case"rgba16unorm":case"r16snorm":case"rg16snorm":case"rgba16snorm":case"r16float":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":return{width:1,height:1,length:2};case"r32uint":case"r32sint":case"r32float":case"rg16uint":case"rg16sint":case"rg16float":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb9e5ufloat":case"rgb10a2uint":case"rgb10a2unorm":case"rg11b10ufloat":return{width:1,height:1,length:4};case"rg32uint":case"rg32sint":case"rg32float":case"rgba16uint":case"rgba16sint":case"rgba16float":return{width:1,height:1,length:8};case"rgba32uint":case"rgba32sint":case"rgba32float":return{width:1,height:1,length:16};case"stencil8":throw"No fixed size for Stencil8 format!";case"depth16unorm":return{width:1,height:1,length:2};case"depth24plus":throw"No fixed size for Depth24Plus format!";case"depth24plus-stencil8":throw"No fixed size for Depth24PlusStencil8 format!";case"depth32float":return{width:1,height:1,length:4};case"depth32float-stencil8":return{width:1,height:1,length:5};case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"bc5-rg-unorm":case"bc5-rg-snorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":return{width:4,height:4,length:16};case"bc4-r-unorm":case"bc4-r-snorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":return{width:4,height:4,length:8};case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":return{width:4,height:4,length:8};case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-rg11unorm":case"eac-rg11snorm":return{width:4,height:4,length:16};case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":return{width:4,height:4,length:16};case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":return{width:5,height:4,length:16};case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":return{width:5,height:5,length:16};case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":return{width:6,height:5,length:16};case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":return{width:6,height:6,length:16};case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":return{width:8,height:5,length:16};case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":return{width:8,height:6,length:16};case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":return{width:8,height:8,length:16};case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":return{width:10,height:5,length:16};case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":return{width:10,height:6,length:16};case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":return{width:10,height:8,length:16};case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":return{width:10,height:10,length:16};case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":return{width:12,height:10,length:16};case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return e.close!==void 0}static IsImageBitmapArray(e){return Array.isArray(e)&&e[0].close!==void 0}static IsCompressedFormat(e){switch(e){case"bc7-rgba-unorm-srgb":case"bc7-rgba-unorm":case"bc6h-rgb-float":case"bc6h-rgb-ufloat":case"bc5-rg-snorm":case"bc5-rg-unorm":case"bc4-r-snorm":case"bc4-r-unorm":case"bc3-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc1-rgba-unorm-srgb":case"bc1-rgba-unorm":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return"depth16unorm";case 16:return"depth24plus";case 13:return"depth24plus-stencil8";case 14:return"depth32float";case 18:return"depth32float-stencil8";case 19:return"stencil8";case 36492:return i?"bc7-rgba-unorm-srgb":"bc7-rgba-unorm";case 36495:return"bc6h-rgb-ufloat";case 36494:return"bc6h-rgb-float";case 33779:return i?"bc3-rgba-unorm-srgb":"bc3-rgba-unorm";case 33778:return i?"bc2-rgba-unorm-srgb":"bc2-rgba-unorm";case 33777:case 33776:return i?"bc1-rgba-unorm-srgb":"bc1-rgba-unorm";case 37808:return i?"astc-4x4-unorm-srgb":"astc-4x4-unorm";case 36196:case 37492:return i?"etc2-rgb8unorm-srgb":"etc2-rgb8unorm";case 37496:return i?"etc2-rgba8unorm-srgb":"etc2-rgba8unorm"}switch(e){case 3:switch(t){case 6:return"r8snorm";case 7:return"rg8snorm";case 4:throw"RGB format not supported in WebGPU";case 8:return"r8sint";case 9:return"rg8sint";case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return"rgba8sint";default:return"rgba8snorm"}case 0:switch(t){case 6:return"r8unorm";case 7:return"rg8unorm";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?"rgba8unorm-srgb":"rgba8unorm";case 12:return i?"bgra8unorm-srgb":"bgra8unorm";case 8:return"r8uint";case 9:return"rg8uint";case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return"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"rgba8unorm"}case 4:switch(t){case 8:return"r16sint";case 9:return"rg16sint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba16sint";default:return"rgba16sint"}case 5:switch(t){case 8:return"r16uint";case 9:return"rg16uint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba16uint";default:return"rgba16uint"}case 6:switch(t){case 8:return"r32sint";case 9:return"rg32sint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba32sint";default:return"rgba32sint"}case 7:switch(t){case 8:return"r32uint";case 9:return"rg32uint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba32uint";default:return"rgba32uint"}case 1:switch(t){case 6:return"r32float";case 7:return"rg32float";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return"rgba32float";default:return"rgba32float"}case 2:switch(t){case 6:return"r16float";case 7:return"rg16float";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return"rgba16float";default:return"rgba16float"}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:return"rg11b10ufloat";case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return"rg11b10ufloat"}case 14:switch(t){case 5:return"rgb9e5ufloat";case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV";default:return"rgb9e5ufloat"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:return"rgb10a2unorm";case 11:return"rgb10a2uint";default:return"rgb10a2unorm"}}return i?"rgba8unorm-srgb":"rgba8unorm"}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":case"bc4-r-unorm":case"bc4-r-snorm":case"r16uint":case"r16sint":case"depth16unorm":case"r16float":case"r16unorm":case"r16snorm":case"r32uint":case"r32sint":case"r32float":case"depth32float":case"stencil8":case"depth24plus":case"eac-r11unorm":case"eac-r11snorm":return 1;case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth32float-stencil8":case"bc5-rg-unorm":case"bc5-rg-snorm":case"rg16uint":case"rg16sint":case"rg16float":case"rg16unorm":case"rg16snorm":case"rg32uint":case"rg32sint":case"rg32float":case"depth24plus-stencil8":case"eac-rg11unorm":case"eac-rg11snorm":return 2;case"rgb9e5ufloat":case"rg11b10ufloat":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":return 3;case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgba16unorm":case"rgba16snorm":case"rgb10a2uint":case"rgb10a2unorm":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"rgba16uint":case"rgba16sint":case"rgba16float":case"rgba32uint":case"rgba32sint":case"rgba32float":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return 4}throw"Unknown format ".concat(e,"!")}static HasStencilAspect(e){switch(e){case"stencil8":case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static GetDepthFormatOnly(e){switch(e){case"depth16unorm":return"depth16unorm";case"depth24plus":return"depth24plus";case"depth24plus-stencil8":return"depth24plus";case"depth32float":return"depth32float";case"depth32float-stencil8":return"depth32float"}return e}static GetSample(e){return e>1?4:1}}class gc{constructor(){this._gpuTimeInFrameId=-1,this.counter=new ui}_addDuration(e,t){e0){this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label);return}U.Warn('Missing data for buffer "'.concat(this._label,'" ').concat(this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":"",". Buffer reconstruction failed.")),this._buffer=null}}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._isDisposed=!0,this._data=null,this._buffer=null)}}class A{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,s,n,r,o,h,l,c,u=!1,f=!1,d=1,_=!1){var m,b,I,T,x;this._isDisposed=!1;let p=!1;if(this.engine=e,typeof s=="object"&&s!==null?(p=(m=s.updatable)!=null?m:!1,n=s.postponeInternalCreation,r=s.stride,o=s.instanced,h=s.offset,l=s.size,c=s.type,u=(b=s.normalized)!=null?b:!1,f=(I=s.useBytes)!=null?I:!1,d=(T=s.divisor)!=null?T:1,_=(x=s.takeBufferOwnership)!=null?x:!1,this._label=s.label):p=!!s,t instanceof ln?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new ln(e,t,p,r,n,o,f,d,this._label),this._ownsBuffer=!0),this.uniqueId=A._Counter++,this._kind=i,c===void 0){const y=this.getData();this.type=y?A.GetDataType(y):A.FLOAT}else this.type=c;const g=A.GetTypeByteLength(this.type);f?(this._size=l||(r?r/g:A.DeduceStride(i)),this.byteStride=r||this._buffer.byteStride||this._size*g,this.byteOffset=h||0):(this._size=l||r||A.DeduceStride(i),this.byteStride=r?r*g:this._buffer.byteStride||this._size*g,this.byteOffset=(h||0)*g),this.normalized=u,this._instanced=o!==void 0?o:!1,this._instanceDivisor=o?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){var e;(e=this._buffer)==null||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?A.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/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),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){A.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}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.ColorInstanceKind: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 GetDataType(e){return e instanceof Int8Array?A.BYTE:e instanceof Uint8Array?A.UNSIGNED_BYTE:e instanceof Int16Array?A.SHORT:e instanceof Uint16Array?A.UNSIGNED_SHORT:e instanceof Int32Array?A.INT:e instanceof Uint32Array?A.UNSIGNED_INT:A.FLOAT}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,h){if(e instanceof Array){let l=t/4;const c=i/4;for(let u=0;uu[d]=f),u}if(!(e instanceof Array||e instanceof Float32Array)||s!==0||e.length!==c)if(e instanceof Array){const u=s/4;return e.slice(u,u+c)}else{if(e instanceof ArrayBuffer)return new Float32Array(e,s,c);{const u=e.byteOffset+s;if(u&3&&(U.Warn("Float array must be aligned to 4-bytes border"),h=!0),h){const f=new Uint8Array(c*Float32Array.BYTES_PER_ELEMENT),d=new Uint8Array(e.buffer,u,f.length);return f.set(d),new Float32Array(f.buffer)}else return new Float32Array(e.buffer,u,c)}}return h?e.slice():e}}A._Counter=0;A.BYTE=5120;A.UNSIGNED_BYTE=5121;A.SHORT=5122;A.UNSIGNED_SHORT=5123;A.INT=5124;A.UNSIGNED_INT=5125;A.FLOAT=5126;A.PositionKind="position";A.NormalKind="normal";A.TangentKind="tangent";A.UVKind="uv";A.UV2Kind="uv2";A.UV3Kind="uv3";A.UV4Kind="uv4";A.UV5Kind="uv5";A.UV6Kind="uv6";A.ColorKind="color";A.ColorInstanceKind="instanceColor";A.MatricesIndicesKind="matricesIndices";A.MatricesWeightsKind="matricesWeights";A.MatricesIndicesExtraKind="matricesIndicesExtra";A.MatricesWeightsExtraKind="matricesWeightsExtra";const Rh=(a,e,t)=>!a||a.getClassName&&a.getClassName()==="Mesh"?null:a.getClassName&&(a.getClassName()==="SubMesh"||a.getClassName()==="PhysicsBody")?a.clone(e):a.clone?a.clone():Array.isArray(a)?a.slice():t&&typeof a=="object"?{...a}:null;function c_(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 I0{static DeepCopy(e,t,i,s,n=!1){const r=c_(e);for(const o of r){if(o[0]==="_"&&(!s||s.indexOf(o)===-1)||o.endsWith("Observable")||i&&i.indexOf(o)!==-1)continue;const h=e[o],l=typeof h;if(l!=="function")try{if(l==="object")if(h instanceof Uint8Array)t[o]=Uint8Array.from(h);else if(h instanceof Array){if(t[o]=[],h.length>0)if(typeof h[0]=="object")for(let c=0;ce.indexOf("/")?!1:e.indexOf("://"){Ts(e,n=>{i(n)},void 0,void 0,t,(n,r)=>{s(r)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(J.ScriptBaseUrl&&e.startsWith(J._DefaultCdnUrl)){const i=J.ScriptBaseUrl[J.ScriptBaseUrl.length-1]==="/"?J.ScriptBaseUrl.substring(0,J.ScriptBaseUrl.length-1):J.ScriptBaseUrl;e=e.replace(J._DefaultCdnUrl,i)}return e=J.ScriptPreprocessUrl(e),t&&(e=J.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=J.GetBabylonScriptURL(e),J.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=J.GetBabylonScriptURL(e),J.LoadScriptAsync(e)}static LoadScript(e,t,i,s,n=!1){if(typeof importScripts=="function"){try{importScripts(e),t&&t()}catch(h){i==null||i("Unable to load script '".concat(e,"' in worker"),h)}return}else if(!St()){i==null||i("Cannot load script '".concat(e,"' outside of a window or a worker"));return}const r=document.getElementsByTagName("head")[0],o=document.createElement("script");n?(o.setAttribute("type","module"),o.innerText=e):(o.setAttribute("type","text/javascript"),o.setAttribute("src",e)),s&&(o.id=s),o.onload=()=>{t&&t()},o.onerror=h=>{i&&i("Unable to load script '".concat(e,"'"),h)},r.appendChild(o)}static LoadScriptAsync(e,t){return new Promise((i,s)=>{this.LoadScript(e,()=>{i()},(n,r)=>{s(r||new Error(n))},t)})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,n={onCompleteObservable:new Z,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 Ln(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){I0.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 h=atob(this.toDataURL(r,o).split(",")[1]),l=h.length,c=new Uint8Array(l);for(let u=0;ut(n)):e.toBlob(function(n){t(n)},i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const i=new Date;t="screenshot_"+((i.getFullYear()+"-"+(i.getMonth()+1)).slice(2)+"-"+i.getDate()+"_"+i.getHours()+"-"+("0"+i.getMinutes()).slice(-2))+".png"}J.Download(e,t)}else if(e&&typeof URL<"u"){const i=URL.createObjectURL(e),s=window.open("");if(!s)return;const n=s.document.createElement("img");n.onload=function(){URL.revokeObjectURL(i)},n.src=i,s.document.body.appendChild(n)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,n){if(typeof s=="string"||!t)this.ToBlob(e,function(r){r&&J.DownloadBlob(r,s),t&&t("")},i,n);else if(t){if(J._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:n}).then(o=>{const h=new FileReader;h.readAsDataURL(o),h.onloadend=()=>{const l=h.result;t(l)}});return}const r=e.toDataURL(i,n);t(r)}}static Download(e,t){if(typeof URL>"u")return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",()=>{s.parentElement&&s.parentElement.removeChild(s)}),s.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return typeof e[0]=="boolean"?e[0]:typeof e[1]=="boolean"?e[1]:!1}static CreateScreenshot(e,t,i,s,n="image/png",r=!1,o){throw ye("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",n){throw ye("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,n="image/png",r=1,o=!1,h,l=!1,c=!1,u=!0,f,d){throw ye("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",n=1,r=!1,o,h=!1,l=!1,c=!0,u,f){throw ye("ScreenshotTools")}static RandomId(){return g0()}static IsBase64(e){return y0(e)}static DecodeBase64(e){return T0(e)}static get errorsCount(){return U.errorsCount}static Log(e){U.Log(e)}static Warn(e){U.Warn(e)}static Error(e){U.Error(e)}static get LogCache(){return U.LogCache}static ClearLogCache(){U.ClearLogCache()}static set LogLevels(e){U.LogLevels=e}static set PerformanceLogLevel(e){if((e&J.PerformanceUserMarkLogLevel)===J.PerformanceUserMarkLogLevel){J.StartPerformanceCounter=J._StartUserMark,J.EndPerformanceCounter=J._EndUserMark;return}if((e&J.PerformanceConsoleLogLevel)===J.PerformanceConsoleLogLevel){J.StartPerformanceCounter=J._StartPerformanceConsole,J.EndPerformanceCounter=J._EndPerformanceConsole;return}J.StartPerformanceCounter=J._StartPerformanceCounterDisabled,J.EndPerformanceCounter=J._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!J._Performance){if(!St())return;J._Performance=window.performance}!t||!J._Performance.mark||J._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!J._Performance.mark||(J._Performance.mark(e+"-End"),J._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(J._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(J._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return bi.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 Qs()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}J.UseCustomRequestHeaders=!1;J.CustomRequestHeaders=Ft.CustomRequestHeaders;J.GetDOMTextContent=h0;J._DefaultCdnUrl="https://cdn.babylonjs.com";J.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.")};J.NoneLogLevel=U.NoneLogLevel;J.MessageLogLevel=U.MessageLogLevel;J.WarningLogLevel=U.WarningLogLevel;J.ErrorLogLevel=U.ErrorLogLevel;J.AllLogLevel=U.AllLogLevel;J.IsWindowObjectExist=St;J.PerformanceNoneLogLevel=0;J.PerformanceUserMarkLogLevel=1;J.PerformanceConsoleLogLevel=2;J.StartPerformanceCounter=J._StartPerformanceCounterDisabled;J.EndPerformanceCounter=J._EndPerformanceCounterDisabled;class Sr{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 h=0;h=e)break;if(i(l),n&&n()){o.breakLoop();break}}o.executeNext()},r)},s)}}J.Mix=Fa;J.IsExponentOfTwo=wn;Ee.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class fe{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&&(fe._UpdatedUbosInFrame[this._name]||(fe._UpdatedUbosInFrame[this._name]=0),fe._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){U.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let n=0;n=0&&(f.push(o[u]),d.push(_))}this.shaderProcessingContext.attributeNamesFromEffect=f,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){var e;if(this.shaderProcessingContext.leftOverUniforms.length){(e=this.uniformBuffer)==null||e.dispose(),this.uniformBuffer=new fe(this.engine,void 0,void 0,"leftOver-"+this._name);for(const t of this.shaderProcessingContext.leftOverUniforms){const i=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),s=At.UniformSizes[i];this.uniformBuffer.addUniform(t.name,s,t.length),this._leftOverUniformsByName[t.name]=t.type}this.uniformBuffer.create()}}setEngine(e){this.engine=e}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?void 0:e.vertex}_getFragmentShaderCode(){var e;return(e=this.sources)==null?void 0:e.fragment}}const f_=4,d_=65536,Ih={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class ni{static get KnownUBOs(){return ni._SimplifiedKnownBindings?ni._SimplifiedKnownUBOs:ni._KnownUBOs}constructor(e,t=!1){this.vertexBufferKindToNumberOfComponents={},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=[],t||this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=ni.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 s;const i=this._attributeNextLocation;return this._attributeNextLocation+=((s=Ih[e])!=null?s:1)*(t||1),i}getVaryingNextLocation(e,t=0){var s;const i=this._varyingNextLocation;return this._varyingNextLocation+=((s=Ih[e])!=null?s:1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>d_-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===f_)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}}ni._SimplifiedKnownBindings=!0;ni._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}}};ni._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}}};function ar(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 Na(a){let e=0,t="",i=!1;const s=[];for(;e=0&&a.charAt(e)!==t&&a.charAt(e)!==i;)e--;return e}function p_(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ua(a,e,t,i){let s=a.indexOf(e);if(s<0)return a;if(t){for(;s++0&&r>0){const o=e.substring(n+1,r);s=+o,isNaN(s)&&(s=+i[o.trim()]),e=e.substring(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\nuniform ".concat(At.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)}varyingCheck(e,t){const i=/(flat\s)?\s*\bout\b/,s=/(flat\s)?\s*\bin\b/,n=/(flat\s)?\s*\bvarying\b/;return(t&&this._fragmentIsGLES3?s:!t&&this._vertexIsGLES3?i:n).test(e)}varyingProcessor(e,t,i){var l;this._preProcessors=i;const s=/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,n=/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,r=/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,h=(t&&this._fragmentIsGLES3?n:!t&&this._vertexIsGLES3?s:r).exec(e);if(h!==null){const c=(l=h[1])!=null?l:"",u=h[2],f=h[3];let d;t?(d=this._webgpuProcessingContext.availableVaryings[f],this._missingVaryings[d]="",d===void 0&&U.Warn('Invalid fragment shader: The varying named "'.concat(f,'" is not declared in the vertex shader! This declaration will be ignored.'))):(d=this._webgpuProcessingContext.getVaryingNextLocation(u,this._getArraySize(f,u,i)[2]),this._webgpuProcessingContext.availableVaryings[f]=d,this._missingVaryings[d]="layout(location = ".concat(d,") ").concat(c," in ").concat(u," ").concat(f,";")),e=e.replace(h[0],d===void 0?"":"layout(location = ".concat(d,") ").concat(c," ").concat(t?"in":"out"," ").concat(u," ").concat(f,";"))}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],h=r[2],l=this._webgpuProcessingContext.getAttributeNextLocation(o,this._getArraySize(h,o,t)[2]);this._webgpuProcessingContext.availableAttributes[h]=l,this._webgpuProcessingContext.orderedAttributes[l]=h;const c=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[h];if(c!==void 0){const u=c<0?c===-1?"int":"ivec"+-c:c===1?"uint":"uvec"+c,f="_int_".concat(h,"_");e=e.replace(r[0],"layout(location = ".concat(l,") in ").concat(u," ").concat(f,"; ").concat(o," ").concat(h," = ").concat(o,"(").concat(f,");"))}else e=e.replace(r[0],"layout(location = ".concat(l,") in ").concat(o," ").concat(h,";"))}return e}uniformProcessor(e,t,i){var r;this._preProcessors=i;const n=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(n!==null){let o=n[1],h=n[2];if(o.indexOf("sampler")===0||o.indexOf("sampler")===1){let l=0;[h,o,l]=this._getArraySize(h,o,i);let c=this._webgpuProcessingContext.availableTextures[h];if(!c){c={autoBindSampler:!0,isTextureArray:l>0,isStorageTexture:!1,textures:[],sampleType:"float"};for(let E=0;E<(l||1);++E)c.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const u=(r=At._SamplerTypeByWebGLSamplerType[o])!=null?r:"sampler",f=!!At._IsComparisonSamplerByWebGPUSamplerType[u],d=f?"comparison":"filtering",_=h+"Sampler";let p=this._webgpuProcessingContext.availableSamplers[_];p||(p={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:d});const g=o.charAt(0)==="u"?"u":o.charAt(0)==="i"?"i":"";g&&(o=o.substring(1));const m=f?"depth":g==="u"?"uint":g==="i"?"sint":"float";c.sampleType=m;const b=l>0,I=p.binding.groupIndex,T=p.binding.bindingIndex,x=At._SamplerFunctionByWebGLSamplerType[o],y=At._TextureTypeByWebGLSamplerType[o],R=At._GpuTextureViewDimensionByWebGPUTextureType[y];if(!b)l=1,e="layout(set = ".concat(I,", binding = ").concat(T,") uniform ").concat(u," ").concat(_,";\n layout(set = ").concat(c.textures[0].groupIndex,", binding = ").concat(c.textures[0].bindingIndex,") uniform ").concat(g).concat(y," ").concat(h,"Texture;\n #define ").concat(h," ").concat(g).concat(x,"(").concat(h,"Texture, ").concat(_,")");else{const E=[];E.push("layout(set = ".concat(I,", binding = ").concat(T,") uniform ").concat(g).concat(u," ").concat(_,";")),e="\n";for(let C=0;C0?"\n":"","#define ").concat(h).concat(C," ").concat(g).concat(x,"(").concat(h,"Texture").concat(C,", ").concat(_,")")}e=E.join("\n")+e,this._textureArrayProcessing.push(h)}this._webgpuProcessingContext.availableTextures[h]=c,this._webgpuProcessingContext.availableSamplers[_]=p,this._addSamplerBindingDescription(_,p,!t);for(let E=0;E=0,l="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",c=h?"vec4 glFragCoord_;\n":"",u=e.search(/layout *\(location *= *0\) *out/g)!==-1;if(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/gl_FragCoord/g,"glFragCoord_"),!this._fragmentIsGLES3)e=e.replace(/void\s+?main\s*\(/g,(r||u?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");else{const f=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);f!==null&&(e=e.substring(0,f.index)+"layout(location = 0) "+e.substring(f.index))}e=e.replace(/dFdy/g,"(-yFactor_)*dFdy"),e=e.replace("##INJECTCODE##",c),h&&(e=Ua(e,"void main",l))}else if(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex"),e=e.replace(/gl_VertexID/g,"gl_VertexIndex"),t.indexOf("#define MULTIVIEW")!==-1)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const h=e.lastIndexOf("}");e=e.substring(0,h),e+="gl_Position.y *= yFactor_;\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,this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}const m_="bakedVertexAnimationDeclaration",v_="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n";Me.IncludesShadersStoreWGSL[m_]=v_;const b_="bakedVertexAnimation",x_="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\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#endif\n";Me.IncludesShadersStoreWGSL[b_]=x_;const y_="instancesDeclaration",T_="#ifdef INSTANCES\nattribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute 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) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nattribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute 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) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";Me.IncludesShadersStoreWGSL[y_]=T_;const A_="instancesVertex",R_="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nvar finalPreviousWorld=mat4x4(\nvertexInputs.previousWorld0,vertexInputs.previousWorld1,\nvertexInputs.previousWorld2,vertexInputs.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) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nfinalPreviousWorld=uniforms.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) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nvar finalPreviousWorld=uniforms.previousWorld;\n#endif\n#endif\n";Me.IncludesShadersStoreWGSL[A_]=R_;const I_="helperFunctions",E_="const PI: f32=3.1415926535897932384626433832795;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const HALF_MIN: f32=5.96046448e-08; \nconst LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3=vec3 (0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;fn square(x: f32)->f32 {return x*x;}\nfn saturate(x: f32)->f32 {return clamp(x,0.0,1.0);}\nfn saturateVec3(x: vec3f)->vec3f {return clamp(x,vec3f(0.0),vec3f(1.0));}\nfn saturateEps(x: f32)->f32 {return clamp(x,Epsilon,1.0);} \nfn maxEps(x: f32)->f32 {return max(x,Epsilon);}\nfn maxEpsVec3(x: vec3f)->vec3f {return max(x,vec3f(Epsilon));}\nfn absEps(x: f32)->f32 {return abs(x)+Epsilon;}\nfn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3=inMatrix[0];let i1: vec3=inMatrix[1];let i2: vec3=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nfn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det,\nb11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,\nb21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}\n#if USE_EXACT_SRGB_CONVERSIONS\nfn toLinearSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=0.0773993808*color;let remainingSection: vec3=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));}\nfn toGammaSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=12.92*color;let remainingSection: vec3=1.055*pow(color,vec3(0.41666))-vec3(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));}\n#endif\nfn toLinearSpace(color: f32)->f32\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nvar nearZeroSection=0.0773993808*color;var remainingSection=pow(0.947867299*(color+0.055),2.4);return select(remainingSection,nearZeroSection,color<=0.04045);\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nfn toLinearSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nfn toLinearSpaceVec4(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4f(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4f(pow(color.rgb,vec3f(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpace(color: vec4)->vec4\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}\nfn toGammaSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nfn squareVec3(value: vec3)->vec3\n{return value*value;}\nfn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}\nfn getLuminance(color: vec3)->f32\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfn dither(seed: vec2,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;}\nconst rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3)->vec4 {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3 =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4(clamp(rgb,vec3(0.,0.,0.),vec3(1.,1.,1.)),D); }\nfn fromRGBD(rgbd: vec4)->vec3 {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}\nfn parallaxCorrectNormal(vertexPos: vec3,origVec: vec3,cubeSize: vec3,cubePos: vec3)->vec3 {let invOrigVec: vec3=vec3(1.0,1.0,1.0)/origVec;let halfSize: vec3=cubeSize*0.5;let intersecAtMaxPlane: vec3=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";Me.IncludesShadersStoreWGSL[I_]=E_;const C_="fresnelFunction",S_="#ifdef FRESNEL\nfn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32\n{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n";Me.IncludesShadersStoreWGSL[C_]=S_;const M_="meshUboDeclaration",P_="struct Mesh {world : mat4x4,\nvisibility : f32,};var mesh : Mesh;\n#define WORLD_UBO\n";Me.IncludesShadersStoreWGSL[M_]=P_;const w_="sceneUboDeclaration",D_="struct Scene {viewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,};var scene : Scene;\n";Me.IncludesShadersStoreWGSL[w_]=D_;const F_="decalFragment",O_="#ifdef DECAL\nvar decalTempColor=decalColor.rgb;var decalTempAlpha=decalColor.a;\n#ifdef GAMMADECAL\ndecalTempColor=toLinearSpaceVec3(decalColor.rgb);\n#endif\n#ifdef DECAL_SMOOTHALPHA\ndecalTempAlpha=decalColor.a*decalColor.a;\n#endif\nsurfaceAlbedo=mix(surfaceAlbedo.rgb,decalTempColor,decalTempAlpha);\n#endif\n";Me.IncludesShadersStoreWGSL[F_]=O_;const Ch="fragmentOutputs.fragDepth",B_="uniforms",L_="internals",N_={texture_1d:"1d",texture_2d:"2d",texture_2d_array:"2d-array",texture_3d:"3d",texture_cube:"cube",texture_cube_array:"cube-array",texture_multisampled_2d:"2d",texture_depth_2d:"2d",texture_depth_2d_array:"2d-array",texture_depth_cube:"cube",texture_depth_cube_array:"cube-array",texture_depth_multisampled_2d:"2d",texture_storage_1d:"1d",texture_storage_2d:"2d",texture_storage_2d_array:"2d-array",texture_storage_3d:"3d",texture_external:null};class U_ extends At{constructor(){super(...arguments),this.shaderLanguage=1,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,this.pureMode=!1}preProcessor(e,t,i,s,n){for(const r in i){if(r==="__VERSION__")continue;const o=i[r];(!isNaN(parseInt(o))||!isNaN(parseFloat(o)))&&(e="const ".concat(r," = ").concat(o,";\n")+e)}return e}_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._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=this.pureMode?"":"struct ".concat(At.InternalsUBOName," {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar ").concat(L_," : ").concat(At.InternalsUBOName,";\n");return e.indexOf(t)!==-1?e:t+Na(e)}varyingCheck(e){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){var r,o;const n=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(n!==null){const h=(r=n[1])!=null?r:"perspective",l=(o=n[2])!=null?o:"center",c=n[4],u=n[3],f=h==="flat"?"@interpolate(".concat(h,")"):"@interpolate(".concat(h,", ").concat(l,")");let d;t?(d=this._webgpuProcessingContext.availableVaryings[u],d===void 0&&U.Warn('Invalid fragment shader: The varying named "'.concat(u,'" is not declared in the vertex shader! This declaration will be ignored.'))):(d=this._webgpuProcessingContext.getVaryingNextLocation(c,this._getArraySize(u,c,i)[2]),this._webgpuProcessingContext.availableVaryings[u]=d,this._varyingsWGSL.push(" @location(".concat(d,") ").concat(f," ").concat(u," : ").concat(c,",")),this._varyingNamesWGSL.push(u)),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;const h=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[r];if(h!==void 0){const l=h<0?h===-1?"i32":"vec"+-h+"":h===1?"u32":"vec"+h+"",c="_int_".concat(r,"_");this._attributesInputWGSL.push("@location(".concat(o,") ").concat(c," : ").concat(l,",")),this._attributesWGSL.push("".concat(r," : ").concat(n,",")),this._attributesConversionCodeWGSL.push("vertexInputs.".concat(r," = ").concat(n,"(vertexInputs_.").concat(c,");")),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push("@location(".concat(o,") ").concat(r," : ").concat(n,",")),this._attributesWGSL.push("".concat(r," : ").concat(n,",")),this._attributesConversionCodeWGSL.push("vertexInputs.".concat(r," = vertexInputs_.").concat(r,";"));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],h=s[4],l=h.indexOf("storage")>0,c=s[6],u=l?c.substring(0,c.indexOf(",")).trim():null;let f=o?this._getArraySize(n,r,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[n];if(d)f=d.textures.length;else{d={isTextureArray:f>0,isStorageTexture:l,textures:[],sampleType:"float"},f=f||1;for(let m=0;m0,p=N_[h],g=_?"depth":c==="u32"?"uint":c==="i32"?"sint":"float";if(d.sampleType=g,p===void 0)throw"Can't get the texture dimension corresponding to the texture function \"".concat(h,'"!');for(let m=0;m=0&&!this.pureMode?"\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 (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;"),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._attributesInputWGSL.length>0&&(n+=this._attributesInputWGSL.join("\n")),n+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(n+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",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;let o="\n vertexInputs".concat(this._hasNonFloatAttribute?"_":""," = input;\n");this._hasNonFloatAttribute&&(o+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",o+=this._attributesConversionCodeWGSL.join("\n"),o+="\n");const h=this.pureMode?" return vertexOutputs;":" vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;";let l=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")!==-1;e=(l?"diagnostic(off, derivative_uniformity);\n":"")+"diagnostic(off, chromium.unreachable_code);\n"+Ua(e,"fn main",o,h),t=t.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;"),t=t.replace(/#define /g,"//#define "),t=this._processStridedUniformArrays(t),this.pureMode||(t=t.replace(/dpdy/g,"(-internals.yFactor_)*dpdy"));let c="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(c+=this._varyingsWGSL.join("\n")),c+="\n};\nvar fragmentInputs : FragmentInputs;\n";let u="struct FragmentOutputs {\n";const f="fragmentOutputs\\.fragData";let d=t.match(new RegExp(f+"0","g")),_=0;if(d){u+=" @location(".concat(_,") fragData0 : vec4,\n"),_++;for(let T=1;T<8;T++)d=t.match(new RegExp(f+T,"g")),d&&(u+=" @location(".concat(_,") fragData").concat(_," : vec4,\n"),_++);t.indexOf("MRT_AND_COLOR")!==-1&&(u+=" @location(".concat(_,") color : vec4,\n"),_++)}const p=/oitDepthSampler/;d=t.match(p),d&&(u+=" @location(".concat(_++,") depth : vec2,\n"),u+=" @location(".concat(_++,") frontColor : vec4,\n"),u+=" @location(".concat(_++,") backColor : vec4,\n")),_===0&&(u+=" @location(0) color : vec4,\n",_++);let g=!1,m=0;for(;!g&&(m=t.indexOf(Ch,m),!(m<0));){const T=m;for(g=!0;m>1&&t.charAt(m)!=="\n";){if(t.charAt(m)==="/"&&t.charAt(m-1)==="/"){g=!1;break}m--}m=T+Ch.length}g&&(u+=" @builtin(frag_depth) fragDepth: f32,\n"),u+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=c+u+t;const b=" fragmentInputs = input;\n "+i,I=" return fragmentOutputs;";return l=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")!==-1,t=(l?"diagnostic(off, derivative_uniformity);\n":"")+"diagnostic(off, chromium.unreachable_code);\n"+Ua(t,"fn main",b,I),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{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=At.UniformSizes[r];if(n.length>0)if(o<=2){const h="".concat(e,"_").concat(this._stridedUniformArrays.length,"_strided_arr");i+="struct ".concat(h," {\n @size(16)\n el: ").concat(r,",\n }"),this._stridedUniformArrays.push(n.name),s+=" @align(16) ".concat(n.name," : array<").concat(h,", ").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(B_," : ").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.length-7,h=n.lastIndexOf("Sampler")===o?n.substring(0,o):null,l=r==="sampler_comparison"?"comparison":"filtering";if(h){const _=this._webgpuProcessingContext.availableTextures[h];_&&(_.autoBindSampler=!0)}let c=this._webgpuProcessingContext.availableSamplers[n];c||(c={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:l},this._webgpuProcessingContext.availableSamplers[n]=c),this._addSamplerBindingDescription(n,c,t);const u=e.substring(0,s.index),f="@group(".concat(c.binding.groupIndex,") @binding(").concat(c.binding.bindingIndex,") "),d=e.substring(s.index);e=u+f+d,i.lastIndex+=f.length}return e}_processCustomBuffers(e,t){var s;const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const n=i.exec(e);if(n===null)break;const r=n[1],o=n[3];let h=n[4];const l=n[5];let c=this._webgpuProcessingContext.availableBuffers[h];if(!c){const g=r==="uniform"?ni.KnownUBOs[l]:null;let m;g?(h=l,m=g.binding,m.groupIndex===-1&&(m=(s=this._webgpuProcessingContext.availableBuffers[h])==null?void 0:s.binding,m||(m=this._webgpuProcessingContext.getNextFreeUBOBinding()))):m=this._webgpuProcessingContext.getNextFreeUBOBinding(),c={binding:m},this._webgpuProcessingContext.availableBuffers[h]=c}this._addBufferBindingDescription(h,this._webgpuProcessingContext.availableBuffers[h],o==="read_write"?"storage":r==="storage"?"read-only-storage":"uniform",t);const u=c.binding.groupIndex,f=c.binding.bindingIndex,d=e.substring(0,n.index),_="@group(".concat(u,") @binding(").concat(f,") "),p=e.substring(n.index);e=d+_+p,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 pr{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e){var t,i;return(i=(t=this._webgpuMSAATexture)==null?void 0:t[e])!=null?i:null}setMSAATexture(e,t){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),this._webgpuMSAATexture[t]=e}releaseMSAATexture(e){if(this._webgpuMSAATexture)if(e!==void 0)this._engine._textureHelper.releaseTexture(this._webgpuMSAATexture[e]),delete this._webgpuMSAATexture[e];else{for(const t of this._webgpuMSAATexture)this._engine._textureHelper.releaseTexture(t);this._webgpuMSAATexture=null}}constructor(e,t=null){this._engine=e,this._originalFormatIsRGB=!1,this.format="rgba8unorm",this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=t,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,s,n,r,o,h){let l="2d",c=1;s?(l=i?"cube-array":"cube",c=6*(h||1)):n?(l="3d",c=1):i&&(l="2d-array",c=h);const u=Ve.GetDepthFormatOnly(this.format),f=Ve.HasDepthAndStencilAspects(this.format)?"depth-only":"all";this.createView({label:"TextureView".concat(n?"3D":s?"Cube":"2D").concat(i?"_Array"+c:"","_").concat(r,"x").concat(o,"_").concat(t?"wmips":"womips","_").concat(this.format,"_").concat(l),format:u,dimension:l,mipLevelCount:t?ec(Math.max(r,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:c,aspect:f})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const i=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=i}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;(e=this._webgpuTexture)==null||e.destroy(),this.releaseMSAATexture(),(t=this._copyInvertYTempTexture)==null||t.destroy(),this.reset()}}const k_="\n const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n const tex = array, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f));\n\n varying vTex: vec2f;\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.vTex = tex[input.vertexIndex];\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",V_="\n var imgSampler: sampler;\n var img: texture_2d;\n\n varying vTex: vec2f;\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n fragmentOutputs.color = textureSample(img, imgSampler, input.vTex);\n }\n ",mc="\n const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n const tex = array, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f));\n\n var img: texture_2d;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n #ifdef INVERTY\n vertexOutputs.vTextureSize = vec2f(textureDimensions(img, 0));\n #endif\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",G_="\n var img: texture_2d;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n #ifdef INVERTY\n var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(input.vTextureSize.y - input.position.y)), 0);\n #else\n var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n fragmentOutputs.color = vec4f(color.rgb * color.a, color.a);\n #endif\n fragmentOutputs.color = color;\n }\n ",z_=mc,W_="\n var img: texture_2d;\n uniform ofstX: f32;\n uniform ofstY: f32;\n uniform width: f32;\n uniform height: f32;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n if (input.position.x < uniforms.ofstX || input.position.x >= uniforms.ofstX + uniforms.width) {\n discard;\n }\n if (input.position.y < uniforms.ofstY || input.position.y >= uniforms.ofstY + uniforms.height) {\n discard;\n }\n #ifdef INVERTY\n var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(uniforms.ofstY + uniforms.height - (input.position.y - uniforms.ofstY))), 0);\n #else\n var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color = vec4f(color.rgb * color.a, color.a);\n #endif\n fragmentOutputs.color = color;\n }\n ",H_="\n const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",K_="\n uniform color: vec4f;\n\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n fragmentOutputs.color = uniforms.color;\n }\n ",X_="\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 ",Y_="\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 ",q_="\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 gi;(function(a){a[a.MipMap=0]="MipMap",a[a.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",a[a.Clear=2]="Clear",a[a.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(gi||(gi={}));var en;(function(a){a[a.DontInvertY=0]="DontInvertY",a[a.InvertY=1]="InvertY"})(en||(en={}));const Sh=[{vertex:k_,fragment:V_},{vertex:mc,fragment:G_},{vertex:H_,fragment:K_},{vertex:z_,fragment:W_}],Vi={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38,r16unorm:39,rg16unorm:40,rgba16unorm:41,r16snorm:42,rg16snorm:43,rgba16snorm:44};class j_{constructor(e,t,i,s){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._bufferManager=i,s.indexOf("rg11b10ufloat-renderable")!==-1){const n=Object.keys(Vi);Vi.rg11b10ufloat=Vi[n[n.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:"linear"}),this._videoSampler=t.createSampler({minFilter:"linear"}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,We.Uniform|We.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline("rgba8unorm"),this._getVideoPipeline("rgba8unorm")}_getPipeline(e,t=gi.MipMap,i){const s=t===gi.MipMap?1:t===gi.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===gi.Clear?8:t===gi.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="";(t===gi.InvertYPremultiplyAlpha||t===gi.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(r+="#define INVERTY\n"),i.premultiplyAlpha&&(r+="#define PREMULTIPLYALPHA\n"));let o=this._compiledShaders[s];if(!o){let l=Sh[t].vertex,c=Sh[t].fragment;const u={defines:r.split("\n"),indexParameters:null,isFragment:!1,shouldUseHighPrecisionShader:!0,processor:this._engine._getShaderProcessor(1),supportsUniformBuffers:!0,shadersRepository:"",includesShadersStore:{},version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._engine._getShaderProcessingContext(1,!0),isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};f0(u),u.processor.pureMode=!0,Tr(l,u,p=>{l=p},this._engine),u.isFragment=!0,Tr(c,u,p=>{c=p},this._engine);const f=d0(l,c,u);u.processor.pureMode=!1;const d=this._device.createShaderModule({code:f.vertexCode}),_=this._device.createShaderModule({code:f.fragmentCode});o=this._compiledShaders[s]=[d,_]}const h=this._device.createRenderPipeline({layout:"auto",vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});n=this._pipelines[e][s]=[h,h.getBindGroupLayout(0)]}return n}_getVideoPipeline(e,t=en.DontInvertY){const i=t===en.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:X_}),h=this._device.createShaderModule({code:i===0?Y_:q_});n=this._videoCompiledShaders[i]=[o,h]}const r=this._device.createRenderPipeline({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_CopyVideoToTexture_").concat(e,"_").concat(i===0?"DontInvertY":"InvertY"),layout:"auto",vertex:{module:n[0],entryPoint:"main"},fragment:{module:n[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});s=this._videoPipelines[e][i]=[r,r.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,s=!1,n){var _,p;const r=n===void 0,[o,h]=this._getVideoPipeline(i,s?en.InvertY:en.DontInvertY);r&&(n=this._device.createCommandEncoder({})),(_=n.pushDebugGroup)==null||_.call(n,"copy video to texture - invertY=".concat(s));const l=t._hardwareTexture,c={label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_copyVideoToTexture_").concat(i,"_").concat(s?"InvertY":"DontInvertY").concat(t.label?"_"+t.label:""),colorAttachments:[{view:l.underlyingResource.createView({format:i,dimension:"2d",mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:"all"}),loadOp:"load",storeOp:"store"}]},u=n.beginRenderPass(c),f={layout:h,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(f);u.setPipeline(o),u.setBindGroup(0,d),u.draw(4,1,0,0),u.end(),(p=n.popDebugGroup)==null||p.call(n),r&&(this._device.queue.submit([n.finish()]),n=null)}invertYPreMultiplyAlpha(e,t,i,s,n=!1,r=!1,o=0,h=0,l=1,c=0,u=0,f=0,d=0,_,p){var S,w,P,G;const g=f!==0,m=_===void 0,[b,I]=this._getPipeline(s,g?gi.InvertYPremultiplyAlphaWithOfst:gi.InvertYPremultiplyAlpha,{invertY:n,premultiplyAlpha:r});o=Math.max(o,0),m&&(_=this._device.createCommandEncoder({})),(S=_.pushDebugGroup)==null||S.call(_,"internal process texture - invertY=".concat(n," premultiplyAlpha=").concat(r));let T;if(Ve.IsHardwareTexture(e)?(T=e.underlyingResource,n&&!r&&l===1&&o===0||(e=void 0)):(T=e,e=void 0),!T)return;g&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([c,u,f,d]),0,4*4);const x=e,y=(w=x==null?void 0:x._copyInvertYTempTexture)!=null?w:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,_,21,void 0,"TempTextureForCopyWithInvertY"),R=(P=x==null?void 0:x._copyInvertYRenderPassDescr)!=null?P:{label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_invertYPreMultiplyAlpha_").concat(s,"_").concat(n?"InvertY":"DontInvertY","_").concat(r?"PremultiplyAlpha":"DontPremultiplyAlpha"),colorAttachments:[{view:y.createView({format:s,dimension:"2d",baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:"load",storeOp:"store"}]},E=_.beginRenderPass(R);let C=g?x==null?void 0:x._copyInvertYBindGroupWithOfst:x==null?void 0:x._copyInvertYBindGroup;if(!C){const L={layout:I,entries:[{binding:0,resource:T.createView({format:s,dimension:"2d",baseMipLevel:h,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};g&&L.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),C=this._device.createBindGroup(L)}E.setPipeline(b),E.setBindGroup(0,C),E.draw(4,1,0,0),E.end(),_.copyTextureToTexture({texture:y},{texture:T,mipLevel:h,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),x?(x._copyInvertYTempTexture=y,x._copyInvertYRenderPassDescr=R,g?x._copyInvertYBindGroupWithOfst=C:x._copyInvertYBindGroup=C):this._deferredReleaseTextures.push([y,null]),(G=_.popDebugGroup)==null||G.call(_),m&&(this._device.queue.submit([_.finish()]),_=null)}copyWithInvertY(e,t,i,s){var c,u;const n=s===void 0,[r,o]=this._getPipeline(t,gi.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});n&&(s=this._device.createCommandEncoder({})),(c=s.pushDebugGroup)==null||c.call(s,"internal copy texture with invertY");const h=s.beginRenderPass(i),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});h.setPipeline(r),h.setBindGroup(0,l),h.draw(4,1,0,0),h.end(),(u=s.popDebugGroup)==null||u.call(s),n&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,n=!1,r=!1,o="rgba8unorm",h=1,l,c=-1,u=0,f){h=Ve.GetSample(h);const d=e.layers||1,_={width:e.width,height:e.height,depthOrArrayLayers:d},p=Vi[o]?16:0,g=Ve.IsCompressedFormat(o),m=t?Ve.ComputeNumMipmapLevels(e.width,e.height):1,b=c>=0?c:7;u|=t&&!g?1|p:0,!g&&!r&&(u|=p|2);const I=this._device.createTexture({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_Texture").concat(r?"3D":"2D","_").concat(f?f+"_":"").concat(_.width,"x").concat(_.height,"x").concat(_.depthOrArrayLayers,"_").concat(t?"wmips":"womips","_").concat(o,"_samples").concat(h),size:_,dimension:r?"3d":"2d",format:o,usage:b|u,sampleCount:h,mipLevelCount:m});return Ve.IsImageBitmap(e)&&(this.updateTexture(e,I,e.width,e.height,d,o,0,0,s,n,0,0),t&&i&&this.generateMipmaps(I,o,m,0,r,l)),I}createCubeTexture(e,t=!1,i=!1,s=!1,n=!1,r="rgba8unorm",o=1,h,l=-1,c=0,u){o=Ve.GetSample(o);const f=Ve.IsImageBitmapArray(e)?e[0].width:e.width,d=Ve.IsImageBitmapArray(e)?e[0].height:e.height,_=Vi[r]?16:0,p=Ve.IsCompressedFormat(r),g=t?Ve.ComputeNumMipmapLevels(f,d):1,m=l>=0?l:7;c|=t&&!p?1|_:0,p||(c|=_|2);const b=this._device.createTexture({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_TextureCube_").concat(u?u+"_":"").concat(f,"x").concat(d,"x6_").concat(t?"wmips":"womips","_").concat(r,"_samples").concat(o),size:{width:f,height:d,depthOrArrayLayers:6},dimension:"2d",format:r,usage:m|c,sampleCount:o,mipLevelCount:g});return Ve.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,b,f,d,r,s,n,0,0),t&&i&&this.generateCubeMipmaps(b,r,g,h)),b}generateCubeMipmaps(e,t,i,s){var r,o;const n=s===void 0;n&&(s=this._device.createCommandEncoder({})),(r=s.pushDebugGroup)==null||r.call(s,"create cube mipmaps - ".concat(i," levels"));for(let h=0;h<6;++h)this.generateMipmaps(e,t,i,h,!1,s);(o=s.popDebugGroup)==null||o.call(s),n&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,n=!1,r){var f,d,_,p,g,m;const o=r===void 0,[h,l]=this._getPipeline(t);s=Math.max(s,0),o&&(r=this._device.createCommandEncoder({})),(f=r.pushDebugGroup)==null||f.call(r,"create mipmaps for face #".concat(s," - ").concat(i," levels"));let c;if(Ve.IsHardwareTexture(e)?(c=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(c=e,e=void 0),!c)return;const u=e;for(let b=1;b=0;){let u=a[l];u<0?u=0:u>1&&(u=1),c[l]=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 l=document.createElement("canvas");l.width=i,l.height=s;const c=l.getContext("2d");return c?(c.translate(0,s),c.scale(1,-1),c.drawImage(n,0,0),l.toDataURL("image/png")):null}return n.toDataURL("image/png")}function Z_(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=a._readPixelsSync(e,t);return s?vc(s,a.getSize(),i.invertY):null}async function Q_(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=await a.readPixels(e,t);return s?vc(s,a.getSize(),i.invertY):null}class ie extends st{static _CreateVideoTexture(e,t,i,s=!1,n=!1,r=ie.TRILINEAR_SAMPLINGMODE,o={},h,l=5){throw ye("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,s,n=ie.TRILINEAR_SAMPLINGMODE,r=null,o=null,h=null,l=!1,c,u,f,d,_){var R,E,C,S,w,P,G,L,W,K,ce;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._cachedIdentity3x2=!0,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 Z,this._isBlocking=!0,this.name=e||"",this.url=e;let p,g=!1,m=null,b=!0;typeof i=="object"&&i!==null?(p=(R=i.noMipmap)!=null?R:!1,s=(E=i.invertY)!=null?E:!0,n=(C=i.samplingMode)!=null?C:ie.TRILINEAR_SAMPLINGMODE,r=(S=i.onLoad)!=null?S:null,o=(w=i.onError)!=null?w:null,h=(P=i.buffer)!=null?P:null,l=(G=i.deleteBuffer)!=null?G:!1,c=i.format,u=i.mimeType,f=i.loaderOptions,d=i.creationFlags,g=(L=i.useSRGBBuffer)!=null?L:!1,m=(W=i.internalTexture)!=null?W:null,b=(K=i.gammaSpace)!=null?K:b,_=(ce=i.forcedExtension)!=null?ce:_):p=!!i,this._gammaSpace=b,this._noMipmap=p,this._invertY=s===void 0?!0:s,this._initialSamplingMode=n,this._buffer=h,this._deleteBuffer=l,this._mimeType=u,this._loaderOptions=f,this._creationFlags=d,this._useSRGBBuffer=g,this._forcedExtension=_,c&&(this._format=c);const I=this.getScene(),T=this._getEngine();if(!T)return;T.onBeforeTextureInitObservable.notifyObservers(this);const x=()=>{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&&I&&I.resetCachedMaterial()},y=($,z)=>{this._loadingError=!0,this._errorObject={message:$,exception:z},o&&o($,z),ie.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!m){this._delayedOnLoad=x,this._delayedOnError=y;return}if(this._texture=m!=null?m:this._getFromCache(this.url,p,n,this._invertY,g,this.isCube),this._texture)if(this._texture.isReady)Bn.SetImmediate(()=>x());else{const $=this._texture.onLoadedObservable.add(x);this._texture.onErrorObservable.add(z=>{var k;y(z.message,z.exception),(k=this._texture)==null||k.onLoadedObservable.remove($)})}else if(!I||!I.useDelayedTextureLoading){try{this._texture=T.createTexture(this.url,p,this._invertY,I,n,x,y,this._buffer,void 0,this._format,this._forcedExtension,u,f,d,g)}catch($){throw y("error loading",$),$}l&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=x,this._delayedOnError=y}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,n=>n.hasTexture(this))),(!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.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Bn.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}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=O.Zero(),this._rowGenerationMatrix=new O,this._t0=v.Zero(),this._t1=v.Zero(),this._t2=v.Zero()),O.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(O.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,N.Matrix[0]),O.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,N.Matrix[1]),O.ScalingToRef(this._cachedUScale,this._cachedVScale,0,N.Matrix[2]),O.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,N.Matrix[3]),N.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(N.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(N.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(N.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),O.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();if(!t)return this._cachedTextureMatrix;const i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,s=>s.hasTexture(this)),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===ie.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=O.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=O.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 ie.PLANAR_MODE:{O.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 ie.PROJECTION_MODE:{O.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:O.IdentityToRef(this._cachedReflectionTextureMatrix);break}return t&&e.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return Ae.Clone(()=>new ie(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var i,s;const e=this.name;ie.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(ie._SerializeInternalTextureUniqueId);return t?((ie.SerializeBuffers||ie.ForceSerializeBuffers)&&(typeof this._buffer=="string"&&this._buffer.substring(0,5)==="data:"?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+sc(this._buffer):(ie.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Z_(this):Q_(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,ie._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=(i=this._texture)==null?void 0:i.uniqueId),t.internalTextureLabel=(s=this._texture)==null?void 0:s.label,t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const l=Sn.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&l.updateSamplingMode&&l._samplingMode&&l._samplingMode!==e.samplingMode&&l.updateSamplingMode(e.samplingMode),l}if(e.isCube&&!e.isRenderTarget)return ie._CubeTextureParser(e,t,i);const s=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!s)return null;let n;if(s){const h=t.getEngine().getLoadedTexturesCache();for(const l of h)if(l.uniqueId===e.internalTextureUniqueId){n=l;break}}const r=h=>{if(h&&h._texture&&(h._texture._cachedWrapU=null,h._texture._cachedWrapV=null,h._texture._cachedWrapR=null),e.samplingMode){const l=e.samplingMode;h&&h.samplingMode!==l&&h.updateSamplingMode(l)}if(h&&e.animations)for(let l=0;l{var l,c,u;let h=!0;if(e.noMipmap&&(h=!1),e.mirrorPlane){const f=ie._CreateMirror(e.name,e.renderTargetSize,t,h);return f._waitingRenderList=e.renderList,f.mirrorPlane=Xt.FromArray(e.mirrorPlane),r(f),f}else if(e.isRenderTarget){let f=null;if(e.isCube){if(t.reflectionProbes)for(let d=0;d{r(f)},(c=e._creationFlags)!=null?c:0,(u=e._useSRGBBuffer)!=null?u:!1),f.name=e.name;else{let d;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?d=e.name:d=i+e.name,e.url&&(e.url.startsWith("data:")||ie.UseSerializedUrlIfAny)&&(d=e.url);const _={noMipmap:!h,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{r(f)},internalTexture:n};f=new ie(d,t,_)}return f}},e,t)}static CreateFromBase64String(e,t,i,s,n,r=ie.TRILINEAR_SAMPLINGMODE,o=null,h=null,l=5,c,u){return new ie("data:"+t,i,s,n,r,o,h,e,!1,l,void 0,void 0,c,u)}static LoadFromDataString(e,t,i,s=!1,n,r=!0,o=ie.TRILINEAR_SAMPLINGMODE,h=null,l=null,c=5,u,f){return e.substring(0,5)!=="data:"&&(e="data:"+e),new ie(e,i,n,r,o,h,l,t,s,c,void 0,void 0,u,f)}}ie.SerializeBuffers=!0;ie.ForceSerializeBuffers=!1;ie.OnTextureLoadErrorObservable=new Z;ie._SerializeInternalTextureUniqueId=!1;ie._CubeTextureParser=(a,e,t)=>{throw ye("CubeTexture")};ie._CreateMirror=(a,e,t,i)=>{throw ye("MirrorTexture")};ie._CreateRenderTargetTexture=(a,e,t,i,s)=>{throw ye("RenderTargetTexture")};ie.NEAREST_SAMPLINGMODE=1;ie.NEAREST_NEAREST_MIPLINEAR=8;ie.BILINEAR_SAMPLINGMODE=2;ie.LINEAR_LINEAR_MIPNEAREST=11;ie.TRILINEAR_SAMPLINGMODE=3;ie.LINEAR_LINEAR_MIPLINEAR=3;ie.NEAREST_NEAREST_MIPNEAREST=4;ie.NEAREST_LINEAR_MIPNEAREST=5;ie.NEAREST_LINEAR_MIPLINEAR=6;ie.NEAREST_LINEAR=7;ie.NEAREST_NEAREST=1;ie.LINEAR_NEAREST_MIPNEAREST=9;ie.LINEAR_NEAREST_MIPLINEAR=10;ie.LINEAR_LINEAR=2;ie.LINEAR_NEAREST=12;ie.EXPLICIT_MODE=0;ie.SPHERICAL_MODE=1;ie.PLANAR_MODE=2;ie.CUBIC_MODE=3;ie.PROJECTION_MODE=4;ie.SKYBOX_MODE=5;ie.INVCUBIC_MODE=6;ie.EQUIRECTANGULAR_MODE=7;ie.FIXED_EQUIRECTANGULAR_MODE=8;ie.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;ie.CLAMP_ADDRESSMODE=0;ie.WRAP_ADDRESSMODE=1;ie.MIRROR_ADDRESSMODE=2;ie.UseSerializedUrlIfAny=!1;D([B()],ie.prototype,"url",void 0);D([B()],ie.prototype,"uOffset",void 0);D([B()],ie.prototype,"vOffset",void 0);D([B()],ie.prototype,"uScale",void 0);D([B()],ie.prototype,"vScale",void 0);D([B()],ie.prototype,"uAng",void 0);D([B()],ie.prototype,"vAng",void 0);D([B()],ie.prototype,"wAng",void 0);D([B()],ie.prototype,"uRotationCenter",void 0);D([B()],ie.prototype,"vRotationCenter",void 0);D([B()],ie.prototype,"wRotationCenter",void 0);D([B()],ie.prototype,"homogeneousRotationInUVTransform",void 0);D([B()],ie.prototype,"isBlocking",null);vt("BABYLON.Texture",ie);Ae._TextureParser=ie.Parse;class ka{constructor(e){this._vertexBuffers={},this.onBeforeRenderObservable=new Z,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 h;const o=this._scene.getEngine();for(let l=0;ll!=null),s.length===0||!this._scene.postProcessesEnabled))return;const o=this._scene.getEngine();for(let l=0,c=s.length;lthis.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}}Ut._GlobalId=0;class Ms extends Ut{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.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(this._particleSystems.length===0)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i{const r=this._renderList?this._renderList.length:0;(n===0&&r>0||r===0)&&this._scene.meshes.forEach(o=>{o._markSubMeshesAsLightDirty()})},this.particleSystemList=null,this.getCustomRenderList=null,this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.onBeforeRenderObservable=new Z,this.onAfterRenderObservable=new Z,this.onBeforeRenderingManagerRenderObservable=new Z,this.onAfterRenderingManagerRenderObservable=new Z,this.onFastPathRenderObservable=new Z,this._currentRefreshId=-1,this._refreshRate=1,this._currentSceneCamera=null,this.name=e,this._scene=t,this.renderList=[],this._renderPassIds=[],this.options={numPasses:1,doNotChangeAspectRatio:!0,...i},this._createRenderPassId(),this.renderPassId=this._renderPassIds[0],this._renderingManager=new Lt(t),this._renderingManager._useSceneAutoClearSetup=!0}_releaseRenderPassId(){const e=this._scene.getEngine();for(let t=0;t1&&(e.incrementRenderId(),e.resetCachedMaterial())}const r=this.particleSystemList||e.particleSystems;for(const o of r)o.isReady()||(s=!1);return t.currentRenderPassId=i,s}_prepareRenderingManager(e,t,i){const s=this._scene,n=s.activeCamera;this._renderingManager.reset();const r=s.getRenderId();for(let h=0;h{for(const P of this._scene._beforeRenderTargetClearStage)P.action(this,this._currentFaceIndex,this._currentLayer);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(T):this.skipInitialClear||T.clear(this.clearColor||this._scene.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0);for(const P of this._scene._beforeRenderTargetDrawStage)P.action(this,this._currentFaceIndex,this._currentLayer)}),this._objectRenderer.onAfterRenderingManagerRenderObservable.add(()=>{var G,L,W,K;for(const ce of this._scene._afterRenderTargetDrawStage)ce.action(this,this._currentFaceIndex,this._currentLayer);const P=(L=(G=this._texture)==null?void 0:G.generateMipMaps)!=null?L:!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,(W=this._renderTarget)!=null?W:void 0,this._currentFaceIndex,this._postProcesses,this.ignoreCameraViewport):this._currentUseCameraPostProcess&&this._scene.postProcessManager._finalizeFrame(!1,(K=this._renderTarget)!=null?K:void 0,this._currentFaceIndex);for(const ce of this._scene._afterRenderTargetPostProcessStage)ce.action(this,this._currentFaceIndex,this._currentLayer);this._texture&&(this._texture.generateMipMaps=P),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0),this._currentDumpForDebug&&(this._dumpTools?this._dumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),T):U.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project"))}),this._objectRenderer.onFastPathRenderObservable.add(()=>{this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(T):this.skipInitialClear||T.clear(this.clearColor||this._scene.clearColor,!0,!0,!0)}),this._resizeObserver=T.onResizeObservable.add(()=>{}),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=n,!u&&(this._renderTargetOptions={generateMipMaps:s,type:r,format:(w=this._format)!=null?w:void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:c,samples:_,creationFlags:p,noColorAttachment:g,useSRGBBuffer:m,colorAttachment:b,label:this.name},this.samplingMode===ie.NEAREST_SAMPLINGMODE&&(this.wrapU=ie.CLAMP_ADDRESSMODE,this.wrapV=ie.CLAMP_ADDRESSMODE),d||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=ie.INVCUBIC_MODE,this._textureMatrix=O.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,_!==void 0&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,n=14,r){var o;(o=this._renderTarget)==null||o.createDepthStencilTexture(e,t,i,s,n,r)}_processSizeParameter(e){if(e.ratio){this._sizeRatio=e.ratio;const t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e}get samples(){var e,t;return(t=(e=this._renderTarget)==null?void 0:e.samples)!=null?t:this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}addPostProcess(e){if(!this._postProcessManager){const t=this.getScene();if(!t)return;this._postProcessManager=new ka(t),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(const t of this._postProcesses)t.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;const t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}resetRefreshCounter(){this._objectRenderer.resetRefreshCounter()}get refreshRate(){return this._objectRenderer.refreshRate}set refreshRate(e){this._objectRenderer.refreshRate=e}_shouldRender(){return this._objectRenderer.shouldRender()}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;if(e)return e;const t=this._size.depth;return t||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 s;const t=this.isCube;(s=this._renderTarget)==null||s.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e),t?this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){this._dumpToolsLoading||(this._dumpToolsLoading=!0,Oe(()=>Promise.resolve().then(()=>qg),void 0).then(t=>this._dumpTools=t)),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight());const e=this._objectRenderer._checkReadiness();return this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),e}_render(e=!1,t=!1){const i=this.getScene();if(i){if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight()),(this.is2DArray||this.is3D)&&!this.isMulti)for(let s=0;s{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){var o,h;const n=this.getScene();if(!n)return;const r=n.getEngine();this._currentFaceIndex=e,this._currentLayer=s,this._currentUseCameraPostProcess=t,this._currentDumpForDebug=i,this._prepareFrame(n,e,s,t),(o=r._debugPushGroup)==null||o.call(r,"render to face #".concat(e," layer #").concat(s),2),this._objectRenderer.render(e+s,!0),(h=r._debugPopGroup)==null||h.call(r,2),this._unbindFrameBuffer(r,e),this._texture&&this.isCube&&e===5&&r.generateMipMapsForCubemap(this._texture,!0)}setRenderingOrder(e,t=null,i=null,s=null){this._objectRenderer.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._objectRenderer.setRenderingAutoClearDepthStencil(e,t)}clone(){const e=this.getSize(),t=new us(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(const s of e.cameras)t=s.customRenderTargets.indexOf(this),t>=0&&s.customRenderTargets.splice(t,1);(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this._objectRenderer._rebuild(),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._objectRenderer.freeRenderingGroups()}getViewCount(){return 1}}us.REFRESHRATE_RENDER_ONCE=Pi.REFRESHRATE_RENDER_ONCE;us.REFRESHRATE_RENDER_ONEVERYFRAME=Pi.REFRESHRATE_RENDER_ONEVERYFRAME;us.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=Pi.REFRESHRATE_RENDER_ONEVERYTWOFRAMES;ie._CreateRenderTargetTexture=(a,e,t,i,s)=>new us(a,e,t,i);class Xn{static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var s;this.effect=e,t!==void 0&&(this.defines=t),i&&((s=this.drawContext)==null||s.reset())}dispose(e=!1){var t;if(this.effect){const i=this.effect;e?i.dispose():Bn.SetImmediate(()=>{i.getEngine().onEndFrameObservable.addOnce(()=>{i.dispose()})}),this.effect=null}(t=this.drawContext)==null||t.dispose()}}const bc="postprocessVertexShader",xc="attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const 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;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";Me.ShadersStore[bc]=xc;const ep={name:bc,shader:xc},yc=Object.freeze(Object.defineProperty({__proto__:null,postprocessVertexShader:ep},Symbol.toStringTag,{value:"Module"})),ba={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class tp{constructor(e,t=ba){var n,r;this._fullscreenViewport=new on(0,0,1,1);const i=(n=t.positions)!=null?n:ba.positions,s=(r=t.indices)!=null?r:ba.indices;this.engine=e,this._vertexBuffers={[A.PositionKind]:new A(e,i,A.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(s);for(const o in this._vertexBuffers)this._vertexBuffers[o]._rebuild()})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e.drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return e.renderTarget!==void 0}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=t===null?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[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 Kt{static RegisterShaderCodeProcessing(e,t){if(!t){delete Kt._CustomShaderCodeProcessing[e!=null?e:""];return}Kt._CustomShaderCodeProcessing[e!=null?e:""]=t}static _GetShaderCodeProcessing(e){var t;return(t=Kt._CustomShaderCodeProcessing[e])!=null?t:Kt._CustomShaderCodeProcessing[""]}get name(){return this.options.name}set name(e){this.options.name=e}isReady(){var e,t;return(t=(e=this._drawWrapper.effect)==null?void 0:e.isReady())!=null?t:!1}get drawWrapper(){return this._drawWrapper}get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){var i;this.alphaMode=0,this.onEffectCreatedObservable=new Z(void 0,!0),this.onApplyObservable=new Z,this._shadersLoaded=!1,this._webGPUReady=!1,this._importPromises=[],this.options={...e,name:e.name||"effectWrapper",engine:e.engine,uniforms:e.uniforms||e.uniformNames||[],uniformNames:void 0,samplers:e.samplers||e.samplerNames||[],samplerNames:void 0,attributeNames:e.attributeNames||["position"],uniformBuffers:e.uniformBuffers||[],defines:e.defines||"",useShaderStore:e.useShaderStore||!1,vertexUrl:e.vertexUrl||e.vertexShader||"postprocess",vertexShader:void 0,fragmentShader:e.fragmentShader||"pass",indexParameters:e.indexParameters,blockCompilation:e.blockCompilation||!1,shaderLanguage:e.shaderLanguage||0,onCompiled:e.onCompiled||void 0,extraInitializations:e.extraInitializations||void 0,extraInitializationsAsync:e.extraInitializationsAsync||void 0,useAsPostProcess:(i=e.useAsPostProcess)!=null?i:!1},this.options.uniformNames=this.options.uniforms,this.options.samplerNames=this.options.samplers,this.options.vertexShader=this.options.vertexUrl,this.options.useAsPostProcess&&(this.options.samplers.indexOf("textureSampler")===-1&&this.options.samplers.push("textureSampler"),this.options.uniforms.indexOf("scale")===-1&&this.options.uniforms.push("scale")),e.vertexUrl||e.vertexShader?this._shaderPath={vertexSource:this.options.vertexShader}:(this.options.useAsPostProcess||(this.options.uniforms.push("scale"),this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)})),this._shaderPath={vertex:this.options.vertexShader}),this._shaderPath.fragmentSource=this.options.fragmentShader,this._shaderPath.spectorName=this.options.name,this.options.useShaderStore&&(this._shaderPath.fragment=this._shaderPath.fragmentSource,this._shaderPath.vertex||(this._shaderPath.vertex=this._shaderPath.vertexSource),delete this._shaderPath.fragmentSource,delete this._shaderPath.vertexSource),this.onApplyObservable.add(()=>{this.bind()}),this.options.useShaderStore||(this._onContextRestoredObserver=this.options.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})),this._drawWrapper=new Xn(this.options.engine),this._webGPUReady=this.options.shaderLanguage===1;const t=Array.isArray(this.options.defines)?this.options.defines.join("\n"):this.options.defines;this._postConstructor(this.options.blockCompilation,t,this.options.extraInitializations)}_gatherImports(e=!1,t){this.options.useAsPostProcess&&(e&&this._webGPUReady?t.push(Promise.all([Oe(()=>import("./postprocess.vertex-DvFhjUjz.js"),__vite__mapDeps([17,3,4,5,6,7,8,9,10]))])):t.push(Promise.all([Oe(()=>Promise.resolve().then(()=>yc),void 0)])))}_postConstructor(e,t=null,i,s){this._importPromises.length=0,s&&this._importPromises.push(...s);const n=this.options.engine.isWebGPU&&!Kt.ForceGLSL;this._gatherImports(n,this._importPromises),i!==void 0&&i(n,this._importPromises),n&&this._webGPUReady&&(this.options.shaderLanguage=1),e||this.updateEffect(t)}updateEffect(e=null,t=null,i=null,s,n,r,o,h){var f,d;const l=Kt._GetShaderCodeProcessing(this.name);if(l!=null&&l.defineCustomBindings){const _=(f=t==null?void 0:t.slice())!=null?f:[];_.push(...this.options.uniforms);const p=(d=i==null?void 0:i.slice())!=null?d:[];p.push(...this.options.samplers),e=l.defineCustomBindings(this.name,e,_,p),t=_,i=p}this.options.defines=e||"";const c=this._shadersLoaded||this._importPromises.length===0?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0};let u;this.options.extraInitializationsAsync?u=async()=>{c==null||c(),await this.options.extraInitializationsAsync}:u=c,this.options.useShaderStore?this._drawWrapper.effect=this.options.engine.createEffect({vertex:o!=null?o:this._shaderPath.vertex,fragment:h!=null?h:this._shaderPath.fragment},{attributes:this.options.attributeNames,uniformsNames:t||this.options.uniforms,uniformBuffersNames:this.options.uniformBuffers,samplers:i||this.options.samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:n!=null?n:this.options.onCompiled,onError:r!=null?r:null,indexParameters:s||this.options.indexParameters,processCodeAfterIncludes:l!=null&&l.processCodeAfterIncludes?(_,p)=>l.processCodeAfterIncludes(this.name,_,p):null,processFinalCode:l!=null&&l.processFinalCode?(_,p)=>l.processFinalCode(this.name,_,p):null,shaderLanguage:this.options.shaderLanguage,extraInitializationsAsync:u},this.options.engine):this._drawWrapper.effect=new Et(this._shaderPath,this.options.attributeNames,t||this.options.uniforms,i||this.options.samplerNames,this.options.engine,e,void 0,n||this.options.onCompiled,void 0,void 0,void 0,this.options.shaderLanguage,u),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}bind(){var e,t;this.options.useAsPostProcess&&(this.options.engine.setAlphaMode(this.alphaMode),this.drawWrapper.effect.setFloat2("scale",1,1)),(t=(e=Kt._GetShaderCodeProcessing(this.name))==null?void 0:e.bindCustomBindings)==null||t.call(e,this.name,this._drawWrapper.effect)}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.onEffectCreatedObservable.clear(),this.effect.dispose()}}Kt.ForceGLSL=!1;Kt._CustomShaderCodeProcessing={};ae.prototype.setTextureFromPostProcess=function(a,e,t){var s;let i=null;e&&(e._forcedOutputTexture?i=e._forcedOutputTexture:e._textures.data[e._currentRenderTextureInd]&&(i=e._textures.data[e._currentRenderTextureInd])),this._bindTexture(a,(s=i==null?void 0:i.texture)!=null?s:null,t)};ae.prototype.setTextureFromPostProcessOutput=function(a,e,t){var i,s;this._bindTexture(a,(s=(i=e==null?void 0:e._outputTexture)==null?void 0:i.texture)!=null?s:null,t)};Et.prototype.setTextureFromPostProcess=function(a,e){this._engine.setTextureFromPostProcess(this._samplers[a],e,a)};Et.prototype.setTextureFromPostProcessOutput=function(a,e){this._engine.setTextureFromPostProcessOutput(this._samplers[a],e,a)};class mt{static get ForceGLSL(){return Kt.ForceGLSL}static set ForceGLSL(e){Kt.ForceGLSL=e}static RegisterShaderCodeProcessing(e,t){Kt.RegisterShaderCodeProcessing(e,t)}get name(){return this._effectWrapper.name}set name(e){this._effectWrapper.name=e}get alphaMode(){return this._effectWrapper.alphaMode}set alphaMode(e){this._effectWrapper.alphaMode=e}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)})}get shaderLanguage(){return this._shaderLanguage}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,h,l,c=null,u=0,f="postprocess",d,_=!1,p=5,g,m){var y,R,E,C,S,w,P,G,L,W,K,ce;this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Ut(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new oe(1,1),this._texelSize=oe.Zero(),this.onActivateObservable=new Z,this.onSizeChangedObservable=new Z,this.onApplyObservable=new Z,this.onBeforeRenderObservable=new Z,this.onAfterRenderObservable=new Z;let b=1,I=null,T;if(i&&!Array.isArray(i)){const $=i;i=(y=$.uniforms)!=null?y:null,s=(R=$.samplers)!=null?R:null,b=(E=$.size)!=null?E:1,r=(C=$.camera)!=null?C:null,o=(S=$.samplingMode)!=null?S:1,h=$.engine,l=$.reusable,c=Array.isArray($.defines)?$.defines.join("\n"):(w=$.defines)!=null?w:null,u=(P=$.textureType)!=null?P:0,f=(G=$.vertexUrl)!=null?G:"postprocess",d=$.indexParameters,_=(L=$.blockCompilation)!=null?L:!1,p=(W=$.textureFormat)!=null?W:5,g=(K=$.shaderLanguage)!=null?K:0,I=(ce=$.uniformBuffers)!=null?ce:null,m=$.extraInitializations,T=$.effectWrapper}else n&&(typeof n=="number"?b=n:b={width:n.width,height:n.height});const x=!!T;if(this._effectWrapper=T!=null?T:new Kt({name:e,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:t,engine:h||(r==null?void 0:r.getScene().getEngine()),uniforms:i,samplers:s,uniformBuffers:I,defines:c,vertexUrl:f,indexParameters:d,blockCompilation:!0,shaderLanguage:g,extraInitializations:void 0}),this.name=e,this.onEffectCreatedObservable=this._effectWrapper.onEffectCreatedObservable,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()):h&&(this._engine=h,this._engine.postProcesses.push(this)),this._options=b,this.renderTargetSamplingMode=o||1,this._reusable=l||!1,this._textureType=u,this._textureFormat=p,this._shaderLanguage=g||0,this._samplers=s||[],this._samplers.indexOf("textureSampler")===-1&&this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=f,this._parameters=i||[],this._parameters.indexOf("scale")===-1&&this._parameters.push("scale"),this._uniformBuffers=I||[],this._indexParameters=d,!x){this._webGPUReady=this._shaderLanguage===1;const $=[];this._gatherImports(this._engine.isWebGPU&&!mt.ForceGLSL,$),this._effectWrapper._webGPUReady=this._webGPUReady,this._effectWrapper._postConstructor(_,c,m,$)}}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([Oe(()=>import("./postprocess.vertex-DvFhjUjz.js"),__vite__mapDeps([17,3,4,5,6,7,8,9,10]))])):t.push(Promise.all([Oe(()=>Promise.resolve().then(()=>yc),void 0)]))}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._effectWrapper.drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new Ut(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,n,r,o,h){this._effectWrapper.updateEffect(e,t,i,s,n,r,o,h),this._postProcessDefines=Array.isArray(this._effectWrapper.options.defines)?this._effectWrapper.options.defines.join("\n"):this._effectWrapper.options.defines}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;if(i){for(let l=0;l{p.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(p,this.samples)}),this._flushTextureCache(),this._renderId++}return f||(f=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,h/c),this._engine.bindFramebuffer(f,0,o,h,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(f,0,void 0,void 0,this.forceFullscreenViewport)),(_=(d=this._engine)._debugInsertMarker)==null||_.call(d,"post process ".concat(this.name," input")),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),f}get isSupported(){return this._effectWrapper.drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._effectWrapper.isReady()}apply(){if(!this._effectWrapper.isReady())return null;this._engine.enableEffect(this._effectWrapper.drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a);let e;return this._shareOutputWithPostProcess?e=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?e=this._forcedOutputTexture:e=this.inputTexture,this.externalTextureSamplerBinding||this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler",e==null?void 0:e.texture),this._effectWrapper.drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect),this._effectWrapper.bind(),this._effectWrapper.drawWrapper.effect}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return this._prePassEffectConfiguration?(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0):!1}dispose(e){e=e||this._camera,this._disposeTextures();let t;if(this._scene&&(t=this._scene.postProcesses.indexOf(this),t!==-1&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const i=this._parentContainer.postProcesses.indexOf(this);i>-1&&this._parentContainer.postProcesses.splice(i,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),t!==-1&&this._engine.postProcesses.splice(t,1),!!e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),t===0&&e._postProcesses.length>0){const i=this._camera._getFirstPostProcess();i&&i.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear(),this.onEffectCreatedObservable.clear()}}serialize(){const e=Ae.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.uniformBuffers=this._uniformBuffers,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=mt.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=ys(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 Ae.Parse(()=>new mt(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)}}D([B()],mt.prototype,"uniqueId",void 0);D([B()],mt.prototype,"name",null);D([B()],mt.prototype,"width",void 0);D([B()],mt.prototype,"height",void 0);D([B()],mt.prototype,"renderTargetSamplingMode",void 0);D([p0()],mt.prototype,"clearColor",void 0);D([B()],mt.prototype,"autoClear",void 0);D([B()],mt.prototype,"forceAutoClearInAlphaMode",void 0);D([B()],mt.prototype,"alphaMode",null);D([B()],mt.prototype,"alphaConstants",void 0);D([B()],mt.prototype,"enablePixelPerfectMode",void 0);D([B()],mt.prototype,"forceFullscreenViewport",void 0);D([B()],mt.prototype,"scaleMode",void 0);D([B()],mt.prototype,"alwaysForcePOT",void 0);D([B("samples")],mt.prototype,"_samples",void 0);D([B()],mt.prototype,"adaptScaleToCurrentViewport",void 0);vt("BABYLON.PostProcess",mt);class Yn extends mt{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,n,r,o=0,h=!1){super(e,"pass",null,null,t,i,s,n,r,void 0,o,void 0,null,h)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Oe(()=>import("./pass.fragment-CM2j9WLA.js"),__vite__mapDeps([18,3,4,5,6,7,8,9,10]))]))):t.push(Promise.all([Oe(()=>import("./pass.fragment-BkcfUm5b.js"),__vite__mapDeps([19,3,4,5,6,7,8,9,10]))])),super._gatherImports(e,t)}static _Parse(e,t,i,s){return Ae.Parse(()=>new Yn(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}vt("BABYLON.PassPostProcess",Yn);ae._RescalePostProcessFactory=a=>new Yn("rescale",1,null,2,a,!1,0);function ip(a,e,t,i,s,n,r,o){const h=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(l=>{const c=new mt("postprocess",a,null,null,1,null,s,h,!1,void 0,i,void 0,null,!1,n);c.externalTextureSamplerBinding=!0;const u=h.createRenderTargetTexture({width:r,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:i,format:n});c.onEffectCreatedObservable.addOnce(f=>{f.executeWhenCompiled(()=>{c.onApply=d=>{d._bindTexture("textureSampler",e),d.setFloat2("scale",1,1)},t.postProcessManager.directRender([c],u,!0),h.restoreDefaultFramebuffer(),h._releaseTexture(e),c&&c.dispose(),u._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,l(e)})})})}let or,Mh;function rx(a){or||(or=new Float32Array(1),Mh=new Int32Array(or.buffer)),or[0]=a;const e=Mh[0];let t=e>>16&32768,i=e>>12&2047;const s=e>>23&255;return s<103?t:s>142?(t|=31744,t|=(s==255?0:1)&&e&8388607,t):s<113?(i|=2048,t|=(i>>114-s)+(i>>113-s&1),t):(t|=s-112<<10|i>>1,t+=i&1,t)}function sp(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 Mr{static _IsGPUBuffer(e){return e.underlyingResource===void 0}static _FlagsToString(e,t=""){let i=t;for(let s=0;s<=9;++s)e&1<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]=sp(s[e]);return i}readDataFromBuffer(e,t,i,s,n,r,o=0,h=0,l=null,c=!0,u=!1){const f=o===1?2:o===2?1:0,d=this._engine.uniqueId;return new Promise((_,p)=>{e.mapAsync(1,h,t).then(()=>{const g=e.getMappedRange(h,t);let m=l;if(u)m===null?m=Pa(o,t,!0,g):m=Pa(o,m.buffer,void 0,g);else if(m===null)switch(f){case 0:m=new Uint8Array(t),m.set(new Uint8Array(g));break;case 1:m=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,g);break;case 2:m=new Float32Array(t/4),m.set(new Float32Array(g));break}else switch(f){case 0:m=new Uint8Array(m.buffer),m.set(new Uint8Array(g));break;case 1:m=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,g,l);break;case 2:m=new Float32Array(m.buffer),m.set(new Float32Array(g));break}if(n!==r){f===1&&!u&&(n*=2,r*=2);const b=new Uint8Array(m.buffer);let I=n,T=0;for(let x=1;x{this._engine.isDisposed||this._engine.uniqueId!==d?_(new Uint8Array):p(g)})})}releaseBuffer(e){return Mr._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&&(r!==0||o!==0)&&n!=="nearest"?{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:n,lodMinClamp:r,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return"repeat";case 0:return"clamp-to-edge";case 2:return"mirror-repeat"}return"repeat"}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel?e._cachedAnisotropicFilteringLevel:1,s=this._GetSamplerFilterDescriptor(e,i);return{label:t,...s,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?Fs.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return"always";case 514:return"equal";case 516:return"greater";case 518:return"greater-equal";case 513:return"less";case 515:return"less-equal";case 512:return"never";case 517:return"not-equal";default:return"less"}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(Fs._GetSamplerDescriptor(e,s));t?i=0:i===0&&(i=Fs.GetSamplerHashCode(e));let n=t?void 0:this._samplers[i];return n||(n=this._device.createSampler(Fs._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=n)),n}}const op={[A.PositionKind]:!0,[A.NormalKind]:!0,[A.TangentKind]:!0,[A.UVKind]:!0,[A.UV2Kind]:!0,[A.UV3Kind]:!0,[A.UV4Kind]:!0,[A.UV5Kind]:!0,[A.UV6Kind]:!0,[A.ColorKind]:!0,[A.ColorInstanceKind]:!0,[A.MatricesIndicesKind]:!0,[A.MatricesWeightsKind]:!0,[A.MatricesIndicesExtraKind]:!0,[A.MatricesWeightsExtraKind]:!0};function hp(a){switch(a){case A.BYTE:case A.SHORT:case A.INT:case A.FLOAT:return!0;case A.UNSIGNED_BYTE:case A.UNSIGNED_SHORT:case A.UNSIGNED_INT:return!1;default:throw new Error("Invalid type '".concat(a,"'"))}}function lp(a,e){const t=e.getEngine(),i=e._pipelineContext;if(!(i!=null&&i.vertexBufferKindToType))return;let s=null;for(const n in a){const r=a[n];if(!r||!op[n])continue;const o=r.normalized?A.FLOAT:r.type,h=i.vertexBufferKindToType[n];(o!==A.FLOAT&&h===void 0||h!==void 0&&h!==o)&&(s||(s=t._getShaderProcessingContext(e.shaderLanguage,!1)),i.vertexBufferKindToType[n]=o,o!==A.FLOAT&&(s.vertexBufferKindToNumberOfComponents[n]=A.DeduceStride(n),hp(o)&&(s.vertexBufferKindToNumberOfComponents[n]*=-1)))}if(s){const n=t._caps.parallelShaderCompile;t._caps.parallelShaderCompile=void 0,e._processShaderCodeAsync(null,t._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,s),t._caps.parallelShaderCompile=n}}var dt;(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"})(dt||(dt={}));const hr={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},Ys={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class rt{constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=["bgra8unorm"],this.setColorFormat("bgra8unorm"),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat("depth24plus-stencil8"),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=Ve.GetSample(i),this.disabled){const r=rt._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,r,i),rt.NumCacheMiss++,rt._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,rt.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return rt.NumCacheHitWithHash++,this._parameter.pipeline;const n=rt._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,n,i),this._setRenderPipeline(this._parameter),rt.NumCacheMiss++,rt._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){rt.NumPipelineCreationLastFrame=rt._NumPipelineCreationCurrentFrame,rt._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,h){this._depthWriteEnabled=o,this._depthTestEnabled=r,this._depthCompare=(h!=null?h: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[dt.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[dt.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=Vi[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 i=[0,0];let s=0,n=0,r=0;for(let l=0;l=32&&(n=0,s++)}this._mrtFormats.length=r,(this._mrtAttachments1!==i[0]||this._mrtAttachments2!==i[1])&&(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[dt.MRTAttachments1]=i[0],this._states[dt.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.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:Vi[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:Ys[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:Ys[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:Ys[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[dt.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[dt.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.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:Ys[i],this._stencilFrontPassOp=s===null?2:Ys[s],this._stencilFrontFailOp=n===null?1:Ys[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"triangle-list";case 2:return"point-list";case 1:return"line-list";case 3:return"point-list";case 4:return"line-list";case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return"line-strip";case 7:return"triangle-strip";case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return"triangle-list"}}static _GetAphaBlendOperation(e){switch(e){case 32774:return"add";case 32778:return"subtract";case 32779:return"reverse-subtract";case 32775:return"min";case 32776:return"max";default:return"add"}}static _GetAphaBlendFactor(e){switch(e){case 0:return"zero";case 1:return"one";case 768:return"src";case 769:return"one-minus-src";case 770:return"src-alpha";case 771:return"one-minus-src-alpha";case 772:return"dst-alpha";case 773:return"one-minus-dst-alpha";case 774:return"dst";case 775:return"one-minus-dst";case 776:return"src-alpha-saturated";case 32769:return"constant";case 32770:return"one-minus-constant";case 32771:return"constant";case 32772:return"one-minus-constant";case 35065:return"src1";case 35066:return"one-minus-src1";case 34185:return"src1-alpha";case 35067:return"one-minus-src1-alpha";default:return"one"}}static _GetCompareFunction(e){switch(e){case 0:return"never";case 1:return"less";case 2:return"equal";case 3:return"less-equal";case 4:return"greater";case 5:return"not-equal";case 6:return"greater-equal";case 7:return"always"}return"never"}static _GetStencilOpFunction(e){switch(e){case 0:return"zero";case 1:return"keep";case 2:return"replace";case 3:return"increment-clamp";case 4:return"decrement-clamp";case 5:return"invert";case 6:return"increment-wrap";case 7:return"decrement-wrap"}return"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?"snorm8x2":"sint8x2";case 3:case 4:return i?"snorm8x4":"sint8x4"}break;case A.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?"unorm8x2":"uint8x2";case 3:case 4:return i?"unorm8x4":"uint8x4"}break;case A.SHORT:switch(s){case 1:case 2:return i?"snorm16x2":"sint16x2";case 3:case 4:return i?"snorm16x4":"sint16x4"}break;case A.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?"unorm16x2":"uint16x2";case 3:case 4:return i?"unorm16x4":"uint16x4"}break;case A.INT:switch(s){case 1:return"sint32";case 2:return"sint32x2";case 3:return"sint32x3";case 4:return"sint32x4"}break;case A.UNSIGNED_INT:switch(s){case 1:return"uint32";case 2:return"uint32x2";case 3:return"uint32x3";case 4:return"uint32x4"}break;case A.FLOAT:switch(s){case 1:return"float32";case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4"}break}throw new Error("Invalid Format '".concat(e.getKind(),"' - type=").concat(t,", normalized=").concat(i,", size=").concat(s))}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:rt._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:rt._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:rt._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:rt._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:rt._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:rt._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[dt.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.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[dt.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.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:hr[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:hr[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:hr[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:hr[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[dt.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.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[dt.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.DepthStencilState))}_setVertexState(e){var l,c;const t=this._statesLength;let i=dt.VertexState;const s=e._pipelineContext,n=s.shaderProcessingContext.attributeNamesFromEffect,r=s.shaderProcessingContext.attributeLocationsFromEffect;let o,h=0;for(let u=0;u0)for(let m=0;m=this._video.HAVE_CURRENT_DATA}dispose(){}}class zr{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=zr._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?Fs.GetSamplerHashCode(t):0;const n=s!==i.hashCode;n&&this.updateId++,this.isDirty||(this.isDirty=n)}setTexture(e,t){var r,o,h;let i=this.textures[e],s=-1;i?s=(o=(r=i.texture)==null?void 0:r.uniqueId)!=null?o:-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=t.type===1||t.format>=13&&t.format<=18,i.isExternalTexture=Tc.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const n=s!==((h=t==null?void 0:t.uniqueId)!=null?h:-1);n&&this.updateId++,this.isDirty||(this.isDirty=n)}}zr._Counter=0;class Wr{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,We.CopyDst|We.Indirect|We.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=Wr._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(t==null?void 0:t.uniqueId)!==((i=this.buffers[e])==null?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t===this._currentInstanceCount||!this.indirectDrawBuffer||!this._indirectDrawData||(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}Wr._Counter=0;const fp=1<<20,dp=2**35;class Tn{constructor(){this.values={}}}class qe{static get Statistics(){return{totalCreated:qe.NumBindGroupsCreatedTotal,lastFrameCreated:qe.NumBindGroupsCreatedLastFrame,lookupLastFrame:qe.NumBindGroupsLookupLastFrame,noLookupLastFrame:qe.NumBindGroupsNoLookupLastFrame}}static ResetCache(){qe._Cache=new Tn,qe.NumBindGroupsCreatedTotal=0,qe.NumBindGroupsCreatedLastFrame=0,qe.NumBindGroupsLookupLastFrame=0,qe.NumBindGroupsNoLookupLastFrame=0,qe._NumBindGroupsCreatedCurrentFrame=0,qe._NumBindGroupsLookupCurrentFrame=0,qe._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){qe.NumBindGroupsCreatedLastFrame=qe._NumBindGroupsCreatedCurrentFrame,qe.NumBindGroupsLookupLastFrame=qe._NumBindGroupsLookupCurrentFrame,qe.NumBindGroupsNoLookupLastFrame=qe._NumBindGroupsNoLookupCurrentFrame,qe._NumBindGroupsCreatedCurrentFrame=0,qe._NumBindGroupsLookupCurrentFrame=0,qe._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var h,l,c,u,f,d,_,p,g,m;let s,n=qe._Cache;const r=this.disabled||i.forceBindGroupCreation;if(!r){if(!t.isDirty(i.updateId)&&!i.isDirty)return qe._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const b of e.shaderProcessingContext.bufferNames){const I=((l=(h=t.buffers[b])==null?void 0:h.uniqueId)!=null?l:0)+fp;let T=n.values[I];T||(T=new Tn,n.values[I]=T),n=T}for(const b of e.shaderProcessingContext.samplerNames){const I=(u=(c=i.samplers[b])==null?void 0:c.hashCode)!=null?u:0;let T=n.values[I];T||(T=new Tn,n.values[I]=T),n=T}for(const b of e.shaderProcessingContext.textureNames){const I=((_=(d=(f=i.textures[b])==null?void 0:f.texture)==null?void 0:d.uniqueId)!=null?_:0)+dp;let T=n.values[I];T||(T=new Tn,n.values[I]=T),n=T}s=n.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,s)return t.bindGroups=s,qe._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,r||(n.bindGroups=s),qe.NumBindGroupsCreatedTotal++,qe._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let b=0;b":G),", materialContext.uniqueId=").concat(i.uniqueId),50);continue}T[y].resource=this._cacheSampler.getSampler(w,!1,S.hashCode,w.label)}else U.Error('Sampler "'.concat(C,'" could not be bound. entry=').concat(JSON.stringify(R),", materialContext=").concat(JSON.stringify(i,(w,P)=>w==="texture"||w==="sampler"?"":P)),50)}else if(R.texture||R.storageTexture){const S=i.textures[C];if(S){if(this._engine.dbgSanityChecks&&S.texture===null){U.Error("Trying to bind a null texture! entry=".concat(JSON.stringify(R),", bindingInfo=").concat(JSON.stringify(S,(P,G)=>P==="texture"?"":G),", materialContext.uniqueId=").concat(i.uniqueId),50);continue}const w=S.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!w||R.texture&&!w.view||R.storageTexture&&!w.viewForWriting)){U.Error("Trying to bind a null gpu texture or view! entry=".concat(JSON.stringify(R),", name=").concat(C,", bindingInfo=").concat(JSON.stringify(S,(P,G)=>P==="texture"?"":G),", isReady=").concat((g=S.texture)==null?void 0:g.isReady,", materialContext.uniqueId=").concat(i.uniqueId),50);continue}T[y].resource=R.storageTexture?w.viewForWriting:w.view}else U.Error('Texture "'.concat(C,'" could not be bound. entry=').concat(JSON.stringify(R),", materialContext=").concat(JSON.stringify(i,(w,P)=>w==="texture"||w==="sampler"?"":P)),50)}else if(R.externalTexture){const S=i.textures[C];if(S){if(this._engine.dbgSanityChecks&&S.texture===null){U.Error("Trying to bind a null external texture! entry=".concat(JSON.stringify(R),", name=").concat(C,", bindingInfo=").concat(JSON.stringify(S,(P,G)=>P==="texture"?"":G),", materialContext.uniqueId=").concat(i.uniqueId),50);continue}const w=S.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!w){U.Error("Trying to bind a null gpu external texture! entry=".concat(JSON.stringify(R),", name=").concat(C,", bindingInfo=").concat(JSON.stringify(S,(P,G)=>P==="texture"?"":G),", isReady=").concat((m=S.texture)==null?void 0:m.isReady,", materialContext.uniqueId=").concat(i.uniqueId),50);continue}T[y].resource=this._device.importExternalTexture({source:w})}else U.Error('Texture "'.concat(C,'" could not be bound. entry=').concat(JSON.stringify(R),", materialContext=").concat(JSON.stringify(i,(w,P)=>w==="texture"||w==="sampler"?"":P)),50)}else if(R.buffer){const S=t.buffers[C];if(S){const w=S.underlyingResource;T[y].resource.buffer=w,T[y].resource.size=S.capacity}else U.Error("Can't find buffer \"".concat(C,'". entry=').concat(JSON.stringify(R),", buffers=").concat(JSON.stringify(t.buffers),", drawContext.uniqueId=").concat(t.uniqueId),50)}}const x=o[b];s[b]=this._device.createBindGroup({layout:x,entries:T})}return s}}qe.NumBindGroupsCreatedTotal=0;qe.NumBindGroupsCreatedLastFrame=0;qe.NumBindGroupsLookupLastFrame=0;qe.NumBindGroupsNoLookupLastFrame=0;qe._Cache=new Tn;qe._NumBindGroupsCreatedCurrentFrame=0;qe._NumBindGroupsLookupCurrentFrame=0;qe._NumBindGroupsNoLookupCurrentFrame=0;const _p="clearQuadVertexShader",pp="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Me.ShadersStoreWGSL[_p]=pp;const gp="clearQuadPixelShader",mp="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";Me.ShadersStoreWGSL[gp]=mp;class vp{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 Ci(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,1)}clear(e,t,i,s,n=1){var g,m;let r,o=null,h;const l=!!this._engine._currentRenderTarget;if(e)r=e;else{let b=0;this._keyTemp.length=0;for(let T=0;T1?2**36:0)+I*2**37,h=this._keyTemp.join("_"),o=this._bundleCache[h],o)return o;r=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Ve.GetSample(n)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&Ve.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 c=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,n),u=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),u.uniformBuffer.update();const f=l?this._engine._ubInvertY:this._engine._ubDontInvertY,d=u.uniformBuffer.getBuffer(),_=d.uniqueId+"-"+f.uniqueId;let p=this._bindGroups[_];if(!p){const b=u.bindGroupLayouts[0];p=this._bindGroups[_]=[],p.push(this._device.createBindGroup({label:"clearQuadBindGroup0-".concat(_),layout:b[0],entries:[]})),ni._SimplifiedKnownBindings||p.push(this._device.createBindGroup({label:"clearQuadBindGroup1-".concat(_),layout:b[1],entries:[]})),p.push(this._device.createBindGroup({label:"clearQuadBindGroup".concat(ni._SimplifiedKnownBindings?1:2,"-").concat(_),layout:b[ni._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:f.underlyingResource,size:f.capacity}},{binding:1,resource:{buffer:d.underlyingResource,size:d.capacity}}]}))}r.setPipeline(c);for(let b=0;b{const n=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,n},n=>{if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw n})}async readValue(e=0){const t=this._getBuffer(e,1);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(1).then(()=>{const s=new BigUint64Array(t.getMappedRange()),n=Number(s[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,n},s=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw s})}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(1).then(()=>{const s=new BigUint64Array(t.getMappedRange()),n=Number(s[1]-s[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,n},s=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw s})}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{t!==null&&t>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(t,!0)),this._measureDurationState=0}))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then(s=>{t._addDuration(i,s!==null&&s>0?s:0)})}dispose(){var e;(e=this._measureDuration)==null||e.dispose()}}class xp{constructor(e,t,i,s=2,n){this._count=s,this._querySet=new Ac(e,s,"timestamp",t,i,!0,n)}start(e){var t;(t=e.writeTimestamp)==null||t.call(e,this._querySet.querySet,0)}async stop(e){var t;return(t=e.writeTimestamp)==null||t.call(e,this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class yp{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet!==void 0;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,s=50,n=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=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]=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.dispose(),this._availableIndices.length=0}}class Hr{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&&U.Log("Start inlining process (code size=".concat(this._sourceCode.length,")...")),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&U.Log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&d.push(m.substring(b+1))}n!=="void"&&d.push("return"),this._functionDescr.push({name:r,type:n,parameters:d,body:u,callIndex:0}),e=c+1;const _=t>0?this._sourceCode.substring(0,t):"",p=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=l[0];return va(e.charAt(c-1))||va(e.charAt(c+r))?t[s]:o})}return e}}Hr._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class ei{async initTwgsl(e){if(!ei._Twgsl)return e=e||{},e={...ei._TWgslDefaultOptions,...e},e.twgsl?(ei._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await J.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(ei._Twgsl=await self.twgsl(J.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=ei._Twgsl.convertSpirV2WGSL(e,ei.DisableUniformityAnalysis||t);return ei.ShowWGSLShaderCode&&(U.Log(i),U.Log("***********************************************")),ei.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}ei._TWgslDefaultOptions={jsPath:"".concat(J._DefaultCdnUrl,"/twgsl/twgsl.js"),wasmPath:"".concat(J._DefaultCdnUrl,"/twgsl/twgsl.wasm")};ei.ShowWGSLShaderCode=!1;ei.DisableUniformityAnalysis=!1;ei._Twgsl=null;class Tp{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error("Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=".concat(this._playBundleListIndex,", allBundleLists.length=").concat(this._allBundleLists.length,"}"));t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),this._mode===1&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this._record&&(this._mode=this._modeSaved),this.enabled=!1,this.enabled=!0}}const xn=(()=>{const a=new Uint8Array(4),e=new Uint32Array(a.buffer);return!!((e[0]=1)&a[0])})();Object.defineProperty(A.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0});Object.defineProperty(A.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0});Object.defineProperty(A.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0});A.prototype._rebuild=function(){var a,e;(a=this._buffer)==null||a._rebuild(),(e=this._alignedBuffer)==null||e._rebuild()};A.prototype.dispose=function(){var a;this._ownsBuffer&&this._buffer.dispose(),(a=this._alignedBuffer)==null||a.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0};A.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer};A.prototype._alignBuffer=function(){var u,f;const a=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4===0&&this.byteOffset%4===0||!a)return;const e=A.GetTypeByteLength(this.type),t=this.byteStride+3&-4,i=t/e,s=this._maxVerticesCount,r=s*t/e;let o;if(Array.isArray(a)){const d=new Float32Array(a);o=new DataView(d.buffer,d.byteOffset,d.byteLength)}else a instanceof ArrayBuffer?o=new DataView(a,0,a.byteLength):o=new DataView(a.buffer,a.byteOffset,a.byteLength);let h;this.type===A.BYTE?h=new Int8Array(r):this.type===A.UNSIGNED_BYTE?h=new Uint8Array(r):this.type===A.SHORT?h=new Int16Array(r):this.type===A.UNSIGNED_SHORT?h=new Uint16Array(r):this.type===A.INT?h=new Int32Array(r):this.type===A.UNSIGNED_INT?h=new Uint32Array(r):h=new Float32Array(r);const l=this.getSize();let c=this.byteOffset;for(let d=0;d{e==null||e.removePendingData(f),l&&p&&l(p.status+" "+p.statusText,g)},_=p=>{const g=f.width,m=r(p);if(m){if(o){const b=i===4,I=o(m),T=f._hardwareTexture,x=[0,1,2,3,4,5];for(let y=0;y>y,E=[];for(let C=0;C<6;C++){let S=I[y][x[C]];b&&(S=qn(S,R,R,s)),E.push(new Uint8Array(S.buffer,S.byteOffset,S.byteLength))}this._textureHelper.updateCubeTextures(E,T.underlyingResource,R,R,T.format,u,!1,0,0)}}else this.updateRawCubeTexture(f,m,i,s,u);f.isReady=!0,e==null||e.removePendingData(f),h&&h()}};return this._loadFile(a,p=>{_(p)},void 0,e==null?void 0:e.offlineProvider,!0,d),f};et.prototype.createRawTexture3D=function(a,e,t,i,s,n,r,o,h=null,l=0,c=0){const f=new ft(this,10);return f.baseWidth=e,f.baseHeight=t,f.baseDepth=i,f.width=e,f.height=t,f.depth=i,f.format=s,f.type=l,f.generateMipMaps=n,f.samplingMode=o,f.is3D=!0,f._creationFlags=c,this._doNotHandleContextLost||(f._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(f,e,t,void 0,c),this.updateRawTexture3D(f,a,s,r,h,l),this._internalTexturesCache.push(f),f};et.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=qn(e,a.width,a.height,n));const h=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(h,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};et.prototype.createRawTexture2DArray=function(a,e,t,i,s,n,r,o,h=null,l=0,c=0){const f=new ft(this,11);return f.baseWidth=e,f.baseHeight=t,f.baseDepth=i,f.width=e,f.height=t,f.depth=i,f.format=s,f.type=l,f.generateMipMaps=n,f.samplingMode=o,f.is2DArray=!0,f._creationFlags=c,this._doNotHandleContextLost||(f._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(f,e,t,i,c),this.updateRawTexture2DArray(f,a,s,r,h,l),this._internalTexturesCache.push(f),f};et.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=qn(e,a.width,a.height,n));const h=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(h,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 qn(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;r{const m=g,b=m[0].width,I=b;this._setCubeMapTextureParams(p,!i),p.format=r!=null?r:-1;const T=this._textureHelper.createGPUTextureForInternalTexture(p,b,I);this._textureHelper.updateCubeTextures(m,T.underlyingResource,b,I,T.format,!1,!1,0,0),i||this._generateMipmaps(p,this._uploadEncoder),p.isReady=!0,p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),s&&s()},!!d,_)};et.prototype._setCubeMapTextureParams=function(a,e,t){a.samplingMode=e?3:2,a._cachedWrapU=0,a._cachedWrapV=0,t&&(a._maxLodLevel=t)};et.prototype.generateMipMapsForCubemap=function(a){var e;a.generateMipMaps&&((e=a._hardwareTexture)!=null&&e.underlyingResource||this._textureHelper.createGPUTextureForInternalTexture(a),this._generateMipmaps(a))};class Rp extends Zl{constructor(e,t,i,s,n){super(e,t,i,s,n),s.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new gc)}}et.prototype._createHardwareRenderTargetWrapper=function(a,e,t){const i=new Rp(a,e,t,this);return this._renderTargetWrapperCache.push(i),i};et.prototype.createRenderTargetTexture=function(a,e){var n,r,o,h,l;const t=this._createHardwareRenderTargetWrapper(!1,!1,a),i={};e!==void 0&&typeof e=="object"?(i.generateMipMaps=e.generateMipMaps,i.generateDepthBuffer=e.generateDepthBuffer===void 0?!0:e.generateDepthBuffer,i.generateStencilBuffer=i.generateDepthBuffer&&e.generateStencilBuffer,i.samplingMode=e.samplingMode===void 0?3:e.samplingMode,i.creationFlags=(n=e.creationFlags)!=null?n:0,i.noColorAttachment=!!e.noColorAttachment,i.colorAttachment=e.colorAttachment,i.samples=e.samples,i.label=e.label,i.format=e.format,i.type=e.type):(i.generateMipMaps=e,i.generateDepthBuffer=!0,i.generateStencilBuffer=!1,i.samplingMode=3,i.creationFlags=0,i.noColorAttachment=!1);const s=i.colorAttachment||(i.noColorAttachment?null:this._createInternalTexture(a,i,!0,5));return t.label=(r=i.label)!=null?r:"RenderTargetWrapper",t._samples=(l=(h=(o=i.colorAttachment)==null?void 0:o.samples)!=null?h:i.samples)!=null?l:1,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=!!i.generateStencilBuffer,t.setTextures(s),(t._generateDepthBuffer||t._generateStencilBuffer)&&t.createDepthStencilTexture(0,!1,t._generateStencilBuffer,t.samples,i.generateStencilBuffer?13:14,i.label?i.label+"-DepthStencil":void 0),s&&!i.colorAttachment&&(e!==void 0&&typeof e=="object"&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s,void 0,void 0,void 0,i.creationFlags),e!==void 0&&typeof e=="object"&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!1)),t};et.prototype._createDepthStencilTexture=function(a,e,t){const i={bilinearFiltering:!1,comparisonFunction:0,samples:1,depthTextureFormat:e.generateStencil?13:14,...e},s=i.depthTextureFormat===17||i.depthTextureFormat===13||i.depthTextureFormat===18;t._depthStencilTextureWithStencil=s;const n=new ft(this,s?12:14);return n.label=e.label,n.format=i.depthTextureFormat,n.type=id(n.format),this._setupDepthStencilTexture(n,a,i.bilinearFiltering,i.comparisonFunction,i.samples),this._textureHelper.createGPUTextureForInternalTexture(n),this._internalTexturesCache.push(n),n};et.prototype._setupDepthStencilTexture=function(a,e,t,i,s=1){var l,c;const n=(l=e.width)!=null?l:e,r=(c=e.height)!=null?c:e,o=e.layers||0,h=e.depth||0;a.baseWidth=n,a.baseHeight=r,a.width=n,a.height=r,a.is2DArray=o>0,a.is3D=h>0,a.depth=o||h,a.isReady=!0,a.samples=s,a.generateMipMaps=!1,a.samplingMode=t?2:1,a.type=1,a._comparisonFunction=i,a._cachedWrapU=0,a._cachedWrapV=0};et.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};et.prototype.setDepthStencilTexture=function(a,e,t,i){!t||!t.depthStencilTexture?this._setTexture(a,null,void 0,void 0,i):this._setTexture(a,t,!1,!0,i)};et.prototype.createRenderTargetCubeTexture=function(a,e){var n;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.label=(n=i.label)!=null?n:"RenderTargetWrapper",t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer;const s=new ft(this,5);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};function Ga(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 Ip(a=25){let e;return(t,i,s)=>{const n=performance.now();e===void 0||n-e>a?(e=n,setTimeout(()=>{Ga(t,i,s)},0)):Ga(t,i,s)}}function Rc(a,e,t,i,s){const n=()=>{let r;const o=h=>{h.done?t(h.value):r===void 0?r=!0:n()};do r=void 0,e(a,o,i),r===void 0&&(r=!1);while(r)};n()}function F0(a,e){let t;return Rc(a,Ga,i=>t=i,i=>{throw i}),t}function Ep(a,e,t){return new Promise((i,s)=>{Rc(a,e,i,s)})}function Cp(a,e){return(...t)=>F0(a(...t))}class za{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class is{constructor(e,t,i){this.vectors=zi(8,v.Zero),this.center=v.Zero(),this.centerWorld=v.Zero(),this.extendSize=v.Zero(),this.extendSizeWorld=v.Zero(),this.directions=zi(3,v.Zero),this.vectorsWorld=zi(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,h=t.y,l=t.z,c=this.vectors;this.minimum.copyFromFloats(s,n,r),this.maximum.copyFromFloats(o,h,l),c[0].copyFromFloats(s,n,r),c[1].copyFromFloats(o,h,l),c[2].copyFromFloats(o,n,r),c[3].copyFromFloats(s,h,r),c[4].copyFromFloats(s,n,l),c[5].copyFromFloats(o,h,r),c[6].copyFromFloats(s,h,l),c[7].copyFromFloats(o,n,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||O.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=is._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]),h=this.center.addToRef(r,t[2]);return this.reConstruct(o,h,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 h=n[o];v.TransformCoordinatesToRef(r[o],e,h),t.minimizeInPlace(h),i.maximizeInPlace(h)}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 is.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return is.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,h=i.y,l=i.z,c=e.x,u=e.y,f=e.z,d=-.001;return!(o-cc-s||h-uu-n||l-ff-r)}intersectsSphere(e){return is.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,h=s.x,l=s.y,c=s.z,u=e.x,f=e.y,d=e.z,_=t.x,p=t.y,g=t.z;return!(h_||lp||cg)}dispose(){var e,t;(e=this._drawWrapperFront)==null||e.dispose(),(t=this._drawWrapperBack)==null||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const n=is._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}}is._TmpVector3=zi(3,v.Zero);class Ls{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||O.IdentityReadOnly)}scale(e){const t=this.radius*e,i=Ls._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=Ls._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},qt=(a,e,t)=>(Ph(a,e,xa),Ph(a,t,ya),!(xa.min>ya.max||ya.min>xa.max));class ri{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new is(e,t,i),this.boundingSphere=new Ls(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=ri._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=ri._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=N.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=N.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,ri._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(!Ls.Intersects(this.boundingSphere,e.boundingSphere)||!is.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!(!qt(i.directions[0],i,s)||!qt(i.directions[1],i,s)||!qt(i.directions[2],i,s)||!qt(s.directions[0],i,s)||!qt(s.directions[1],i,s)||!qt(s.directions[2],i,s)||!qt(v.Cross(i.directions[0],s.directions[0]),i,s)||!qt(v.Cross(i.directions[0],s.directions[1]),i,s)||!qt(v.Cross(i.directions[0],s.directions[2]),i,s)||!qt(v.Cross(i.directions[1],s.directions[0]),i,s)||!qt(v.Cross(i.directions[1],s.directions[1]),i,s)||!qt(v.Cross(i.directions[1],s.directions[2]),i,s)||!qt(v.Cross(i.directions[2],s.directions[0]),i,s)||!qt(v.Cross(i.directions[2],s.directions[1]),i,s)||!qt(v.Cross(i.directions[2],s.directions[2]),i,s))}}ri._TmpVector3=zi(2,v.Zero);class Kr{static extractMinAndMaxIndexed(e,t,i,s,n,r){for(let o=i;o!Array.isArray(a)&&!Array.isArray(e))],Kr,"extractMinAndMaxIndexed",null);D([rs.filter((...[a])=>!Array.isArray(a))],Kr,"extractMinAndMax",null);function Sp(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 Kr.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 Ic(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),Kr.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 vi{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(e=this._getDrawWrapper())==null?void 0:e.defines}set materialDefines(e){var i;const t=(i=this._mainDrawWrapperOverride)!=null?i:this._getDrawWrapper(void 0,!0);t.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 Xn(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0,i=!1){var s;t&&((s=this._drawWrappers[e])==null||s.dispose(i)),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:(t=(e=this._getDrawWrapper())==null?void 0:e.effect)!=null?t:null}get _drawWrapper(){var e;return(e=this._mainDrawWrapperOverride)!=null?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,t=!1){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e,!0,t);return}else for(const i of this._drawWrappers)i==null||i.dispose(t);this._drawWrappers=[]}static AddToMesh(e,t,i,s,n,r,o,h=!0){return new vi(e,t,i,s,n,r,o,h)}constructor(e,t,i,s,n,r,o,h=!0,l=!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,l&&r.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=r.subMeshes.length-1,h&&(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.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){const e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var i;const t=(i=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))!=null?i:this._renderingMesh.material;if(t){if(this._isMultiMaterial(t)){const s=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==s&&(this._currentMaterial=s,this.resetDrawCache()),s}}else return e?this._mesh.getScene().defaultMaterial:null;return t}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(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=Sp(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new ri(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;sh&&(h=f)}return new vi(e,o,h-o+1,t,i,s,n,r)}}class Ta{}class j{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=Cp(this._applyToCoroutine.bind(this)),this.uniqueId=j._UniqueIDGenerator,j._UniqueIDGenerator++}set(e,t){switch(e.length||U.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){if(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),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),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),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const s=e;s.subMeshes=[];for(const n of this.materialInfos)new vi(n.materialIndex,n.verticesStart,n.verticesCount,n.indexStart,n.indexCount,s)}return 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=N.Vector3[0],r=N.Vector3[1];for(let o=i;o({vertexData:o})):[{vertexData:e}];return F0(this._mergeCoroutine(void 0,r,t,!1,i,s,n))}*_mergeCoroutine(e,t,i=!1,s,n,r=!1,o=!1){var d,_,p,g;this._validate();let h=t.map(m=>m.vertexData),l=this;if(o)for(const m of h)m&&(m._validate(),!this.normals&&m.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&m.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&m.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&m.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&m.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&m.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&m.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&m.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&m.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&m.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&m.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&m.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&m.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const m of h)if(m){if(o)this.normals&&!m.normals&&(m.normals=new Float32Array(m.positions.length)),this.tangents&&!m.tangents&&(m.tangents=new Float32Array(m.positions.length/3*4)),this.uvs&&!m.uvs&&(m.uvs=new Float32Array(m.positions.length/3*2)),this.uvs2&&!m.uvs2&&(m.uvs2=new Float32Array(m.positions.length/3*2)),this.uvs3&&!m.uvs3&&(m.uvs3=new Float32Array(m.positions.length/3*2)),this.uvs4&&!m.uvs4&&(m.uvs4=new Float32Array(m.positions.length/3*2)),this.uvs5&&!m.uvs5&&(m.uvs5=new Float32Array(m.positions.length/3*2)),this.uvs6&&!m.uvs6&&(m.uvs6=new Float32Array(m.positions.length/3*2)),this.colors&&!m.colors&&(m.colors=new Float32Array(m.positions.length/3*4),m.colors.fill(1)),this.matricesIndices&&!m.matricesIndices&&(m.matricesIndices=new Float32Array(m.positions.length/3*4)),this.matricesWeights&&!m.matricesWeights&&(m.matricesWeights=new Float32Array(m.positions.length/3*4)),this.matricesIndicesExtra&&!m.matricesIndicesExtra&&(m.matricesIndicesExtra=new Float32Array(m.positions.length/3*4)),this.matricesWeightsExtra&&!m.matricesWeightsExtra&&(m.matricesWeightsExtra=new Float32Array(m.positions.length/3*4));else if(m._validate(),!this.normals!=!m.normals||!this.tangents!=!m.tangents||!this.uvs!=!m.uvs||!this.uvs2!=!m.uvs2||!this.uvs3!=!m.uvs3||!this.uvs4!=!m.uvs4||!this.uvs5!=!m.uvs5||!this.uvs6!=!m.uvs6||!this.colors!=!m.colors||!this.matricesIndices!=!m.matricesIndices||!this.matricesWeights!=!m.matricesWeights||!this.matricesIndicesExtra!=!m.matricesIndicesExtra||!this.matricesWeightsExtra!=!m.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(r){let m=0,b=0,I=0;const T=[];let x=null;const y=[];for(const E of this.splitBasedOnMaterialID())y.push({vertexData:E,transform:e});for(const E of t)if(E.vertexData)for(const C of E.vertexData.splitBasedOnMaterialID())y.push({vertexData:C,transform:E.transform});y.sort((E,C)=>{const S=E.vertexData.materialInfos?E.vertexData.materialInfos[0].materialIndex:0,w=C.vertexData.materialInfos?C.vertexData.materialInfos[0].materialIndex:0;return S>w?1:S===w?0:-1});for(const E of y){const C=E.vertexData;if(C.materialInfos?m=C.materialInfos[0].materialIndex:m=0,x&&x.materialIndex===m)x.indexCount+=C.indices.length,x.verticesCount+=C.positions.length/3;else{const S=new Ta;S.materialIndex=m,S.indexStart=b,S.indexCount=C.indices.length,S.verticesStart=I,S.verticesCount=C.positions.length/3,T.push(S),x=S}b+=C.indices.length,I+=C.positions.length/3}const R=y.splice(0,1)[0];l=R.vertexData,e=R.transform,h=y.map(E=>E.vertexData),t=y,this.materialInfos=T}const c=h.reduce((m,b)=>{var I,T;return m+((T=(I=b.indices)==null?void 0:I.length)!=null?T:0)},(_=(d=l.indices)==null?void 0:d.length)!=null?_:0);let f=n||h.some(m=>m.indices===l.indices)?(p=l.indices)==null?void 0:p.slice():l.indices;if(c>0){let m=(g=f==null?void 0:f.length)!=null?g:0;if(f||(f=new Array(c)),f.length!==c){if(Array.isArray(f))f.length=c;else{const I=i||f instanceof Uint32Array?new Uint32Array(c):new Uint16Array(c);I.set(f),f=I}e&&e.determinant()<0&&j._FlipFaces(f,0,m)}let b=l.positions?l.positions.length/3:0;for(const{vertexData:I,transform:T}of t)if(I.indices){for(let x=0;x[m.vertexData.positions,m.transform])),s&&(yield),l.normals&&(this.normals=j._MergeElement(A.NormalKind,l.normals,e,t.map(m=>[m.vertexData.normals,m.transform])),s&&(yield)),l.tangents&&(this.tangents=j._MergeElement(A.TangentKind,l.tangents,e,t.map(m=>[m.vertexData.tangents,m.transform])),s&&(yield)),l.uvs&&(this.uvs=j._MergeElement(A.UVKind,l.uvs,e,t.map(m=>[m.vertexData.uvs,m.transform])),s&&(yield)),l.uvs2&&(this.uvs2=j._MergeElement(A.UV2Kind,l.uvs2,e,t.map(m=>[m.vertexData.uvs2,m.transform])),s&&(yield)),l.uvs3&&(this.uvs3=j._MergeElement(A.UV3Kind,l.uvs3,e,t.map(m=>[m.vertexData.uvs3,m.transform])),s&&(yield)),l.uvs4&&(this.uvs4=j._MergeElement(A.UV4Kind,l.uvs4,e,t.map(m=>[m.vertexData.uvs4,m.transform])),s&&(yield)),l.uvs5&&(this.uvs5=j._MergeElement(A.UV5Kind,l.uvs5,e,t.map(m=>[m.vertexData.uvs5,m.transform])),s&&(yield)),l.uvs6&&(this.uvs6=j._MergeElement(A.UV6Kind,l.uvs6,e,t.map(m=>[m.vertexData.uvs6,m.transform])),s&&(yield)),l.colors&&(this.colors=j._MergeElement(A.ColorKind,l.colors,e,t.map(m=>[m.vertexData.colors,m.transform])),(l.hasVertexAlpha!==void 0||t.some(m=>m.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some(m=>m.vertexData.hasVertexAlpha)),s&&(yield)),l.matricesIndices&&(this.matricesIndices=j._MergeElement(A.MatricesIndicesKind,l.matricesIndices,e,t.map(m=>[m.vertexData.matricesIndices,m.transform])),s&&(yield)),l.matricesWeights&&(this.matricesWeights=j._MergeElement(A.MatricesWeightsKind,l.matricesWeights,e,t.map(m=>[m.vertexData.matricesWeights,m.transform])),s&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=j._MergeElement(A.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map(m=>[m.vertexData.matricesIndicesExtra,m.transform])),s&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=j._MergeElement(A.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map(m=>[m.vertexData.matricesWeightsExtra,m.transform]))),this}static _MergeElement(e,t,i,s){const n=s.filter(h=>h[0]!==null&&h[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((h,l)=>h+l[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 h=new Float32Array(r);h.set(t),i&&o(h,i,0,t.length);let l=t.length;for(const[c,u]of n)h.set(c,l),u&&o(h,u,l,c.length),l+=c.length;return h}else{const h=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)}clone(){const e=this.serialize();return j.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return 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;if(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)){const n=e.geometry||e,r=n.getVertexBuffer(A.ColorKind),o=n.getVerticesData(A.ColorKind,t,i);if(r.getSize()===3){const h=new Float32Array(o.length*4/3);for(let l=0,c=0;l!Array.isArray(a))],j,"_TransformVector3Coordinates",null);D([rs.filter((...[a])=>!Array.isArray(a))],j,"_TransformVector3Normals",null);D([rs.filter((...[a])=>!Array.isArray(a))],j,"_TransformVector4Normals",null);D([rs.filter((...[a])=>!Array.isArray(a))],j,"_FlipFaces",null);class Mp{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new Z,this._onClonedObservable=new Z}}class bt{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._isDirty=!0,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,i=!0){this._isDirty=!1,this._nodeDataStorage=new Mp,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new Z,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=O.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new Z,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||Ee.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}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={}}updateCache(e){!e&&this.isSynchronized()||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._parentNode&&!this.isSynchronizedWithParent()?!1:this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return e===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,this._children&&this._children.forEach(e=>{e._syncParentEnabledState()})}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return this.parent?this.parent===e?!0:this.parent.isDescendantOf(e):!1}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s(!t||t(s))&&s.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew bt(e,this.getScene()),this);if(t&&(s.parent=t),!i){const n=this.getDescendants(!0);for(let r=0;r{throw ye("AnimationRange")};bt._NodeConstructors={};D([B()],bt.prototype,"name",void 0);D([B()],bt.prototype,"id",void 0);D([B()],bt.prototype,"uniqueId",void 0);D([B()],bt.prototype,"state",void 0);D([B()],bt.prototype,"metadata",void 0);const Pp=O.Compose(v.One(),re.FromEulerAngles(0,Math.PI,0),v.Zero());class Te extends bt{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&Te.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!==Te.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,!1),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=Te.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=O.Zero(),this._usePivotMatrix=!1,this._absolutePosition=v.Zero(),this._absoluteScaling=v.Zero(),this._absoluteRotationQuaternion=re.Identity(),this._pivotMatrix=O.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new Z,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._markAsDirtyInternal()}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._markAsDirtyInternal()}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._markAsDirtyInternal()}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._markAsDirtyInternal()}_markAsDirtyInternal(){this._isDirty||(this._isDirty=!0,this.customMarkAsDirty&&this.customMarkAsDirty())}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=O.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Te.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=O.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||re.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=N.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=N.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=0){const r=Te._LookAtVectorCache,o=n===0?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,r),this.setDirection(r,t,i,s),n===1&&this.parent)if(this.rotationQuaternion){const h=N.Matrix[0];this.rotationQuaternion.toRotationMatrix(h);const l=N.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(l),l.invert(),h.multiplyToRef(l,h),this.rotationQuaternion.fromRotationMatrix(h)}else{const h=N.Quaternion[0];re.FromEulerVectorToRef(this.rotation,h);const l=N.Matrix[0];h.toRotationMatrix(l);const c=N.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),l.multiplyToRef(c,l),h.fromRotationMatrix(l),h.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?re.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=0){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==1){const s=N.Matrix[0];i.invertToRef(s),e=v.TransformCoordinates(e,s)}return this.setPivotMatrix(O.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=N.Quaternion[0],n=N.Vector3[0],r=N.Vector3[1],o=N.Matrix[1];O.IdentityToRef(o);const h=N.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=Te._TmpRotation,re.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),O.ComposeToRef(this.scaling,l,this.position,h),this.parent&&h.multiplyToRef(this.parent.computeWorldMatrix(!0),h),e&&(e.computeWorldMatrix(!0).invertToRef(o),h.multiplyToRef(o,h)),h.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(O.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling===e?!1:(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0));let s;if(!i||i===0)s=re.RotationAxisToRef(e,t,Te._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);else{if(this.parent){const n=this.parent.getWorldMatrix(),r=N.Matrix[0];n.invertToRef(r),e=v.TransformNormal(e,r),n.determinant()<0&&(t*=-1)}s=re.RotationAxisToRef(e,t,Te._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=re.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=N.Vector3[0],n=N.Vector3[1],r=N.Vector3[2],o=N.Quaternion[0],h=N.Matrix[0],l=N.Matrix[1],c=N.Matrix[2],u=N.Matrix[3];return e.subtractToRef(this.position,s),O.TranslationToRef(s.x,s.y,s.z,h),O.TranslationToRef(-s.x,-s.y,-s.z,l),O.RotationAxisToRef(t,i,c),l.multiplyToRef(c,u),u.multiplyToRef(h,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===0){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=N.Quaternion[1],re.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const n=N.Quaternion[0];return re.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!==Te.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=Te._TmpScaling;let o=this._position;if(this._infiniteDistance&&!this.parent&&t){const l=t.getWorldMatrix(),c=new v(l.m[12],l.m[13],l.m[14]);o=Te._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 h;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,h=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(re.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(h=Te._TmpRotation,re.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),this._usePivotMatrix){const l=N.Matrix[1];O.ScalingToRef(r.x,r.y,r.z,l);const c=N.Matrix[0];h.toRotationMatrix(c),this._pivotMatrix.multiplyToRef(l,N.Matrix[4]),N.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 O.ComposeToRef(r,h,o,this._localMatrix);if(n&&n.getWorldMatrix){if(e&&n.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const f=this.parent;f.getSkeleton().prepare(),f.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),N.Matrix[7])}else N.Matrix[7].copyFrom(n.getWorldMatrix());const l=N.Vector3[5],c=N.Vector3[6],u=N.Quaternion[0];N.Matrix[7].decompose(c,u,l),O.ScalingToRef(c.x,c.y,c.z,N.Matrix[7]),N.Matrix[7].setTranslation(l),Te.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,l),this._localMatrix.setTranslation(l)),this._localMatrix.multiplyToRef(N.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const l=this.parent;l.getSkeleton().prepare(),this._localMatrix.multiplyToRef(l.getFinalMatrix(),N.Matrix[6]),N.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(n.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const l=N.Vector3[0];if(this._worldMatrix.getTranslationToRef(l),N.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&N.Matrix[1].multiplyToRef(Pp,N.Matrix[1]),N.Matrix[1].setTranslationFromFloats(0,0,0),N.Matrix[1].invertToRef(N.Matrix[0]),(this.billboardMode&Te.BILLBOARDMODE_ALL)!==Te.BILLBOARDMODE_ALL){N.Matrix[0].decompose(void 0,N.Quaternion[0],void 0);const c=N.Vector3[1];N.Quaternion[0].toEulerAnglesToRef(c),(this.billboardMode&Te.BILLBOARDMODE_X)!==Te.BILLBOARDMODE_X&&(c.x=0),(this.billboardMode&Te.BILLBOARDMODE_Y)!==Te.BILLBOARDMODE_Y&&(c.y=0),(this.billboardMode&Te.BILLBOARDMODE_Z)!==Te.BILLBOARDMODE_Z&&(c.z=0),O.RotationYawPitchRollToRef(c.y,c.x,c.z,N.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(N.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(N.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const l=N.Vector3[0];this._worldMatrix.getTranslationToRef(l);const c=t.globalPosition;this._worldMatrix.invertToRef(N.Matrix[1]);const u=N.Vector3[1];v.TransformCoordinatesToRef(c,N.Matrix[1],u),u.normalize();const f=-Math.atan2(u.z,u.x)+Math.PI/2,d=Math.sqrt(u.x*u.x+u.z*u.z),_=-Math.atan2(u.y,d);if(re.RotationYawPitchRollToRef(f,_,0,N.Quaternion[0]),(this.billboardMode&Te.BILLBOARDMODE_ALL)!==Te.BILLBOARDMODE_ALL){const p=N.Vector3[1];N.Quaternion[0].toEulerAnglesToRef(p),(this.billboardMode&Te.BILLBOARDMODE_X)!==Te.BILLBOARDMODE_X&&(p.x=0),(this.billboardMode&Te.BILLBOARDMODE_Y)!==Te.BILLBOARDMODE_Y&&(p.y=0),(this.billboardMode&Te.BILLBOARDMODE_Z)!==Te.BILLBOARDMODE_Z&&(p.z=0),O.RotationYawPitchRollToRef(p.y,p.x,p.z,N.Matrix[0])}else O.FromQuaternionToRef(N.Quaternion[0],N.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(N.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(N.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=O.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;inew Te(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 Te(e.name,t),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(O.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(O.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),e.animations){for(let n=0;n(!t||t(s))&&s instanceof Te),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),h=Math.max(o.x,o.y,o.z);if(h===0)return this;const l=1/h;return this.scaling.scaleInPlace(l),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)}}Te.BILLBOARDMODE_NONE=0;Te.BILLBOARDMODE_X=1;Te.BILLBOARDMODE_Y=2;Te.BILLBOARDMODE_Z=4;Te.BILLBOARDMODE_ALL=7;Te.BILLBOARDMODE_USE_POSITION=128;Te.BillboardUseParentOrientation=!1;Te._TmpRotation=re.Zero();Te._TmpScaling=v.Zero();Te._TmpTranslation=v.Zero();Te._LookAtVectorCache=new v(0,0,0);Te._RotationAxisCache=new re;D([yi("position")],Te.prototype,"_position",void 0);D([yi("rotation")],Te.prototype,"_rotation",void 0);D([Jd("rotationQuaternion")],Te.prototype,"_rotationQuaternion",void 0);D([yi("scaling")],Te.prototype,"_scaling",void 0);D([B("billboardMode")],Te.prototype,"_billboardMode",void 0);D([B()],Te.prototype,"scalingDeterminant",void 0);D([B("infiniteDistance")],Te.prototype,"_infiniteDistance",void 0);D([B()],Te.prototype,"ignoreNonUniformScaling",void 0);D([B()],Te.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class as{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;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let s;const n=N.Vector3[0],r=N.Vector3[1],o=N.Vector3[2];if(t){const l=this.pickedMesh.getVerticesData(A.NormalKind);let c=i?v.FromArrayToRef(l,i[this.faceId*3]*3,n):n.copyFromFloats(l[this.faceId*3*3],l[this.faceId*3*3+1],l[this.faceId*3*3+2]),u=i?v.FromArrayToRef(l,i[this.faceId*3+1]*3,r):r.copyFromFloats(l[(this.faceId*3+1)*3],l[(this.faceId*3+1)*3+1],l[(this.faceId*3+1)*3+2]),f=i?v.FromArrayToRef(l,i[this.faceId*3+2]*3,o):o.copyFromFloats(l[(this.faceId*3+2)*3],l[(this.faceId*3+2)*3+1],l[(this.faceId*3+2)*3+2]);c=c.scale(this.bu),u=u.scale(this.bv),f=f.scale(1-this.bu-this.bv),s=new v(c.x+u.x+f.x,c.y+u.y+f.y,c.z+u.z+f.z)}else{const l=this.pickedMesh.getVerticesData(A.PositionKind),c=i?v.FromArrayToRef(l,i[this.faceId*3]*3,n):n.copyFromFloats(l[this.faceId*3*3],l[this.faceId*3*3+1],l[this.faceId*3*3+2]),u=i?v.FromArrayToRef(l,i[this.faceId*3+1]*3,r):r.copyFromFloats(l[(this.faceId*3+1)*3],l[(this.faceId*3+1)*3+1],l[(this.faceId*3+1)*3+2]),f=i?v.FromArrayToRef(l,i[this.faceId*3+2]*3,o):o.copyFromFloats(l[(this.faceId*3+2)*3],l[(this.faceId*3+2)*3+1],l[(this.faceId*3+2)*3+2]),d=c.subtract(u),_=f.subtract(u);s=v.Cross(d,_)}const h=(l,c)=>{let u=l.getWorldMatrix();l.nonUniformScaling&&(N.Matrix[0].copyFrom(u),u=N.Matrix[0],u.setTranslationFromFloats(0,0,0),u.invert(),u.transposeToRef(N.Matrix[1]),u=N.Matrix[1]),v.TransformNormalToRef(c,u,c)};if(e&&h(this.pickedMesh,s),this.ray){const l=N.Vector3[0].copyFrom(s);e||h(this.pickedMesh,l),v.Dot(l,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=oe.FromArray(i,t[this.faceId*3]*2),n=oe.FromArray(i,t[this.faceId*3+1]*2),r=oe.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 oe(s.x+n.x+r.x,s.y+n.y+r.y)}}class wp{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}}function Dp(a,e,t){let i=null;switch(e){case A.PositionKind:i=s=>s.getPositions();break;case A.NormalKind:i=s=>s.getNormals();break;case A.TangentKind:i=s=>s.getTangents();break;case A.UVKind:i=s=>s.getUVs();break;default:return}for(let s=0;s0&&(O.FromFloat32ArrayToRefScaled(t,Math.floor(i[f+d]*16),_,l),h.addToSelf(l));if(n&&r)for(d=0;d<4;d++)_=r[f+d],_>0&&(O.FromFloat32ArrayToRefScaled(t,Math.floor(n[f+d]*16),_,l),h.addToSelf(l));c(a[u],a[u+1],a[u+2],h,o),o.toArray(a,u)}}class Op{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 Bp{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Op,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 wp,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._inheritVisibility=!1}}class Qe extends Te{static get BILLBOARDMODE_NONE(){return Te.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Te.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Te.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Te.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Te.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Te.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return super._updateNonUniformScalingState(e)?(this._markSubMeshesAsMiscDirty(),!0):!1}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(t===1&&e!==1||t!==1&&e===1)&&this._markSubMeshesAsDirty(i=>{i.markAsMiscDirty(),i.markAsPrePassDirty()})}get inheritVisibility(){return this._internalAbstractMeshDataInfo._inheritVisibility}set inheritVisibility(e){this._internalAbstractMeshDataInfo._inheritVisibility=e}get isVisible(){if(!this._isVisible||!this.inheritVisibility||!this._parentNode)return this._isVisible;if(this._isVisible){let e=this._parentNode;for(;e;){const t=e.isVisible;if(typeof t<"u")return t;e=e.parent}}return this._isVisible}set isVisible(e){this._isVisible=e}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._setMaterial(e)}_setMaterial(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(void 0,e==null),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return(t=this._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:t[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}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 Bp,this._waitingMaterialId=null,this._waitingMorphTargetManagerId=null,this.cullingStrategy=Qe.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new Z,this.onCollisionPositionChangeObservable=new Z,this.onMaterialChangedObservable=new Z,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=de.Red(),this.outlineWidth=.02,this.overlayColor=de.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 H(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 Z,this._onCollisionPositionChange=(i,s,n=null)=>{s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>ae.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 fe(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1: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!==Te.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes){for(const t of this.subMeshes)t._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let 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,super.markAsDirty(e),this._isDirty=!0,this}resetDrawCache(e,t=!1){if(this.subMeshes)for(const i of this.subMeshes)i.resetDrawCache(e,t)}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:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new ri(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===Te.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 O;(this.rotationQuaternion?this.rotationQuaternion:re.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,t){if(e){const i=Ic(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new ri(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i{if(s){const o=s._vertexData||(s._vertexData={});return o[r]||this.copyVerticesData(r,o),o[r]}return this.getVerticesData(r)};if(t||(t=n(i)),!t)return null;if(s?(s._outputData?s._outputData.set(t):s._outputData=new Float32Array(t),t=s._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&Dp(t,i,this.morphTargetManager),e.applySkeleton&&this.skeleton){const r=n(A.MatricesIndicesKind),o=n(A.MatricesWeightsKind);if(o&&r){const h=this.numBoneInfluencers>4,l=h?n(A.MatricesIndicesExtraKind):null,c=h?n(A.MatricesWeightsExtraKind):null,u=this.skeleton.getTransformMatrices(this);Qe._ApplySkeleton(t,i,u,r,o,l,c)}}if(e.updatePositionsArray!==!1&&i===A.PositionKind){const r=this._internalAbstractMeshDataInfo._positions||[],o=r.length;if(r.length=t.length/3,o1||!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=N.Matrix[0],i=N.Matrix[1];return O.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 as,h=this.getClassName(),l=h==="InstancedLinesMesh"||h==="LinesMesh"||h==="GreasedLineMesh"?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes||!r&&(!e.intersectsSphere(c.boundingSphere,l)||!e.intersectsBox(c.boundingBox,l)))return o;if(s)return o.hit=!r,o.pickedMesh=r?null:this,o.distance=r?0:v.Distance(e.origin,c.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let u=null;const f=this._scene.getIntersectingSubMeshCandidates(this,e),d=f.length;let _=!1;for(let p=0;p1&&!r&&!g.canIntersects(e))continue;const m=g.intersects(e,this._positions,this.getIndices(),t,i);if(m&&(t||!u||m.distanceo!==this&&o.actionManager===this.actionManager)&&this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let h=o.includedOnlyMeshes.indexOf(this);h!==-1&&o.includedOnlyMeshes.splice(h,1),h=o.excludedMeshes.indexOf(this),h!==-1&&o.excludedMeshes.splice(h,1);const l=o.getShadowGenerators();if(l){const c=l.values();for(let u=c.next();u.done!==!0;u=c.next()){const d=u.value.getShadowMap();d&&d.renderList&&(h=d.renderList.indexOf(this),h!==-1&&d.renderList.splice(h,1))}}}),(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes(!0);const r=s.getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),s.removeMesh(this),this._parentContainer){const o=this._parentContainer.meshes.indexOf(this);o>-1&&this._parentContainer.meshes.splice(o,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){o=!0;break}o?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(o,h){return h.sqDistance-o.sqDistance},!e.facetDepthSortFrom){const o=this.getScene().activeCamera;e.facetDepthSortFrom=o?o.position:v.Zero()}e.depthSortedFacets=[];for(let o=0;oLe?n.maximum.x-n.minimum.x:Le,e.bbSize.y=n.maximum.y-n.minimum.y>Le?n.maximum.y-n.minimum.y:Le,e.bbSize.z=n.maximum.z-n.minimum.z>Le?n.maximum.z-n.minimum.z:Le;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 h=0;hn.subDiv.max||o<0||o>n.subDiv.max||h<0||h>n.subDiv.max?null:n.facetPartitioning[r+n.subDiv.max*o+n.subDiv.max*n.subDiv.max*h]}getClosestFacetAtCoordinates(e,t,i,s,n=!1,r=!0){const o=this.getWorldMatrix(),h=N.Matrix[5];o.invertToRef(h);const l=N.Vector3[8];v.TransformCoordinatesFromFloatsToRef(e,t,i,h,l);const c=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.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,h=0,l=0,c=0,u=0,f=0,d=0,_=0,p=0;const g=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),b=this.getFacetsAtLocalCoordinates(e,t,i);if(!b)return null;let I=Number.MAX_VALUE,T=I,x,y,R;for(let E=0;E=0||n&&!r&&u<=0)&&(u=y.x*R.x+y.y*R.y+y.z*R.z,f=-(y.x*e+y.y*t+y.z*i-u)/(y.x*y.x+y.y*y.y+y.z*y.z),d=e+y.x*f,_=t+y.y*f,p=i+y.z*f,h=d-e,l=_-t,c=p-i,T=h*h+l*l+c*c,Te.emitter===this)}}Qe.OCCLUSION_TYPE_NONE=0;Qe.OCCLUSION_TYPE_OPTIMISTIC=1;Qe.OCCLUSION_TYPE_STRICT=2;Qe.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;Qe.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;Qe.CULLINGSTRATEGY_STANDARD=0;Qe.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;Qe.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;Qe.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;D([rs.filter((...[a,e,t,i,s])=>!Array.isArray(a)&&!Array.isArray(e)&&!Array.isArray(t)&&!Array.isArray(i)&&!Array.isArray(s))],Qe,"_ApplySkeleton",null);vt("BABYLON.AbstractMesh",Qe);class Lp{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Qe.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Qe.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}ae.prototype.getGPUFrameTimeCounter=function(){return null};ae.prototype.captureGPUFrameTime=function(a){};ae.prototype.createQuery=function(){return null};ae.prototype.deleteQuery=function(a){return this};ae.prototype.isQueryResultAvailable=function(a){return!1};ae.prototype.getQueryResult=function(a){return 0};ae.prototype.beginOcclusionQuery=function(a,e){return!1};ae.prototype.endOcclusionQuery=function(a){return this};Object.defineProperty(Qe.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(a){this._occlusionDataStorage.isOcclusionQueryInProgress=a},enumerable:!1,configurable:!0});Object.defineProperty(Qe.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new Lp),this.__occlusionDataStorage},enumerable:!1,configurable:!0});Object.defineProperty(Qe.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(a){this._occlusionDataStorage.isOccluded=a},enumerable:!0,configurable:!0});Object.defineProperty(Qe.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(a){this._occlusionDataStorage.occlusionQueryAlgorithmType=a},enumerable:!0,configurable:!0});Object.defineProperty(Qe.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(a){this._occlusionDataStorage.occlusionType=a},enumerable:!0,configurable:!0});Object.defineProperty(Qe.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(a){this._occlusionDataStorage.occlusionRetryCount=a},enumerable:!0,configurable:!0});Object.defineProperty(Qe.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(a){this._occlusionDataStorage.forceRenderingWhenOccluded=a},enumerable:!0,configurable:!0});Qe.prototype._checkOcclusionQuery=function(){const a=this._occlusionDataStorage;if(a.occlusionType===Qe.OCCLUSION_TYPE_NONE)return a.isOccluded=!1,!1;const e=this.getEngine();if(!e.getCaps().supportOcclusionQuery||!e.isQueryResultAvailable)return a.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery!==null&&this._occlusionQuery!==void 0)if(e.isQueryResultAvailable(this._occlusionQuery)){const s=e.getQueryResult(this._occlusionQuery);a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=!(s>0)}else if(a.occlusionInternalRetryCounter++,a.occlusionRetryCount!==-1&&a.occlusionInternalRetryCounter>a.occlusionRetryCount)a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=a.occlusionType===Qe.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;else return a.occlusionType===Qe.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;const t=this.getScene();if(t.getBoundingBoxRenderer){const i=t.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=e.createQuery()),this._occlusionQuery&&e.beginOcclusionQuery(a.occlusionQueryAlgorithmType,this._occlusionQuery)&&(i.renderOcclusionBoundingBox(this),e.endOcclusionQuery(a.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return a.isOccluded};et.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter};et.prototype.captureGPUFrameTime=function(a){this._timestampQuery.enable=a&&!!this._caps.timerQuery};et.prototype.createQuery=function(){return this._occlusionQuery.createQuery()};et.prototype.deleteQuery=function(a){return this._occlusionQuery.deleteQuery(a),this};et.prototype.isQueryResultAvailable=function(a){return this._occlusionQuery.isQueryResultAvailable(a)};et.prototype.getQueryResult=function(a){return this._occlusionQuery.getQueryResult(a)};et.prototype.beginOcclusionQuery=function(a,e){var t;if(this.compatibilityMode){if(this._occlusionQuery.canBeginQuery(e))return(t=this._currentRenderPass)==null||t.beginOcclusionQuery(e),!0}else return this._bundleList.addItem(new M0(e)),!0;return!1};et.prototype.endOcclusionQuery=function(){var a;return this.compatibilityMode?(a=this._currentRenderPass)==null||a.endOcclusionQuery():this._bundleList.addItem(new P0),this};const wh={label:"TextureView_SwapChain_ResolveTarget",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},Dh={label:"TextureView_SwapChain",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},Np=new H;class Ye extends et{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return this._cacheSampler?this._cacheSampler.disabled:!1}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return this._cacheRenderPipeline?this._cacheRenderPipeline.disabled:!1}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return this._cacheBindGroups?this._cacheBindGroups.disabled:!1}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}areAllEffectsReady(){return!0}getFontOffset(e){return cc(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return U.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 Ye(e,t);return new Promise(s=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>s(i))})}constructor(e,t={}){var i,s;if(super((i=t.antialias)!=null?i:!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._glslangAndTintAreFullyLoaded=!1,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.scenes=[],this._virtualScenes=new Array,this._commandBuffers=[null,null],this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._workingGlslangAndTintPromise=null,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._performanceMonitor=new Yl,this._name="WebGPU",this._drawCalls=new ui,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=(s=t.enableGPUDebugMarkers)!=null?s:!1,U.Log("Babylon.js v".concat(ae.Version," - ").concat(this.description," engine")),!navigator.gpu){U.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,navigator&&navigator.userAgent&&this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new g_,this._shaderProcessorWGSL=new U_}prepareGlslangAndTintAsync(){return this._workingGlslangAndTintPromise||(this._workingGlslangAndTintPromise=new Promise(e=>{var t,i;this._initGlslang((i=this._glslangOptions)!=null?i:(t=this._options)==null?void 0:t.glslangOptions).then(s=>{var n,r;this._glslang=s,this._tintWASM=new ei,this._tintWASM.initTwgsl((r=this._twgslOptions)!=null?r:(n=this._options)==null?void 0:n.twgslOptions).then(()=>{this._glslangAndTintAreFullyLoaded=!0,e()})})})),this._workingGlslangAndTintPromise}initAsync(e,t){return this.uniqueId=Ye._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,navigator.gpu.requestAdapter(this._options).then(i=>{var s,n,r;if(i){this._adapter=i,this._adapterSupportedExtensions=[],(s=this._adapter.features)==null||s.forEach(l=>this._adapterSupportedExtensions.push(l)),this._adapterSupportedLimits=this._adapter.limits,this._adapterInfo=this._adapter.info;const o=(n=this._options.deviceDescriptor)!=null?n:{},h=(r=o==null?void 0:o.requiredFeatures)!=null?r:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(h){const l=h,c=[];for(const u of l)this._adapterSupportedExtensions.indexOf(u)!==-1&&c.push(u);o.requiredFeatures=c}if(this._options.setMaximumLimits&&!o.requiredLimits){o.requiredLimits={};for(const l in this._adapterSupportedLimits)l==="minSubgroupSize"||l==="maxSubgroupSize"||(o.requiredLimits[l]=this._adapterSupportedLimits[l])}return o.label="BabylonWebGPUDevice".concat(this.uniqueId),this._adapter.requestDevice(o)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(i=>{var n,r;this._device=i,this._deviceEnabledExtensions=[],(n=this._device.features)==null||n.forEach(o=>this._deviceEnabledExtensions.push(o)),this._deviceLimits=i.limits;let s=-1;this._device.addEventListener("uncapturederror",o=>{++s{this._isDisposed||(this._contextWasLost=!0,U.Warn("WebGPU context lost. "+o),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(async()=>{var _,p,g,m;const h=this.snapshotRenderingMode,l=this.snapshotRendering,c=this.disableCacheSamplers,u=this.disableCacheRenderPipelines,f=this.disableCacheBindGroups,d=this.enableGPUTimingMeasurements;await this.initAsync((p=this._glslangOptions)!=null?p:(_=this._options)==null?void 0:_.glslangOptions,(m=this._twgslOptions)!=null?m:(g=this._options)==null?void 0:g.twgslOptions),this.snapshotRenderingMode=h,this.snapshotRendering=l,this.disableCacheSamplers=c,this.disableCacheRenderPipelines=u,this.disableCacheBindGroups=f,this.enableGPUTimingMeasurements=d,this._currentRenderPass=null}))})}).then(()=>{this._initializeLimits(),this._bufferManager=new Mr(this,this._device),this._textureHelper=new j_(this,this._device,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new Fs(this._device),this._cacheBindGroups=new qe(this._device,this._cacheSampler,this),this._timestampQuery=new bp(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new yp(this,this._device,this._bufferManager):void 0,this._bundleList=new D0(this._device),this._snapshotRendering=new Tp(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),We.Uniform|We.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),We.Uniform|We.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&this._count===void 0&&(this._count=0,U.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._emptyVertexBuffer=new A(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new Ci(this._device,this._emptyVertexBuffer),this._depthCullingState=new up(this._cacheRenderPipeline),this._stencilStateComposer=new cp(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 vp(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(i=>{throw U.Error("A fatal error occurred during WebGPU creation/initialization."),i})}_initGlslang(e){return e=e||{},e={...Ye._GlslangDefaultOptions,...e},e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?J.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(J.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage*2,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxDrawBuffers:8,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf("texture-compression-astc")>=0?!0:void 0,s3tc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0?!0:void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf("texture-compression-etc2")>=0?!0:void 0,bptc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0?!0:void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf("rg11b10ufloat-renderable")>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf("float32-filterable")>=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("timestamp-query")!==-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,textureNorm16:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportIBLShadows:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!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 pr(this)],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e);let t;if(this._options.antialias){const n={label:"Texture_MainColor_".concat(this._mainTextureExtends.width,"x").concat(this._mainTextureExtends.height,"_antialiasing"),size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._options.swapChainFormat,usage:16};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(n),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:"2d",format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new H(0,0,0,1),loadOp:"clear",storeOp:"store"}]}else t=[{view:void 0,clearValue:new H(0,0,0,1),loadOp:"clear",storeOp:"store"}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?"depth24plus-stencil8":"depth32float",this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(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:"2d",format:this._mainRenderPassWrapper.depthTextureFormat,usage:16};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:"2d",format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:"clear",depthStoreOp:"store",stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?"clear":void 0,stencilStoreOp:this.isStencilEnable?"store":void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_sharedInit(e){super._sharedInit(e),hc(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:17,alphaMode:this.premultipliedAlpha?"premultiplied":"opaque"})}resizeImageBitmap(e,t,i){return fc(this,e,t,i)}_createImageBitmapFromSource(e,t){return uc(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&dc(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&_c()}enterPointerlock(){this._renderingCanvas&&R0(this._renderingCanvas)}exitPointerlock(){pc()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){Ci.ResetCache(),qe.ResetCache();const t=s=>{var n;for(const r of s){for(const o of r.meshes){const h=o.subMeshes;if(h)for(const l of h)l._drawWrappers=[]}for(const o of r.materials)(n=o._materialContext)==null||n.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const s of this._uniformBuffers)s.name.indexOf("leftOver")<0&&i.push(s);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return super.setSize(e,t,i)?(this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count=0,n=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,r=i===0?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===0?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("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,r=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,o="#version 450\n",h=s===0?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=s===0?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),c=this._createPipelineStageDescriptor(h,l,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 Hr(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new u_(e,this)}createMaterialContext(){return new zr}createDrawContext(){return new Wr(this._bufferManager)}async _preparePipelineContext(e,t,i,s,n,r,o,h,l,c,u){const f=e,d=f.shaderProcessingContext.shaderLanguage;d===0&&!this._glslangAndTintAreFullyLoaded&&await this.prepareGlslangAndTintAsync(),this.dbgShowShaderCode&&(U.Log(["defines",h]),U.Log(t),U.Log(i),U.Log("***********************************************")),f.sources={fragment:i,vertex:t,rawVertex:n,rawFragment:r},s?f.stages=this._compileRawPipelineStageDescriptor(t,i,d):f.stages=this._compilePipelineStageDescriptor(t,i,h,d),u()}getAttributes(e,t){const i=new Array(t.length),s=e;for(let n=0;n0,r.is3D=l>0,r._cachedWrapU=0,r._cachedWrapV=0,r._useSRGBBuffer=n.useSRGBBuffer,r.label=n.label,this._internalTexturesCache.push(r),!i){const _=!n.generateMipMaps&&n.createMipMaps;_&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r,o,h,c||1,n.creationFlags),_&&(r.generateMipMaps=!1)}return r}createTexture(e,t,i,s,n=3,r=null,o=null,h=null,l=null,c=null,u=null,f,d,_,p){return this._createTextureBase(e,t,i,s,n,r,o,(g,m,b,I,T,x,y,R)=>{var C;const E=I;if(g.baseWidth=E.width,g.baseHeight=E.height,g.width=E.width,g.height=E.height,g.format=g.format!==-1?g.format:c!=null?c:5,g.type=g.type!==-1?g.type:0,g._creationFlags=_!=null?_:0,R(g.width,g.height,E,m,g,()=>{}),(C=g._hardwareTexture)!=null&&C.underlyingResource)!x&&!y&&this._generateMipmaps(g,this._uploadEncoder);else{const S=this._textureHelper.createGPUTextureForInternalTexture(g,E.width,E.height,void 0,_);Ve.IsImageBitmap(E)&&(this._textureHelper.updateTexture(E,g,E.width,E.height,g.depth,S.format,0,0,T,!1,0,0),!x&&!y&&this._generateMipmaps(g,this._uploadEncoder))}b&&b.removePendingData(g),g.isReady=!0,g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>!1,h,l,c,u,f,d,p)}wrapWebGPUTexture(e){const t=new pr(this,e),i=new ft(this,0,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers}_unpackFlipY(e){}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+"Sampler";this._currentMaterialContext.setSampler(r,t)}}}createPrefilteredCubeTexture(e,t,i,s,n=null,r=null,o,h=null,l=!0){const c=u=>{if(!u){n&&n(null);return}const f=u.texture;l?u.info.sphericalPolynomial&&(f._sphericalPolynomial=u.info.sphericalPolynomial):f._sphericalPolynomial=new On,f._source=9,n&&n(f)};return this.createCubeTexture(e,t,null,!1,c,r,o,h,l,i,s)}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let n=0;n=13&&T.format<=18;((T==null?void 0:T.type)===1&&!this._caps.textureFloatLinearFiltering||x)&&(u|=m),m=m<<1}}this._currentMaterialContext.textureState=u;const f=this._cacheRenderPipeline.getRenderPipeline(t,this._currentEffect,this.currentSampleCount,u),d=this._cacheBindGroups.getBindGroups(h,this._currentDrawContext,this._currentMaterialContext);this._snapshotRendering.record||(this._applyRenderPassChanges(this.compatibilityMode?null:o),this.compatibilityMode||(this._counters.numBundleCreationNonCompatMode++,c=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Ve.GetSample(this.currentSampleCount)}))),c.setPipeline(f),this._currentIndexBuffer&&c.setIndexBuffer(this._currentIndexBuffer.underlyingResource,this._currentIndexBuffer.is32Bits?"uint32":"uint16",0);const _=this._cacheRenderPipeline.vertexBuffers;for(let m=0;m<_.length;m++){const b=_[m],I=b.effectiveBuffer;I&&c.setVertexBuffer(m,I.underlyingResource,b._validOffsetRange?0:b.byteOffset)}for(let m=0;m{const o=()=>{e.mapAsync(1,0,t).then(()=>{const h=e.getMappedRange(0,t);let l=i;if(l===void 0)l=new Uint8Array(t),l.set(new Uint8Array(h));else{const c=l.constructor;l=new c(l.buffer),l.set(new c(h))}e.unmap(),this._bufferManager.releaseBuffer(e),n(l)},h=>{this.isDisposed?n(new Uint8Array):r(h)})};s?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce(()=>{o()})})}readFromStorageBuffer(e,t,i,s,n){i=i||e.capacity;const r=this._bufferManager.createRawBuffer(i,We.MapRead|We.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,t!=null?t:0,r,0,i),this._readFromGPUBuffer(r,i,s,n)}readFromMultipleStorageBuffers(e,t,i,s,n){i=i||e[0].capacity;const r=this._bufferManager.createRawBuffer(i*e.length,We.MapRead|We.CopyDst,void 0,"TempReadFromMultipleStorageBuffers");for(let o=0;othis.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}}function Ec(a){a.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class ot{constructor(){this._dirty=!0,this._tempColor=new H(0,0,0,0),this._globalCurve=new H(0,0,0,0),this._highlightsCurve=new H(0,0,0,0),this._midtonesCurve=new H(0,0,0,0),this._shadowsCurve=new H(0,0,0,0),this._positiveCurve=new H(0,0,0,0),this._negativeCurve=new H(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",n="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(n,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,n){e!=null&&(e=ot._Clamp(e,0,360),t=ot._Clamp(t,-100,100),i=ot._Clamp(i,-100,100),s=ot._Clamp(s,-100,100),t=ot._ApplyColorGradingSliderNonlinear(t),t*=.5,s=ot._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),ot._FromHSBToRef(e,t,50+.25*s,n),n.scaleToRef(2,n),n.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,s){let n=ot._Clamp(e,0,360);const r=ot._Clamp(t/100,0,1),o=ot._Clamp(i/100,0,1);if(r===0)s.r=o,s.g=o,s.b=o;else{n/=60;const h=Math.floor(n),l=n-h,c=o*(1-r),u=o*(1-r*l),f=o*(1-r*(1-l));switch(h){case 0:s.r=o,s.g=f,s.b=c;break;case 1:s.r=u,s.g=o,s.b=c;break;case 2:s.r=c,s.g=o,s.b=f;break;case 3:s.r=c,s.g=u,s.b=o;break;case 4:s.r=f,s.g=c,s.b=o;break;default:s.r=o,s.g=c,s.b=u;break}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return Ae.Clone(()=>new ot,this)}serialize(){return Ae.Serialize(this)}static Parse(e){return Ae.Parse(()=>new ot,e,null,null)}}ot.PrepareUniforms=Ec;D([B()],ot.prototype,"_globalHue",void 0);D([B()],ot.prototype,"_globalDensity",void 0);D([B()],ot.prototype,"_globalSaturation",void 0);D([B()],ot.prototype,"_globalExposure",void 0);D([B()],ot.prototype,"_highlightsHue",void 0);D([B()],ot.prototype,"_highlightsDensity",void 0);D([B()],ot.prototype,"_highlightsSaturation",void 0);D([B()],ot.prototype,"_highlightsExposure",void 0);D([B()],ot.prototype,"_midtonesHue",void 0);D([B()],ot.prototype,"_midtonesDensity",void 0);D([B()],ot.prototype,"_midtonesSaturation",void 0);D([B()],ot.prototype,"_midtonesExposure",void 0);Ae._ColorCurvesParser=ot.Parse;function Up(a,e){e.EXPOSURE&&a.push("exposureLinear"),e.CONTRAST&&a.push("contrast"),e.COLORGRADING&&a.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&a.push("vInverseScreenSize"),e.VIGNETTE&&(a.push("vignetteSettings1"),a.push("vignetteSettings2")),e.COLORCURVES&&Ec(a),e.DITHER&&a.push("ditherIntensity")}function kp(a,e){e.COLORGRADING&&a.push("txColorTransform")}class Ne{constructor(){this.colorCurves=new ot,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Ne.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new H(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Ne.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new Z}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=0,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}if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===Ne._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,!this._toneMappingEnabled)e.TONEMAPPING=0;else switch(this._toneMappingType){case Ne.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case Ne.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=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&&ot.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 h=Math.sqrt(o*r);o=Fa(o,h,this.vignetteStretch),r=Fa(r,h,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,r,-o*this.vignetteCenterX,-r*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return Ae.Clone(()=>new Ne,this)}serialize(){return Ae.Serialize(this)}static Parse(e){const t=Ae.Parse(()=>new Ne,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}}Ne.TONEMAPPING_STANDARD=0;Ne.TONEMAPPING_ACES=1;Ne.TONEMAPPING_KHR_PBR_NEUTRAL=2;Ne.PrepareUniforms=Up;Ne.PrepareSamplers=kp;Ne._VIGNETTEMODE_MULTIPLY=0;Ne._VIGNETTEMODE_OPAQUE=1;D([Qd()],Ne.prototype,"colorCurves",void 0);D([B()],Ne.prototype,"_colorCurvesEnabled",void 0);D([_i("colorGradingTexture")],Ne.prototype,"_colorGradingTexture",void 0);D([B()],Ne.prototype,"_colorGradingEnabled",void 0);D([B()],Ne.prototype,"_colorGradingWithGreenDepth",void 0);D([B()],Ne.prototype,"_colorGradingBGR",void 0);D([B()],Ne.prototype,"_exposure",void 0);D([B()],Ne.prototype,"_toneMappingEnabled",void 0);D([B()],Ne.prototype,"_toneMappingType",void 0);D([B()],Ne.prototype,"_contrast",void 0);D([B()],Ne.prototype,"vignetteStretch",void 0);D([B()],Ne.prototype,"vignetteCenterX",void 0);D([B()],Ne.prototype,"vignetteCenterY",void 0);D([B()],Ne.prototype,"vignetteWeight",void 0);D([p0()],Ne.prototype,"vignetteColor",void 0);D([B()],Ne.prototype,"vignetteCameraFov",void 0);D([B()],Ne.prototype,"_vignetteBlendMode",void 0);D([B()],Ne.prototype,"_vignetteEnabled",void 0);D([B()],Ne.prototype,"_ditheringEnabled",void 0);D([B()],Ne.prototype,"_ditheringIntensity",void 0);D([B()],Ne.prototype,"_skipFinalColorClamp",void 0);D([B()],Ne.prototype,"_applyByPostProcess",void 0);D([B()],Ne.prototype,"_isEnabled",void 0);Ae._ImageProcessingConfigurationParser=Ne.Parse;vt("BABYLON.ImageProcessingConfiguration",Ne);class Ot{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 Ot(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new Ot(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new Ot(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new Ot(e,t.x,t.y,null,i,s)}}class Re{}Re.NAME_EFFECTLAYER="EffectLayer";Re.NAME_LAYER="Layer";Re.NAME_LENSFLARESYSTEM="LensFlareSystem";Re.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer";Re.NAME_PARTICLESYSTEM="ParticleSystem";Re.NAME_GAMEPAD="Gamepad";Re.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue";Re.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer";Re.NAME_PREPASSRENDERER="PrePassRenderer";Re.NAME_DEPTHRENDERER="DepthRenderer";Re.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer";Re.NAME_IBLSHADOWSRENDERER="IblShadowsRenderer";Re.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager";Re.NAME_SPRITE="Sprite";Re.NAME_SUBSURFACE="SubSurface";Re.NAME_OUTLINERENDERER="Outline";Re.NAME_PROCEDURALTEXTURE="ProceduralTexture";Re.NAME_SHADOWGENERATOR="ShadowGenerator";Re.NAME_OCTREE="Octree";Re.NAME_PHYSICSENGINE="PhysicsEngine";Re.NAME_AUDIO="Audio";Re.NAME_FLUIDRENDERER="FluidRenderer";Re.STEP_ISREADYFORMESH_EFFECTLAYER=0;Re.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0;Re.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0;Re.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0;Re.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1;Re.STEP_BEFORECAMERADRAW_PREPASS=0;Re.STEP_BEFORECAMERADRAW_EFFECTLAYER=1;Re.STEP_BEFORECAMERADRAW_LAYER=2;Re.STEP_BEFORERENDERTARGETDRAW_PREPASS=0;Re.STEP_BEFORERENDERTARGETDRAW_LAYER=1;Re.STEP_BEFORERENDERINGMESH_PREPASS=0;Re.STEP_BEFORERENDERINGMESH_OUTLINE=1;Re.STEP_AFTERRENDERINGMESH_PREPASS=0;Re.STEP_AFTERRENDERINGMESH_OUTLINE=1;Re.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0;Re.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1;Re.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0;Re.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0;Re.STEP_BEFORECLEAR_PREPASS=1;Re.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0;Re.STEP_AFTERRENDERTARGETDRAW_PREPASS=0;Re.STEP_AFTERRENDERTARGETDRAW_LAYER=1;Re.STEP_AFTERCAMERADRAW_PREPASS=0;Re.STEP_AFTERCAMERADRAW_EFFECTLAYER=1;Re.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2;Re.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3;Re.STEP_AFTERCAMERADRAW_LAYER=4;Re.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5;Re.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0;Re.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0;Re.STEP_AFTERRENDER_AUDIO=0;Re.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0;Re.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1;Re.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2;Re.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3;Re.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0;Re.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1;Re.STEP_POINTERMOVE_SPRITE=0;Re.STEP_POINTERDOWN_SPRITE=0;Re.STEP_POINTERUP_SPRITE=0;class _t extends Array{constructor(e){super(...e)}static Create(){return Object.create(_t.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 li.Triggers)if(Object.prototype.hasOwnProperty.call(li.Triggers,t)&&parseInt(t)===e)return!0;return!1}}li.Triggers={};class Nn{}Nn.KEYDOWN=1;Nn.KEYUP=2;class Wa{constructor(e,t){this.type=e,this.event=t}}class Oh extends Wa{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 ge;(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"})(ge||(ge={}));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 Bh;(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"})(Bh||(Bh={}));var Lh;(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"})(Lh||(Lh={}));var Nh;(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"})(Nh||(Nh={}));var Uh;(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"})(Uh||(Uh={}));var kh;(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"})(kh||(kh={}));var Vh;(function(a){a[a.PointerMove=0]="PointerMove",a[a.PointerDown=1]="PointerDown",a[a.PointerUp=2]="PointerUp"})(Vh||(Vh={}));class jn{}jn.DOM_DELTA_PIXEL=0;jn.DOM_DELTA_LINE=1;jn.DOM_DELTA_PAGE=2;class Ps{static CreateDeviceEvent(e,t,i,s,n,r,o){switch(e){case ge.Keyboard:return this._CreateKeyboardEvent(i,s,n,r);case ge.Mouse:if(i===xe.MouseWheelX||i===xe.MouseWheelY||i===xe.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,n,r);case ge.Touch:return this._CreatePointerEvent(e,t,i,s,n,r,o);default:throw"Unable to generate event for device ".concat(ge[e])}}static _CreatePointerEvent(e,t,i,s,n,r,o){const h=this._CreateMouseEvent(e,t,i,s,n,r);e===ge.Mouse?(h.deviceType=ge.Mouse,h.pointerId=1,h.pointerType="mouse"):(h.deviceType=ge.Touch,h.pointerId=o!=null?o:t,h.pointerType="touch");let l=0;return l+=n.pollInput(e,t,xe.LeftClick),l+=n.pollInput(e,t,xe.RightClick)*2,l+=n.pollInput(e,t,xe.MiddleClick)*4,h.buttons=l,i===xe.Move?h.type="pointermove":i>=xe.LeftClick&&i<=xe.RightClick&&(h.type=s===1?"pointerdown":"pointerup",h.button=i-2),h}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=jn.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),h=n.pollInput(e,t,xe.Horizontal),l=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,10),o.movementY=n.pollInput(e,t,11),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,n),o.clientX=h,o.clientY=l,o.x=h,o.y=l,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=ge.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(ge.Keyboard),s=i&&t.pollInput(ge.Keyboard,0,18)===1,n=i&&t.pollInput(ge.Keyboard,0,17)===1,r=i&&(t.pollInput(ge.Keyboard,0,91)===1||t.pollInput(ge.Keyboard,0,92)===1||t.pollInput(ge.Keyboard,0,93)===1),o=i&&t.pollInput(ge.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 Gp{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(s,n,r,o)=>{const h=Ps.CreateDeviceEvent(s,n,r,o,this);i(s,n,h)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===ge.Mouse||e===ge.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const Gh=255,zh=Object.keys(xe).length/2;class zp{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=J.IsSafari(),this._usingMacOS=Qs()&&/(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._pointerMacOSChromeOutEvent=n=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Qs()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=Qs()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=n=>{},this._gamepadDisconnectedEvent=n=>{},this._eventPrefix=J.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(ge[e]);e>=ge.DualShock&&e<=ge.DualSense&&this._updateDevice(e,t,i);const n=s[i];if(n===void 0)throw"Unable to find input ".concat(i," for device ").concat(ge[e]," in slot ").concat(t);return i===xe.Move&&J.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?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(ge.Keyboard,0,Gh));const t=this._inputs[ge.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(ge.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ge.Keyboard,0,Gh));const t=this._inputs[ge.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=Ps.CreateDeviceEvent(ge.Keyboard,0,s,0,this,this._elementToAttachTo);t[s]=0,this._onInputChanged(ge.Keyboard,0,n)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(ge.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[ge.Keyboard][0];for(let t=0;t{const s=this._getPointerType(i);let n=s===ge.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===ge.Touch&&n===-1){const o=this._activeTouchIds.indexOf(-1);if(o>=0)n=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(s,n);else{J.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]||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,s===ge.Touch&&r[xe.LeftClick]===0&&(r[xe.LeftClick]=1),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===ge.Mouse?0:i.pointerId;if(s===ge.Touch){let o=this._activeTouchIds.indexOf(i.pointerId);if(o===-1&&(o=this._activeTouchIds.indexOf(-1)),o>=0)n=o,this._activeTouchIds[o]=i.pointerId;else{J.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===ge.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],h=r[xe.Vertical];if(s===ge.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 l=i;l.inputIndex=i.button+2,this._onInputChanged(s,n,l),(o!==i.clientX||h!==i.clientY)&&(l.inputIndex=xe.Move,this._onInputChanged(s,n,l))}},this._pointerUpEvent=i=>{var o,h,l,c,u;const s=this._getPointerType(i),n=s===ge.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===ge.Touch){if(n===-1)return;this._activeTouchIds[n]=-1}const r=(o=this._inputs[s])==null?void 0:o[n];if(r&&r[i.button+2]!==0){const f=r[xe.Horizontal],d=r[xe.Vertical];r[xe.Horizontal]=i.clientX,r[xe.Vertical]=i.clientY,r[i.button+2]=0;const _=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(f!==i.clientX||d!==i.clientY)&&(_.inputIndex=xe.Move,this._onInputChanged(s,n,_)),_.inputIndex=i.button+2,s===ge.Mouse&&this._mouseId>=0&&((l=(h=this._elementToAttachTo).hasPointerCapture)!=null&&l.call(h,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&((u=(c=this._elementToAttachTo).hasPointerCapture)!=null&&u.call(c,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(s,n,_),s===ge.Touch&&this._onDeviceDisconnected(s,n)}},this._pointerCancelEvent=i=>{var s,n,r,o;if(i.pointerType==="mouse"){const h=this._inputs[ge.Mouse][0];this._mouseId>=0&&((n=(s=this._elementToAttachTo).hasPointerCapture)!=null&&n.call(s,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let l=xe.LeftClick;l<=xe.BrowserForward;l++)if(h[l]===1){h[l]=0;const c=Ps.CreateDeviceEvent(ge.Mouse,0,l,0,this,this._elementToAttachTo);this._onInputChanged(ge.Mouse,0,c)}}else{const h=this._activeTouchIds.indexOf(i.pointerId);if(h===-1)return;(o=(r=this._elementToAttachTo).hasPointerCapture)!=null&&o.call(r,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[ge.Touch][h][xe.LeftClick]=0;const l=Ps.CreateDeviceEvent(ge.Touch,h,xe.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(ge.Touch,h,l),this._activeTouchIds[h]=-1,this._onDeviceDisconnected(ge.Touch,h)}},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(ge.Mouse)){const h=this._inputs[ge.Mouse][0];this._mouseId>=0&&((s=(i=this._elementToAttachTo).hasPointerCapture)!=null&&s.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let l=xe.LeftClick;l<=xe.BrowserForward;l++)if(h[l]===1){h[l]=0;const c=Ps.CreateDeviceEvent(ge.Mouse,0,l,0,this,this._elementToAttachTo);this._onInputChanged(ge.Mouse,0,c)}}if(this.isDeviceAvailable(ge.Touch)){const h=this._inputs[ge.Touch];for(let l=0;l{const s=ge.Mouse,n=0;this._inputs[s]||(this._inputs[s]=[]),this._inputs[s][n]||(this._pointerActive=!0,this._registerDevice(s,n,zh));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._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=i=>{i.buttons>1&&this._pointerCancelEvent(i)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,e?{passive:!1}:!1),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(ge.Mouse)){const i=this._inputs[ge.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?ge.DualSense:ge.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?ge.Xbox:e.indexOf("057e")!==-1?ge.Switch:ge.Generic}_getPointerType(e){let t=ge.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=ge.Touch),t}}class Wh{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new Z,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Wp{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(ge).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 h of this._registeredManagers){const l=new Wh(this._deviceInputSystem,r,o);h._addDevice(l)}},s=(r,o)=>{var h;(h=this._devices[r])!=null&&h[o]&&delete this._devices[r][o];for(const l of this._registeredManagers)l._removeDevice(r,o)},n=(r,o,h)=>{if(h)for(const l of this._registeredManagers)l._onInputChanged(r,o,h)};typeof _native<"u"?this._deviceInputSystem=new Gp(i,s,n):this._deviceInputSystem=new zp(e,i,s,n)}dispose(){this._deviceInputSystem.dispose()}}class Hp{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(ge).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Wp(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new Z(i=>{for(const s of this._devices)if(s)for(const n of s)n&&this.onDeviceConnectedObservable.notifyObserver(i,n)}),this.onDeviceDisconnectedObservable=new Z,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 s,n;const i=(s=this._devices[e])==null?void 0:s[t];this.onDeviceDisconnectedObservable.notifyObservers(i),(n=this._devices[e])!=null&&n[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var s,n;(n=(s=this._devices[e])==null?void 0:s[t])==null||n.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case ge.Keyboard:case ge.Mouse:this._firstDevice[e]=0;break;case ge.Touch:case ge.DualSense:case ge.DualShock:case ge.Xbox:case ge.Switch:case ge.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i=xe.MouseWheelX&&t.inputIndex<=xe.MouseWheelZ?Ce.POINTERWHEEL:Ce.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,r));let o;e?(o=new Ji(r,t,e),this._setRayOnPointerInfo(e,t)):(o=new Ji(r,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,r)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&O0._IsPickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,O.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 Vp(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(n.originalPickingInfo=e,n.ray=e.ray,t.pointerType==="xr-near"&&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,t.pointerMoveFastCheck,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,Ce.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,Ce.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,Ot.CreateNew(e.pickedMesh,t,e)),t.button){case 0:r.processTrigger(2,Ot.CreateNew(e.pickedMesh,t,e));break;case 1:r.processTrigger(4,Ot.CreateNew(e.pickedMesh,t,e));break;case 2:r.processTrigger(3,Ot.CreateNew(e.pickedMesh,t,e));break}r.hasSpecificTrigger(8)&&window.setTimeout(()=>{const o=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,h=>h.isPickable&&h.isVisible&&h.isReady()&&h.actionManager&&h.actionManager.hasSpecificTrigger(8)&&h===this._pickedDownMesh,!1,i.cameraToUseForPointers);o!=null&&o.pickedMesh&&r&&this._activePointerIdsCount!==0&&Date.now()-this._startingPointerTime>pt.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,r.processTrigger(8,Ot.CreateNew(o.pickedMesh,t)))},pt.LongPressDelay)}}else for(const r of i._pointerDownStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const n=Ce.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,n),s=new Ji(n,t,e),this._setRayOnPointerInfo(e,t)):s=new Ji(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 Hh;i?n.doubleClick=!0:n.singleClick=!0,!this._checkPrePointerObservable(e,s,Ce.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=Ce.POINTERPICK,o=new Ji(r,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(o,r)}const n=e.pickedMesh._getActionManagerForTrigger();if(n&&!i.ignore){n.processTrigger(7,Ot.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&n.processTrigger(1,Ot.CreateNew(e.pickedMesh,t,e));const r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,Ot.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,Ot.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const n=new Ji(Ce.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,Ce.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,Ce.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=Ce.POINTERTAP:i.doubleClick&&(r=Ce.POINTERDOUBLETAP),r){const o=new Ji(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 Hp(r),this._initActionManager=o=>{if(!this._meshPickProceed){const h=n.skipPointerUpPicking||n._registeredActions===0&&!this._checkForPicking()&&!n.onPointerUp?null:n.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,n.pointerUpPredicate,n.pointerUpFastCheck,n.cameraToUseForPointers,n.pointerUpTrianglePredicate);this._currentPickResult=h,h&&(o=h.hit&&h.pickedMesh?h.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,h,l)=>{if((Date.now()-this._previousStartingPointerTime>pt.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,h.singleClick=!0,h.ignore=!1,this._delayedClicks[o])){const c=this._delayedClicks[o].evt,u=Ce.POINTERTAP,f=new Ji(u,c,this._currentPickResult);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(u)&&n.onPointerObservable.notifyObservers(f,u),this._delayedClicks[o]=null}},this._initClickEvent=(o,h,l,c)=>{var p,g;const u=new Hh;this._currentPickResult=null;let f=null,d=o.hasSpecificMask(Ce.POINTERPICK)||h.hasSpecificMask(Ce.POINTERPICK)||o.hasSpecificMask(Ce.POINTERTAP)||h.hasSpecificMask(Ce.POINTERTAP)||o.hasSpecificMask(Ce.POINTERDOUBLETAP)||h.hasSpecificMask(Ce.POINTERDOUBLETAP);!d&&li&&(f=this._initActionManager(f,u),f&&(d=f.hasPickTriggers));let _=!1;if(d){const m=l.button;if(u.hasSwiped=this._isPointerSwiping(),!u.hasSwiped){let b=!pt.ExclusiveDoubleClickMode;if(b||(b=!o.hasSpecificMask(Ce.POINTERDOUBLETAP)&&!h.hasSpecificMask(Ce.POINTERDOUBLETAP),b&&!li.HasSpecificTrigger(6)&&(f=this._initActionManager(f,u),f&&(b=!f.hasSpecificTrigger(6)))),b)(Date.now()-this._previousStartingPointerTime>pt.DoubleClickDelay||m!==this._previousButtonPressed)&&(u.singleClick=!0,c(u,this._currentPickResult),_=!0);else{const T={evt:l,clickInfo:u,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,m,u,c),pt.DoubleClickDelay)};this._delayedClicks[m]=T}let I=o.hasSpecificMask(Ce.POINTERDOUBLETAP)||h.hasSpecificMask(Ce.POINTERDOUBLETAP);!I&&li.HasSpecificTrigger(6)&&(f=this._initActionManager(f,u),f&&(I=f.hasSpecificTrigger(6))),I&&(m===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>pt.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>pt.DragMovementThreshold),r.isPointerLock&&r._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=xe.MouseWheelX&&o.inputIndex<=xe.MouseWheelZ?Ce.POINTERWHEEL:Ce.POINTERMOVE)||!n.cameraToUseForPointers&&!n.activeCamera)return;if(n.skipPointerMovePicking){this._processPointerMove(new as,o);return}n.pointerMovePredicate||(n.pointerMovePredicate=l=>l.isPickable&&l.isVisible&&l.isReady()&&l.isEnabled()&&(l.enablePointerMoveEvents||n.constantlyUpdateMeshUnderPointer||l._getActionManagerForTrigger()!==null)&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&l.layerMask)!==0));const h=n._registeredActions>0||n.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(h,o)},this._onPointerDown=o=>{var c;const h=this._activePointerIds.indexOf(-1);if(h===-1?this._activePointerIds.push(o.pointerId):this._activePointerIds[h]=o.pointerId,this._activePointerIdsCount++,this._pickedDownMesh=null,this._meshPickProceed=!1,pt.ExclusiveDoubleClickMode){for(let u=0;uu.isPickable&&u.isVisible&&u.isReady()&&u.isEnabled()&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&u.layerMask)!==0)),this._pickedDownMesh=null;let l;n.skipPointerDownPicking||n._registeredActions===0&&!this._checkForPicking()&&!n.onPointerDown?l=new as:l=n.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,n.pointerDownPredicate,n.pointerDownFastCheck,n.cameraToUseForPointers,n.pointerDownTrianglePredicate),this._processPointerDown(l,o)},this._onPointerUp=o=>{const h=this._activePointerIds.indexOf(o.pointerId);h!==-1&&(this._activePointerIds[h]=-1,this._activePointerIdsCount--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),n.preventDefaultOnPointerUp&&s&&(o.preventDefault(),s.focus()),this._initClickEvent(n.onPrePointerObservable,n.onPointerObservable,o,(l,c)=>{if(n.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,o,Ce.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}l.hasSwiped||(l.singleClick&&n.onPrePointerObservable.hasSpecificMask(Ce.POINTERTAP)&&this._checkPrePointerObservable(null,o,Ce.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&n.onPrePointerObservable.hasSpecificMask(Ce.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,Ce.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=u=>u.isPickable&&u.isVisible&&u.isReady()&&u.isEnabled()&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&u.layerMask)!==0)),!this._meshPickProceed&&(li&&li.HasTriggers||this._checkForPicking()||n.onPointerUp)&&this._initActionManager(null,l),c||(c=this._currentPickResult),this._processPointerUp(c,o,l),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{const h=Nn.KEYDOWN;if(n.onPreKeyboardObservable.hasObservers()){const l=new Oh(h,o);if(n.onPreKeyboardObservable.notifyObservers(l,h),l.skipOnKeyboardObservable)return}if(n.onKeyboardObservable.hasObservers()){const l=new Wa(h,o);n.onKeyboardObservable.notifyObservers(l,h)}n.actionManager&&n.actionManager.processTrigger(14,Ot.CreateNewFromScene(n,o))},this._onKeyUp=o=>{const h=Nn.KEYUP;if(n.onPreKeyboardObservable.hasObservers()){const l=new Oh(h,o);if(n.onPreKeyboardObservable.notifyObservers(l,h),l.skipOnKeyboardObservable)return}if(n.onKeyboardObservable.hasObservers()){const l=new Wa(h,o);n.onKeyboardObservable.notifyObservers(l,h)}n.actionManager&&n.actionManager.processTrigger(15,Ot.CreateNewFromScene(n,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===ge.Mouse?o.onInputChangedObservable.add(h=>{this._originMouseEvent=h,h.inputIndex===xe.LeftClick||h.inputIndex===xe.MiddleClick||h.inputIndex===xe.RightClick||h.inputIndex===xe.BrowserBack||h.inputIndex===xe.BrowserForward?t&&o.getInput(h.inputIndex)===1?this._onPointerDown(h):e&&o.getInput(h.inputIndex)===0&&this._onPointerUp(h):i&&(h.inputIndex===xe.Move?this._onPointerMove(h):(h.inputIndex===xe.MouseWheelX||h.inputIndex===xe.MouseWheelY||h.inputIndex===xe.MouseWheelZ)&&this._onPointerMove(h))}):o.deviceType===ge.Touch?o.onInputChangedObservable.add(h=>{h.inputIndex===xe.LeftClick&&(t&&o.getInput(h.inputIndex)===1?(this._onPointerDown(h),this._activePointerIdsCount>1&&(this._isMultiTouchGesture=!0)):e&&o.getInput(h.inputIndex)===0&&(this._onPointerUp(h),this._activePointerIdsCount===0&&(this._isMultiTouchGesture=!1))),i&&h.inputIndex===xe.Move&&this._onPointerMove(h)}):o.deviceType===ge.Keyboard&&o.onInputChangedObservable.add(h=>{h.type==="keydown"?this._onKeyDown(h):h.type==="keyup"&&this._onKeyUp(h)})}),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,Ot.CreateNew(n,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,r=e._getActionManagerForTrigger(9),r&&r.processTrigger(9,Ot.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]}}pt.DragMovementThreshold=10;pt.LongPressDelay=500;pt.DoubleClickDelay=300;pt.ExclusiveDoubleClickMode=!1;class Sc{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Sc._UniqueIdCounter=1;class Xe{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Xe.FALLOFF_DEFAULT=0;Xe.FALLOFF_PHYSICAL=1;Xe.FALLOFF_GLTF=2;Xe.FALLOFF_STANDARD=3;Xe.LIGHTMAP_DEFAULT=0;Xe.LIGHTMAP_SPECULAR=1;Xe.LIGHTMAP_SHADOWSONLY=2;Xe.INTENSITYMODE_AUTOMATIC=0;Xe.INTENSITYMODE_LUMINOUSPOWER=1;Xe.INTENSITYMODE_LUMINOUSINTENSITY=2;Xe.INTENSITYMODE_ILLUMINANCE=3;Xe.INTENSITYMODE_LUMINANCE=4;Xe.LIGHTTYPEID_POINTLIGHT=0;Xe.LIGHTTYPEID_DIRECTIONALLIGHT=1;Xe.LIGHTTYPEID_SPOTLIGHT=2;Xe.LIGHTTYPEID_HEMISPHERICLIGHT=3;class Kp{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Ha;(function(a){a[a.BackwardCompatible=0]="BackwardCompatible",a[a.Intermediate=1]="Intermediate",a[a.Aggressive=2]="Aggressive"})(Ha||(Ha={}));class it{static DefaultMaterialFactory(e){throw ye("StandardMaterial")}static CollisionCoordinatorFactory(){throw ye("DefaultCollisionCoordinator")}get clearColor(){return this._clearColor}set clearColor(e){e!==this._clearColor&&(this._clearColor=e,this.onClearColorChangedObservable.notifyObservers(this._clearColor))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2: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 environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return pt.DragMovementThreshold}static set DragMovementThreshold(e){pt.DragMovementThreshold=e}static get LongPressDelay(){return pt.LongPressDelay}static set LongPressDelay(e){pt.LongPressDelay=e}static get DoubleClickDelay(){return pt.DoubleClickDelay}static set DoubleClickDelay(e){pt.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return pt.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){pt.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,n=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return N.Vector4[0].set(s.x,s.y,s.z,n?-1:1),e&&(i?e.setFloat3(t,N.Vector4[0].x,N.Vector4[0].y,N.Vector4[0].z):e.setVector4(t,N.Vector4[0])),N.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=Ql(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=it.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}get frameGraph(){return this._frameGraph}set frameGraph(e){if(this._frameGraph){this._frameGraph=e,e||(this.customRenderFunction=this._currentCustomRenderFunction);return}this._frameGraph=e,e&&(this._currentCustomRenderFunction=this.customRenderFunction,this.customRenderFunction=this._renderWithFrameGraph)}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=it.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){this._inputManager=new pt(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this._clearColor=new H(.2,.2,.3,1),this.onClearColorChangedObservable=new Z,this.ambientColor=new de(0,0,0),this.environmentIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new Z,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.effectLayers=[],this.sounds=null,this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new Z,this._onDisposeObserver=null,this.onBeforeRenderObservable=new Z,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new Z,this.onAfterRenderCameraObservable=new Z,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new Z,this.onAfterAnimationsObservable=new Z,this.onBeforeDrawPhaseObservable=new Z,this.onAfterDrawPhaseObservable=new Z,this.onReadyObservable=new Z,this.onBeforeCameraRenderObservable=new Z,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new Z,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new Z,this.onAfterActiveMeshesEvaluationObservable=new Z,this.onBeforeParticlesRenderingObservable=new Z,this.onAfterParticlesRenderingObservable=new Z,this.onDataLoadedObservable=new Z,this.onNewCameraAddedObservable=new Z,this.onCameraRemovedObservable=new Z,this.onNewLightAddedObservable=new Z,this.onLightRemovedObservable=new Z,this.onNewGeometryAddedObservable=new Z,this.onGeometryRemovedObservable=new Z,this.onNewTransformNodeAddedObservable=new Z,this.onTransformNodeRemovedObservable=new Z,this.onNewMeshAddedObservable=new Z,this.onMeshRemovedObservable=new Z,this.onNewSkeletonAddedObservable=new Z,this.onSkeletonRemovedObservable=new Z,this.onNewMaterialAddedObservable=new Z,this.onNewMultiMaterialAddedObservable=new Z,this.onMaterialRemovedObservable=new Z,this.onMultiMaterialRemovedObservable=new Z,this.onNewTextureAddedObservable=new Z,this.onTextureRemovedObservable=new Z,this.onBeforeRenderTargetsRenderObservable=new Z,this.onAfterRenderTargetsRenderObservable=new Z,this.onBeforeStepObservable=new Z,this.onAfterStepObservable=new Z,this.onActiveCameraChanged=new Z,this.onActiveCamerasChanged=new Z,this.onBeforeRenderingGroupObservable=new Z,this.onAfterRenderingGroupObservable=new Z,this.onMeshImportedObservable=new Z,this.onAnimationFileImportedObservable=new Z,this._registeredForLateAnimationBindings=new Ms(256),this._pointerPickingConfiguration=new Kp,this.onPrePointerObservable=new Z,this.onPointerObservable=new Z,this.onPreKeyboardObservable=new Z,this.onKeyboardObservable=new Z,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=it.FOGMODE_NONE,this.fogColor=new de(.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._frameGraph=null,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=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Ms(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new ui,this._activeIndices=new ui,this._activeParticles=new ui,this._activeBones=new ui,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 Ut(256),this._processedMaterials=new Ut(256),this._renderTargets=new Ms(256),this._materialsRenderTargets=new Ms(256),this._activeParticleSystems=new Ut(256),this._activeSkeletons=new Ms(32),this._softwareSkinnedMeshes=new Ms(32),this._activeAnimatables=new Array,this._transformMatrix=O.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=_t.Create(),this._beforeClearStage=_t.Create(),this._beforeRenderTargetClearStage=_t.Create(),this._gatherRenderTargetsStage=_t.Create(),this._gatherActiveCameraRenderTargetsStage=_t.Create(),this._isReadyForMeshStage=_t.Create(),this._beforeEvaluateActiveMeshStage=_t.Create(),this._evaluateSubMeshStage=_t.Create(),this._preActiveMeshStage=_t.Create(),this._cameraDrawRenderTargetStage=_t.Create(),this._beforeCameraDrawStage=_t.Create(),this._beforeRenderTargetDrawStage=_t.Create(),this._beforeRenderingGroupDrawStage=_t.Create(),this._beforeRenderingMeshStage=_t.Create(),this._afterRenderingMeshStage=_t.Create(),this._afterRenderingGroupDrawStage=_t.Create(),this._afterCameraDrawStage=_t.Create(),this._afterCameraPostProcessStage=_t.Create(),this._afterRenderTargetDrawStage=_t.Create(),this._afterRenderTargetPostProcessStage=_t.Create(),this._afterRenderStage=_t.Create(),this._pointerMoveStage=_t.Create(),this._pointerDownStage=_t.Create(),this._pointerUpStage=_t.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||Ee.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(Ee._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new Lt(this),ka&&(this.postProcessManager=new ka(this)),St()&&this.attachControl(),this._createUbo(),Ne&&(this._imageProcessingConfiguration=new Ne),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return this._animationRatio!==void 0?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var r,o,h;if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=(o=(r=this.activeCamera)==null?void 0:r.renderPassId)!=null?o:s;let n=!0;for(this._pendingData.length>0&&(n=!1),(h=this.prePassRenderer)==null||h.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&n&&(n=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const f of this._isReadyForMeshStage)f.action(l,c)||(n=!1);if(!e)continue;const u=l.material||this.defaultMaterial;if(u)if(u._storeEffectOnSubMeshes)for(const f of l.subMeshes){const d=f.getMaterial();d&&d.hasRenderTargetTextures&&d.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(d)===-1&&(this._processedMaterials.push(d),this._materialsRenderTargets.concatWithNoDuplicate(d.getRenderTargetTextures()))}else u.hasRenderTargetTextures&&u.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(u)===-1&&(this._processedMaterials.push(u),this._materialsRenderTargets.concatWithNoDuplicate(u.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const l of this.activeCameras)l.isReady(!0)||(n=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(n=!1));for(const l of this.particleSystems)l.isReady()||(n=!1);if(this.layers)for(const l of this.layers)l.isReady()||(n=!1);return i.areAllEffectsReady()||(n=!1),i.currentRenderPassId=s,n}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=bi.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?mi.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=mi.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 fe(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 Sc.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),J.SetImmediate(()=>{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.splice(i,1),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&&t{this.onNewLightAddedObservable.notifyObservers(e)})}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(Xe.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),J.SetImmediate(()=>{this.onNewCameraAddedObservable.notifyObservers(e)}),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),J.SetImmediate(()=>{this.onNewSkeletonAddedObservable.notifyObservers(e)}))}addParticleSystem(e){this._blockEntityCollection||this.particleSystems.push(e)}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||this.animationGroups.push(e)}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),J.SetImmediate(()=>{this.onNewMultiMaterialAddedObservable.notifyObservers(e)}))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneMaterialArray!==-1||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),J.SetImmediate(()=>{this.onNewMaterialAddedObservable.notifyObservers(e)}))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){const t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){const t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;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{this.onNewGeometryAddedObservable.notifyObservers(e)}),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],t===void 0)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){const i=this.geometries[this.geometries.length-1];i&&(this.geometries[t]=i,this._geometriesByUniqueId&&(this._geometriesByUniqueId[i.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const 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 i;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((i=this.activeCamera)==null||i._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const 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.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),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 l of this._gatherActiveCameraRenderTargetsStage)l.action(this._renderTargets);let n=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){J.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let l=0;l0),this._renderId++}for(const l of this._cameraDrawRenderTargetStage)n=l.action(this.activeCamera)||n;this._intermediateRendering=!1}this._engine.currentRenderPassId=(h=(o=(r=e.outputRenderTarget)==null?void 0:r.renderPassId)!=null?o:e.renderPassId)!=null?h:0,n&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(const l of this._beforeCameraDrawStage)l.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&s.snapshotRenderingMode===1&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const l of this._afterCameraDrawStage)l.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const l=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,l)}for(const l of this._afterCameraPostProcessStage)l.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(Ot.CreateNew(t,void 0,r)),(!t.actionManager.hasSpecificTrigger(13,l=>{const c=l.mesh?l.mesh:l;return r===c})||s.trigger===13)&&t._intersectionsInProgress.splice(h,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(it.MinDeltaTime,Math.min(this._engine.getDeltaTime(),it.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 r=0;r0),this._intermediateRendering=!0;for(let h=0;h0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(n=o==null?void 0:o.renderPassId)!=null?n:0,this.activeCamera=o,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const h of this._beforeClearStage)h.action();this._clearFrameBuffer(this.activeCamera);for(const h of this._gatherRenderTargetsStage)h.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let h=0;h0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}}this._checkIntersections();for(const r of this._afterRenderStage)r.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let r=0;r{n.onAnimationEndObservable.clear(),n.onAnimationEnd=null}),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const n of e)n.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(n){U.Error("An error occurred while calling onDisposeObservable!",n)}if(this.detachControl(),this._engine.getInputElement())for(let n=0;nn.dispose(!0)),this._disposeList(this.transformNodes,n=>n.dispose(!0));const i=this.cameras;this._disposeList(i),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),Ee._LastCreatedScene===this&&(this._engine.scenes.length>0?Ee._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:Ee._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.onClearColorChangedObservable.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 ye("Ray")}createPickingRayToRef(e,t,i,s,n,r=!1,o=!1){throw ye("Ray")}createPickingRayInCameraSpace(e,t,i){throw ye("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw ye("Ray")}pick(e,t,i,s,n,r){const o=ye("Ray",!0);return o&&U.Warn(o),new as}pickWithBoundingInfo(e,t,i,s,n){const r=ye("Ray",!0);return r&&U.Warn(r),new as}pickWithRay(e,t,i,s){throw ye("Ray")}multiPick(e,t,i,s,n){throw ye("Ray")}multiPickWithRay(e,t,i){throw ye("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;const s=[];for(const n in e){const r=e[n];ke&&ke.MatchesQuery(r,t)&&(!i||i(r))&&s.push(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)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,n,r,o){const h=Ts(e,t,i,s?this.offlineProvider:void 0,n,r,o);return this._activeRequests.push(h),h.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),h}_loadFileAsync(e,t,i,s,n){return new Promise((r,o)=>{this._loadFile(e,h=>{r(h)},t,i,s,(h,l)=>{o(l)},n)})}_requestFile(e,t,i,s,n,r,o){const h=x0(e,t,i,s?this.offlineProvider:void 0,n,r,o);return this._activeRequests.push(h),h.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),h}_requestFileAsync(e,t,i,s,n){return new Promise((r,o)=>{this._requestFile(e,h=>{r(h)},t,i,s,h=>{o(h)},n)})}_readFile(e,t,i,s,n){const r=Ln(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 ye("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}it.FOGMODE_NONE=0;it.FOGMODE_EXP=1;it.FOGMODE_EXP2=2;it.FOGMODE_LINEAR=3;it.MinDeltaTime=1;it.MaxDeltaTime=1e3;vt("BABYLON.Scene",it);class ve extends bt{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 i,s,n,r;let e=0,t=0;if(this.mode===ve.PERSPECTIVE_CAMERA)this.fovMode===ve.FOVMODE_VERTICAL_FIXED?(t=this.minZ*2*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=this.minZ*2*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const o=this.getEngine().getRenderWidth()/2,h=this.getEngine().getRenderHeight()/2;e=((i=this.orthoRight)!=null?i:o)-((s=this.orthoLeft)!=null?s:-o),t=((n=this.orthoTop)!=null?n:h)-((r=this.orthoBottom)!=null?r:-h)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,s=!0){super(e,i,!1),this._position=v.Zero(),this._upVector=v.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=ve.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new on(0,0,1,1),this.layerMask=268435455,this.fovMode=ve.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ve.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new Z,this.onProjectionMatrixChangedObservable=new Z,this.onAfterCheckInputsObservable=new Z,this.onRestoreStateObservable=new Z,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new O,this._postProcesses=new Array,this._activeMeshes=new Ut(256),this._globalPosition=v.Zero(),this._computedViewMatrix=O.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=O.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=re.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}hasStateStored(){return!!this._stateStored}_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?(U.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 O.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var n,r,o,h,l,c,u,f,d,_,p,g,m,b,I,T,x,y,R;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),s=t.useReverseDepthBuffer;if(this.mode===ve.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let E;i.useRightHandedSystem?E=O.PerspectiveFovRHToRef:E=O.PerspectiveFovLHToRef,E(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ve.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const E=t.getRenderWidth()/2,C=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?O.ObliqueOffCenterRHToRef((n=this.orthoLeft)!=null?n:-E,(r=this.orthoRight)!=null?r:E,(o=this.orthoBottom)!=null?o:-C,(h=this.orthoTop)!=null?h:C,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):O.OrthoOffCenterRHToRef((l=this.orthoLeft)!=null?l:-E,(c=this.orthoRight)!=null?c:E,(u=this.orthoBottom)!=null?u:-C,(f=this.orthoTop)!=null?f:C,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?O.ObliqueOffCenterLHToRef((d=this.orthoLeft)!=null?d:-E,(_=this.orthoRight)!=null?_:E,(p=this.orthoBottom)!=null?p:-C,(g=this.orthoTop)!=null?g:C,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):O.OrthoOffCenterLHToRef((m=this.orthoLeft)!=null?m:-E,(b=this.orthoRight)!=null?b:E,(I=this.orthoBottom)!=null?I:-C,(T=this.orthoTop)!=null?T:C,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=(x=this.oblique)==null?void 0:x.angle,this._cache.obliqueLength=(y=this.oblique)==null?void 0:y.length,this._cache.obliqueOffset=(R=this.oblique)==null?void 0:R.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){const t=this,i=this;return(t.radius||(i.target?v.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?mi.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=mi.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 ye("Ray")}getForwardRayToRef(e,t=100,i,s){throw ye("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!==ve.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=J.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ve.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 O.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=J.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eve._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=ve.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),n=Ae.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 ye("UniversalCamera")};ve.PERSPECTIVE_CAMERA=0;ve.ORTHOGRAPHIC_CAMERA=1;ve.FOVMODE_VERTICAL_FIXED=0;ve.FOVMODE_HORIZONTAL_FIXED=1;ve.RIG_MODE_NONE=0;ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;ve.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;ve.RIG_MODE_STEREOSCOPIC_INTERLACED=14;ve.RIG_MODE_VR=20;ve.RIG_MODE_CUSTOM=22;ve.ForceAttachControlToAlwaysPreventDefault=!1;D([yi("position")],ve.prototype,"_position",void 0);D([yi("upVector")],ve.prototype,"_upVector",void 0);D([B()],ve.prototype,"orthoLeft",null);D([B()],ve.prototype,"orthoRight",null);D([B()],ve.prototype,"orthoBottom",null);D([B()],ve.prototype,"orthoTop",null);D([B()],ve.prototype,"fov",void 0);D([B()],ve.prototype,"projectionPlaneTilt",void 0);D([B()],ve.prototype,"minZ",void 0);D([B()],ve.prototype,"maxZ",void 0);D([B()],ve.prototype,"inertia",void 0);D([B()],ve.prototype,"mode",null);D([B()],ve.prototype,"layerMask",void 0);D([B()],ve.prototype,"fovMode",void 0);D([B()],ve.prototype,"cameraRigMode",void 0);D([B()],ve.prototype,"interaxialDistance",void 0);D([B()],ve.prototype,"isStereoscopicSideBySide",void 0);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;function Xp(a,e,t,i,s,n,r,o){const h=e*A.GetTypeByteLength(t),l=r*e;if(o.length!==l)throw new Error("Output length is not valid");if(t!==A.FLOAT||s!==h){A.ForEach(a,i,s,e,t,l,n,(c,u)=>o[u]=c);return}if(a instanceof Array){const c=i/4;o.set(a,c)}else if(a instanceof ArrayBuffer){const c=new Float32Array(a,i,l);o.set(c)}else{const c=a.byteOffset+i;if(c%4){U.Warn("CopyFloatData: copied misaligned data."),o.set(new Float32Array(a.buffer.slice(c,c+l*4)));return}const f=new Float32Array(a.buffer,c,l);o.set(f)}}class Nt{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 Nt(Nt.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||Ee.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;e{t._rebuild()})}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const n=new A(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(n)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const n=this._meshes,r=n.length;if(s===A.PositionKind){this._totalVertices=t!=null?t:e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const o=this._extend&&this._extend.minimum||new v(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),h=this._extend&&this._extend.maximum||new v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let l=0;l65535);for(const s of this._meshes)s._createGlobalSubMesh(!0),s.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1,s=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),t!=null&&(this._totalVertices=t);for(const n of this._meshes)n._createGlobalSubMesh(!s),n.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._totalIndices!==void 0?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return!t&&(!e||this._meshes.length===1)?i:i.slice()}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){!e||!this._vertexArrayObjects||this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,s=i.indexOf(e);s!==-1&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,i.length===0&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&(e=this.getVerticesData(A.PositionKind),!e))return;this._extend=Ic(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)t===1&&this._vertexBuffers[i].create(),i===A.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());t===1&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const 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 h=0;h0){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);t.setVerticesData(A.UVKind,o,!1)}if(r.uvs2AttrDesc&&r.uvs2AttrDesc.count>0){const o=new Float32Array(e,r.uvs2AttrDesc.offset,r.uvs2AttrDesc.count);t.setVerticesData(A.UV2Kind,o,!1)}if(r.uvs3AttrDesc&&r.uvs3AttrDesc.count>0){const o=new Float32Array(e,r.uvs3AttrDesc.offset,r.uvs3AttrDesc.count);t.setVerticesData(A.UV3Kind,o,!1)}if(r.uvs4AttrDesc&&r.uvs4AttrDesc.count>0){const o=new Float32Array(e,r.uvs4AttrDesc.offset,r.uvs4AttrDesc.count);t.setVerticesData(A.UV4Kind,o,!1)}if(r.uvs5AttrDesc&&r.uvs5AttrDesc.count>0){const o=new Float32Array(e,r.uvs5AttrDesc.offset,r.uvs5AttrDesc.count);t.setVerticesData(A.UV5Kind,o,!1)}if(r.uvs6AttrDesc&&r.uvs6AttrDesc.count>0){const o=new Float32Array(e,r.uvs6AttrDesc.offset,r.uvs6AttrDesc.count);t.setVerticesData(A.UV6Kind,o,!1)}if(r.colorsAttrDesc&&r.colorsAttrDesc.count>0){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),h=[];for(let l=0;l>8),h.push((c&16711680)>>16),h.push(c>>24&255)}t.setVerticesData(A.MatricesIndicesKind,h,!1)}if(r.matricesIndicesExtraAttrDesc&&r.matricesIndicesExtraAttrDesc.count>0){const o=new Int32Array(e,r.matricesIndicesExtraAttrDesc.offset,r.matricesIndicesExtraAttrDesc.count),h=[];for(let l=0;l>8),h.push((c&16711680)>>16),h.push(c>>24&255)}t.setVerticesData(A.MatricesIndicesExtraKind,h,!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 h=0;h>8),r.push((h&16711680)>>16),r.push(h>>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((h&16711680)>>16),r.push(h>>24&255)}t.setVerticesData(A.MatricesIndicesExtraKind,r,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(Nt._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,h=e.matricesWeightsExtra,l=e.numBoneInfluencer,c=o.length;for(let u=0;ul-1)&&(d=l-1),f>.001){const _=1/f;for(let p=0;p<4;p++)o[u+p]*=_;if(h)for(let p=0;p<4;p++)h[u+p]*=_}else d>=4?(h[u+d-4]=1-f,r[u+d-4]=s):(o[u+d]=1-f,n[u+d]=s)}t.setVerticesData(A.MatricesIndicesKind,n),e.matricesWeightsExtra&&t.setVerticesData(A.MatricesIndicesExtraKind,r)}static Parse(e,t,i){const s=new Nt(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,ke&&ke.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new ri(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 fs{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){Ae.Clone(()=>e,this)}serialize(){return Ae.Serialize(this)}parse(e,t,i){Ae.Parse(()=>this,e,t,i)}}D([B()],fs.prototype,"func",null);D([B()],fs.prototype,"funcRef",null);D([B()],fs.prototype,"funcMask",null);D([B()],fs.prototype,"opStencilFail",null);D([B()],fs.prototype,"opDepthFail",null);D([B()],fs.prototype,"opStencilDepthPass",null);D([B()],fs.prototype,"mask",null);D([B()],fs.prototype,"enabled",null);function Xr(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 Mc(a,e,t){var l,c,u,f,d,_;const i=!!((l=a.clipPlane)!=null?l:e.clipPlane),s=!!((c=a.clipPlane2)!=null?c:e.clipPlane2),n=!!((u=a.clipPlane3)!=null?u:e.clipPlane3),r=!!((f=a.clipPlane4)!=null?f:e.clipPlane4),o=!!((d=a.clipPlane5)!=null?d:e.clipPlane5),h=!!((_=a.clipPlane6)!=null?_:e.clipPlane6);i&&t.push("#define CLIPPLANE"),s&&t.push("#define CLIPPLANE2"),n&&t.push("#define CLIPPLANE3"),r&&t.push("#define CLIPPLANE4"),o&&t.push("#define CLIPPLANE5"),h&&t.push("#define CLIPPLANE6")}function Yp(a,e,t){var c,u,f,d,_,p;let i=!1;const s=!!((c=a.clipPlane)!=null?c:e.clipPlane),n=!!((u=a.clipPlane2)!=null?u:e.clipPlane2),r=!!((f=a.clipPlane3)!=null?f:e.clipPlane3),o=!!((d=a.clipPlane4)!=null?d:e.clipPlane4),h=!!((_=a.clipPlane5)!=null?_:e.clipPlane5),l=!!((p=a.clipPlane6)!=null?p:e.clipPlane6);return t.CLIPPLANE!==s&&(t.CLIPPLANE=s,i=!0),t.CLIPPLANE2!==n&&(t.CLIPPLANE2=n,i=!0),t.CLIPPLANE3!==r&&(t.CLIPPLANE3=r,i=!0),t.CLIPPLANE4!==o&&(t.CLIPPLANE4=o,i=!0),t.CLIPPLANE5!==h&&(t.CLIPPLANE5=h,i=!0),t.CLIPPLANE6!==l&&(t.CLIPPLANE6=l,i=!0),i}function Yr(a,e,t){var s,n,r,o,h,l;let i=(s=e.clipPlane)!=null?s:t.clipPlane;qs(a,"vClipPlane",i),i=(n=e.clipPlane2)!=null?n:t.clipPlane2,qs(a,"vClipPlane2",i),i=(r=e.clipPlane3)!=null?r:t.clipPlane3,qs(a,"vClipPlane3",i),i=(o=e.clipPlane4)!=null?o:t.clipPlane4,qs(a,"vClipPlane4",i),i=(h=e.clipPlane5)!=null?h:t.clipPlane5,qs(a,"vClipPlane5",i),i=(l=e.clipPlane6)!=null?l:t.clipPlane6,qs(a,"vClipPlane6",i)}function qs(a,e,t){t&&a.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}const Kh=de.Black(),Xh={NUM_MORPH_INFLUENCERS:0};function B0(a,e,t){if(!a||a.LOGARITHMICDEPTH||a.indexOf&&a.indexOf("LOGARITHMICDEPTH")>=0){const i=t.activeCamera;i.mode===1&&U.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}function L0(a,e,t,i=!1){t&&a.fogEnabled&&(!e||e.applyFog)&&a.fogMode!==0&&(t.setFloat4("vFogInfos",a.fogMode,a.fogStart,a.fogEnd,a.fogDensity),i?(a.fogColor.toLinearSpaceToRef(Kh,a.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",Kh)):t.setColor3("vFogColor",a.fogColor))}function qp(a,e,t){Xh.NUM_MORPH_INFLUENCERS=t,Pc(a,e,Xh)}function Pc(a,e,t){const i=t.NUM_MORPH_INFLUENCERS;if(i>0&&Ee.LastCreatedEngine){const s=Ee.LastCreatedEngine.getCaps().maxVertexAttribs,n=e.morphTargetManager;if(n!=null&&n.isUsingTextureForTargets)return;const r=n&&n.supportsNormals&&t.NORMAL,o=n&&n.supportsTangents&&t.TANGENT,h=n&&n.supportsUVs&&t.UV1;for(let l=0;ls&&U.Error("Cannot add more vertex attributes for mesh "+e.name)}}function N0(a,e=!1){a.push("world0"),a.push("world1"),a.push("world2"),a.push("world3"),e&&(a.push("previousWorld0"),a.push("previousWorld1"),a.push("previousWorld2"),a.push("previousWorld3"))}function U0(a,e){const t=a.morphTargetManager;!a||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function wc(a,e){e.bindToEffect(a,"Scene")}function ms(a,e,t){e._needUVs=!0,e[t]=!0,a.optimizeUVAllocation&&a.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=a.coordinatesIndex+1,e["MAINUV"+(a.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function vs(a,e,t){const i=a.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function Dc(a,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&a.push("bakedVertexAnimationSettingsInstanced")}function Fc(a,e,t){if(!(!e||!a)&&(a.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(a.computeBonesUsingShaders=!1),a.useBones&&a.computeBonesUsingShaders&&a.skeleton)){const i=a.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureWidth")>-1){const s=i.getTransformMatrixTexture(a);e.setTexture("boneSampler",s),e.setFloat("boneTextureWidth",4*(i.bones.length+1))}else{const s=i.getTransformMatrices(a);s&&e.setMatrices("mBones",s)}}}function jp(a,e,t,i,s,n=!0){a._bindLight(e,t,i,s,n)}function $p(a,e,t,i,s=4){const n=Math.min(e.lightSources.length,s);for(let r=0;r0&&(i.addCPUSkinningFallback(0,e),a.push("matricesIndices"),a.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(a.push("matricesIndicesExtra"),a.push("matricesWeightsExtra")))}function Oc(a,e){(e.INSTANCES||e.THIN_INSTANCES)&&N0(a,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&a.push("instanceColor")}function Qp(a,e,t=4,i=0){let s=0;for(let n=0;n0&&(s=i+n,e.addFallback(s,"LIGHT"+n)),a.SHADOWS||(a["SHADOW"+n]&&e.addFallback(i,"SHADOW"+n),a["SHADOWPCF"+n]&&e.addFallback(i,"SHADOWPCF"+n),a["SHADOWPCSS"+n]&&e.addFallback(i,"SHADOWPCSS"+n),a["SHADOWPOISSON"+n]&&e.addFallback(i,"SHADOWPOISSON"+n),a["SHADOWESM"+n]&&e.addFallback(i,"SHADOWESM"+n),a["SHADOWCLOSEESM"+n]&&e.addFallback(i,"SHADOWCLOSEESM"+n));return s++}function Jp(a,e){return e.fogEnabled&&a.applyFog&&e.fogMode!==0}function Bc(a,e,t,i,s,n,r,o=!1){r._areMiscDirty&&(r.LOGARITHMICDEPTH=t,r.POINTSIZE=i,r.FOG=s&&Jp(a,e),r.NONUNIFORMSCALING=a.nonUniformScaling,r.ALPHATEST=n,r.DECAL_AFTER_DETAIL=o)}function eg(a,e,t,i,s=4,n=!1){if(!t._areLightsDirty)return t._needNormals;let r=0;const o={needNormals:t._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(a.lightsEnabled&&!n){for(const l of e.lightSources)if(tg(a,e,l,r,t,i,o),r++,r===s)break}t.SPECULARTERM=o.specularEnabled,t.SHADOWS=o.shadowEnabled;for(let l=r;l0&&(r.shadowEnabled=!0,h.prepareDefines(s,i))}}t.lightmapMode!=Xe.LIGHTMAP_DEFAULT?(r.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+i]=!0,s["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==Xe.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+i]=!1,s["LIGHTMAPNOSPECULAR"+i]=!1)}function Lc(a,e,t,i,s,n=null,r=!1){let o=hg(a,i);n!==!1&&(o=Yp(t,a,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==s&&(i.INSTANCES=s,o=!0),i.THIN_INSTANCES!==r&&(i.THIN_INSTANCES=r,o=!0),o&&i.markAsUnprocessed()}function ig(a,e){if(a.useBones&&a.computeBonesUsingShaders&&a.skeleton){e.NUM_BONE_INFLUENCERS=a.numBoneInfluencers;const t=e.BONETEXTURE!==void 0;if(a.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=a.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;const i=a.getScene().prePassRenderer;if(i&&i.enabled){const s=i.excludedSkinnedMesh.indexOf(a)===-1;e.BONES_VELOCITY_ENABLED=s}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function sg(a,e){const t=a.morphTargetManager;t?(e.MORPHTARGETS_UV=t.supportsUVs&&e.UV1,e.MORPHTARGETS_TANGENT=t.supportsTangents&&e.TANGENT,e.MORPHTARGETS_NORMAL=t.supportsNormals&&e.NORMAL,e.NUM_MORPH_INFLUENCERS=t.numMaxInfluencers||t.numInfluencers,e.MORPHTARGETS=e.NUM_MORPH_INFLUENCERS>0,e.MORPHTARGETS_TEXTURE=t.isUsingTextureForTargets):(e.MORPHTARGETS_UV=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS=!1,e.NUM_MORPH_INFLUENCERS=0)}function ng(a,e){const t=a.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function Nc(a,e,t,i,s=!1,n=!0,r=!0){if(!e._areAttributesDirty&&e._needNormals===e._normals&&e._needUVs===e._uvs)return!1;e._normals=e._needNormals,e._uvs=e._needUVs,e.NORMAL=e._needNormals&&a.isVerticesDataPresent("normal"),e._needNormals&&a.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let o=1;o<=6;++o)e["UV"+o]=e._needUVs?a.isVerticesDataPresent("uv".concat(o===1?"":o)):!1;if(t){const o=a.useVertexColors&&a.isVerticesDataPresent("color");e.VERTEXCOLOR=o,e.VERTEXALPHA=a.hasVertexAlpha&&o&&n}return a.isVerticesDataPresent("instanceColor")&&(a.hasInstances||a.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&ig(a,e),s&&sg(a,e),r&&ng(a,e),!0}function rg(a,e){if(a.activeCamera){const t=e.MULTIVIEW;e.MULTIVIEW=a.activeCamera.outputRenderTarget!==null&&a.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function ag(a,e,t){const i=e.ORDER_INDEPENDENT_TRANSPARENCY,s=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=a.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!a.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||s!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function og(a,e,t){const i=e.PREPASS;if(!e._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:9,define:"PREPASS_LOCAL_POSITION",index:"PREPASS_LOCAL_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:11,define:"PREPASS_VELOCITY_LINEAR",index:"PREPASS_VELOCITY_LINEAR_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:10,define:"PREPASS_SCREENSPACE_DEPTH",index:"PREPASS_SCREENSPACE_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"},{type:8,define:"PREPASS_WORLD_NORMAL",index:"PREPASS_WORLD_NORMAL_INDEX"}];if(a.prePassRenderer&&a.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=a.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=a.prePassRenderer.generateNormalsInWorldSpace,e.PREPASS_COLOR=!0,e.PREPASS_COLOR_INDEX=0;for(let n=0;n{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const n=t||Ee.LastCreatedScene;n&&(this._scene=n,this._dirtyCallbacks={},this._forceGLSL=s,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||J.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Xn(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new fe(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,this._createUniformBuffer(),i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),X.OnEventObservable.notifyObservers(this,1))}_createUniformBuffer(){var t;const e=this.getScene().getEngine();(t=this._uniformBuffer)==null||t.dispose(),e.isWebGPU&&!this._forceGLSL?(this._uniformBuffer=new fe(e,void 0,void 0,this.name,!0),this._shaderLanguage=1):this._uniformBuffer=new fe(this._scene.getEngine(),void 0,void 0,this.name),this._uniformBufferLayoutBuilt=!1}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}_getEffectiveOrientation(e){return this.sideOrientation!==null?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===X.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===X.MATERIAL_OPAQUE||this._transparencyMode===X.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)if(s.getMaterial()===this)for(const n of s._drawWrappers)n&&this._materialContext===n.materialContext&&(n._wasPreviouslyReady=!1,n._wasPreviouslyUsingInstances=null,n._forceRebindOnNextCall=e)}e&&this.markAsDirty(X.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),n=(t==null?this.sideOrientation:t)===X.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(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;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,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,wc(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 s=this._scene.getEngine();this._cachedDepthWriteState=s.getDepthWrite(),s.setDepthWrite(!1)}if(this.disableColorWrite){const s=this._scene.getEngine();this._cachedColorWriteState=s.getColorWrite(),s.setColorWrite(!1)}if(this.depthFunction!==0){const s=this._scene.getEngine();this._cachedDepthFunctionState=s.getDepthFunction()||0,s.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(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),X._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const s of this.pluginManager._plugins){const n=e.pluginManager.getPlugin(s.name);n&&s.copyTo(n)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,s){const n={clipPlane:!1,useInstances:!1,...i},r=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const h=()=>{if(!this._scene||!this._scene.getEngine())return;const l=r.clipPlane;if(n.clipPlane&&(r.clipPlane=new Xt(0,0,0,1)),this._storeEffectOnSubMeshes){let c=!0,u=null;if(e.subMeshes){const f=new vi(0,0,0,0,0,e,void 0,!1,!1);f.materialDefines&&(f.materialDefines._renderId=-1),this.isReadyForSubMesh(e,f,n.useInstances)||(f.effect&&f.effect.getCompilationError()&&f.effect.allFallbacksProcessed()?u=f.effect.getCompilationError():(c=!1,setTimeout(h,16)))}c&&(this.allowShaderHotSwapping=o,u&&s&&s(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(h,16);n.clipPlane&&(r.clipPlane=l)};h()}forceCompilationAsync(e,t){return new Promise((i,s)=>{this.forceCompilation(e,()=>{i()},t,n=>{s(n)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(X._DirtyCallbackArray.length=0,e&X.TextureDirtyFlag&&X._DirtyCallbackArray.push(X._TextureDirtyCallBack),e&X.LightDirtyFlag&&X._DirtyCallbackArray.push(X._LightsDirtyCallBack),e&X.FresnelDirtyFlag&&X._DirtyCallbackArray.push(X._FresnelDirtyCallBack),e&X.AttributesDirtyFlag&&X._DirtyCallbackArray.push(X._AttributeDirtyCallBack),e&X.MiscDirtyFlag&&X._DirtyCallbackArray.push(X._MiscDirtyCallBack),e&X.PrePassDirtyFlag&&X._DirtyCallbackArray.push(X._PrePassDirtyCallBack),X._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(X._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(X._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(X._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(X._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(X._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(X._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(X._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(X._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(X._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(X._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(X._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==0){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(2,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&&(this.releaseVertexArrayObject(r,!0),r.material=null)}else{const n=s.meshes;for(const r of n)r.material===this&&!r.sourceMesh&&(this.releaseVertexArrayObject(r,!0),r.material=null)}this._uniformBuffer.dispose(),this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=Ae.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(!e.customType)e.customType="BABYLON.StandardMaterial";else if(e.customType==="BABYLON.PBRMaterial"&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return U.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const n=J.Instantiate(e.customType).Parse(e,t,i);return n._loadedUniqueId=e.uniqueId,n}static _ParsePlugins(e,t,i,s){var n;if(e.plugins)for(const r in e.plugins){const o=e.plugins[r];let h=(n=t.pluginManager)==null?void 0:n.getPlugin(o.name);if(!h){const l=J.Instantiate("BABYLON."+r);l&&(h=new l(t))}h==null||h.parse(o,i,s)}}}X.TriangleFillMode=0;X.WireFrameFillMode=1;X.PointFillMode=2;X.PointListDrawMode=3;X.LineListDrawMode=4;X.LineLoopDrawMode=5;X.LineStripDrawMode=6;X.TriangleStripDrawMode=7;X.TriangleFanDrawMode=8;X.ClockWiseSideOrientation=0;X.CounterClockWiseSideOrientation=1;X.TextureDirtyFlag=1;X.LightDirtyFlag=2;X.FresnelDirtyFlag=4;X.AttributesDirtyFlag=8;X.MiscDirtyFlag=16;X.PrePassDirtyFlag=32;X.AllDirtyFlag=63;X.MATERIAL_OPAQUE=0;X.MATERIAL_ALPHATEST=1;X.MATERIAL_ALPHABLEND=2;X.MATERIAL_ALPHATESTANDBLEND=3;X.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;X.MATERIAL_NORMALBLENDMETHOD_RNM=1;X.OnEventObservable=new Z;X._AllDirtyCallBack=a=>a.markAllAsDirty();X._ImageProcessingDirtyCallBack=a=>a.markAsImageProcessingDirty();X._TextureDirtyCallBack=a=>a.markAsTexturesDirty();X._FresnelDirtyCallBack=a=>a.markAsFresnelDirty();X._MiscDirtyCallBack=a=>a.markAsMiscDirty();X._PrePassDirtyCallBack=a=>a.markAsPrePassDirty();X._LightsDirtyCallBack=a=>a.markAsLightDirty();X._AttributeDirtyCallBack=a=>a.markAsAttributesDirty();X._FresnelAndMiscDirtyCallBack=a=>{X._FresnelDirtyCallBack(a),X._MiscDirtyCallBack(a)};X._TextureAndMiscDirtyCallBack=a=>{X._TextureDirtyCallBack(a),X._MiscDirtyCallBack(a)};X._DirtyCallbackArray=[];X._RunDirtyCallBacks=a=>{for(const e of X._DirtyCallbackArray)e(a)};D([B()],X.prototype,"id",void 0);D([B()],X.prototype,"uniqueId",void 0);D([B()],X.prototype,"name",void 0);D([B()],X.prototype,"metadata",void 0);D([B()],X.prototype,"checkReadyOnEveryCall",void 0);D([B()],X.prototype,"checkReadyOnlyOnce",void 0);D([B()],X.prototype,"state",void 0);D([B("alpha")],X.prototype,"_alpha",void 0);D([B("backFaceCulling")],X.prototype,"_backFaceCulling",void 0);D([B("cullBackFaces")],X.prototype,"_cullBackFaces",void 0);D([B()],X.prototype,"sideOrientation",void 0);D([B("alphaMode")],X.prototype,"_alphaMode",void 0);D([B()],X.prototype,"_needDepthPrePass",void 0);D([B()],X.prototype,"disableDepthWrite",void 0);D([B()],X.prototype,"disableColorWrite",void 0);D([B()],X.prototype,"forceDepthWrite",void 0);D([B()],X.prototype,"depthFunction",void 0);D([B()],X.prototype,"separateCullingPass",void 0);D([B("fogEnabled")],X.prototype,"_fogEnabled",void 0);D([B()],X.prototype,"pointSize",void 0);D([B()],X.prototype,"zOffset",void 0);D([B()],X.prototype,"zOffsetUnits",void 0);D([B()],X.prototype,"pointsCloud",null);D([B()],X.prototype,"fillMode",null);D([B()],X.prototype,"useLogarithmicDepth",null);D([B()],X.prototype,"transparencyMode",null);class cn extends X{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...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 cn(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,ke&&ke.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(s=>i.subMaterials.push(t.getLastMaterialById(s))),i}}vt("BABYLON.MultiMaterial",cn);class ug{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class Uc{}class fg{constructor(){this.visibleInstances={},this.batchCache=new Yh,this.batchCacheReplacementModeInFrozenMode=new Yh,this.instancesBufferSize=32*16*4}}class Yh{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class dg{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class _g{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 F extends Qe{static _GetDefaultSideOrientation(e){return e||F.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 Z),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new Z),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new Z),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new Z),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new Z),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&e===1||!this._scene.useRightHandedSystem&&e===0}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&this.material.sideOrientation===null||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(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}_copySource(e,t,i=!0){const s=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),I0.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,s.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){const n=e._ranges;for(const r in n)Object.prototype.hasOwnProperty.call(n,r)&&n[r]&&this.createAnimationRange(r,n[r].from,n[r].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,ke&&ke.HasTags(e)&&ke.AddTagsTo(this,ke.GetTags(e,!0)),this.setEnabled(e.isEnabled(!1)),this.parent=e.parent,this.setPivotMatrix(e.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=this.name+"."+e.id,this.material=e.material,!t){const n=e.getDescendants(!0);for(let r=0;r{o&&l&&(this._uniformBuffer?this.transferToEffect(h):l.bindOnlyWorldMatrix(h))},s&&this._copySource(s,n,r),i!==null&&(this.parent=i),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=o=>{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 Z(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 U.Warn("You cannot use a mesh as LOD level twice"),this;const i=new ug(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 h=0;h0||this.hasThinInstances);this.computeWorldMatrix();const r=this.material||s.defaultMaterial;if(r){if(r._storeEffectOnSubMeshes)for(const p of this.subMeshes){const g=p.getMaterial();if(g){if(g._storeEffectOnSubMeshes){if(!g.isReadyForSubMesh(this,p,n))return!1}else if(!g.isReady(this,n))return!1}}else if(!r.isReady(this,n))return!1}const o=i.currentRenderPassId;for(const p of this.lightSources){const g=p.getShadowGenerators();if(!g)continue;const m=g.values();for(let b=m.next();b.done!==!0;b=m.next()){const I=b.value;if(I&&(!((h=I.getShadowMap())!=null&&h.renderList)||(l=I.getShadowMap())!=null&&l.renderList&&((u=(c=I.getShadowMap())==null?void 0:c.renderList)==null?void 0:u.indexOf(this))!==-1)){const x=(f=I.getShadowMap().renderPassIds)!=null?f:[i.currentRenderPassId];for(let y=0;y0){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 vi(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++)vi.CreateFromIndices(0,s,n===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const n=new j;n.set(t,e);const r=this.getScene();new Nt(Nt.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=Nt.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(Nt.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new Nt(Nt.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1,s=!1){if(this._geometry)this._geometry.setIndices(e,t,i,s);else{const n=new j;n.indices=e;const r=this.getScene();new Nt(Nt.RandomId(),r,n,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();let r;if(this._unIndexed)switch(this._getRenderingFillMode(i)){case X.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),n);break;default:r=null;break}else switch(this._getRenderingFillMode(i)){case X.PointFillMode:r=null;break;case X.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),n);break;default:case X.TriangleFillMode:r=this._geometry.getIndexBuffer();break}return this._bindDirect(t,r,s)}_bindDirect(e,t,i=!0){return this._geometry?(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),!i||!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(e,t):this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),this):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!==X.WireFrameFillMode||t==X.PointFillMode?n.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==X.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,h=i.getRenderId(),l=s?o.intermediateDefaultRenderId:o.defaultRenderId;r.visibleInstances[e]=o[h],!r.visibleInstances[e]&&l&&(r.visibleInstances[e]=o[l])}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 b;const r=i.visibleInstances[e._id],o=r?r.length:0,h=this._instanceDataStorage,l=h.instancesBufferSize;let c=h.instancesBuffer,u=h.instancesPreviousBuffer;const d=(o+1)*16*4;for(;h.instancesBufferSizex._distanceToCamera>y._distanceToCamera?-1:x._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||n<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const o=this._getInstancesRenderList(e._id,!!i);if(o.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const h=s.getEngine();let l=0,c=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(l=s.activeCamera.maxZ,c=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const u=e.getRenderingMesh(),f=o.hardwareInstancedRendering[e._id]||u.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,d=this._instanceDataStorage,_=e.getMaterial();if(!_)return c&&(c.maxZ=l,s.updateTransformMatrix(!0)),this;if(!d.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==_){if(_._storeEffectOnSubMeshes){if(!_.isReadyForSubMesh(this,e,f))return c&&(c.maxZ=l,s.updateTransformMatrix(!0)),this}else if(!_.isReady(this,f))return c&&(c.maxZ=l,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=_}else if(_._storeEffectOnSubMeshes&&!((C=e._drawWrapper)!=null&&C._wasPreviouslyReady)||!_._storeEffectOnSubMeshes&&!_._getDrawWrapper()._wasPreviouslyReady)return c&&(c.maxZ=l,s.updateTransformMatrix(!0)),this;t&&h.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let p;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?p=e._drawWrapper:p=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const g=(S=p==null?void 0:p.effect)!=null?S:null;for(const w of s._beforeRenderingMeshStage)w.action(this,e,o,g);if(!p||!g)return c&&(c.maxZ=l,s.updateTransformMatrix(!0)),this;const m=i||this;let b;if(!d.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this._internalMeshDataInfo._effectiveMaterial.sideOrientation!==null||this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)){const w=m._getWorldMatrixDeterminant();b=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),w<0&&(b=b===X.ClockWiseSideOrientation?X.CounterClockWiseSideOrientation:X.ClockWiseSideOrientation),d.sideOrientation=b}else b=d.sideOrientation;const I=this._internalMeshDataInfo._effectiveMaterial._preBind(p,b);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&h.setDepthWrite(!0);const T=this._internalMeshDataInfo._effectiveMaterial,x=T.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),f||this._bind(e,g,x,!1);const y=m.getWorldMatrix();T._storeEffectOnSubMeshes?T.bindForSubMesh(y,this,e):T.bind(y,this),!T.backFaceCulling&&T.separateCullingPass&&(h.setState(!0,T.zOffset,!1,!I,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._processRendering(this,e,g,x,o,f,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),h.setState(!0,T.zOffset,!1,I,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,g,x,o,f,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const w of s._afterRenderingMeshStage)w.action(this,e,o,g);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),c&&(c.maxZ=l,s.updateTransformMatrix(!0)),s.performancePriority===2&&!d.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(A.MatricesWeightsKind)&&(this.isVerticesDataPresent(A.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(A.MatricesWeightsKind),t=e.length;for(let i=0;im&&s++,x!==0&&I++,b+=x,m=x}if(l[I]++,I>r&&(r=I),b===0)n++;else{const T=1/b;let x=0;for(let y=0;yc&&o++}}const u=this.skeleton.bones.length,f=this.getVerticesData(A.MatricesIndicesKind),d=this.getVerticesData(A.MatricesIndicesExtraKind);let _=0;for(let g=0;g=u||b<0)&&_++}const p="Number of Weights = "+i/4+"\nMaximum influences = "+r+"\nMissing Weights = "+n+"\nNot Sorted = "+s+"\nNot Normalized = "+o+"\nWeightCounts = ["+l+"]\nNumber of bones = "+u+"\nBad Bone Indices = "+_;return{skinned:!0,valid:n===0&&o===0&&_===0,report:p}}_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 J.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=[];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 f=u.width,d=u.height,p=this.getEngine().createCanvas(f,d).getContext("2d");p.drawImage(u,0,0);const g=p.getImageData(0,0,f,d).data;this.applyDisplacementMapFromBuffer(g,f,d,t,i,n,r,o),s&&s(this)};return J.LoadImage(e,c,h||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,n,r,o,h=!1){if(!this.isVerticesDataPresent(A.PositionKind)||!this.isVerticesDataPresent(A.NormalKind)||!this.isVerticesDataPresent(A.UVKind))return U.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(A.PositionKind,!0,!0),c=this.getVerticesData(A.NormalKind),u=this.getVerticesData(A.UVKind);let f=v.Zero();const d=v.Zero(),_=oe.Zero();r=r||oe.Zero(),o=o||new oe(1,1);for(let p=0;p{var l;return!((l=this.getVertexBuffer(h))!=null&&l.getIsInstanced())}),i=this.getIndices(),s={},n=(h,l)=>{const c=new Float32Array(i.length*l);let u=0;for(let f=0;f{const o=s.length-1-r,h=s[o];for(let l=0;l{for(let o=0;o-1&&(s._waitingMorphTargetManagerId=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,l=h?this.getVerticesData(A.MatricesIndicesExtraKind):null,c=h?this.getVerticesData(A.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),f=v.Zero(),d=new O,_=new O;let p=0,g;for(let m=0;m0&&(O.FromFloat32ArrayToRefScaled(u,Math.floor(r[p+g]*16),b,_),d.addToSelf(_));if(h)for(g=0;g<4;g++)b=c[p+g],b>0&&(O.FromFloat32ArrayToRefScaled(u,Math.floor(l[p+g]*16),b,_),d.addToSelf(_));v.TransformCoordinatesFromFloatsToRef(i._sourcePositions[m],i._sourcePositions[m+1],i._sourcePositions[m+2],d,f),f.toArray(s,m),t&&(v.TransformNormalFromFloatsToRef(i._sourceNormals[m],i._sourceNormals[m+1],i._sourceNormals[m+2],d,f),f.toArray(n,m)),d.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?F.MinMax(e):e;return v.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,n,r){return F0(F._MergeMeshesCoroutine(e,t,i,s,n,r,!1))}static MergeMeshesAsync(e,t=!0,i,s,n,r){return Ep(F._MergeMeshesCoroutine(e,t,i,s,n,r,!0),Ip())}static*_MergeMeshesCoroutine(e,t=!0,i,s,n,r,o){if(e=e.filter(Boolean),e.length===0)return null;let h;if(!i){let R=0;for(h=0;h=65536)return U.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 l=new Array,c=new Array,u=new Array,f=e[0].sideOrientation;for(h=0;h{const E=R.computeWorldMatrix(!0);return{vertexData:j.ExtractFromMesh(R,!1,!1),transform:E}},{vertexData:p,transform:g}=_(d);o&&(yield);const m=new Array(e.length-1);for(let R=1;R{throw ye("GroundMesh")};F._GoldbergMeshParser=(a,e)=>{throw ye("GoldbergMesh")};F._LinesMeshParser=(a,e)=>{throw ye("LinesMesh")};F._GreasedLineMeshParser=(a,e)=>{throw ye("GreasedLineMesh")};F._GreasedLineRibbonMeshParser=(a,e)=>{throw ye("GreasedLineRibbonMesh")};F._TrailMeshParser=(a,e)=>{throw ye("TrailMesh")};vt("BABYLON.Mesh",F);class pg{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===Ce.POINTERDOWN){this._isPointerDown=!0;return}i.type===Ce.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=bi.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,this._lastFrameTime=null}resetLastInteractionTime(e){this._lastInteractionTime=e!=null?e:bi.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}}wi.EASINGMODE_EASEIN=0;wi.EASINGMODE_EASEOUT=1;wi.EASINGMODE_EASEINOUT=2;class gg extends wi{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 mg extends wi{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}class qr{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new qr(this.name,this.from,this.to)}}const vg=Object.freeze(new re(0,0,0,0)),bg=Object.freeze(v.Zero()),xg=Object.freeze(oe.Zero()),yg=Object.freeze(hi.Zero()),Tg=Object.freeze(de.Black()),Ag=Object.freeze(new H(0,0,0,0)),Ii={key:0,repeatCount:0,loopMode:2};class te{static _PrepareAnimation(e,t,i,s,n,r,o,h){let l;if(!isNaN(parseFloat(n))&&isFinite(n)?l=te.ANIMATIONTYPE_FLOAT:n instanceof re?l=te.ANIMATIONTYPE_QUATERNION:n instanceof v?l=te.ANIMATIONTYPE_VECTOR3:n instanceof oe?l=te.ANIMATIONTYPE_VECTOR2:n instanceof de?l=te.ANIMATIONTYPE_COLOR3:n instanceof H?l=te.ANIMATIONTYPE_COLOR4:n instanceof hi&&(l=te.ANIMATIONTYPE_SIZE),l==null)return null;const c=new te(e,t,i,l,o),u=[{frame:0,value:n},{frame:s,value:r}];return c.setKeys(u),h!==void 0&&c.setEasingFunction(h),c}static CreateAnimation(e,t,i,s){const n=new te(e+"Animation",e,i,t,te.ANIMATIONLOOPMODE_CONSTANT);return n.setEasingFunction(s),n}static CreateAndStartAnimation(e,t,i,s,n,r,o,h,l,c,u){const f=te._PrepareAnimation(e,i,s,n,r,o,h,l);return!f||(t.getScene&&(u=t.getScene()),!u)?null:u.beginDirectAnimation(t,[f],0,n,f.loopMode===1,1,c)}static CreateAndStartHierarchyAnimation(e,t,i,s,n,r,o,h,l,c,u){const f=te._PrepareAnimation(e,s,n,r,o,h,l,c);return f?t.getScene().beginDirectHierarchyAnimation(t,i,[f],0,r,f.loopMode===1,1,u):null}static CreateMergeAndStartAnimation(e,t,i,s,n,r,o,h,l,c){const u=te._PrepareAnimation(e,i,s,n,r,o,h,l);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,n,u.loopMode===1,1,c)):null}static MakeAnimationAdditive(e,t,i,s=!1,n){var b,I;let r;typeof t=="object"?r=t:r={referenceFrame:t!=null?t:0,range:i,cloneOriginalAnimation:s,clonedAnimationName:n};let o=e;if(r.cloneOriginalAnimation&&(o=e.clone(),o.name=r.clonedAnimationName||o.name),!o._keys.length)return o;const h=r.referenceFrame&&r.referenceFrame>=0?r.referenceFrame:0;let l=0;const c=o._keys[0];let u=o._keys.length-1;const f=o._keys[u],d={referenceValue:c.value,referencePosition:N.Vector3[0],referenceQuaternion:N.Quaternion[0],referenceScaling:N.Vector3[1],keyPosition:N.Vector3[2],keyQuaternion:N.Quaternion[1],keyScaling:N.Vector3[3]};let _=c.frame,p=f.frame;if(r.range){const T=o.getRange(r.range);T&&(_=T.from,p=T.to)}else _=(b=r.fromFrame)!=null?b:_,p=(I=r.toFrame)!=null?I:p;if(_!==c.frame&&(l=o.createKeyForFrame(_)),p!==f.frame&&(u=o.createKeyForFrame(p)),o._keys.length===1){const T=o._getKeyValue(o._keys[0]);d.referenceValue=T.clone?T.clone():T}else if(h<=c.frame){const T=o._getKeyValue(c.value);d.referenceValue=T.clone?T.clone():T}else if(h>=f.frame){const T=o._getKeyValue(f.value);d.referenceValue=T.clone?T.clone():T}else{Ii.key=0;const T=o._interpolate(h,Ii);d.referenceValue=T.clone?T.clone():T}o.dataType===te.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():o.dataType===te.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace());let g=Number.MAX_VALUE;const m=r.clipKeys?[]:null;for(let T=l;T<=u;T++){let x=o._keys[T];if((m||r.cloneOriginalAnimation)&&(x={frame:x.frame,value:x.value.clone?x.value.clone():x.value,inTangent:x.inTangent,outTangent:x.outTangent,interpolation:x.interpolation,lockedTangent:x.lockedTangent},m&&(g===Number.MAX_VALUE&&(g=x.frame),x.frame-=g,m.push(x))),!(T&&o.dataType!==te.ANIMATIONTYPE_FLOAT&&x.value===c.value))switch(o.dataType){case te.ANIMATIONTYPE_MATRIX:x.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),O.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,x.value);break;case te.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(x.value,x.value);break;case te.ANIMATIONTYPE_VECTOR2:case te.ANIMATIONTYPE_VECTOR3:case te.ANIMATIONTYPE_COLOR3:case te.ANIMATIONTYPE_COLOR4:x.value.subtractToRef(d.referenceValue,x.value);break;case te.ANIMATIONTYPE_SIZE:x.value.width-=d.referenceValue.width,x.value.height-=d.referenceValue.height;break;default:x.value-=d.referenceValue}}return m&&o.setKeys(m,!0),o}static TransitionTo(e,t,i,s,n,r,o,h=null){if(o<=0)return i[e]=t,h&&h(),null;const l=n*(o/1e3);r.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(r);const c=s.beginAnimation(i,0,l,!1);return c.onAnimationEnd=h,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?te.ANIMATIONLOOPMODE_CYCLE:n,this.uniqueId=te._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 s=this._keys,n=s.length;let r=t.key;for(;r>=0&&e=s[r+1].frame;)++r;if(t.key=r,r<0)return i?void 0:this._getKeyValue(s[0].value);if(r+1>n-1)return i?void 0:this._getKeyValue(s[n-1].value);const o=s[r],h=s[r+1];if(i&&(e===o.frame||e===h.frame))return;const l=this._getKeyValue(o.value),c=this._getKeyValue(h.value);if(o.interpolation===1)return h.frame>e?l:c;const u=o.outTangent!==void 0&&h.inTangent!==void 0,f=h.frame-o.frame;let d=(e-o.frame)/f;const _=o.easingFunction||this.getEasingFunction();switch(_!==null&&(d=_.ease(d)),this.dataType){case te.ANIMATIONTYPE_FLOAT:{const g=u?this.floatInterpolateFunctionWithTangents(l,o.outTangent*f,c,h.inTangent*f,d):this.floatInterpolateFunction(l,c,d);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return g;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return((p=t.offsetValue)!=null?p:0)*t.repeatCount+g}break}case te.ANIMATIONTYPE_QUATERNION:{const g=u?this.quaternionInterpolateFunctionWithTangents(l,o.outTangent.scale(f),c,h.inTangent.scale(f),d):this.quaternionInterpolateFunction(l,c,d);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return g;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.addInPlace((t.offsetValue||vg).scale(t.repeatCount))}return g}case te.ANIMATIONTYPE_VECTOR3:{const g=u?this.vector3InterpolateFunctionWithTangents(l,o.outTangent.scale(f),c,h.inTangent.scale(f),d):this.vector3InterpolateFunction(l,c,d);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return g;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||bg).scale(t.repeatCount))}break}case te.ANIMATIONTYPE_VECTOR2:{const g=u?this.vector2InterpolateFunctionWithTangents(l,o.outTangent.scale(f),c,h.inTangent.scale(f),d):this.vector2InterpolateFunction(l,c,d);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return g;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||xg).scale(t.repeatCount))}break}case te.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,c,d);case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,c,d).add((t.offsetValue||yg).scale(t.repeatCount))}break}case te.ANIMATIONTYPE_COLOR3:{const g=u?this.color3InterpolateFunctionWithTangents(l,o.outTangent.scale(f),c,h.inTangent.scale(f),d):this.color3InterpolateFunction(l,c,d);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return g;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||Tg).scale(t.repeatCount))}break}case te.ANIMATIONTYPE_COLOR4:{const g=u?this.color4InterpolateFunctionWithTangents(l,o.outTangent.scale(f),c,h.inTangent.scale(f),d):this.color4InterpolateFunction(l,c,d);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return g;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||Ag).scale(t.repeatCount))}break}case te.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return te.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,c,d,t.workValue):l;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}break}}return 0}matrixInterpolateFunction(e,t,i,s){return te.AllowMatrixDecomposeForInterpolation?s?(O.DecomposeLerpToRef(e,t,i,s),s):O.DecomposeLerp(e,t,i):s?(O.LerpToRef(e,t,i,s),s):O.Lerp(e,t,i)}clone(){const e=new te(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){Ii.key=0;const t=this._interpolate(e,Ii,!0);if(!t)return this._keys[Ii.key].frame===e?Ii.key:Ii.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Ii.key+1,0,i),Ii.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s=2&&(h=o.values[1]),o.values.length>=3&&(l=o.values[2]),o.values.length>=4&&(c=o.values[3]);break;case te.ANIMATIONTYPE_QUATERNION:if(n=re.FromArray(o.values),o.values.length>=8){const f=re.FromArray(o.values.slice(4,8));f.equals(re.Zero())||(h=f)}if(o.values.length>=12){const f=re.FromArray(o.values.slice(8,12));f.equals(re.Zero())||(l=f)}o.values.length>=13&&(c=o.values[12]);break;case te.ANIMATIONTYPE_MATRIX:n=O.FromArray(o.values),o.values.length>=17&&(c=o.values[16]);break;case te.ANIMATIONTYPE_COLOR3:n=de.FromArray(o.values),o.values[3]&&(h=de.FromArray(o.values[3])),o.values[4]&&(l=de.FromArray(o.values[4])),o.values[5]&&(c=o.values[5]);break;case te.ANIMATIONTYPE_COLOR4:n=H.FromArray(o.values),o.values[4]&&(h=H.FromArray(o.values[4])),o.values[5]&&(l=H.FromArray(o.values[5])),o.values[6]&&(c=H.FromArray(o.values[6]));break;case te.ANIMATIONTYPE_VECTOR3:default:n=v.FromArray(o.values),o.values[3]&&(h=v.FromArray(o.values[3])),o.values[4]&&(l=v.FromArray(o.values[4])),o.values[5]&&(c=o.values[5]);break}const u={};u.frame=o.frame,u.value=n,h!=null&&(u.inTangent=h),l!=null&&(u.outTangent=l),c!=null&&(u.interpolation=c),s.push(u)}if(t.setKeys(s),e.ranges)for(r=0;r{const n=new Ft;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=[];for(const h of r)o.push(this.Parse(h));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 Ft;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=[];for(const h of r.animations){const l=this.Parse(h);l.snippetId=e,o.push(l)}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()})}}te._UniqueIdGenerator=0;te.AllowMatricesInterpolation=!1;te.AllowMatrixDecomposeForInterpolation=!0;te.SnippetUrl="https://snippet.babylonjs.com";te.ANIMATIONTYPE_FLOAT=0;te.ANIMATIONTYPE_VECTOR3=1;te.ANIMATIONTYPE_QUATERNION=2;te.ANIMATIONTYPE_MATRIX=3;te.ANIMATIONTYPE_COLOR3=4;te.ANIMATIONTYPE_COLOR4=7;te.ANIMATIONTYPE_VECTOR2=5;te.ANIMATIONTYPE_SIZE=6;te.ANIMATIONLOOPMODE_RELATIVE=0;te.ANIMATIONLOOPMODE_CYCLE=1;te.ANIMATIONLOOPMODE_CONSTANT=2;te.ANIMATIONLOOPMODE_YOYO=4;te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;te.CreateFromSnippetAsync=te.ParseFromSnippetAsync;vt("BABYLON.Animation",te);bt._AnimationRangeFactory=(a,e,t)=>new qr(a,e,t);class Ns{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&&(i.computeWorldMatrix(!0),i.getBoundingInfo)){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||(Ns.EasingFunction.setEasingMode(Ns.EasingMode),this._radiusBounceTransition=te.CreateAnimation("radius",te.ANIMATIONTYPE_FLOAT,60,Ns.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=te.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()}}Ns.EasingFunction=new gg(.3);Ns.EasingMode=wi.EASINGMODE_EASEOUT;class jt{constructor(){this.onTargetFramingAnimationEndObservable=new Z,this._mode=jt.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();jt.EasingFunction.setEasingMode(jt.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===Ce.POINTERDOWN){this._isPointerDown=!0;return}i.type===Ce.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&i.getBoundingInfo&&this.zoomOnMesh(i,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const 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),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===jt.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=bi.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=te.CreateAnimation("beta",te.ANIMATIONTYPE_FLOAT,60,jt.EasingFunction));const s=te.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});s&&this._animatables.push(s)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=bi.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}}jt.EasingFunction=new mg;jt.EasingMode=wi.EASINGMODE_EASEINOUT;jt.IgnoreBoundsSizeMode=0;jt.FitFrustumSidesMode=1;bt.AddNodeConstructor("TargetCamera",(a,e)=>()=>new wt(a,v.Zero(),e));class wt extends ve{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 oe(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new re,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=O.Zero(),this._camMatrix=O.Zero(),this._cameraTransformMatrix=O.Zero(),this._cameraRotationMatrix=O.Zero(),this._referencePoint=new v(0,0,1),this._transformedReferencePoint=v.Zero(),this._deferredPositionUpdate=new v,this._deferredRotationQuaternionUpdate=new re,this._deferredRotationUpdate=new v,this._deferredUpdated=!1,this._deferOnly=!1,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 re(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+=Le),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),O.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&&re.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(N.Matrix[0]),v.TransformNormalToRef(this.cameraDirection,N.Matrix[0],N.Vector3[0]),this._deferredPositionUpdate.addInPlace(N.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,this.noRotationConstraint||(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(re.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))),t&&(Math.abs(this.cameraDirection.x){}}add(e){const t=e.getSimpleName();if(this.attached[t]){U.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=ve.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=Ae.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=Un[i];if(s){const n=t[i],r=Ae.Parse(()=>new s,n,null);this.add(r)}}}else for(const i in this.attached){const s=Un[this.attached[i].getClassName()];if(s){const n=Ae.Parse(()=>new s,e,null);this.remove(this.attached[i]),this.add(n)}}}}class kc{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=J.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 u,f;const h=o.event,l=h.pointerType==="touch";if(o.type!==Ce.POINTERMOVE&&this.buttons.indexOf(h.button)===-1)return;const c=h.target;if(this._altKey=h.altKey,this._ctrlKey=h.ctrlKey,this._metaKey=h.metaKey,this._shiftKey=h.shiftKey,this._buttonsPressed=h.buttons,t.isPointerLock){const d=h.movementX,_=h.movementY;this.onTouch(null,d,_),this._pointA=null,this._pointB=null}else{if(o.type!==Ce.POINTERDOWN&&o.type!==Ce.POINTERDOUBLETAP&&l&&((u=this._pointA)==null?void 0:u.pointerId)!==h.pointerId&&((f=this._pointB)==null?void 0:f.pointerId)!==h.pointerId)return;if(o.type===Ce.POINTERDOWN&&(this._currentActiveButton===-1||l)){try{c==null||c.setPointerCapture(h.pointerId)}catch{}if(this._pointA===null)this._pointA={x:h.clientX,y:h.clientY,pointerId:h.pointerId,type:h.pointerType};else if(this._pointB===null)this._pointB={x:h.clientX,y:h.clientY,pointerId:h.pointerId,type:h.pointerType};else return;this._currentActiveButton===-1&&!l&&(this._currentActiveButton=h.button),this.onButtonDown(h),e||(h.preventDefault(),i&&i.focus())}else if(o.type===Ce.POINTERDOUBLETAP)this.onDoubleTap(h.pointerType);else if(o.type===Ce.POINTERUP&&(this._currentActiveButton===h.button||l)){try{c==null||c.releasePointerCapture(h.pointerId)}catch{}l||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==h.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==h.pointerId?this._pointB=null:this._pointA=this._pointB=null,(s!==0||n)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,n,null),s=0,n=null),this._currentActiveButton=-1,this.onButtonUp(h),e||h.preventDefault()}else if(o.type===Ce.POINTERMOVE){if(e||h.preventDefault(),this._pointA&&this._pointB===null){const d=h.clientX-this._pointA.x,_=h.clientY-this._pointA.y;this._pointA.x=h.clientX,this._pointA.y=h.clientY,this.onTouch(this._pointA,d,_)}else if(this._pointA&&this._pointB){const d=this._pointA.pointerId===h.pointerId?this._pointA:this._pointB;d.x=h.clientX,d.y=h.clientY;const _=this._pointA.x-this._pointB.x,p=this._pointA.y-this._pointB.y,g=_*_+p*p,m={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:h.pointerId,type:o.type};this.onMultiTouch(this._pointA,this._pointB,s,g,n,m),n=m,s=g}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ce.POINTERDOWN|Ce.POINTERUP|Ce.POINTERMOVE|Ce.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,n=null,this.onLostFocus()},this._contextMenuBind=o=>this.onContextMenu(o),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const r=this.camera.getScene().getEngine().getHostWindow();r&&J.RegisterTopRootEvents(r,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&J.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(){}}D([B()],kc.prototype,"buttons",void 0);class Qt extends kc{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||Qt.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(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Qt.MinimumRadiusForPinch=.001;D([B()],Qt.prototype,"buttons",void 0);D([B()],Qt.prototype,"angularSensibilityX",void 0);D([B()],Qt.prototype,"angularSensibilityY",void 0);D([B()],Qt.prototype,"pinchPrecision",void 0);D([B()],Qt.prototype,"pinchDeltaPercentage",void 0);D([B()],Qt.prototype,"useNaturalPinchZoom",void 0);D([B()],Qt.prototype,"pinchZoom",void 0);D([B()],Qt.prototype,"panningSensibility",void 0);D([B()],Qt.prototype,"multiTouchPanning",void 0);D([B()],Qt.prototype,"multiTouchPanAndZoom",void 0);Un.ArcRotateCameraPointersInput=Qt;class Fi{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=J.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===Nn.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=J.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Ce.POINTERWHEEL)return;const i=t.event;let s=0;const n=i.deltaMode===jn.DOM_DELTA_LINE?Ig: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,h=this.camera.inertialRadiusOffset+s;for(let l=0;l<20&&Math.abs(h)>.001;l++)o-=h,h*=this.camera.inertia;o=ht(o,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(r,o)}}else s=r/(this.wheelPrecision*40);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Ce.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=Xt.FromPositionAndNormal(e.target,t)}_getPosition(){var n;const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,O.Identity(),e,!1);(e.targetScreenOffset.x!==0||e.targetScreenOffset.y!==0)&&(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=v.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=(n=i.intersectsPlane(this._hitPlane))!=null?n:0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){var h,l;const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const c=(h=t.lowerRadiusLimit)!=null?h:0;t.radius-(t.inertialRadiusOffset+e)/ic&&(e=(t.radius-c)*i-t.inertialRadiusOffset)}const n=e/i/t.radius,r=this._getPosition(),o=N.Vector3[6];r.subtractToRef(t.target,o),o.scaleInPlace(n),o.scaleInPlace(i),this._inertialPanning.addInPlace(o),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)()=>new tt(a,0,0,1,v.Zero(),e));class tt extends wt{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 O,this._upToYMatrix=new O,this._upVector=v.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){O.RotationAlignToRef(v.UpReadOnly,this._upVector,this._yToUpMatrix),O.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 Ns,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 jt,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 pg,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=oe.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._viewMatrix=new O,this.panningAxis=new v(1,1,0),this._transformedDirection=new v,this.mapPanning=!1,this._progressiveRestore=!1,this.onMeshTargetChangedObservable=new Z,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=(h,l,c=null)=>{c?(this.setPosition(l),this.onCollide&&this.onCollide(c)):this._previousPosition.copyFrom(this._position);const u=Math.cos(this.alpha),f=Math.sin(this.alpha),d=Math.cos(this.beta);let _=Math.sin(this.beta);_===0&&(_=1e-4);const p=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*u*_,this.radius*d,this.radius*f*_),p.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let g=this.upVector;this.allowUpsideDown&&this.beta<0&&(g=g.clone(),g=g.negate()),this._computeViewMatrix(this._position,p,g),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 Eg(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=oe.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._goalAlpha=this.alpha,this._storedBeta=this._goalBeta=this.beta,this._storedRadius=this._goalRadius=this.radius,this._storedTarget=this._goalTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this._goalTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return this.hasStateStored()&&this.restoreStateInterpolationFactor>Le&&this.restoreStateInterpolationFactor<1?(this.interpolateTo(this._storedAlpha,this._storedBeta,this._storedRadius,this._storedTarget,this._storedTargetScreenOffset),!0):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}interpolateTo(e=this.alpha,t=this.beta,i=this.radius,s=this.target,n=this.targetScreenOffset){var r,o,h,l,c,u;this._progressiveRestore=!0,this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,e=ht(e,(r=this.lowerAlphaLimit)!=null?r:-1/0,(o=this.upperAlphaLimit)!=null?o:1/0),t=ht(t,(h=this.lowerBetaLimit)!=null?h:-1/0,(l=this.upperBetaLimit)!=null?l:1/0),i=ht(i,(c=this.lowerRadiusLimit)!=null?c:-1/0,(u=this.upperRadiusLimit)!=null?u:1/0),this._goalAlpha=e,this._goalBeta=t,this._goalRadius=i,this._goalTarget=s,this._goalTargetScreenOffset=n}_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=J.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._progressiveRestore){const e=this._scene.getEngine().getDeltaTime()/1e3,t=1-Math.pow(2,-e/this.restoreStateInterpolationFactor);this.setTarget(v.Lerp(this.getTarget(),this._goalTarget,t)),re.RotationAlphaBetaGammaToRef(this._goalAlpha,this._goalBeta,0,N.Quaternion[0]),re.RotationAlphaBetaGammaToRef(this.alpha,this.beta,0,N.Quaternion[1]),re.SlerpToRef(N.Quaternion[1],N.Quaternion[0],t,N.Quaternion[2]),N.Quaternion[2].normalize(),N.Quaternion[2].toAlphaBetaGammaToRef(N.Vector3[0]),this.alpha=N.Vector3[0].x,this.beta=N.Vector3[0].y,this.radius+=(this._goalRadius-this.radius)*t,oe.LerpToRef(this.targetScreenOffset,this._goalTargetScreenOffset,t,this.targetScreenOffset),(v.DistanceSquared(this.getTarget(),this._goalTarget)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:s,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const 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=F.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),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=F.MinMax(n),s=v.Distance(i.min,i.max)}else{const n=e;i=n,s=n.distance}this._target=F.Center(i),t||(this.maxZ=s*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ve.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ve.RIG_MODE_STEREOSCOPIC_INTERLACED:case ve.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const s=new tt(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 ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ve.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ve.RIG_MODE_STEREOSCOPIC_INTERLACED:case ve.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle;break}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=v.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),h=o*r,c=s*.5*i,u=c*Math.sqrt(1+1/(h*h)),f=c*Math.sqrt(1+1/(o*o));return Math.max(u,f)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}D([B()],tt.prototype,"alpha",void 0);D([B()],tt.prototype,"beta",void 0);D([B()],tt.prototype,"radius",void 0);D([B()],tt.prototype,"overrideCloneAlphaBetaRadius",void 0);D([yi("target")],tt.prototype,"_target",void 0);D([ic("targetHost")],tt.prototype,"_targetHost",void 0);D([B()],tt.prototype,"inertialAlphaOffset",void 0);D([B()],tt.prototype,"inertialBetaOffset",void 0);D([B()],tt.prototype,"inertialRadiusOffset",void 0);D([B()],tt.prototype,"lowerAlphaLimit",void 0);D([B()],tt.prototype,"upperAlphaLimit",void 0);D([B()],tt.prototype,"lowerBetaLimit",void 0);D([B()],tt.prototype,"upperBetaLimit",void 0);D([B()],tt.prototype,"lowerRadiusLimit",void 0);D([B()],tt.prototype,"upperRadiusLimit",void 0);D([B()],tt.prototype,"inertialPanningX",void 0);D([B()],tt.prototype,"inertialPanningY",void 0);D([B()],tt.prototype,"pinchToPanMaxDistance",void 0);D([B()],tt.prototype,"panningDistanceLimit",void 0);D([yi()],tt.prototype,"panningOriginTarget",void 0);D([B()],tt.prototype,"panningInertia",void 0);D([B()],tt.prototype,"zoomToMouseLocation",null);D([B()],tt.prototype,"zoomOnFactor",void 0);D([tc()],tt.prototype,"targetScreenOffset",void 0);D([B()],tt.prototype,"allowUpsideDown",void 0);D([B()],tt.prototype,"useInputToRestoreState",void 0);D([B()],tt.prototype,"restoreStateInterpolationFactor",void 0);vt("BABYLON.ArcRotateCamera",tt);class Fe extends bt{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())}getViewMatrix(e){return null}getProjectionMatrix(e,t){return null}constructor(e,t){super(e,t,!1),this.diffuse=new de(1,1,1),this.specular=new de(1,1,1),this.falloffType=Fe.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=Fe.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 fe(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,s,n=!0){var h;const r=e.toString();let o=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+r),this._renderId!==t.getRenderId()||this._lastUseSpecular!==s||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=s;const l=this.getScaledIntensity();this.transferToEffect(i,r),this.diffuse.scaleToRef(l,Js.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",Js.Color3[0],this.range,r),s&&(this.specular.scaleToRef(l,Js.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",Js.Color3[1],this.radius,r)),o=!0}if(this.transferTexturesToEffect(i,r),t.shadowsEnabled&&this.shadowEnabled&&n){const l=(h=this.getShadowGenerator(t.activeCamera))!=null?h:this.getShadowGenerator();l&&(l.bindShadowLight(r,i),o=!0)}o?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=Fe.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=Ae.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=Ae.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)})),Ae.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const s=bt.Construct("Light_Type_"+e,t,i);return s||null}static Parse(e,t){const i=Fe.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=Ae.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===Fe.INTENSITYMODE_AUTOMATIC&&(t===Fe.LIGHTTYPEID_DIRECTIONALLIGHT?i=Fe.INTENSITYMODE_ILLUMINANCE:i=Fe.INTENSITYMODE_LUMINOUSINTENSITY),t){case Fe.LIGHTTYPEID_POINTLIGHT:case Fe.LIGHTTYPEID_SPOTLIGHT:switch(i){case Fe.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Fe.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Fe.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case Fe.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Fe.INTENSITYMODE_ILLUMINANCE:e=1;break;case Fe.INTENSITYMODE_LUMINANCE:{let s=this.radius;s=Math.max(s,.001),e=2*Math.PI*(1-Math.cos(s));break}}break;case Fe.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Fe.FALLOFF_DEFAULT=Xe.FALLOFF_DEFAULT;Fe.FALLOFF_PHYSICAL=Xe.FALLOFF_PHYSICAL;Fe.FALLOFF_GLTF=Xe.FALLOFF_GLTF;Fe.FALLOFF_STANDARD=Xe.FALLOFF_STANDARD;Fe.LIGHTMAP_DEFAULT=Xe.LIGHTMAP_DEFAULT;Fe.LIGHTMAP_SPECULAR=Xe.LIGHTMAP_SPECULAR;Fe.LIGHTMAP_SHADOWSONLY=Xe.LIGHTMAP_SHADOWSONLY;Fe.INTENSITYMODE_AUTOMATIC=Xe.INTENSITYMODE_AUTOMATIC;Fe.INTENSITYMODE_LUMINOUSPOWER=Xe.INTENSITYMODE_LUMINOUSPOWER;Fe.INTENSITYMODE_LUMINOUSINTENSITY=Xe.INTENSITYMODE_LUMINOUSINTENSITY;Fe.INTENSITYMODE_ILLUMINANCE=Xe.INTENSITYMODE_ILLUMINANCE;Fe.INTENSITYMODE_LUMINANCE=Xe.INTENSITYMODE_LUMINANCE;Fe.LIGHTTYPEID_POINTLIGHT=Xe.LIGHTTYPEID_POINTLIGHT;Fe.LIGHTTYPEID_DIRECTIONALLIGHT=Xe.LIGHTTYPEID_DIRECTIONALLIGHT;Fe.LIGHTTYPEID_SPOTLIGHT=Xe.LIGHTTYPEID_SPOTLIGHT;Fe.LIGHTTYPEID_HEMISPHERICLIGHT=Xe.LIGHTTYPEID_HEMISPHERICLIGHT;D([ls()],Fe.prototype,"diffuse",void 0);D([ls()],Fe.prototype,"specular",void 0);D([B()],Fe.prototype,"falloffType",void 0);D([B()],Fe.prototype,"intensity",void 0);D([B()],Fe.prototype,"range",null);D([B()],Fe.prototype,"intensityMode",null);D([B()],Fe.prototype,"radius",null);D([B()],Fe.prototype,"_renderPriority",void 0);D([je("_reorderLightsInScene")],Fe.prototype,"renderPriority",void 0);D([B("shadowEnabled")],Fe.prototype,"_shadowEnabled",void 0);D([B("excludeWithLayerMask")],Fe.prototype,"_excludeWithLayerMask",void 0);D([B("includeOnlyWithLayerMask")],Fe.prototype,"_includeOnlyWithLayerMask",void 0);D([B("lightmapMode")],Fe.prototype,"_lightmapMode",void 0);class Zn extends Fe{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=O.Identity(),this._projectionMatrix=O.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=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,Gt.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=O.Identity()),O.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=N.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),v.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(v.Dot(t,v.Up()))===1&&(t.z=1e-13);const s=N.Vector3[1];return i.addToRef(t,s),O.LookAtLHToRef(i,s,v.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e!=null?e:this._viewMatrix,t!=null?t:[]),this._projectionMatrix}}D([yi()],Zn.prototype,"position",null);D([yi()],Zn.prototype,"direction",null);D([B()],Zn.prototype,"shadowMinZ",null);D([B()],Zn.prototype,"shadowMaxZ",null);bt.AddNodeConstructor("Light_Type_0",(a,e)=>()=>new jr(a,v.Zero(),e));class jr extends Zn{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 Fe.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;O.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}}D([B()],jr.prototype,"shadowAngle",null);vt("BABYLON.PointLight",jr);class qh{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||t.prePassRenderer.getIndex(11)!==-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 k0{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))e[0]!=="_"&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)this._keys.indexOf(e)===-1&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e))}_setDefaultValue(e){var s,n,r,o,h;const t=(r=(n=(s=this._externalProperties)==null?void 0:s[e])==null?void 0:n.type)!=null?r:typeof this[e],i=(h=(o=this._externalProperties)==null?void 0:o[e])==null?void 0:h.default;switch(t){case"number":this[e]=i!=null?i:0;break;case"string":this[e]=i!=null?i:"";break;default:this[e]=i!=null?i:!1;break}}toString(){let e="";for(let t=0;tthis._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;sthis._handlePluginEvent(s,n),this._plugins.push(e),this._plugins.sort((s,n)=>s.priority-n.priority),this._codeInjectionPoints={};const i={};i[xs._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const s of this._plugins)s.collectDefines(i),this._collectPointNames("vertex",s.getCustomCode("vertex",this._material.shaderLanguage)),this._collectPointNames("fragment",s.getCustomCode("fragment",this._material.shaderLanguage));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&s.uniforms.push(...this._uniformList),this._samplerList.length>0&&s.samplers.push(...this._samplerList),this._uboList.length>0&&s.uniformBuffersNames.push(...this._uboList),s.customCode=this._injectCustomCode(s,s.customCode);break}case 8:{const s=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];const n=this._material.shaderLanguage===1;for(const r of this._plugins){const o=r.getUniforms(this._material.shaderLanguage);if(o){if(o.ubo)for(const h of o.ubo){if(h.size&&h.type){const l=(i=h.arraySize)!=null?i:0;if(s.ubo.addUniform(h.name,h.size,l),n){let c;switch(h.type){case"mat4":c="mat4x4f";break;case"float":c="f32";break;default:c="".concat(h.type,"f");break}this._uboDeclaration+="uniform ".concat(h.name,": ").concat(c).concat(l>0?"[".concat(l,"]"):"",";\n")}else this._uboDeclaration+="".concat(h.type," ").concat(h.name).concat(l>0?"[".concat(l,"]"):"",";\n")}this._uniformList.push(h.name)}o.vertex&&(this._vertexDeclaration+=o.vertex+"\n"),o.fragment&&(this._fragmentDeclaration+=o.fragment+"\n")}r.getSamplers(this._samplerList),r.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{var o,h;t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const n=(o=this._codeInjectionPoints)==null?void 0:o[i];if(!n)return s;let r=null;for(let l in n){let c="";for(const u of this._activePlugins){let f=(h=u.getCustomCode(i,this._material.shaderLanguage))==null?void 0:h[l];f&&(u.resolveIncludes&&(r===null&&(r={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Me.GetShadersRepository(0),includesShadersStore:Me.GetIncludesShadersStore(0),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}),r.isFragment=i==="fragment",Dn(f,r,d=>f=d)),c+=f+"\n")}if(c.length>0)if(l.charAt(0)==="!"){l=l.substring(1);let u="g";if(l.charAt(0)==="!")u="",l=l.substring(1);else{const p=Cg.exec(l);p&&p.length>=2&&(u=p[1],l=l.substring(u.length+1))}u.indexOf("g")<0&&(u+="g");const f=s,d=new RegExp(l,u);let _=d.exec(f);for(;_!==null;){let p=c;for(let g=0;g<_.length;++g)p=p.replace("$"+g,_[g]);s=s.replace(_[0],p),_=d.exec(f)}}else{const u="#define "+l;s=s.replace(u,"\n"+c+"\n"+u)}}return s}}}xs._MaterialPluginClassToMainDefine={};xs._MaterialPluginCounter=0;Ee.OnEnginesDisposedObservable.add(()=>{Mg()});const Sg=[];let jh=null;function Mg(){Sg.length=0,X.OnEventObservable.remove(jh),jh=null}class gn{isCompatible(e){switch(e){case 0:return!0;default:return!1}}_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,n=!0,r=!1,o=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=o,e.pluginManager||(e.pluginManager=new xs(e),e.onDisposeObservable.add(()=>{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,t=0){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(e=0){return{}}copyTo(e){Ae.Clone(()=>e,this)}serialize(){return Ae.Serialize(this)}parse(e,t,i){Ae.Parse(()=>this,e,t,i)}}D([B()],gn.prototype,"name",void 0);D([B()],gn.prototype,"priority",void 0);D([B()],gn.prototype,"resolveIncludes",void 0);D([B()],gn.prototype,"registerForExtraEvents",void 0);vt("BABYLON.MaterialPluginBase",gn);class Pg extends k0{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Ks extends gn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new Pg,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=X.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&&De.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&&De.DetailTextureEnabled&&this._isEnabled?(ms(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&&De.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),vs(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&De.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&((t=this._texture)==null||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}D([_i("detailTexture"),je("_markAllSubMeshesAsTexturesDirty")],Ks.prototype,"texture",void 0);D([B()],Ks.prototype,"diffuseBlendLevel",void 0);D([B()],Ks.prototype,"roughnessBlendLevel",void 0);D([B()],Ks.prototype,"bumpLevel",void 0);D([B(),je("_markAllSubMeshesAsTexturesDirty")],Ks.prototype,"normalBlendMethod",void 0);D([B(),je("_markAllSubMeshesAsTexturesDirty")],Ks.prototype,"isEnabled",void 0);var $h;(function(a){a[a.Zero=0]="Zero",a[a.One=1]="One",a[a.MaxViewZ=2]="MaxViewZ"})($h||($h={}));class ti{static CreateConfiguration(e){return ti._Configurations[e]={defines:{},previousWorldMatrices:{},previousViewProjection:O.Zero(),currentViewProjection:O.Zero(),previousBones:{},lastUpdateFrameId:-1,excludedSkinnedMesh:[]},ti._Configurations[e]}static DeleteConfiguration(e){delete ti._Configurations[e]}static GetConfiguration(e){return ti._Configurations[e]}static AddUniformsAndSamplers(e,t){e.push("previousWorld","previousViewProjection","mPreviousBones")}static MarkAsDirty(e,t){for(const i of t)if(i.subMeshes)for(const s of i.subMeshes)s._removeDrawWrapper(e)}static PrepareDefines(e,t,i){if(!i._arePrePassDirty)return;const s=ti._Configurations[e];if(!s)return;i.PREPASS=!0,i.PREPASS_COLOR=!1,i.PREPASS_COLOR_INDEX=-1;let n=0;for(let r=0;r{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,i=!1){super(e,t,void 0,i||ee.ForceGLSL),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 de(0,0,0),this.diffuseColor=new de(1,1,1),this.specularColor=new de(1,1,1),this.emissiveColor=new de(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._shadersLoaded=!1,this._renderTargets=new Ut(16),this._worldViewProjectionMatrix=O.Zero(),this._globalAmbientColor=new de(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Ks(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new qh,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),ee.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),ee.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 ee.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||ee.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled}needAlphaTesting(){return this._forceAlphaTest?!0:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===X.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==X.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new wg(this._eventInfo.defineNames));const n=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();r._needNormals=eg(n,e,r,!0,this._maxSimultaneousLights,this._disableLighting),rg(n,r);const h=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(og(n,r,this.canRenderToMRT&&!h),ag(n,r,h),ti.PrepareDefines(o.currentRenderPassId,e,r),r._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r._needUVs=!1;for(let c=1;c<=6;++c)r["MAINUV"+c]=!1;if(n.texturesEnabled){if(r.DIFFUSEDIRECTUV=0,r.BUMPDIRECTUV=0,r.AMBIENTDIRECTUV=0,r.OPACITYDIRECTUV=0,r.EMISSIVEDIRECTUV=0,r.SPECULARDIRECTUV=0,r.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&ee.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())ms(this._diffuseTexture,r,"DIFFUSE");else return!1;else r.DIFFUSE=!1;if(this._ambientTexture&&ee.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())ms(this._ambientTexture,r,"AMBIENT");else return!1;else r.AMBIENT=!1;if(this._opacityTexture&&ee.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())ms(this._opacityTexture,r,"OPACITY"),r.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else r.OPACITY=!1;if(this._reflectionTexture&&ee.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(r._needNormals=!0,r.REFLECTION=!0,r.ROUGHNESS=this._roughness>0,r.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,r.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===ie.INVCUBIC_MODE,r.REFLECTIONMAP_3D=this._reflectionTexture.isCube,r.REFLECTIONMAP_OPPOSITEZ=r.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,r.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case ie.EXPLICIT_MODE:r.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case ie.PLANAR_MODE:r.setReflectionMode("REFLECTIONMAP_PLANAR");break;case ie.PROJECTION_MODE:r.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case ie.SKYBOX_MODE:r.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case ie.SPHERICAL_MODE:r.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case ie.EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case ie.FIXED_EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case ie.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case ie.CUBIC_MODE:case ie.INVCUBIC_MODE:default:r.setReflectionMode("REFLECTIONMAP_CUBIC");break}r.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else r.REFLECTION=!1,r.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&ee.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())ms(this._emissiveTexture,r,"EMISSIVE");else return!1;else r.EMISSIVE=!1;if(this._lightmapTexture&&ee.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())ms(this._lightmapTexture,r,"LIGHTMAP"),r.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,r.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else r.LIGHTMAP=!1;if(this._specularTexture&&ee.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())ms(this._specularTexture,r,"SPECULAR"),r.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else r.SPECULAR=!1;if(n.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&ee.BumpTextureEnabled){if(this._bumpTexture.isReady())ms(this._bumpTexture,r,"BUMP"),r.PARALLAX=this._useParallax,r.PARALLAX_RHS=n.useRightHandedSystem,r.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;r.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else r.BUMP=!1,r.PARALLAX=!1,r.PARALLAX_RHS=!1,r.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&ee.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())r._needUVs=!0,r.REFRACTION=!0,r.REFRACTIONMAP_3D=this._refractionTexture.isCube,r.RGBDREFRACTION=this._refractionTexture.isRGBD,r.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else r.REFRACTION=!1;r.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else r.DIFFUSE=!1,r.AMBIENT=!1,r.OPACITY=!1,r.REFLECTION=!1,r.EMISSIVE=!1,r.LIGHTMAP=!1,r.BUMP=!1,r.REFRACTION=!1;r.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),r.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,r.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,r.SPECULAROVERALPHA=this._useSpecularOverAlpha,r.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,r.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,r.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}r._areFresnelDirty&&(ee.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(r.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,r.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,r.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,r.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,r.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,r.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,r._needNormals=!0,r.FRESNEL=!0):r.FRESNEL=!1),Bc(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,r,this._applyDecalMapAfterDetailMap),Lc(n,o,this,r,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=r,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Nc(e,r,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(r.isDirty){const c=r._areLightsDisposed;r.markAsProcessed();const u=new G0;r.REFLECTION&&u.addFallback(0,"REFLECTION"),r.SPECULAR&&u.addFallback(0,"SPECULAR"),r.BUMP&&u.addFallback(0,"BUMP"),r.PARALLAX&&u.addFallback(1,"PARALLAX"),r.PARALLAX_RHS&&u.addFallback(1,"PARALLAX_RHS"),r.PARALLAXOCCLUSION&&u.addFallback(0,"PARALLAXOCCLUSION"),r.SPECULAROVERALPHA&&u.addFallback(0,"SPECULAROVERALPHA"),r.FOG&&u.addFallback(1,"FOG"),r.POINTSIZE&&u.addFallback(0,"POINTSIZE"),r.LOGARITHMICDEPTH&&u.addFallback(0,"LOGARITHMICDEPTH"),Qp(r,u,this._maxSimultaneousLights),r.SPECULARTERM&&u.addFallback(0,"SPECULARTERM"),r.DIFFUSEFRESNEL&&u.addFallback(1,"DIFFUSEFRESNEL"),r.OPACITYFRESNEL&&u.addFallback(2,"OPACITYFRESNEL"),r.REFLECTIONFRESNEL&&u.addFallback(3,"REFLECTIONFRESNEL"),r.EMISSIVEFRESNEL&&u.addFallback(4,"EMISSIVEFRESNEL"),r.FRESNEL&&u.addFallback(4,"FRESNEL"),r.MULTIVIEW&&u.addFallback(0,"MULTIVIEW");const f=[A.PositionKind];r.NORMAL&&f.push(A.NormalKind),r.TANGENT&&f.push(A.TangentKind);for(let y=1;y<=6;++y)r["UV"+y]&&f.push("uv".concat(y===1?"":y));r.VERTEXCOLOR&&f.push(A.ColorKind),Zp(f,e,r,u),Oc(f,r),Pc(f,e,r),Dc(f,e,r);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"],p=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],g=["Material","Scene","Mesh"],m={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=u,this._eventInfo.fallbackRank=0,this._eventInfo.defines=r,this._eventInfo.uniforms=_,this._eventInfo.attributes=f,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=g,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(128,this._eventInfo),ti.AddUniformsAndSamplers(_,p),qh.AddUniforms(_),Ne&&(Ne.PrepareUniforms(_,r),Ne.PrepareSamplers(p,r)),cg({uniformsNames:_,uniformBuffersNames:g,samplers:p,defines:r,maxSimultaneousLights:this._maxSimultaneousLights}),Xr(_);const b={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,_,g,p,r,f,b));const I=r.toString(),T=t.effect;let x=n.getEngine().createEffect(d,{attributes:f,uniformsNames:_,uniformBuffersNames:g,samplers:p,defines:I,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:m,processFinalCode:b.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:r.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this._shaderLanguage===1?await Promise.all([Oe(()=>import("./default.vertex-Caa9iT2n.js"),__vite__mapDeps([20,21,22,23,24,25,26,27,3,4,5,6,7,8,9,10])),Oe(()=>import("./default.fragment-DzWBfowK.js"),__vite__mapDeps([28,21,29,26,30,31,3,4,5,6,7,8,9,10]))]):await Promise.all([Oe(()=>import("./default.vertex-B3P8Ow0L.js"),__vite__mapDeps([32,33,34,35,36,37,38,3,4,5,6,7,8,9,10])),Oe(()=>import("./default.fragment-BQ0cgw4g.js"),__vite__mapDeps([39,33,34,35,3,4,5,6,7,8,9,10]))]),this._shadersLoaded=!0}},o);if(this._eventInfo.customCode=void 0,x)if(this._onEffectCreatedObservable&&(Aa.effect=x,Aa.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Aa)),this.allowShaderHotSwapping&&T&&!x.isReady()){if(x=T,r.markAsUnprocessed(),l=this.isFrozen,c)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(x,r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!l,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var l;const s=this.getScene(),n=i.materialDefines;if(!n)return;const r=i.effect;if(!r)return;this._activeEffect=r,t.getMeshUniformBuffer().bindToEffect(r,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(r,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),ti.Bind(s.getEngine().currentRenderPassId,this._activeEffect,t,e),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,r,i,t.visibility);Fc(t,r);const h=this._uniformBuffer;if(o){if(this.bindViewProjection(r),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(ee.FresnelEnabled&&n.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 de(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))),s.texturesEnabled){if(this._diffuseTexture&&ee.DiffuseTextureEnabled&&(h.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),vs(this._diffuseTexture,h,"diffuse")),this._ambientTexture&&ee.AmbientTextureEnabled&&(h.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),vs(this._ambientTexture,h,"ambient")),this._opacityTexture&&ee.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),vs(this._opacityTexture,h,"opacity")),this._hasAlphaChannel()&&h.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&ee.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&&ee.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),vs(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&ee.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),vs(this._lightmapTexture,h,"lightmap")),this._specularTexture&&ee.SpecularTextureEnabled&&(h.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),vs(this._specularTexture,h,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&ee.BumpTextureEnabled&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),vs(this._bumpTexture,h,"bump"),s._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&&ee.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),h.updateColor4("vSpecularColor",this.specularColor,this.specularPower),h.updateColor3("vEmissiveColor",ee.EmissiveTextureEnabled?this.emissiveColor:de.BlackReadOnly),h.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&ee.DiffuseTextureEnabled&&r.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&ee.AmbientTextureEnabled&&r.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&ee.OpacityTextureEnabled&&r.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&ee.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?r.setTexture("reflectionCubeSampler",this._reflectionTexture):r.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&ee.EmissiveTextureEnabled&&r.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&ee.LightmapTextureEnabled&&r.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&ee.SpecularTextureEnabled&&r.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&ee.BumpTextureEnabled&&r.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&ee.RefractionTextureEnabled&&(this._refractionTexture.isCube?r.setTexture("refractionCubeSampler",this._refractionTexture):r.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(r),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Yr(r,this,s),this.bindEyePosition(r)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&$p(s,t,r,n,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==it.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(r),L0(s,t,r),n.NUM_MORPH_INFLUENCERS&&U0(t,r),n.BAKED_VERTEX_ANIMATION_TEXTURE&&((l=t.bakedVertexAnimationManager)==null||l.bind(r,n.INSTANCES)),this.useLogarithmicDepth&&B0(n,r,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),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,h,l,c,u;t&&((i=this._diffuseTexture)==null||i.dispose(),(s=this._ambientTexture)==null||s.dispose(),(n=this._opacityTexture)==null||n.dispose(),(r=this._reflectionTexture)==null||r.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(h=this._specularTexture)==null||h.dispose(),(l=this._bumpTexture)==null||l.dispose(),(c=this._lightmapTexture)==null||c.dispose(),(u=this._refractionTexture)==null||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=Ae.Clone(()=>new ee(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=Ae.Parse(()=>new ee(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),X._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return De.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){De.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return De.DetailTextureEnabled}static set DetailTextureEnabled(e){De.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return De.AmbientTextureEnabled}static set AmbientTextureEnabled(e){De.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return De.OpacityTextureEnabled}static set OpacityTextureEnabled(e){De.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return De.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){De.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return De.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){De.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return De.SpecularTextureEnabled}static set SpecularTextureEnabled(e){De.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return De.BumpTextureEnabled}static set BumpTextureEnabled(e){De.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return De.LightmapTextureEnabled}static set LightmapTextureEnabled(e){De.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return De.RefractionTextureEnabled}static set RefractionTextureEnabled(e){De.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return De.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){De.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return De.FresnelEnabled}static set FresnelEnabled(e){De.FresnelEnabled=e}}ee.ForceGLSL=!1;D([_i("diffuseTexture")],ee.prototype,"_diffuseTexture",void 0);D([je("_markAllSubMeshesAsTexturesAndMiscDirty")],ee.prototype,"diffuseTexture",void 0);D([_i("ambientTexture")],ee.prototype,"_ambientTexture",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"ambientTexture",void 0);D([_i("opacityTexture")],ee.prototype,"_opacityTexture",void 0);D([je("_markAllSubMeshesAsTexturesAndMiscDirty")],ee.prototype,"opacityTexture",void 0);D([_i("reflectionTexture")],ee.prototype,"_reflectionTexture",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"reflectionTexture",void 0);D([_i("emissiveTexture")],ee.prototype,"_emissiveTexture",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"emissiveTexture",void 0);D([_i("specularTexture")],ee.prototype,"_specularTexture",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"specularTexture",void 0);D([_i("bumpTexture")],ee.prototype,"_bumpTexture",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"bumpTexture",void 0);D([_i("lightmapTexture")],ee.prototype,"_lightmapTexture",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"lightmapTexture",void 0);D([_i("refractionTexture")],ee.prototype,"_refractionTexture",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"refractionTexture",void 0);D([ls("ambient")],ee.prototype,"ambientColor",void 0);D([ls("diffuse")],ee.prototype,"diffuseColor",void 0);D([ls("specular")],ee.prototype,"specularColor",void 0);D([ls("emissive")],ee.prototype,"emissiveColor",void 0);D([B()],ee.prototype,"specularPower",void 0);D([B("useAlphaFromDiffuseTexture")],ee.prototype,"_useAlphaFromDiffuseTexture",void 0);D([je("_markAllSubMeshesAsTexturesAndMiscDirty")],ee.prototype,"useAlphaFromDiffuseTexture",void 0);D([B("useEmissiveAsIllumination")],ee.prototype,"_useEmissiveAsIllumination",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useEmissiveAsIllumination",void 0);D([B("linkEmissiveWithDiffuse")],ee.prototype,"_linkEmissiveWithDiffuse",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"linkEmissiveWithDiffuse",void 0);D([B("useSpecularOverAlpha")],ee.prototype,"_useSpecularOverAlpha",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useSpecularOverAlpha",void 0);D([B("useReflectionOverAlpha")],ee.prototype,"_useReflectionOverAlpha",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useReflectionOverAlpha",void 0);D([B("disableLighting")],ee.prototype,"_disableLighting",void 0);D([je("_markAllSubMeshesAsLightsDirty")],ee.prototype,"disableLighting",void 0);D([B("useObjectSpaceNormalMap")],ee.prototype,"_useObjectSpaceNormalMap",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useObjectSpaceNormalMap",void 0);D([B("useParallax")],ee.prototype,"_useParallax",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useParallax",void 0);D([B("useParallaxOcclusion")],ee.prototype,"_useParallaxOcclusion",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useParallaxOcclusion",void 0);D([B()],ee.prototype,"parallaxScaleBias",void 0);D([B("roughness")],ee.prototype,"_roughness",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"roughness",void 0);D([B()],ee.prototype,"indexOfRefraction",void 0);D([B()],ee.prototype,"invertRefractionY",void 0);D([B()],ee.prototype,"alphaCutOff",void 0);D([B("useLightmapAsShadowmap")],ee.prototype,"_useLightmapAsShadowmap",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useLightmapAsShadowmap",void 0);D([Kn("diffuseFresnelParameters")],ee.prototype,"_diffuseFresnelParameters",void 0);D([je("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"diffuseFresnelParameters",void 0);D([Kn("opacityFresnelParameters")],ee.prototype,"_opacityFresnelParameters",void 0);D([je("_markAllSubMeshesAsFresnelAndMiscDirty")],ee.prototype,"opacityFresnelParameters",void 0);D([Kn("reflectionFresnelParameters")],ee.prototype,"_reflectionFresnelParameters",void 0);D([je("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"reflectionFresnelParameters",void 0);D([Kn("refractionFresnelParameters")],ee.prototype,"_refractionFresnelParameters",void 0);D([je("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"refractionFresnelParameters",void 0);D([Kn("emissiveFresnelParameters")],ee.prototype,"_emissiveFresnelParameters",void 0);D([je("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"emissiveFresnelParameters",void 0);D([B("useReflectionFresnelFromSpecular")],ee.prototype,"_useReflectionFresnelFromSpecular",void 0);D([je("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"useReflectionFresnelFromSpecular",void 0);D([B("useGlossinessFromSpecularMapAlpha")],ee.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useGlossinessFromSpecularMapAlpha",void 0);D([B("maxSimultaneousLights")],ee.prototype,"_maxSimultaneousLights",void 0);D([je("_markAllSubMeshesAsLightsDirty")],ee.prototype,"maxSimultaneousLights",void 0);D([B("invertNormalMapX")],ee.prototype,"_invertNormalMapX",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"invertNormalMapX",void 0);D([B("invertNormalMapY")],ee.prototype,"_invertNormalMapY",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"invertNormalMapY",void 0);D([B("twoSidedLighting")],ee.prototype,"_twoSidedLighting",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"twoSidedLighting",void 0);D([B("applyDecalMapAfterDetailMap")],ee.prototype,"_applyDecalMapAfterDetailMap",void 0);D([je("_markAllSubMeshesAsMiscDirty")],ee.prototype,"applyDecalMapAfterDetailMap",void 0);vt("BABYLON.StandardMaterial",ee);it.DefaultMaterialFactory=a=>new ee("default material",a);function Dg(a,e){const t=e.method||"GET";return new Promise((i,s)=>{const n=new Ft;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const r={};if(e.responseHeaders)for(const o of e.responseHeaders)r[o]=n.getResponseHeader(o)||"";i({response:n.response,headerValues:r})}else s("Unable to fetch data from ".concat(a,". Error code: ").concat(n.status))}),n.open(t,a),n.send()})}var Zh;(function(a){a[a.Clean=0]="Clean",a[a.Stop=1]="Stop",a[a.Sync=2]="Sync",a[a.NoSync=3]="NoSync"})(Zh||(Zh={}));function Fg(a){return!!a.createPlugin}function Og(a){return!!a.name}const Vc=new Z,Wi={};let Ra=!1;function $r(){return Wi[".babylon"]}function Bg(a){for(const e in Wi){const t=Wi[e];if(t.mimeType===a)return t}}function Ka(a,e){const t=Wi[a];return t||(U.Warn("Unable to find a plugin to load "+a+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),e?$r():void 0)}function Lg(a){return!!Wi[a]}function Ng(a){for(const e in Wi){const t=Wi[e].plugin;if(t.canDirectLoad&&t.canDirectLoad(a))return Wi[e]}return $r()}function Ug(a){const e=a.indexOf("?");e!==-1&&(a=a.substring(0,e));const t=a.lastIndexOf(".");return a.substring(t,a.length).toLowerCase()}function kg(a){return a.substring(0,5)==="data:"?a.substring(5):null}function z0(a,e,t){let s="Unable to load from "+(a.rawData?"binary data":a.url);return e?s+=": ".concat(e):t&&(s+=": ".concat(t)),s}async function W0(a,e,t,i,s,n,r,o,h){var d;const l=kg(a.url);if(a.rawData&&!r)throw"When using ArrayBufferView to load data the file extension must be provided.";const c=!l&&!r?Ug(a.url):"";let u=r?Ka(r,!0):l?Ng(a.url):Ka(c,!1);if(!u&&c){if(a.url&&!a.url.startsWith("blob:")){const _=await Dg(a.url,{method:"HEAD",responseHeaders:["Content-Type"]}),p=_.headerValues?_.headerValues["Content-Type"]:"";p&&(u=Bg(p))}u||(u=$r())}if(!u)throw new Error("No plugin or fallback for ".concat(r!=null?r:a.url));if(((d=h==null?void 0:h[u.plugin.name])==null?void 0:d.enabled)===!1)throw new Error("The '".concat(u.plugin.name,"' plugin is disabled via the loader options passed to the loading operation."));if(a.rawData&&!u.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";return(_=>{if(Fg(u.plugin)){const g=u.plugin.createPlugin(h!=null?h:{});return g instanceof Promise?(g.then(_).catch(m=>{s("Error instantiating plugin.",m)}),null):(_(g),g)}else return _(u.plugin),u.plugin})(_=>{var y;if(!_)throw"The loader plugin corresponding to the '".concat(r,"' file type has not been found. If using es6, please import the plugin you wish to use before.");if(Vc.notifyObservers(_),l&&(_.canDirectLoad&&_.canDirectLoad(a.url)||!y0(a.url))){if(_.directLoad){const R=_.directLoad(e,l);R instanceof Promise?R.then(E=>{t(_,E)}).catch(E=>{s("Error in directLoad of _loadData: "+E,E)}):t(_,R)}else t(_,l);return}const p=u.isBinary,g=(R,E)=>{if(e.isDisposed){s("Scene has been disposed");return}t(_,R,E)};let m=null,b=!1;(y=_.onDisposeObservable)==null||y.add(()=>{b=!0,m&&(m.abort(),m=null),n()});const I=()=>{if(b)return;const R=(E,C)=>{s(E==null?void 0:E.statusText,C)};if(!_.loadFile&&a.rawData)throw"Plugin does not support loading ArrayBufferView.";m=_.loadFile?_.loadFile(e,a.rawData||a.file||a.url,a.rootUrl,g,i,p,R,o):e._loadFile(a.file||a.url,g,i,!0,p,R)},T=e.getEngine();let x=T.enableOfflineSupport;if(x){let R=!1;for(const E of e.disableOfflineSupportExceptionRules)if(E.test(a.url)){R=!0;break}x=!R}x&&ae.OfflineProviderFactory?e.offlineProvider=ae.OfflineProviderFactory(a.url,I,T.disableManifestCheck):I()})}function H0(a,e){let t,i,s=null,n=null;if(!e)t=a,i=J.GetFilename(a),a=J.GetFolderPath(a);else if(Og(e))t="file:".concat(e.name),i=e.name,s=e;else if(ArrayBuffer.isView(e))t="",i=g0(),n=e;else if(e.startsWith("data:"))t=e,i="";else if(a){const r=e;if(r.substring(0,1)==="/")return J.Error("Wrong sceneFilename parameter"),null;t=a+r,i=r}else t=e,i=J.GetFilename(e),a=J.GetFolderPath(e);return{url:t,rootUrl:a,name:i,file:s,rawData:n}}function Gc(a){if(typeof a.extensions=="string"){const e=a.extensions;Wi[e.toLowerCase()]={plugin:a,isBinary:!1}}else{const e=a.extensions;Object.keys(e).forEach(t=>{Wi[t.toLowerCase()]={plugin:a,isBinary:e[t].isBinary,mimeType:e[t].mimeType}})}}async function zc(a,e,t="",i=Ee.LastCreatedScene,s=null,n=null,r=null,o=null,h="",l={}){if(!i)return U.Error("No scene available to import mesh to"),null;const c=H0(e,t);if(!c)return null;const u={};i.addPendingData(u);const f=()=>{i.removePendingData(u)},d=(g,m)=>{const b=z0(c,g,m);r?r(i,b,new cs(b,Hs.SceneLoaderError,m)):U.Error(b),f()},_=n?g=>{try{n(g)}catch(m){d("Error in onProgress callback: "+m,m)}}:void 0,p=(g,m,b,I,T,x,y,R)=>{if(i.importedMeshesFiles.push(c.url),s)try{s(g,m,b,I,T,x,y,R)}catch(E){d("Error in onSuccess callback: "+E,E)}i.removePendingData(u)};return await W0(c,i,(g,m,b)=>{if(g.rewriteRootURL&&(c.rootUrl=g.rewriteRootURL(c.rootUrl,b)),g.importMesh){const I=g,T=[],x=[],y=[];if(!I.importMesh(a,i,m,c.rootUrl,T,x,y,d))return;i.loadingPluginName=g.name,p(T,x,y,[],[],[],[],[])}else g.importMeshAsync(a,i,m,c.rootUrl,_,c.name).then(T=>{i.loadingPluginName=g.name,p(T.meshes,T.particleSystems,T.skeletons,T.animationGroups,T.transformNodes,T.geometries,T.lights,T.spriteManagers)}).catch(T=>{d(T.message,T)})},_,d,f,o,h,l)}function Vg(a,e,t,i,s,n,r,o){return new Promise((h,l)=>{zc(a,e,t,i,(c,u,f,d,_,p,g,m)=>{h({meshes:c,particleSystems:u,skeletons:f,animationGroups:d,transformNodes:_,geometries:p,lights:g,spriteManagers:m})},s,(c,u,f)=>{l(f||new Error(u))},n,r,o)})}function Wc(a,e="",t=Ee.LastCreatedEngine,i=null,s=null,n=null,r=null,o="",h={}){if(!t){J.Error("No engine available");return}K0(a,e,new it(t),i,s,n,r,o,h)}function Gg(a,e,t,i,s,n,r){return new Promise((o,h)=>{Wc(a,e,t,l=>{o(l)},i,(l,c,u)=>{h(u||new Error(c))},s,n,r)})}async function K0(a,e="",t=Ee.LastCreatedScene,i=null,s=null,n=null,r=null,o="",h={}){if(!t)return U.Error("No scene available to append to"),null;const l=H0(a,e);if(!l)return null;const c={};t.addPendingData(c);const u=()=>{t.removePendingData(c)};Tt.ShowLoadingScreen&&!Ra&&(Ra=!0,t.getEngine().displayLoadingUI(),t.executeWhenReady(()=>{t.getEngine().hideLoadingUI(),Ra=!1}));const f=(p,g)=>{const m=z0(l,p,g);n?n(t,m,new cs(m,Hs.SceneLoaderError,g)):U.Error(m),u()},d=s?p=>{try{s(p)}catch(g){f("Error in onProgress callback",g)}}:void 0,_=()=>{if(i)try{i(t)}catch(p){f("Error in onSuccess callback",p)}t.removePendingData(c)};return await W0(l,t,(p,g)=>{if(p.load){if(!p.load(t,g,l.rootUrl,f))return;t.loadingPluginName=p.name,_()}else p.loadAsync(t,g,l.rootUrl,d,l.name).then(()=>{t.loadingPluginName=p.name,_()}).catch(b=>{f(b.message,b)})},d,f,u,r,o,h)}function zg(a,e,t,i,s,n,r){return new Promise((o,h)=>{K0(a,e,t,l=>{o(l)},i,(l,c,u)=>{h(u||new Error(c))},s,n,r)})}async function X0(a,e="",t=Ee.LastCreatedScene,i=null,s=null,n=null,r=null,o="",h={}){if(!t)return U.Error("No scene available to load asset container to"),null;const l=H0(a,e);if(!l)return null;const c={};t.addPendingData(c);const u=()=>{t.removePendingData(c)},f=(p,g)=>{const m=z0(l,p,g);n?n(t,m,new cs(m,Hs.SceneLoaderError,g)):U.Error(m),u()},d=s?p=>{try{s(p)}catch(g){f("Error in onProgress callback",g)}}:void 0,_=p=>{if(i)try{i(p)}catch(g){f("Error in onSuccess callback",g)}t.removePendingData(c)};return await W0(l,t,(p,g)=>{if(p.loadAssetContainer){const b=p.loadAssetContainer(t,g,l.rootUrl,f);if(!b)return;b.populateRootNodes(),t.loadingPluginName=p.name,_(b)}else p.loadAssetContainerAsync?p.loadAssetContainerAsync(t,g,l.rootUrl,d,l.name).then(b=>{b.populateRootNodes(),t.loadingPluginName=p.name,_(b)}).catch(b=>{f(b.message,b)}):f("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},d,f,u,r,o,h)}function Wg(a,e,t,i,s,n,r){return new Promise((o,h)=>{X0(a,e,t,l=>{o(l)},i,(l,c,u)=>{h(u||new Error(c))},s,n,r)})}function Hc(a,e="",t=Ee.LastCreatedScene,i=!0,s=0,n=null,r=null,o=null,h=null,l=null,c="",u={}){if(!t){U.Error("No scene available to load animations to");return}if(i){for(const p of t.animatables)p.reset();t.stopAllAnimations(),t.animationGroups.slice().forEach(p=>{p.dispose()}),t.getNodes().forEach(p=>{p.animations&&(p.animations=[])})}else switch(s){case 0:t.animationGroups.slice().forEach(_=>{_.dispose()});break;case 1:t.animationGroups.forEach(_=>{_.stop()});break;case 2:t.animationGroups.forEach(_=>{_.reset(),_.restart()});break;case 3:break;default:U.Error("Unknown animation group loading mode value '"+s+"'");return}const f=t.animatables.length;X0(a,e,t,_=>{_.mergeAnimationsTo(t,t.animatables.slice(f),n),_.dispose(),t.onAnimationFileImportedObservable.notifyObservers(t),r&&r(t)},o,h,l,c,u)}function Hg(a,e,t,i,s,n,r,o,h,l){return new Promise((c,u)=>{Hc(a,e,t,i,s,n,f=>{c(f)},r,(f,d,_)=>{u(_||new Error(d))},o,h,l)})}class ks{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 $r()}static GetPluginForExtension(e){var t;return(t=Ka(e,!0))==null?void 0:t.plugin}static IsPluginForExtensionAvailable(e){return Lg(e)}static RegisterPlugin(e){Gc(e)}static ImportMesh(e,t,i,s,n,r,o,h,l){zc(e,t,i,s,n,r,o,h,l)}static ImportMeshAsync(e,t,i,s,n,r,o){return Vg(e,t,i,s,n,r,o)}static Load(e,t,i,s,n,r,o,h){Wc(e,t,i,s,n,r,o,h)}static LoadAsync(e,t,i,s,n,r){return Gg(e,t,i,s,n,r)}static Append(e,t,i,s,n,r,o,h){K0(e,t,i,s,n,r,o,h)}static AppendAsync(e,t,i,s,n,r){return zg(e,t,i,s,n,r)}static LoadAssetContainer(e,t,i,s,n,r,o,h){X0(e,t,i,s,n,r,o,h)}static LoadAssetContainerAsync(e,t,i,s,n,r){return Wg(e,t,i,s,n,r)}static ImportAnimations(e,t,i,s,n,r,o,h,l,c,u){Hc(e,t,i,s,n,r,o,h,l,c,u)}static ImportAnimationsAsync(e,t,i,s,n,r,o,h,l,c,u){return Hg(e,t,i,s,n,r,h,c,u)}}ks.NO_LOGGING=0;ks.MINIMAL_LOGGING=1;ks.SUMMARY_LOGGING=2;ks.DETAILED_LOGGING=3;ks.OnPluginActivatedObservable=Vc;class Zr extends mt{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,s,n,r,o=0){super(e,"fxaa",["texelSize"],null,t,i,s||ie.BILINEAR_SAMPLINGMODE,n,r,null,o,"fxaa",void 0,!0);const h=this._getDefines();this.updateEffect(h),this.onApplyObservable.add(l=>{const c=this.texelSize;l.setFloat2("texelSize",c.x,c.y)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Oe(()=>import("./fxaa.fragment-CKBSH8ak.js"),__vite__mapDeps([40,3,4,5,6,7,8,9,10])),Oe(()=>import("./fxaa.vertex-pl3gzfER.js"),__vite__mapDeps([41,3,4,5,6,7,8,9,10]))]))):t.push(Promise.all([Oe(()=>import("./fxaa.fragment-CQ-OctB5.js"),__vite__mapDeps([42,3,4,5,6,7,8,9,10])),Oe(()=>import("./fxaa.vertex-D11BDiUg.js"),__vite__mapDeps([43,3,4,5,6,7,8,9,10]))])),super._gatherImports(e,t)}_getDefines(){const e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,s){return Ae.Parse(()=>new Zr(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}vt("BABYLON.FxaaPostProcess",Zr);let Ds,Os=null;async function Kg(){return Os||(Os=new Promise((a,e)=>{let t,i=null;const s={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};Oe(async()=>{const{ThinEngine:n}=await Promise.resolve().then(()=>kd);return{ThinEngine:n}},void 0).then(({ThinEngine:n})=>{try{t=new OffscreenCanvas(100,100),i=new n(t,!1,s)}catch{t=document.createElement("canvas"),i=new n(t,!1,s)}Ee.Instances.pop(),Ee.OnEnginesDisposedObservable.add(o=>{i&&o!==i&&!i.isDisposed&&Ee.Instances.length===0&&j0()}),i.getCaps().parallelShaderCompile=void 0;const r=new tp(i);Oe(async()=>{const{passPixelShader:o}=await import("./pass.fragment-BkcfUm5b.js");return{passPixelShader:o}},__vite__mapDeps([19,3,4,5,6,7,8,9,10])).then(({passPixelShader:o})=>{if(!i){e("Engine is not defined");return}const h=new Kt({engine:i,name:o.name,fragmentShader:o.shader,samplerNames:["textureSampler"]});Ds={canvas:t,engine:i,renderer:r,wrapper:h},a(Ds)})}).catch(e)})),await Os}async function Y0(a,e,t,i,s="image/png",n,r){const o=await t.readPixels(0,0,a,e),h=new Uint8Array(o.buffer);Vs(a,e,h,i,s,n,!0,void 0,r)}function q0(a,e,t,i="image/png",s,n=!1,r=!1,o){return new Promise(h=>{Vs(a,e,t,l=>h(l),i,s,n,r,o)})}function Vs(a,e,t,i,s="image/png",n,r=!1,o=!1,h){Kg().then(l=>{if(l.engine.setSize(a,e,!0),t instanceof Float32Array){const u=new Uint8Array(t.length);let f=t.length;for(;f--;){const d=t[f];u[f]=Math.round(ht(d)*255)}t=u}const c=l.engine.createRawTexture(t,a,e,5,!1,!r,1);l.renderer.setViewport(),l.renderer.applyEffectWrapper(l.wrapper),l.wrapper.effect._bindTexture("textureSampler",c),l.renderer.draw(),o?J.ToBlob(l.canvas,u=>{const f=new FileReader;f.onload=d=>{const _=d.target.result;i&&i(_)},f.readAsArrayBuffer(u)},s,h):J.EncodeScreenshotCanvasData(l.canvas,i,s,n,h),c.dispose()})}function j0(){Ds?(Ds.wrapper.dispose(),Ds.renderer.dispose(),Ds.engine.dispose()):Os==null||Os.then(a=>{a.wrapper.dispose(),a.renderer.dispose(),a.engine.dispose()}),Os=null,Ds=null}const Xg={DumpData:Vs,DumpDataAsync:q0,DumpFramebuffer:Y0,Dispose:j0},Yg=()=>{J.DumpData=Vs,J.DumpDataAsync=q0,J.DumpFramebuffer=Y0};Yg();const qg=Object.freeze(Object.defineProperty({__proto__:null,Dispose:j0,DumpData:Vs,DumpDataAsync:q0,DumpFramebuffer:Y0,DumpTools:Xg},Symbol.toStringTag,{value:"Module"}));let ps=null;function Qr(a,e,t,i,s="image/png",n=!1,r){const{height:o,width:h}=Yc(a,e,t);if(!(o&&h)){U.Error("Invalid 'size' parameter !");return}ps||(ps=document.createElement("canvas")),ps.width=h,ps.height=o;const l=ps.getContext("2d"),c=a.getRenderWidth()/a.getRenderHeight();let u=h,f=u/c;f>o&&(f=o,u=f*c);const d=Math.max(0,h-u)/2,_=Math.max(0,o-f)/2;e.getScene().activeCamera!==e?Jr(a,e,t,g=>{if(n){const m=new Blob([g]);J.DownloadBlob(m),i&&i("")}else i&&i(g)},s,1,a.getCreationOptions().antialias,void 0,void 0,void 0,void 0,r):a.onEndFrameObservable.addOnce(()=>{const g=a.getRenderingCanvas();l&&g&&l.drawImage(g,d,_,u,f),ps&&(n?(J.EncodeScreenshotCanvasData(ps,void 0,s,void 0,r),i&&i("")):J.EncodeScreenshotCanvasData(ps,i,s,void 0,r))})}function Kc(a,e,t,i="image/png",s){return new Promise((n,r)=>{Qr(a,e,t,o=>{typeof o<"u"?n(o):r(new Error("Data is undefined"))},i,void 0,s)})}function jg(a,e,t,i,s="image/png",n){return new Promise(r=>{Qr(a,e,{width:t,height:i},()=>{r()},s,!0,n)})}function Jr(a,e,t,i,s="image/png",n=1,r=!1,o,h=!1,l=!1,c=!0,u,f){const{height:d,width:_,finalWidth:p,finalHeight:g}=Yc(a,e,t),m={width:_,height:d};if(!(d&&_)){U.Error("Invalid 'size' parameter !");return}const b={width:a.getRenderWidth(),height:a.getRenderHeight()};a.setSize(_,d);const I=e.getScene(),T=new us("screenShot",m,I,!1,!1,0,!1,ie.BILINEAR_SAMPLINGMODE,void 0,l,void 0,void 0,void 0,n);T.renderList=I.meshes.slice(),T.samples=n,T.renderSprites=h,T.activeCamera=e,T.forceLayerMaskCheck=c,f==null||f(T);const x=()=>{T.isReadyForRendering()&&e.isReady(!0)?(a.onEndFrameObservable.addOnce(()=>{p===_&&g===d?T.readPixels(void 0,void 0,void 0,!1).then(R=>{Vs(_,d,R,i,s,o,!0,void 0,u),T.dispose()}):(a.isWebGPU?Oe(()=>import("./pass.fragment-CM2j9WLA.js"),__vite__mapDeps([18,3,4,5,6,7,8,9,10])):Oe(()=>import("./pass.fragment-BkcfUm5b.js"),__vite__mapDeps([19,3,4,5,6,7,8,9,10]))).then(()=>ip("pass",T.getInternalTexture(),I,void 0,void 0,void 0,p,g).then(E=>{a._readTexturePixels(E,p,g,-1,0,null,!0,!1,0,0).then(C=>{Vs(p,g,C,i,s,o,!0,void 0,u),E.dispose()})}))}),I.incrementRenderId(),I.resetCachedMaterial(),T.render(!0),a.setSize(b.width,b.height),e.getProjectionMatrix(!0)):setTimeout(x,16)},y=()=>{I.incrementRenderId(),I.resetCachedMaterial(),x()};if(r){const R=new Zr("antialiasing",1,I.activeCamera);T.addPostProcess(R),R.onEffectCreatedObservable.addOnce(E=>{E.isReady()?y():E.onCompiled=()=>{y()}})}else y()}function Xc(a,e,t,i="image/png",s=1,n=!1,r,o=!1,h=!1,l=!0,c,u){return new Promise((f,d)=>{Jr(a,e,t,_=>{typeof _<"u"?f(_):d(new Error("Data is undefined"))},i,s,n,r,o,h,l,c,u)})}function Yc(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 $g={CreateScreenshot:Qr,CreateScreenshotAsync:Kc,CreateScreenshotWithResizeAsync:jg,CreateScreenshotUsingRenderTarget:Jr,CreateScreenshotUsingRenderTargetAsync:Xc},Zg=()=>{J.CreateScreenshot=Qr,J.CreateScreenshotAsync=Kc,J.CreateScreenshotUsingRenderTarget=Jr,J.CreateScreenshotUsingRenderTargetAsync=Xc};Zg();F._instancedMeshFactory=(a,e)=>{const t=new ea(a,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class ea extends Qe{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const i of t.getAnimationRanges())i!=null&&this.createAnimationRange(i.name,i.from,i.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;((t=this._sourceMesh)==null?void 0:t.receiveShadows)!==e&&J.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;((t=this._sourceMesh)==null?void 0:t.material)!==e&&J.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;((t=this._sourceMesh)==null?void 0:t.visibility)!==e&&J.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;((t=this._sourceMesh)==null?void 0:t.skeleton)!==e&&J.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||U.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)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}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;let i;typeof e=="object"?i=e:i={applySkeleton:e,applyMorph:t};const s=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,A.PositionKind),s),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||U.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!==Te.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new O);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,N.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(N.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;sn===e||n.startsWith(i));return s>=0&&this.options.defines.splice(s,1),(typeof t!="boolean"||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var x,y,R;const s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const E=s?i._drawWrapper:this._drawWrapper;if(E.effect&&E._wasPreviouslyReady&&E._wasPreviouslyUsingInstances===t)return!0}const n=this.getScene(),r=n.getEngine(),o=[],h=[],l=new G0;let c=this._shaderPath,u=this._options.uniforms,f=this._options.uniformBuffers,d=this._options.samplers;r.getCaps().multiview&&n.activeCamera&&n.activeCamera.outputRenderTarget&&n.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),u.indexOf("viewProjection")!==-1&&u.indexOf("viewProjectionR")===-1&&u.push("viewProjectionR"));for(let E=0;E4&&(h.push(A.MatricesIndicesExtraKind),h.push(A.MatricesWeightsExtraKind));const E=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l.addCPUSkinningFallback(0,e),E.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),u.indexOf("boneTextureWidth")===-1&&u.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(E.bones.length+1)),u.indexOf("mBones")===-1&&u.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let _=0;const p=e?e.morphTargetManager:null;if(p){const E=p.supportsUVs&&o.indexOf("#define UV1")!==-1,C=p.supportsTangents&&o.indexOf("#define TANGENT")!==-1,S=p.supportsNormals&&o.indexOf("#define NORMAL")!==-1;_=p.numMaxInfluencers||p.numInfluencers,E&&o.push("#define MORPHTARGETS_UV"),C&&o.push("#define MORPHTARGETS_TANGENT"),S&&o.push("#define MORPHTARGETS_NORMAL"),_>0&&o.push("#define MORPHTARGETS"),p.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),u.indexOf("morphTargetTextureIndices")===-1&&u.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+_);for(let w=0;w<_;w++)h.push(A.PositionKind+w),S&&h.push(A.NormalKind+w),C&&h.push(A.TangentKind+w),E&&h.push(A.UVKind+"_"+w);_>0&&(u=u.slice(),u.push("morphTargetInfluences"),u.push("morphTargetCount"),u.push("morphTargetTextureInfo"),u.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const E=e.bakedVertexAnimationManager;E&&E.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),u.indexOf("bakedVertexAnimationSettings")===-1&&u.push("bakedVertexAnimationSettings"),u.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&u.push("bakedVertexAnimationTextureSizeInverted"),u.indexOf("bakedVertexAnimationTime")===-1&&u.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),Dc(h,e,o)}for(const E in this._textures)if(!this._textures[E].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(Xr(u),Mc(this,n,o)),n.fogEnabled&&(e!=null&&e.applyFog)&&n.fogMode!==it.FOGMODE_NONE&&(o.push("#define FOG"),u.indexOf("view")===-1&&u.push("view"),u.indexOf("vFogInfos")===-1&&u.push("vFogInfos"),u.indexOf("vFogColor")===-1&&u.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),u.indexOf("logarithmicDepthConstant")===-1&&u.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(u=u.slice(),f=f.slice(),d=d.slice(),c=this.customShaderNameResolve(this.name,u,f,d,o,h));const g=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,m=(x=g==null?void 0:g.effect)!=null?x:null,b=(y=g==null?void 0:g.defines)!=null?y:null,I=o.join("\n");let T=m;return b!==I&&(T=r.createEffect(c,{attributes:h,uniformsNames:u,uniformBuffersNames:f,samplers:d,defines:I,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:_},shaderLanguage:this._options.shaderLanguage,extraInitializationsAsync:this._options.extraInitializationsAsync},r),s?i.setEffect(T,I,this._materialContext):g&&g.setEffect(T,I),this._onEffectCreatedObservable&&(Ia.effect=T,Ia.subMesh=(R=i!=null?i:e==null?void 0:e.subMeshes[0])!=null?R:null,this._onEffectCreatedObservable.notifyObservers(Ia))),g._wasPreviouslyUsingInstances=!!t,T!=null&&T.isReady()?(m!==T&&n.resetCachedMaterial(),g._wasPreviouslyReady=!0,!0):!1}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)),this._options.uniforms.indexOf("view")!==-1&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){var s;this.bind(e,t,(s=i._drawWrapperOverride)==null?void 0:s.effect,i)}bind(e,t,i,s){var u;const n=s&&this._storeEffectOnSubMeshes,r=i!=null?i:n?s.effect:this.getEffect();if(!r)return;const o=this.getScene();this._activeEffect=r,this.bindOnlyWorldMatrix(e,i);const h=this._options.uniformBuffers;let l=!1;if(r&&h&&h.length>0&&o.getEngine().supportsUniformBuffers)for(let f=0;f0&&U0(t,r);const d=t.bakedVertexAnimationManager;if(d&&d.isEnabled){const _=n?s._drawWrapper:this._drawWrapper;(u=t.bakedVertexAnimationManager)==null||u.bind(r,!!_._wasPreviouslyUsingInstances)}}this._afterBind(t,r,s)}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 os(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 os(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,ie.Parse(e.textures[n],t,i));for(n in e.textureArrays){const r=e.textureArrays[n],o=[];for(let h=0;h(l%3===0?o.push([h]):o[o.length-1].push(h),o),[]).map(o=>de.FromArray(o));s.setColor3Array(n,r)}for(n in e.colors4)s.setColor4(n,H.FromArray(e.colors4[n]));for(n in e.colors4Arrays){const r=e.colors4Arrays[n].reduce((o,h,l)=>(l%4===0?o.push([h]):o[o.length-1].push(h),o),[]).map(o=>H.FromArray(o));s.setColor4Array(n,r)}for(n in e.vectors2)s.setVector2(n,oe.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,Pe.FromArray(e.vectors4[n]));for(n in e.quaternions)s.setQuaternion(n,re.FromArray(e.quaternions[n]));for(n in e.matrices)s.setMatrix(n,O.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 Ft;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const h=JSON.parse(o.responseText),l=this.Parse(h,i||Ee.LastCreatedScene,s);e&&(l.name=e),n(l)}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 Ft;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){const o=JSON.parse(JSON.parse(r.responseText).jsonPayload),h=JSON.parse(o.shaderMaterial),l=this.Parse(h,t||Ee.LastCreatedScene,i);l.snippetId=e,s(l)}else n("Unable to load the snippet "+e)}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}}os.SnippetUrl="https://snippet.babylonjs.com";os.CreateFromSnippetAsync=os.ParseFromSnippetAsync;vt("BABYLON.ShaderMaterial",os);F._LinesMeshParser=(a,e)=>Hi.Parse(a,e);class Hi extends F{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,s=null,n,r,o,h){super(e,t,i,s,n),this.useVertexColor=r,this.useVertexAlpha=o,this.color=new de(1,1,1),this.alpha=1,this._shaderLanguage=0,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const l=[],c={attributes:[A.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:l,useClipPlane:null,shaderLanguage:0};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 H),h?this.material=h:(this.getScene().getEngine().isWebGPU&&!Hi.ForceGLSL&&(this._shaderLanguage=1),c.shaderLanguage=this._shaderLanguage,c.extraInitializationsAsync=async()=>{this._shaderLanguage===1?await Promise.all([Oe(()=>import("./color.vertex-Ccg8Ge1R.js"),__vite__mapDeps([44,22,23,24,3,4,5,6,7,8,9,10])),Oe(()=>import("./color.fragment-DNkpzaOC.js"),__vite__mapDeps([45,29,30,3,4,5,6,7,8,9,10]))]):await Promise.all([Oe(()=>import("./color.vertex-BL9BK6Le.js"),__vite__mapDeps([46,36,38,3,4,5,6,7,8,9,10])),Oe(()=>import("./color.fragment-BjUREcw_.js"),__vite__mapDeps([47,3,4,5,6,7,8,9,10]))])},this.material=new os("colorShader",this.getScene(),"color",c,!1),this.material.doNotSerialize=!0)}isReady(){return this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)?super.isReady():!1}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=X.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:s,g: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(X.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(X.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 Hi(e,this.getScene(),t,this,i)}createInstance(e){const t=new qc(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 Hi(e.name,t);return i.color=de.FromArray(e.color),i.alpha=e.alpha,i}}Hi.ForceGLSL=!1;class qc extends ea{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}Qe.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this};Qe.prototype.enableEdgesRendering=function(a=.95,e=!1,t){return this.disableEdgesRendering(),this._edgesRenderer=new ta(this,a,e,!0,t),this};Object.defineProperty(Qe.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0});Hi.prototype.enableEdgesRendering=function(a=.95,e=!1){return this.disableEdgesRendering(),this._edgesRenderer=new Jg(this,a,e),this};qc.prototype.enableEdgesRendering=function(a=.95,e=!1){return Hi.prototype.enableEdgesRendering.apply(this,arguments),this};class Qg{constructor(){this.edges=[],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,t){if(!e._edgeRenderLineShader){const i=new os("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"],uniformBuffers:["Scene","Mesh"],shaderLanguage:t,extraInitializationsAsync:async()=>{t===1?await Promise.all([Oe(()=>import("./line.vertex-ChOZncX4.js"),__vite__mapDeps([48,23,26,27,3,4,5,6,7,8,9,10])),Oe(()=>import("./line.fragment-azBhzxfj.js"),__vite__mapDeps([49,29,26,31,3,4,5,6,7,8,9,10]))]):await Promise.all([Oe(()=>import("./line.vertex-DNyxgHBi.js"),__vite__mapDeps([50,34,3,4,5,6,7,8,9,10])),Oe(()=>import("./line.fragment-thDij4Gq.js"),__vite__mapDeps([51,3,4,5,6,7,8,9,10]))])}},!1);i.disableDepthWrite=!0,i.backFaceCulling=!1,i.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=i}return e._edgeRenderLineShader}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=.95,i=!1,s=!0,n){var o;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 Ut(32),this._shaderLanguage=0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=n!=null?n:null,this._epsilon=t;const r=this._source.getScene().getEngine();r.isWebGPU&&(this._drawWrapper=new Xn(r),this._shaderLanguage=1),this._prepareRessources(),s&&((o=n==null?void 0:n.useAlternateEdgeFinder)==null||o?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(),this._shaderLanguage))}_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 t;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[A.PositionKind];e&&(e.dispose(),this._buffers[A.PositionKind]=null),e=this._buffers[A.NormalKind],e&&(e.dispose(),this._buffers[A.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),(t=this._drawWrapper)==null||t.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]){S>=0&&C.push(S);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 E=0;E<3;++E)E===r?e[E].sort((C,S)=>C[1]S[1]?1:0):e[E].sort((C,S)=>C[1]>S[1]?-1:C[1]=r+1;--E)n(e[E%3],h,E!==r+2?s[i[t+(E+1)%3]]:-1);const c=h.length,u=0,f=0;i.push(s[i[t+r]],o[0],h[0]),i.push(s[i[t+(r+1)%3]],h[c-1],o[l-1]);const d=l<=c,_=d?l:c,p=d?c:l,g=d?l-1:c-1,m=d?0:1;let b=l+c-2,I=d?u:f,T=d?f:u;const x=d?o:h,y=d?h:o;let R=0;for(;b-- >0;){m?i.push(x[I],y[T]):i.push(y[T],x[I]),R+=_;let E;R>=p&&IR){const w=y;y=R,R=w}const C=y+"_"+R,S=o[C];S?S.done||(v.Dot(T,S.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 h=0;for(let l=0;l=0?c.substring(0,u):c;f=f.toLowerCase();const d=u>=0?c.substring(u+1).trim():"";if(f==="newmtl")h&&this.materials.push(h),e._blockEntityCollection=!!s,h=new ee(d,e),h._parentContainer=s,e._blockEntityCollection=!1;else if(f==="kd"&&h)o=d.split(r,3).map(parseFloat),h.diffuseColor=de.FromArray(o);else if(f==="ka"&&h)o=d.split(r,3).map(parseFloat),h.ambientColor=de.FromArray(o);else if(f==="ks"&&h)o=d.split(r,3).map(parseFloat),h.specularColor=de.FromArray(o);else if(f==="ke"&&h)o=d.split(r,3).map(parseFloat),h.emissiveColor=de.FromArray(o);else if(f==="ns"&&h)h.specularPower=parseFloat(d);else if(f==="d"&&h)h.alpha=parseFloat(d);else if(f==="map_ka"&&h)h.ambientTexture=Si._GetTexture(i,d,e);else if(f==="map_kd"&&h)h.diffuseTexture=Si._GetTexture(i,d,e);else if(f==="map_ks"&&h)h.specularTexture=Si._GetTexture(i,d,e);else if(f!=="map_ns")if(f==="map_bump"&&h){const _=d.split(r),p=_.indexOf("-bm");let g=null;p>=0&&(g=_[p+1],_.splice(p,2)),h.bumpTexture=Si._GetTexture(i,_.join(" "),e),h.bumpTexture&&g!==null&&(h.bumpTexture.level=parseFloat(g))}else f==="map_d"&&h&&(h.opacityTexture=Si._GetTexture(i,d,e))}h&&this.materials.push(h)}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.substring(n+1):s+=t}else s+=t;return new ie(s,i,!1,Si.INVERT_TEXTURE_Y)}}Si.INVERT_TEXTURE_Y=!0;class He{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._extColors=[],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 H(.5,.5,.5,1),this._hasLineData=!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 h;this._loadingOptions.optimizeWithUV?h=this._isInArrayUV(this._tuplePosNorm,[e,i,t]):h=this._isInArray(this._tuplePosNorm,[e,i]),h===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(s),n=n!=null?n:new oe(0,0),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(h)}_unwrapData(){try{for(let e=0;e0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&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._handledMesh.hasLines=this._hasLineData,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,this._hasLineData=!1)}_optimizeNormals(e){const t=e.getVerticesData(A.PositionKind),i=e.getVerticesData(A.NormalKind),s={};if(!t||!i)return;for(let r=0;rthis._triangles.push(f[0],f[d],f[d+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(f,d)=>this._triangles.push(f[0],f[d+1],f[d]),this._handednessSign=1):(this._pushTriangle=(f,d)=>this._triangles.push(f[0],f[d],f[d+1]),this._handednessSign=-1);const r=t.split("\n"),o=[];let h=[];o.push(h);for(let f=0;f=7){const p=parseFloat(_[4]),g=parseFloat(_[5]),m=parseFloat(_[6]);this._colors.push(new H(p>1?p/255:p,g>1?g/255:g,m>1?m/255:m,_.length===7||_[7]===void 0?1:parseFloat(_[7])))}else this._colors.push(this._grayColor)}else if((_=He.NormalPattern.exec(d))!==null)this._normals.push(new v(parseFloat(_[1]),parseFloat(_[2]),parseFloat(_[3])));else if((_=He.UVPattern.exec(d))!==null)this._uvs.push(new oe(parseFloat(_[1])*this._loadingOptions.UVScaling.x,parseFloat(_[2])*this._loadingOptions.UVScaling.y));else if((_=He.FacePattern3.exec(d))!==null)this._setDataForCurrentFaceWithPattern3(_[1].trim().split(" "),1);else if((_=He.FacePattern4.exec(d))!==null)this._setDataForCurrentFaceWithPattern4(_[1].trim().split(" "),1);else if((_=He.FacePattern5.exec(d))!==null)this._setDataForCurrentFaceWithPattern5(_[1].trim().split(" "),1);else if((_=He.FacePattern2.exec(d))!==null)this._setDataForCurrentFaceWithPattern2(_[1].trim().split(" "),1);else if((_=He.FacePattern1.exec(d))!==null)this._setDataForCurrentFaceWithPattern1(_[1].trim().split(" "),1);else if((_=He.LinePattern1.exec(d))!==null)this._setDataForCurrentFaceWithPattern1(_[1].trim().split(" "),0),this._hasLineData=!0;else if((_=He.LinePattern2.exec(d))!==null)this._setDataForCurrentFaceWithPattern2(_[1].trim().split(" "),0),this._hasLineData=!0;else if(_=He._GetZbrushMRGB(d,!this._loadingOptions.importVertexColors))_.forEach(p=>{this._extColors.push(p)});else if((_=He.LinePattern3.exec(d))!==null)this._setDataForCurrentFaceWithPattern3(_[1].trim().split(" "),0),this._hasLineData=!0;else if(He.GroupDescriptor.test(d)||He.ObjectDescriptor.test(d)){const p={name:d.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:He.ObjectDescriptor.test(d)};this._addPreviousObjMesh(),this._meshesFromObj.push(p),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(He.UseMtlDescriptor.test(d)){if(this._materialNameFromObj=d.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const p={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(p),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else He.MtlLibGroupDescriptor.test(d)?n(d.substring(7).trim()):He.SmoothDescriptor.test(d)||U.Log("Unhandled expression at line : "+d)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&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._handledMesh.hasLines=this._hasLineData,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let f=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(const d of this._positions)this._unwrappedPositionsForBabylon.push(d.x,d.y,d.z);if(this._normals.length)for(const d of this._normals)this._unwrappedNormalsForBabylon.push(d.x,d.y,d.z);if(this._uvs.length)for(const d of this._uvs)this._unwrappedUVForBabylon.push(d.x,d.y);if(this._extColors.length)for(const d of this._extColors)this._unwrappedColorsForBabylon.push(d.r,d.g,d.b,d.a);else if(this._colors.length)for(const d of this._colors)this._unwrappedColorsForBabylon.push(d.r,d.g,d.b,d.a);this._materialNameFromObj||(f=new ee(Nt.RandomId(),i),f.pointsCloud=!0,this._materialNameFromObj=f.name,this._normals.length||(f.disableLighting=!0,f.emissiveColor=de.White()))}this._meshesFromObj.push({name:Nt.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:f,isObject:!0,hasLines:this._hasLineData})}for(let f=0;f=0;--p)if(this._meshesFromObj[p].isObject&&this._meshesFromObj[p]._babylonMesh){d.parent=this._meshesFromObj[p]._babylonMesh;break}}if(this._materialToUse.push(this._meshesFromObj[f].materialName),this._handledMesh.hasLines&&((c=d._internalMetadata)!=null||(d._internalMetadata={}),d._internalMetadata._isLine=!0),((u=this._handledMesh.positions)==null?void 0:u.length)===0){this._babylonMeshesArray.push(d);continue}const _=new j;if(_.uvs=this._handledMesh.uvs,_.indices=this._handledMesh.indices,_.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const p=new Array;j.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,p),_.normals=p}else _.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(_.colors=this._handledMesh.colors),_.applyToMesh(d),this._loadingOptions.invertY&&(d.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(d),this._babylonMeshesArray.push(d),this._handledMesh.directMaterial&&(d.material=this._handledMesh.directMaterial)}}}He.ObjectDescriptor=/^o/;He.GroupDescriptor=/^g/;He.MtlLibGroupDescriptor=/^mtllib /;He.UseMtlDescriptor=/^usemtl /;He.SmoothDescriptor=/^s /;He.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/;He.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;He.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;He.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/;He.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;He.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;He.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;He.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;He.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/;He.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;He.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class jc{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.sounds=null,this.effectLayers=[],this.layers=[],this.reflectionProbes=[]}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}}class e1 extends jc{}class t1{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach(e=>{e.dispose()}),this.rootNodes.length=0,this.skeletons.slice(0).forEach(e=>{e.dispose()}),this.skeletons.length=0,this.animationGroups.slice(0).forEach(e=>{e.dispose()}),this.animationGroups.length=0}}class i1 extends jc{constructor(e){super(),this._wasAddedToScene=!1,e=e||Ee.LastCreatedScene,e&&(this.scene=e,this.proceduralTextures=[],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 h=o.uniqueId;i.dependsOn.set(h,new Set),i.dependedBy.set(h,new Set)}for(const o of e){const h=o.uniqueId,l=i.dependsOn.get(h);if(o instanceof ea){const u=o.sourceMesh;t.has(u.uniqueId)&&(l.add(u.uniqueId),i.dependedBy.get(u.uniqueId).add(h))}const c=i.dependedBy.get(h);for(const u of o.getDescendants()){const f=u.uniqueId;t.has(f)&&(c.add(f),i.dependsOn.get(f).add(h))}}const s=[],n=[];for(const o of e){const h=o.uniqueId;i.dependsOn.get(h).size===0&&(n.push(o),t.delete(h))}const r=n;for(;r.length>0;){const o=r.shift();s.push(o);const h=i.dependedBy.get(o.uniqueId);for(const l of Array.from(h.values())){const c=i.dependsOn.get(l);c.delete(o.uniqueId),c.size===0&&t.get(l)&&(r.push(t.get(l)),t.delete(l))}}return t.size>0&&(U.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>U.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 Qe&&this.meshes.indexOf(e)!==-1||e instanceof Te&&this.transformNodes.indexOf(e)!==-1||e instanceof Fe&&this.lights.indexOf(e)!==-1||e instanceof ve&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return U.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 U.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 U.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 U.Warn("Node ".concat(e.name," has a parent that is not in the container.")),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||J.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},n={},r=new t1,o=[],h=[],l={doNotInstantiate:!0,...i},c=(p,g)=>{if(s[p.uniqueId]=g.uniqueId,n[g.uniqueId]=g,e&&(g.name=e(p.name)),g instanceof F){const m=g;if(m.morphTargetManager){const b=p.morphTargetManager;m.morphTargetManager=b.clone();for(let I=0;I{if(c(p,g),p.parent){const m=s[p.parent.uniqueId],b=n[m];b?g.parent=b:g.parent=p.parent}if(g.position&&p.position&&g.position.copyFrom(p.position),g.rotationQuaternion&&p.rotationQuaternion&&g.rotationQuaternion.copyFrom(p.rotationQuaternion),g.rotation&&p.rotation&&g.rotation.copyFrom(p.rotation),g.scaling&&p.scaling&&g.scaling.copyFrom(p.scaling),g.material){const m=g;if(m.material)if(t){const b=p.material;if(h.indexOf(b)===-1){let I=b.clone(e?e(b.name):"Clone of "+b.name);if(h.push(b),s[b.uniqueId]=I.uniqueId,n[I.uniqueId]=I,b.getClassName()==="MultiMaterial"){const T=b;for(const x of T.subMaterials)x&&(I=x.clone(e?e(x.name):"Clone of "+x.name),h.push(x),s[x.uniqueId]=I.uniqueId,n[I.uniqueId]=I);T.subMaterials=T.subMaterials.map(x=>x&&n[s[x.uniqueId]])}}m.getClassName()!=="InstancedMesh"&&(m.material=n[s[b.uniqueId]])}else m.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(m.material)===-1&&this.scene.addMultiMaterial(m.material):this.scene.materials.indexOf(m.material)===-1&&this.scene.addMaterial(m.material)}g.parent===null&&r.rootNodes.push(g)};return d.forEach(p=>{if(p.getClassName()==="InstancedMesh"){const g=p,m=g.sourceMesh,b=s[m.uniqueId],T=(typeof b=="number"?n[b]:m).createInstance(g.name);_(g,T)}else{let g=!0;p.getClassName()==="TransformNode"||p.getClassName()==="Node"||p.skeleton||!p.getTotalVertices||p.getTotalVertices()===0?g=!1:l.doNotInstantiate&&(typeof l.doNotInstantiate=="function"?g=!l.doNotInstantiate(p):g=!l.doNotInstantiate);const m=g?p.createInstance("instance of ".concat(p.name)):p.clone("Clone of ".concat(p.name),null,!0);if(!m)throw new Error("Could not clone or instantiate node on Asset Container ".concat(p.name));_(p,m)}}),this.skeletons.forEach(p=>{if(l.predicate&&!l.predicate(p))return;const g=p.clone(e?e(p.name):"Clone of "+p.name);for(const m of this.meshes)if(m.skeleton===p&&!m.isAnInstance){const b=n[s[m.uniqueId]];if(!b||b.isAnInstance||(b.skeleton=g,o.indexOf(g)!==-1))continue;o.push(g);for(const I of g.bones)I._linkedTransformNode&&(I._linkedTransformNode=n[s[I._linkedTransformNode.uniqueId]])}r.skeletons.push(g)}),this.animationGroups.forEach(p=>{if(l.predicate&&!l.predicate(p))return;const g=p.clone(e?e(p.name):"Clone of "+p.name,m=>n[s[m.uniqueId]]||m);r.animationGroups.push(g)}),r}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||J.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach(i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))}),this.skeletons.forEach(i=>{e&&!e(i)||this.scene.addSkeleton(i)}),this.animations.forEach(i=>{e&&!e(i)||this.scene.addAnimation(i)}),this.animationGroups.forEach(i=>{e&&!e(i)||this.scene.addAnimationGroup(i)}),this.multiMaterials.forEach(i=>{e&&!e(i)||this.scene.addMultiMaterial(i)}),this.materials.forEach(i=>{e&&!e(i)||this.scene.addMaterial(i)}),this.morphTargetManagers.forEach(i=>{e&&!e(i)||this.scene.addMorphTargetManager(i)}),this.geometries.forEach(i=>{e&&!e(i)||this.scene.addGeometry(i)}),this.transformNodes.forEach(i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))}),this.actionManagers.forEach(i=>{e&&!e(i)||this.scene.addActionManager(i)}),this.textures.forEach(i=>{e&&!e(i)||this.scene.addTexture(i)}),this.reflectionProbes.forEach(i=>{e&&!e(i)||this.scene.addReflectionProbe(i)});for(const i of t)i.parent&&this.scene.getNodes().indexOf(i.parent)===-1&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){this._isValidHierarchy()||J.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach(t=>{e&&!e(t)||this.scene.removeCamera(t)}),this.lights.forEach(t=>{e&&!e(t)||this.scene.removeLight(t)}),this.meshes.forEach(t=>{e&&!e(t)||this.scene.removeMesh(t,!0)}),this.skeletons.forEach(t=>{e&&!e(t)||this.scene.removeSkeleton(t)}),this.animations.forEach(t=>{e&&!e(t)||this.scene.removeAnimation(t)}),this.animationGroups.forEach(t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)}),this.multiMaterials.forEach(t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)}),this.materials.forEach(t=>{e&&!e(t)||this.scene.removeMaterial(t)}),this.morphTargetManagers.forEach(t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)}),this.geometries.forEach(t=>{e&&!e(t)||this.scene.removeGeometry(t)}),this.transformNodes.forEach(t=>{e&&!e(t)||this.scene.removeTransformNode(t)}),this.actionManagers.forEach(t=>{e&&!e(t)||this.scene.removeActionManager(t)}),this.textures.forEach(t=>{e&&!e(t)||this.scene.removeTexture(t)}),this.reflectionProbes.forEach(t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)})}dispose(){this.cameras.slice(0).forEach(e=>{e.dispose()}),this.cameras.length=0,this.lights.slice(0).forEach(e=>{e.dispose()}),this.lights.length=0,this.meshes.slice(0).forEach(e=>{e.dispose()}),this.meshes.length=0,this.skeletons.slice(0).forEach(e=>{e.dispose()}),this.skeletons.length=0,this.animationGroups.slice(0).forEach(e=>{e.dispose()}),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach(e=>{e.dispose()}),this.multiMaterials.length=0,this.materials.slice(0).forEach(e=>{e.dispose()}),this.materials.length=0,this.geometries.slice(0).forEach(e=>{e.dispose()}),this.geometries.length=0,this.transformNodes.slice(0).forEach(e=>{e.dispose()}),this.transformNodes.length=0,this.actionManagers.slice(0).forEach(e=>{e.dispose()}),this.actionManagers.length=0,this.textures.slice(0).forEach(e=>{e.dispose()}),this.textures.length=0,this.reflectionProbes.slice(0).forEach(e=>{e.dispose()}),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach(e=>{e.dispose()}),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(!(!e||!t))for(const 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 e1);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 F("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=Ee.LastCreatedScene,t,i=null){if(!e)return U.Error("No scene available to merge animations to"),[];const s=i||(o=>{let h=null;const l=o.animations.length?o.animations[0].targetProperty:"",c=o.name.split(".").join("").split("_primitive")[0];switch(l){case"position":case"rotationQuaternion":h=e.getTransformNodeByName(o.name)||e.getTransformNodeByName(c);break;case"influence":h=e.getMorphTargetByName(o.name)||e.getMorphTargetByName(c);break;default:h=e.getNodeByName(o.name)||e.getNodeByName(c)}return h});this.getNodes().forEach(o=>{const h=s(o);if(h!==null){for(const l of o.animations){const c=h.animations.filter(u=>u.targetProperty===l.targetProperty);for(const u of c){const f=h.animations.indexOf(u,0);f>-1&&h.animations.splice(f,1)}}h.animations=h.animations.concat(o.animations)}});const r=[];return this.animationGroups.slice().forEach(o=>{r.push(o.clone(o.name,s)),o.animatables.forEach(h=>{h.stop()})}),t.forEach(o=>{const h=s(o.target);h&&(e.beginAnimation(h,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}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.transformNodes.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.lights.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.cameras.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)})}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const s=t.pop();if(s instanceof F?(s.geometry&&this.geometries.indexOf(s.geometry)===-1&&this.geometries.push(s.geometry),this.meshes.push(s)):s instanceof Te?this.transformNodes.push(s):s instanceof Fe?this.lights.push(s):s instanceof ve&&this.cameras.push(s),s instanceof Qe){if(s.material&&this.materials.indexOf(s.material)===-1){this.materials.push(s.material);for(const n of s.material.getActiveTextures())this.textures.indexOf(n)===-1&&this.textures.push(n)}s.skeleton&&this.skeletons.indexOf(s.skeleton)===-1&&this.skeletons.push(s.skeleton),s.morphTargetManager&&this.morphTargetManagers.indexOf(s.morphTargetManager)===-1&&this.morphTargetManagers.push(s.morphTargetManager)}for(const n of s.getChildren())i.has(n)||t.push(n);i.add(s)}this.populateRootNodes()}}const Qh={name:"obj",extensions:".obj"};class xt{static get INVERT_TEXTURE_Y(){return Si.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){Si.INVERT_TEXTURE_Y=e}constructor(e){this.name=Qh.name,this.extensions=Qh.extensions,this._assetContainer=null,this._loadingOptions=e||xt._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:xt.COMPUTE_NORMALS,optimizeNormals:xt.OPTIMIZE_NORMALS,importVertexColors:xt.IMPORT_VERTEX_COLORS,invertY:xt.INVERT_Y,invertTextureY:xt.INVERT_TEXTURE_Y,UVScaling:xt.UV_SCALING,materialLoadingFailsSilently:xt.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:xt.OPTIMIZE_WITH_UV,skipMaterials:xt.SKIP_MATERIALS,useLegacyBehavior:xt.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,s){const n=t+e;J.LoadFile(n,i,void 0,void 0,!1,(r,o)=>{s(n,o)})}createPlugin(){return new xt(xt._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:[],spriteManagers:[]}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then(()=>{})}loadAssetContainerAsync(e,t,i){const s=new i1(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(l=>{s.textures.indexOf(l)==-1&&s.textures.push(l)}))}),this._assetContainer=null,s)).catch(n=>{throw this._assetContainer=null,n})}_parseSolid(e,t,i,s){let n="";const r=new Si,o=[],h=[];i=i.replace(/#.*$/gm,"").trim(),new He(o,h,this._loadingOptions).parse(e,i,t,this._assetContainer,u=>{n=u});const c=[];return n!==""&&!this._loadingOptions.skipMaterials&&c.push(new Promise((u,f)=>{this._loadMTL(n,s,d=>{try{r.parseMTL(t,d,s,this._assetContainer);for(let _=0;_-1;)g.push(m),p=m+1;if(m===-1&&g.length===0)r.materials[_].dispose();else for(let b=0;b{J.Warn("Error downloading MTL file: '".concat(n,"'")),this._loadingOptions.materialLoadingFailsSilently?u():f(_)})})),Promise.all(c).then(()=>{const u=f=>{var d,_;return!!((_=(d=f._internalMetadata)==null?void 0:d._isLine)!=null&&_)};return h.forEach(f=>{var d,_;if(u(f)){let p=(d=f.material)!=null?d:new ee(f.name+"_line",t);p.getBindedMeshes().filter(m=>!u(m)).length>0&&(p=(_=p.clone(p.name+"_line"))!=null?_:p),p.wireframe=!0,f.material=p,f._internalMetadata&&(f._internalMetadata._isLine=void 0)}}),h})}}xt.OPTIMIZE_WITH_UV=!0;xt.INVERT_Y=!1;xt.IMPORT_VERTEX_COLORS=!1;xt.COMPUTE_NORMALS=!1;xt.OPTIMIZE_NORMALS=!1;xt.UV_SCALING=new oe(1,1);xt.SKIP_MATERIALS=!1;xt.MATERIAL_LOADING_FAILS_SILENTLY=!0;xt.USE_LEGACY_BEHAVIOR=!1;Gc(new xt);class Ue{constructor(e,t,i=Number.MAX_VALUE,s=Le){this.origin=e,this.direction=t,this.length=i,this.epsilon=s}clone(){return new Ue(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=Ue._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),n=Ue._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let r=0,o=Number.MAX_VALUE,h,l,c,u;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xn.x)return!1}else if(h=1/this.direction.x,l=(s.x-this.origin.x)*h,c=(n.x-this.origin.x)*h,c===-1/0&&(c=1/0),l>c&&(u=l,l=c,c=u),r=Math.max(l,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(h=1/this.direction.y,l=(s.y-this.origin.y)*h,c=(n.y-this.origin.y)*h,c===-1/0&&(c=1/0),l>c&&(u=l,l=c,c=u),r=Math.max(l,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(h=1/this.direction.z,l=(s.z-this.origin.z)*h,c=(n.z-this.origin.z)*h,c===-1/0&&(c=1/0),l>c&&(u=l,l=c,c=u),r=Math.max(l,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,h=o*o;if(r<=h)return!0;const l=i*this.direction.x+s*this.direction.y+n*this.direction.z;return l<0?!1:r-l*l<=h}intersectsTriangle(e,t,i){const s=Ue._TmpVector3[0],n=Ue._TmpVector3[1],r=Ue._TmpVector3[2],o=Ue._TmpVector3[3],h=Ue._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,n),v.CrossToRef(this.direction,n,r);const l=v.Dot(s,r);if(l===0)return null;const c=1/l;this.origin.subtractToRef(e,o);const u=v.Dot(o,r)*c;if(u<-this.epsilon||u>1+this.epsilon)return null;v.CrossToRef(o,s,h);const f=v.Dot(this.direction,h)*c;if(f<-this.epsilon||u+f>1+this.epsilon)return null;const d=v.Dot(n,h)*c;return d>this.length?null:new za(1-u-f,u,d)}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,i,s=!1,n,r=!1){const o=N.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?Ue.TransformToRef(this,o,this._tmpRay):this._tmpRay=Ue.Transform(this,o),e.intersects(this._tmpRay,t,i,s,n,r)}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=N.Vector3[0],r=N.Vector3[1],o=N.Vector3[2],h=N.Vector3[3];t.subtractToRef(e,n),this.direction.scaleToRef(Ue._Rayl,o),s.addToRef(o,r),e.subtractToRef(s,h);const l=v.Dot(n,n),c=v.Dot(n,o),u=v.Dot(o,o),f=v.Dot(n,h),d=v.Dot(o,h),_=l*u-c*c;let p,g=_,m,b=_;_g&&(p=g,m=d+c,b=u)),m<0?(m=0,-f<0?p=0:-f>l?p=g:(p=-f,g=l)):m>b&&(m=b,-f+c<0?p=0:-f+c>l?p=g:(p=-f+c,g=l));const I=Math.abs(p)0&&T<=this.length&&R.lengthSquared()=a.distance?null:l}function $0(a,e,t,i,s,n){let r=null;const o=!!(a.activeCameras&&a.activeCameras.length>1&&a.cameraToUseForPointers!==a.activeCamera),h=a.cameraToUseForPointers||a.activeCamera,l=Zc;for(let c=0;c1&&a.cameraToUseForPointers!==a.activeCamera),r=a.cameraToUseForPointers||a.activeCamera,o=Zc;for(let h=0;h(a._tempPickingRay||(a._tempPickingRay=Ue.Zero()),sa(a,e,t,o,a._tempPickingRay,n||null),a._tempPickingRay),i,s,!0);return r&&(r.ray=ia(a,e,t,O.Identity(),n||null)),r}function r1(a,e,t,i,s,n,r,o=!1){const h=$0(a,(l,c)=>(a._tempPickingRay||(a._tempPickingRay=Ue.Zero()),sa(a,e,t,l,a._tempPickingRay,n||null,!1,c),a._tempPickingRay),i,s,!1,r);return h&&(h.ray=ia(a,e,t,O.Identity(),n||null)),h}function a1(a,e,t,i,s){const n=$0(a,r=>(a._pickWithRayInverseMatrix||(a._pickWithRayInverseMatrix=O.Identity()),r.invertToRef(a._pickWithRayInverseMatrix),a._cachedRayForTransform||(a._cachedRayForTransform=Ue.Zero()),Ue.TransformToRef(e,a._pickWithRayInverseMatrix,a._cachedRayForTransform),a._cachedRayForTransform),t,i,!1,s);return n&&(n.ray=e),n}function o1(a,e,t,i,s,n){return Qc(a,r=>ia(a,e,t,r,s||null),i,n)}function h1(a,e,t,i){return Qc(a,s=>(a._pickWithRayInverseMatrix||(a._pickWithRayInverseMatrix=O.Identity()),s.invertToRef(a._pickWithRayInverseMatrix),a._cachedRayForTransform||(a._cachedRayForTransform=Ue.Zero()),Ue.TransformToRef(e,a._pickWithRayInverseMatrix,a._cachedRayForTransform),a._cachedRayForTransform),t,i)}function Jh(a,e,t=100,i,s){i||(i=a.getWorldMatrix()),e.length=t,s?e.origin.copyFrom(s):e.origin.copyFrom(a.position);const n=N.Vector3[2];n.set(0,0,a._scene.useRightHandedSystem?-1:1);const r=N.Vector3[3];return v.TransformNormalToRef(n,i,r),v.NormalizeToRef(r,e.direction),e}function l1(a,e){e&&(e.prototype.getForwardRay=function(t=100,i,s){return Jh(this,new Ue(v.Zero(),v.Zero(),t),t,i,s)},e.prototype.getForwardRayToRef=function(t,i=100,s,n){return Jh(this,t,i,s,n)}),a&&(O0._IsPickingAvailable=!0,a.prototype.createPickingRay=function(t,i,s,n,r=!1){return ia(this,t,i,s,n,r)})}l1(it,ve);it.prototype.createPickingRayToRef=function(a,e,t,i,s,n=!1,r=!1){return sa(this,a,e,t,i,s,n,r)};it.prototype.createPickingRayInCameraSpace=function(a,e,t){return s1(this,a,e,t)};it.prototype.createPickingRayInCameraSpaceToRef=function(a,e,t,i){return $c(this,a,e,t,i)};it.prototype.pickWithBoundingInfo=function(a,e,t,i,s){return n1(this,a,e,t,i,s)};it.prototype.pick=function(a,e,t,i,s,n,r=!1){return r1(this,a,e,t,i,s,n,r)};it.prototype.pickWithRay=function(a,e,t,i){return a1(this,a,e,t,i)};it.prototype.multiPick=function(a,e,t,i,s){return o1(this,a,e,t,i,s)};it.prototype.multiPickWithRay=function(a,e,t){return h1(this,a,e,t)};class un{constructor(e,t,i,s=""){var h,l;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new Z,this.onErrorObservable=new Z,this.onBindObservable=new Z,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=1,this.name=e,this._key=s,this._engine=i,this.uniqueId=un._UniqueIdSeed++,this.defines=(h=t.defines)!=null?h:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=(l=t.entryPoint)!=null?l:"main",this._shaderStore=Me.GetShadersStore(this._shaderLanguage),this._shaderRepository=Me.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Me.GetIncludesShadersStore(this._shaderLanguage);let n;const r=St()?this._engine.getHostDocument():null;typeof e=="string"?n=e:e.computeSource?n="source:"+e.computeSource:e.computeElement?n=(r==null?void 0:r.getElementById(e.computeElement))||e.computeElement:n=e.compute||e;const o={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,processCodeAfterIncludes:(c,u,f)=>{if(!f)return u;for(const d of f){const p=d.replace("#define","").replace(";","").trim().split(" ");if(p.length===2){const g=p[0],m=p[1];(!isNaN(parseInt(m))||!isNaN(parseFloat(m)))&&(u="const ".concat(g," = ").concat(m,";\n")+u)}}return u}};this._loadShader(n,"Compute","",c=>{f0(o),Id(c,o,u=>{this._rawComputeSourceCode=c,t.processFinalCode&&(u=t.processFinalCode(u));const f=d0(u,"",o);this._useFinalCode(f.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=h0(e);s(r);return}if(e.substring(0,7)==="source:"){s(e.substring(7));return}if(e.substring(0,7)==="base64:"){const r=window.atob(e.substring(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?void 0:e._getComputeShaderCode())!=null?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,s=>{if(s&&s.numErrors>0){this._processCompilationErrors(s,t);return}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)}}_processCompilationErrors(e,t=null){var i;if(this._compilationError="",U.Error("Unable to compile compute effect:"),this.defines&&U.Error("Defines:\n"+this.defines),un.LogShaderCodeOnCompilationError){const s=(i=this._pipelineContext)==null?void 0:i._getComputeShaderCode();s&&(U.Error("Compute code:"),U.Error(s))}if(typeof e=="string")this._compilationError=e,U.Error("Error: "+this._compilationError);else for(const s of e.messages){let n="";s.line!==void 0&&(n+="Line "+s.line+", "),s.offset!==void 0&&(n+="Offset "+s.offset+", "),s.length!==void 0&&(n+="Length "+s.length+", "),n+=s.type+": "+s.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=n,U.Error(n)}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){Me.GetShadersStore(1)["".concat(e,"ComputeShader")]=t}}un._UniqueIdSeed=0;un.LogShaderCodeOnCompilationError=!0;class na{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],h=o.group,l=o.binding,c=r.type,u=r.object;let f=r.indexInGroupEntries,d=this._bindGroupEntries[h];switch(d||(d=this._bindGroupEntries[h]=[]),c){case 5:{const _=u;f!==void 0&&s?d[f].resource=this._cacheSampler.getSampler(_):(r.indexInGroupEntries=d.length,d.push({binding:l,resource:this._cacheSampler.getSampler(_)}));break}case 0:case 4:{const _=u,p=_._texture._hardwareTexture;f!==void 0&&s?(c===0&&(d[f++].resource=this._cacheSampler.getSampler(_._texture)),d[f].resource=p.view):(r.indexInGroupEntries=d.length,c===0&&d.push({binding:l-1,resource:this._cacheSampler.getSampler(_._texture)}),d.push({binding:l,resource:p.view}));break}case 1:{const _=u,p=_._texture._hardwareTexture;p.textureAdditionalUsages&8||U.Error("computeDispatch: The texture (name=".concat(_.name,", uniqueId=").concat(_.uniqueId,") is not a storage texture!"),50),f!==void 0&&s?d[f].resource=p.viewForWriting:(r.indexInGroupEntries=d.length,d.push({binding:l,resource:p.viewForWriting}));break}case 6:{const p=u.underlyingResource;f!==void 0&&s?d[f].resource=this._device.importExternalTexture({source:p}):(r.indexInGroupEntries=d.length,d.push({binding:l,resource:this._device.importExternalTexture({source:p})}));break}case 2:case 3:case 7:{const _=c===7?u:u.getBuffer(),p=_.underlyingResource;f!==void 0&&s?(d[f].resource.buffer=p,d[f].resource.size=_.capacity):(r.indexInGroupEntries=d.length,d.push({binding:l,resource:{buffer:p,offset:0,size:_.capacity}}));break}}}for(let n=0;n0&&f.dispatchWorkgroups(i,s,n),f.end(),l&&(this._timestampQuery.endPass(this._timestampIndex,l),this._timestampIndex+=2)};Ye.prototype.releaseComputeEffects=function(){for(const a in this._compiledComputeEffects){const e=this._compiledComputeEffects[a].getPipelineContext();this._deleteComputePipelineContext(e)}this._compiledComputeEffects={}};Ye.prototype._prepareComputePipelineContext=function(a,e,t,i,s){const n=a;this.dbgShowShaderCode&&(U.Log(i),U.Log(e)),n.sources={compute:e,rawCompute:t},n.stage=this._createComputePipelineStageDescriptor(e,i,s)};Ye.prototype._releaseComputeEffect=function(a){this._compiledComputeEffects[a._key]&&(delete this._compiledComputeEffects[a._key],this._deleteComputePipelineContext(a.getPipelineContext()))};Ye.prototype._rebuildComputeEffects=function(){for(const a in this._compiledComputeEffects){const e=this._compiledComputeEffects[a];e._pipelineContext=null,e._wasPreviouslyReady=!1,e._prepareEffect()}};Ye.prototype._executeWhenComputeStateIsCompiled=function(a,e){a.stage.module.getCompilationInfo().then(t=>{const i={numErrors:0,messages:[]};for(const s of t.messages)s.type==="error"&&i.numErrors++,i.messages.push({type:s.type,text:s.message,line:s.lineNum,column:s.linePos,length:s.length,offset:s.offset});e(i)})};Ye.prototype._deleteComputePipelineContext=function(a){a&&a.dispose()};Ye.prototype._createComputePipelineStageDescriptor=function(a,e,t){return e?e="//"+e.split("\n").join("\n//")+"\n":e="",{module:this._device.createShaderModule({code:e+a}),entryPoint:t}};Ye.prototype._debugPushGroup=function(a,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?(e===1&&(this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass()),this._renderEncoder.pushDebugGroup(a)):this._currentRenderPass?(this._currentRenderPass.pushDebugGroup(a),this._debugStackRenderPass.push(a)):this._pendingDebugCommands.push(["push",a,e]))};Ye.prototype._debugPopGroup=function(a){this._options.enableGPUDebugMarkers&&(a===0||a===1?(a===1&&(this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass()),this._renderEncoder.popDebugGroup()):this._currentRenderPass?(this._currentRenderPass.popDebugGroup(),this._debugStackRenderPass.pop()):this._pendingDebugCommands.push(["pop",null,a]))};Ye.prototype._debugInsertMarker=function(a,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?(e===1&&(this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass()),this._renderEncoder.insertDebugMarker(a)):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(a):this._pendingDebugCommands.push(["insert",a,e]))};Ye.prototype._debugFlushPendingCommands=function(){if(this._debugStackRenderPass.length!==0){const a=this._debugStackRenderPass.slice();this._debugStackRenderPass.length=0;for(let e=0;e{this._textureHelper.updateTexture(n,a,a.width,a.height,a.depth,i.format,0,0,!t,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a),a.isReady=!0}).catch(()=>{a.isReady=!0})};var f1={value:()=>{}};function Jc(){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}})}gr.prototype=Jc.prototype={constructor:gr,on:function(a,e){var t=this._,i=d1(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)),il.hasOwnProperty(e)?{space:il[e],local:a}:a}function p1(a){return function(){var e=this.ownerDocument,t=this.namespaceURI;return t===Xa&&e.documentElement.namespaceURI===Xa?e.createElement(a):e.createElementNS(t,a)}}function g1(a){return function(){return this.ownerDocument.createElementNS(a.space,a.local)}}function Z0(a){var e=ra(a);return(e.local?g1:p1)(e)}function m1(){}function Q0(a){return a==null?m1:function(){return this.querySelector(a)}}function v1(a){typeof a!="function"&&(a=Q0(a));for(var e=this._groups,t=e.length,i=new Array(t),s=0;s=I&&(I=b+1);!(x=g[I])&&++I<_;);T._next=x||null}}return r=new di(r,i),r._enter=o,r._exit=h,r}function U1(a){return typeof a=="object"&&"length"in a?a:Array.from(a)}function k1(){return new di(this._exit||this._groups.map(su),this._parents)}function V1(a,e,t){var i=this.enter(),s=this,n=this.exit();return typeof a=="function"?(i=a(i),i&&(i=i.selection())):i=i.append(a+""),e!=null&&(s=e(s),s&&(s=s.selection())),t==null?n.remove():t(n),i&&s?i.merge(s).order():s}function G1(a){for(var e=a.selection?a.selection():a,t=this._groups,i=e._groups,s=t.length,n=i.length,r=Math.min(s,n),o=new Array(s),h=0;h=0;)(r=i[s])&&(n&&r.compareDocumentPosition(n)^4&&n.parentNode.insertBefore(r,n),n=r);return this}function W1(a){a||(a=H1);function e(u,f){return u&&f?a(u.__data__,f.__data__):!u-!f}for(var t=this._groups,i=t.length,s=new Array(i),n=0;ne?1:a>=e?0:NaN}function K1(){var a=arguments[0];return arguments[0]=this,a.apply(null,arguments),this}function X1(){return Array.from(this)}function Y1(){for(var a=this._groups,e=0,t=a.length;e1?this.each((e==null?nm:typeof e=="function"?am:rm)(a,e,t==null?"":t)):fn(this.node(),a)}function fn(a,e){return a.style.getPropertyValue(e)||nu(a).getComputedStyle(a,null).getPropertyValue(e)}function hm(a){return function(){delete this[a]}}function lm(a,e){return function(){this[a]=e}}function cm(a,e){return function(){var t=e.apply(this,arguments);t==null?delete this[a]:this[a]=t}}function um(a,e){return arguments.length>1?this.each((e==null?hm:typeof e=="function"?cm:lm)(a,e)):this.node()[a]}function ru(a){return a.trim().split(/^|\s+/)}function J0(a){return a.classList||new au(a)}function au(a){this._node=a,this._names=ru(a.getAttribute("class")||"")}au.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 ou(a,e){for(var t=J0(a),i=-1,s=e.length;++i=0&&(t=e.slice(i+1),e=e.slice(0,i)),{type:e,name:t}})}function km(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?lr(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):t===4?lr(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=jm.exec(a))?new ai(e[1],e[2],e[3],1):(e=$m.exec(a))?new ai(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=Zm.exec(a))?lr(e[1],e[2],e[3],e[4]):(e=Qm.exec(a))?lr(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=Jm.exec(a))?ll(e[1],e[2]/100,e[3]/100,1):(e=e2.exec(a))?ll(e[1],e[2]/100,e[3]/100,e[4]):sl.hasOwnProperty(a)?al(sl[a]):a==="transparent"?new ai(NaN,NaN,NaN,0):null}function al(a){return new ai(a>>16&255,a>>8&255,a&255,1)}function lr(a,e,t,i){return i<=0&&(a=e=t=NaN),new ai(a,e,t,i)}function s2(a){return a instanceof Jn||(a=Gn(a)),a?(a=a.rgb(),new ai(a.r,a.g,a.b,a.opacity)):new ai}function Ya(a,e,t,i){return arguments.length===1?s2(a):new ai(a,e,t,i==null?1:i)}function ai(a,e,t,i){this.r=+a,this.g=+e,this.b=+t,this.opacity=+i}eo(ai,Ya,fu(Jn,{brighter(a){return a=a==null?Dr:Math.pow(Dr,a),new ai(this.r*a,this.g*a,this.b*a,this.opacity)},darker(a){return a=a==null?kn:Math.pow(kn,a),new ai(this.r*a,this.g*a,this.b*a,this.opacity)},rgb(){return this},clamp(){return new ai(Us(this.r),Us(this.g),Us(this.b),Fr(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:ol,formatHex:ol,formatHex8:n2,formatRgb:hl,toString:hl}));function ol(){return"#".concat(Bs(this.r)).concat(Bs(this.g)).concat(Bs(this.b))}function n2(){return"#".concat(Bs(this.r)).concat(Bs(this.g)).concat(Bs(this.b)).concat(Bs((isNaN(this.opacity)?1:this.opacity)*255))}function hl(){const a=Fr(this.opacity);return"".concat(a===1?"rgb(":"rgba(").concat(Us(this.r),", ").concat(Us(this.g),", ").concat(Us(this.b)).concat(a===1?")":", ".concat(a,")"))}function Fr(a){return isNaN(a)?1:Math.max(0,Math.min(1,a))}function Us(a){return Math.max(0,Math.min(255,Math.round(a)||0))}function Bs(a){return a=Us(a),(a<16?"0":"")+a.toString(16)}function ll(a,e,t,i){return i<=0?a=e=t=NaN:t<=0||t>=1?a=e=NaN:e<=0&&(a=NaN),new Mi(a,e,t,i)}function du(a){if(a instanceof Mi)return new Mi(a.h,a.s,a.l,a.opacity);if(a instanceof Jn||(a=Gn(a)),!a)return new Mi;if(a instanceof Mi)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,h=(n+s)/2;return o?(e===n?r=(t-i)/o+(t0&&h<1?0:r,new Mi(r,o,h,a.opacity)}function r2(a,e,t,i){return arguments.length===1?du(a):new Mi(a,e,t,i==null?1:i)}function Mi(a,e,t,i){this.h=+a,this.s=+e,this.l=+t,this.opacity=+i}eo(Mi,r2,fu(Jn,{brighter(a){return a=a==null?Dr:Math.pow(Dr,a),new Mi(this.h,this.s,this.l*a,this.opacity)},darker(a){return a=a==null?kn:Math.pow(kn,a),new Mi(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 ai(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 Mi(cl(this.h),cr(this.s),cr(this.l),Fr(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=Fr(this.opacity);return"".concat(a===1?"hsl(":"hsla(").concat(cl(this.h),", ").concat(cr(this.s)*100,"%, ").concat(cr(this.l)*100,"%").concat(a===1?")":", ".concat(a,")"))}}));function cl(a){return a=(a||0)%360,a<0?a+360:a}function cr(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 _u=a=>()=>a;function a2(a,e){return function(t){return a+t*e}}function o2(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 h2(a){return(a=+a)==1?pu:function(e,t){return t-e?o2(e,t,a):_u(isNaN(e)?t:e)}}function pu(a,e){var t=e-a;return t?a2(a,t):_u(isNaN(a)?e:a)}const ul=function a(e){var t=h2(e);function i(s,n){var r=t((s=Ya(s)).r,(n=Ya(n)).r),o=t(s.g,n.g),h=t(s.b,n.b),l=pu(s.opacity,n.opacity);return function(c){return s.r=r(c),s.g=o(c),s.b=h(c),s.opacity=l(c),s+""}}return i.gamma=a,i}(1);function bs(a,e){return a=+a,e=+e,function(t){return a*(1-t)+e*t}}var qa=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ca=new RegExp(qa.source,"g");function l2(a){return function(){return a}}function c2(a){return function(e){return a(e)+""}}function u2(a,e){var t=qa.lastIndex=Ca.lastIndex=0,i,s,n,r=-1,o=[],h=[];for(a=a+"",e=e+"";(i=qa.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,h.push({i:r,x:bs(i,s)})),t=Ca.lastIndex;return t180?c+=360:c-l>180&&(l+=360),f.push({i:u.push(s(u)+"rotate(",null,i)-2,x:bs(l,c)})):c&&u.push(s(u)+"rotate("+c+i)}function o(l,c,u,f){l!==c?f.push({i:u.push(s(u)+"skewX(",null,i)-2,x:bs(l,c)}):c&&u.push(s(u)+"skewX("+c+i)}function h(l,c,u,f,d,_){if(l!==u||c!==f){var p=d.push(s(d)+"scale(",null,",",null,")");_.push({i:p-4,x:bs(l,u)},{i:p-2,x:bs(c,f)})}else(u!==1||f!==1)&&d.push(s(d)+"scale("+u+","+f+")")}return function(l,c){var u=[],f=[];return l=a(l),c=a(c),n(l.translateX,l.translateY,c.translateX,c.translateY,u,f),r(l.rotate,c.rotate,u,f),o(l.skewX,c.skewX,u,f),h(l.scaleX,l.scaleY,c.scaleX,c.scaleY,u,f),l=c=null,function(d){for(var _=-1,p=f.length,g;++_=0&&a._call.call(void 0,e),a=a._next;--dn}function dl(){Gs=(Br=zn.now())+aa,dn=An=0;try{m2()}finally{dn=0,b2(),Gs=0}}function v2(){var a=zn.now(),e=a-Br;e>vu&&(aa-=e,Br=a)}function b2(){for(var a,e=Or,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:Or=t);Rn=a,$a(i)}function $a(a){if(!dn){An&&(An=clearTimeout(An));var e=a-Gs;e>24?(a<1/0&&(An=setTimeout(dl,a-zn.now()-aa)),yn&&(yn=clearInterval(yn))):(yn||(Br=zn.now(),yn=setInterval(v2,vu)),dn=1,bu(dl))}}function _l(a,e,t){var i=new Lr;return e=e==null?0:+e,i.restart(s=>{i.stop(),a(s+e)},e,t),i}var x2=Jc("start","end","cancel","interrupt"),y2=[],yu=0,pl=1,Za=2,mr=3,gl=4,Qa=5,vr=6;function oa(a,e,t,i,s,n){var r=a.__transition;if(!r)a.__transition={};else if(t in r)return;T2(a,t,{name:e,index:i,group:s,on:x2,tween:y2,time:n.time,delay:n.delay,duration:n.duration,ease:n.ease,timer:null,state:yu})}function io(a,e){var t=Oi(a,e);if(t.state>yu)throw new Error("too late; already scheduled");return t}function Xi(a,e){var t=Oi(a,e);if(t.state>mr)throw new Error("too late; already running");return t}function Oi(a,e){var t=a.__transition;if(!t||!(t=t[e]))throw new Error("transition not found");return t}function T2(a,e,t){var i=a.__transition,s;i[e]=t,t.timer=xu(n,0,t.time);function n(l){t.state=pl,t.timer.restart(r,t.delay,t.time),t.delay<=l&&r(l-t.delay)}function r(l){var c,u,f,d;if(t.state!==pl)return h();for(c in i)if(d=i[c],d.name===t.name){if(d.state===mr)return _l(r);d.state===gl?(d.state=vr,d.timer.stop(),d.on.call("interrupt",a,a.__data__,d.index,d.group),delete i[c]):+cZa&&i.state=0&&(e=e.slice(0,t)),!e||e==="start"})}function J2(a,e,t){var i,s,n=Q2(e)?io:Xi;return function(){var r=n(this,a),o=r.on;o!==i&&(s=(i=o).copy()).on(e,t),r.on=s}}function ev(a,e){var t=this._id;return arguments.length<2?Oi(this.node(),t).on.on(a):this.each(J2(t,a,e))}function tv(a){return function(){var e=this.parentNode;for(var t in this.__transition)if(+t!==a)return;e&&e.removeChild(this)}}function iv(){return this.on("end.remove",tv(this._id))}function sv(a){var e=this._name,t=this._id;typeof a!="function"&&(a=Q0(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,h=a.uvs,l=a.colors,c=[],u=[],f=[],d=[],_=[],p=[],g=[],m=[];let b;const I=[],T=[];let x,y,R;if(e.length<2){const Q=[],be=[];for(y=0;y0&&(G=w[R].subtract(w[R-1]).length(),L=G+g[x],_[x].push(L),g[x]=L),R++;i&&(R--,c.push(w[0].x,w[0].y,w[0].z),G=w[R].subtract(w[0]).length(),L=G+g[x],_[x].push(L),g[x]=L),I[x]=P+C,T[x]=E,E+=P+C}let W,K,ce=null,$=null;for(y=0;y{let _=i[0].length;const p=o;let g=0;const m=p._originalBuilderSideOrientation===F.DOUBLESIDE?2:1;for(let b=1;b<=m;++b)for(let I=0;Izs(a,{pathArray:e,closeArray:t,closePath:i,offset:s,updatable:r,sideOrientation:o,instance:h},n);function Eu(a){const e=[],t=[],i=[],s=[],n=a.radius||.5,r=a.tessellation||64,o=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,h=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE;e.push(0,0,0),s.push(.5,.5);const l=Math.PI*2*o,c=o===1?l/r:l/(r-1);let u=0;for(let _=0;_Cu(a,{radius:e,tessellation:t,sideOrientation:n,updatable:s},i);F._GroundMeshParser=(a,e)=>er.Parse(a,e);class er extends F{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=N.Matrix[5];i.invertToRef(s);const n=N.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=N.Matrix[5];s.invertToRef(n);const r=N.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){l=!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),f=(u.x+a.width/2)/a.width*(a.bufferWidth-1)|0,d=(1-(u.z+a.height/2)/a.height)*(a.bufferHeight-1)|0,_=(f+d*a.bufferWidth)*4;let p=a.buffer[_]/255,g=a.buffer[_+1]/255,m=a.buffer[_+2]/255;const b=a.buffer[_+3]/255;l&&(p=1-p,g=1-g,m=1-m);const I=p*o.r+g*o.g+m*o.b;b>=h?u.y=a.minHeight+(a.maxHeight-a.minHeight)*I:u.y=a.minHeight-Le,a.heightBuffer&&(a.heightBuffer[n*(a.subdivisions+1)+r]=u.y),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,g=t[f*3+1]>=a.minHeight,m=t[d*3+1]>=a.minHeight;p&&g&&m&&(e.push(u),e.push(f),e.push(d)),t[_*3+1]>=a.minHeight&&p&&m&&(e.push(_),e.push(u),e.push(d))}j.ComputeNormals(t,e,i);const c=new j;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function wu(a,e={},t){const i=new er(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,Su(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function Du(a,e,t=null){const i=new F(a,t);return Mu(e).applyToMesh(i,e.updatable),i}function Fu(a,e,t={},i=null){const s=t.width||10,n=t.height||10,r=t.subdivisions||1,o=t.minHeight||0,h=t.maxHeight||1,l=t.colorFilter||new de(.3,.59,.11),c=t.alphaFilter||0,u=t.updatable,f=t.onReady;i=i||Ee.LastCreatedScene;const d=new er(a,i);d._subdivisionsX=r,d._subdivisionsY=r,d._width=s,d._height=n,d._maxX=d._width/2,d._maxZ=d._height/2,d._minX=-d._maxX,d._minZ=-d._maxZ,d._setReady(!1);let _;t.passHeightBufferInCallback&&(_=new Float32Array((r+1)*(r+1)));const p=(g,m,b)=>{Pu({width:s,height:n,subdivisions:r,minHeight:o,maxHeight:h,colorFilter:l,buffer:g,bufferWidth:m,bufferHeight:b,alphaFilter:c,heightBuffer:_}).applyToMesh(d,u),f&&f(d,_),d._setReady(!0)};if(typeof e=="string"){const g=m=>{const b=m.width,I=m.height;if(i.isDisposed)return;const T=i==null?void 0:i.getEngine().resizeImageBitmap(m,b,I);p(T,b,I)};J.LoadImage(e,g,t.onError?t.onError:()=>{},i.offlineProvider)}else p(e.data,e.width,e.height);return d}j.CreateGround=Su;j.CreateTiledGround=Mu;j.CreateGroundFromHeightMap=Pu;F.CreateGround=(a,e,t,i,s,n)=>wu(a,{width:e,height:t,subdivisions:i,updatable:n},s);F.CreateTiledGround=(a,e,t,i,s,n,r,o,h)=>Du(a,{xmin:e,zmin:t,xmax:i,zmax:s,subdivisions:n,precision:r,updatable:h},o);F.CreateGroundFromHeightMap=(a,e,t,i,s,n,r,o,h,l,c)=>Fu(a,e,{width:t,height:i,subdivisions:s,minHeight:n,maxHeight:r,updatable:h,onReady:l,alphaFilter:c},o);function Ou(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,h=a.depth||a.size||1,l=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 f=[2,0,3,1],d=[2,0,1,3];let _=f[c],p=d[u],g=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],g=[-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 R=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],E=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const C=[17,18,19,16],S=[22,23,20,21];for(;_>0;)R.unshift(R.pop()),C.unshift(C.pop()),_--;for(;p>0;)E.unshift(E.pop()),S.unshift(S.pop()),p--;R=R.flat(),E=E.flat(),g=g.concat(R).concat(E),t.push(C[0],C[2],C[3],C[0],C[1],C[2]),t.push(S[0],S[2],S[3],S[0],S[1],S[2])}const m=[r/2,o/2,h/2];n=g.reduce((R,E,C)=>R.concat(E*m[C%3]),[]);const b=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,I=a.faceUV||new Array(6),T=a.faceColors,x=[];for(let R=0;R<6;R++)I[R]===void 0&&(I[R]=new Pe(0,0,1,1)),T&&T[R]===void 0&&(T[R]=new H(1,1,1,1));for(let R=0;R<6;R++)if(s.push(I[R].z,I[R].w),s.push(I[R].x,I[R].w),s.push(I[R].x,I[R].y),s.push(I[R].z,I[R].y),T)for(let E=0;E<4;E++)x.push(T[R].r,T[R].g,T[R].b,T[R].a);j._ComputeSides(b,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,T){const R=b===j.DOUBLESIDE?x.concat(x):x;y.colors=R}return y}function Bu(a,e={},t=null){const i=new F(a,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Ou(e).applyToMesh(i,e.updatable),i}j.CreateBox=Ou;F.CreateBox=(a,e,t=null,i,s)=>Bu(a,{size:e,sideOrientation:s,updatable:i},t);function Mn(a){const e=a.pattern||F.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 h=r-o*t;const l=a.height||a.size||1,c=Math.floor(l/i);let u=l-c*i;const f=t*o/2,d=i*c/2;let _=0,p=0,g=0,m=0,b=0,I=0;if(h>0||u>0){switch(g=-f,m=-d,b=f,I=d,s){case F.CENTER:h/=2,g-=h,b+=h;break;case F.LEFT:b+=h,_=-h/2;break;case F.RIGHT:g-=h,_=h/2;break}switch(n){case F.CENTER:u/=2,m-=u,I+=u;break;case F.BOTTOM:I+=u,p=-u/2;break;case F.TOP:m-=u,p=u/2;break}}const T=[],x=[],y=[];y[0]=[0,0,1,0,1,1,0,1],y[1]=[0,0,1,0,1,1,0,1],(e===F.ROTATE_TILE||e===F.ROTATE_ROW)&&(y[1]=[1,1,0,1,0,0,1,0]),(e===F.FLIP_TILE||e===F.FLIP_ROW)&&(y[1]=[1,0,0,0,0,1,1,1]),(e===F.FLIP_N_ROTATE_TILE||e===F.FLIP_N_ROTATE_ROW)&&(y[1]=[0,1,1,1,1,0,0,0]);let R=[];const E=[],C=[];let S=0;for(let L=0;L0||u>0){const L=u>0&&(n===F.CENTER||n===F.TOP),W=u>0&&(n===F.CENTER||n===F.BOTTOM),K=h>0&&(s===F.CENTER||s===F.RIGHT),ce=h>0&&(s===F.CENTER||s===F.LEFT);let $=[],z,k,M,V;if(L&&K&&(T.push(g+_,m+p,0),T.push(-f+_,m+p,0),T.push(-f+_,m+u+p,0),T.push(g+_,m+u+p,0),C.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,z=1-h/t,k=1-u/i,M=1,V=1,$=[z,k,M,k,M,V,z,V],e===F.ROTATE_ROW&&($=[1-z,1-k,1-M,1-k,1-M,1-V,1-z,1-V]),e===F.FLIP_ROW&&($=[1-z,k,1-M,k,1-M,V,1-z,V]),e===F.FLIP_N_ROTATE_ROW&&($=[z,1-k,M,1-k,M,1-V,z,1-V]),R=R.concat($),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),x.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L&&ce&&(T.push(f+_,m+p,0),T.push(b+_,m+p,0),T.push(b+_,m+u+p,0),T.push(f+_,m+u+p,0),C.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,z=0,k=1-u/i,M=h/t,V=1,$=[z,k,M,k,M,V,z,V],(e===F.ROTATE_ROW||e===F.ROTATE_TILE&&o%2===0)&&($=[1-z,1-k,1-M,1-k,1-M,1-V,1-z,1-V]),(e===F.FLIP_ROW||e===F.FLIP_TILE&&o%2===0)&&($=[1-z,k,1-M,k,1-M,V,1-z,V]),(e===F.FLIP_N_ROTATE_ROW||e===F.FLIP_N_ROTATE_TILE&&o%2===0)&&($=[z,1-k,M,1-k,M,1-V,z,1-V]),R=R.concat($),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),x.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),W&&K&&(T.push(g+_,d+p,0),T.push(-f+_,d+p,0),T.push(-f+_,I+p,0),T.push(g+_,I+p,0),C.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,z=1-h/t,k=0,M=1,V=u/i,$=[z,k,M,k,M,V,z,V],(e===F.ROTATE_ROW&&c%2===1||e===F.ROTATE_TILE&&c%1===0)&&($=[1-z,1-k,1-M,1-k,1-M,1-V,1-z,1-V]),(e===F.FLIP_ROW&&c%2===1||e===F.FLIP_TILE&&c%2===0)&&($=[1-z,k,1-M,k,1-M,V,1-z,V]),(e===F.FLIP_N_ROTATE_ROW&&c%2===1||e===F.FLIP_N_ROTATE_TILE&&c%2===0)&&($=[z,1-k,M,1-k,M,1-V,z,1-V]),R=R.concat($),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),x.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),W&&ce&&(T.push(f+_,d+p,0),T.push(b+_,d+p,0),T.push(b+_,I+p,0),T.push(f+_,I+p,0),C.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,z=0,k=0,M=h/t,V=u/i,$=[z,k,M,k,M,V,z,V],(e===F.ROTATE_ROW&&c%2===1||e===F.ROTATE_TILE&&(c+o)%2===1)&&($=[1-z,1-k,1-M,1-k,1-M,1-V,1-z,1-V]),(e===F.FLIP_ROW&&c%2===1||e===F.FLIP_TILE&&(c+o)%2===1)&&($=[1-z,k,1-M,k,1-M,V,1-z,V]),(e===F.FLIP_N_ROTATE_ROW&&c%2===1||e===F.FLIP_N_ROTATE_TILE&&(c+o)%2===1)&&($=[z,1-k,M,1-k,M,1-V,z,1-V]),R=R.concat($),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),x.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L){const q=[];z=0,k=1-u/i,M=1,V=1,q[0]=[z,k,M,k,M,V,z,V],q[1]=[z,k,M,k,M,V,z,V],(e===F.ROTATE_TILE||e===F.ROTATE_ROW)&&(q[1]=[1-z,1-k,1-M,1-k,1-M,1-V,1-z,1-V]),(e===F.FLIP_TILE||e===F.FLIP_ROW)&&(q[1]=[1-z,k,1-M,k,1-M,V,1-z,V]),(e===F.FLIP_N_ROTATE_TILE||e===F.FLIP_N_ROTATE_ROW)&&(q[1]=[z,1-k,M,1-k,M,1-V,z,1-V]);for(let he=0;heq+w)),w+=R[M].length,i)for(let q=0;q<4;q++)y.push(i[M].r,i[M].g,i[M].b,i[M].a)}const P=new v(0,0,p),G=O.RotationY(Math.PI);b=R[0].map(M=>v.TransformNormal(M,G).add(P)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[]),I=E[0].map(M=>v.TransformNormal(M,G)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[]),b=b.concat(R[1].map(M=>M.subtract(P)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[])),I=I.concat(E[1].map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[]));const L=new v(d,0,0),W=O.RotationY(-Math.PI/2);b=b.concat(R[2].map(M=>v.TransformNormal(M,W).add(L)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[])),I=I.concat(E[2].map(M=>v.TransformNormal(M,W)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[]));const K=O.RotationY(Math.PI/2);b=b.concat(R[3].map(M=>v.TransformNormal(M,K).subtract(L)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[])),I=I.concat(E[3].map(M=>v.TransformNormal(M,K)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[]));const ce=new v(0,_,0),$=O.RotationX(Math.PI/2);b=b.concat(R[4].map(M=>v.TransformNormal(M,$).add(ce)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[])),I=I.concat(E[4].map(M=>v.TransformNormal(M,$)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[]));const z=O.RotationX(-Math.PI/2);b=b.concat(R[5].map(M=>v.TransformNormal(M,z).subtract(ce)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[])),I=I.concat(E[5].map(M=>v.TransformNormal(M,z)).map(M=>[M.x,M.y,M.z]).reduce((M,V)=>M.concat(V),[])),j._ComputeSides(f,b,x,I,T);const k=new j;if(k.indices=x,k.positions=b,k.normals=I,k.uvs=T,i){const M=f===j.DOUBLESIDE?y.concat(y):y;k.colors=M}return k}function Mv(a,e,t=null){const i=new F(a,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Lu(e).applyToMesh(i,e.updatable),i}j.CreateTiledBox=Lu;function Nu(a){const e=(a.segments||32)|0,t=a.diameterX||a.diameter||1,i=a.diameterY||a.diameter||1,s=a.diameterZ||a.diameter||1,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,h=!!a.dedupTopBottomIndices,l=new v(t/2,i/2,s/2),c=2+e,u=2*c,f=[],d=[],_=[],p=[];for(let m=0;m<=c;m++){const b=m/c,I=b*Math.PI*r;for(let T=0;T<=u;T++){const x=T/u,y=x*Math.PI*2*n,R=O.RotationZ(-I),E=O.RotationY(y),C=v.TransformCoordinates(v.Up(),R),S=v.TransformCoordinates(C,E),w=S.multiply(l),P=S.divide(l).normalize();d.push(w.x,w.y,w.z),_.push(P.x,P.y,P.z),p.push(x,b)}if(m>0){const T=d.length/3;for(let x=T-2*(u+1);x+u+21&&(f.push(x),f.push(x+1),f.push(x+u+1)),(mUu(a,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:n,updatable:s},i);function ku(a){const e=a.height||2;let t=a.diameterTop===0?0:a.diameterTop||a.diameter||1,i=a.diameterBottom===0?0:a.diameterBottom||a.diameter||1;t=t||1e-5,i=i||1e-5;const s=(a.tessellation||24)|0,n=(a.subdivisions||1)|0,r=!!a.hasRings,o=!!a.enclose,h=a.cap===0?0:a.cap||F.CAP_ALL,l=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),f=a.faceColors,d=l!==1&&o?2:0,_=r?n:1,p=2+(1+d)*_;let g;for(g=0;g{const me=ue?t/2:i/2;if(me===0)return;let ne,Ie,Se;const Q=ue?u[p-1]:u[0];let be=null;f&&(be=ue?f[p-1]:f[0]);const Be=b.length/3,ze=ue?e/2:-e/2,Ke=new v(0,ze,0);b.push(Ke.x,Ke.y,Ke.z),I.push(0,ue?1:-1,0);const Rt=Q.y+(Q.w-Q.y)*.5;T.push(Q.x+(Q.z-Q.x)*.5,Rt),be&&x.push(be.r,be.g,be.b,be.a);const Ct=new oe(.5,.5);for(Se=0;Se<=s;Se++){ne=Math.PI*2*Se*l/s;const Ge=Math.cos(-ne),Jt=Math.sin(-ne);Ie=new v(Ge*me,ze,Jt*me);const Wt=new oe(Ge*Ct.x+.5,Jt*Ct.y+.5);b.push(Ie.x,Ie.y,Ie.z),I.push(0,ue?1:-1,0);const ji=Q.y+(Q.w-Q.y)*Wt.y;T.push(Q.x+(Q.z-Q.x)*Wt.x,ji),be&&x.push(be.r,be.g,be.b,be.a)}for(Se=0;Se((r===void 0||!(r instanceof it))&&(r!==void 0&&(h=o||F.DEFAULTSIDE,o=r),r=n,n=1),Vu(a,{height:e,diameterTop:t,diameterBottom:i,tessellation:s,subdivisions:n,sideOrientation:h,updatable:o},r));function Gu(a){const e=[],t=[],i=[],s=[],n=a.diameter||1,r=a.thickness||.5,o=(a.tessellation||16)|0,h=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,l=o+1;for(let u=0;u<=o;u++){const f=u/o,d=u*Math.PI*2/o-Math.PI/2,_=O.Translation(n/2,0,0).multiply(O.RotationY(d));for(let p=0;p<=o;p++){const g=1-p/o,m=p*Math.PI*2/o+Math.PI,b=Math.cos(m),I=Math.sin(m);let T=new v(b,I,0),x=T.scale(r/2);const y=new oe(f,g);x=v.TransformCoordinates(x,_),T=v.TransformNormal(T,_),t.push(x.x,x.y,x.z),i.push(T.x,T.y,T.z),s.push(y.x,y.y);const R=(u+1)%l,E=(p+1)%l;e.push(u*l+p),e.push(u*l+E),e.push(R*l+p),e.push(u*l+E),e.push(R*l+E),e.push(R*l+p)}}j._ComputeSides(h,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 zu(a,e={},t){const i=new F(a,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Gu(e).applyToMesh(i,e.updatable),i}j.CreateTorus=Gu;F.CreateTorus=(a,e,t,i,s,n,r)=>zu(a,{diameter:e,thickness:t,tessellation:i,sideOrientation:r,updatable:n},s);function Wu(a){const e=[],t=[],i=[],s=[],n=a.radius||2,r=a.tube||.5,o=a.radialSegments||32,h=a.tubularSegments||32,l=a.p||2,c=a.q||3,u=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,f=g=>{const m=Math.cos(g),b=Math.sin(g),I=c/l*g,T=Math.cos(I),x=n*(2+T)*.5*m,y=n*(2+T)*b*.5,R=n*Math.sin(I)*.5;return new v(x,y,R)};let d,_;for(d=0;d<=o;d++){const m=d%o/o*2*l*Math.PI,b=f(m),I=f(m+.01),T=I.subtract(b);let x=I.add(b);const y=v.Cross(T,x);for(x=v.Cross(y,T),y.normalize(),x.normalize(),_=0;_Hu(a,{radius:e,tube:t,radialSegments:i,tubularSegments:s,p:n,q:r,sideOrientation:l,updatable:h},o);function Ku(a){const e=[],t=[],i=a.lines,s=a.colors,n=[];let r=0;for(let h=0;h0&&(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 Xu(a){const e=a.dashSize||3,t=a.gapSize||1,i=a.dashNb||200,s=a.points,n=[],r=[],o=v.Zero();let h=0,l=0,c=0,u=0,f=0,d=0,_=0;for(_=0;_{const u=v.Zero(),f=c.length/6;let d=0,_=0,p=0,g=0,m=0,b=0,I=0,T=0;for(I=0;Iqu(a,{points:e,updatable:i,instance:s},t);F.CreateDashedLines=(a,e,t,i,s,n=null,r,o)=>ju(a,{points:e,dashSize:t,gapSize:i,dashNb:s,updatable:r,instance:o},n);class Pv extends oe{constructor(e,t){super(e.x,e.y),this.index=t}}class Sa{constructor(){this.elements=[]}add(e){const t=[];return e.forEach(i=>{const s=new Pv(i,this.elements.length);t.push(s),this.elements.push(s)}),t}computeBounds(){const e=new oe(this.elements[0].x,this.elements[0].y),t=new oe(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 wv{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){this._points=new Sa,this._outlinepoints=new Sa,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||Ee.LastCreatedScene;let n;t instanceof Gr?n=t.getPoints():n=t,this._addToepoint(n),this._points.add(n),this._outlinepoints.add(n),typeof this.bjsEarcut>"u"&&U.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new Sa;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 F(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=[],n=[],r=[],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 h=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let c=0;c0){const c=n.length/3;this._points.elements.forEach(f=>{s.push(0,-1,0),n.push(f.x,-e,f.y),r.push(1-(f.x-o.min.x)/o.width,1-(f.y-o.min.y)/o.height)});const u=h.length;for(let f=0;f{this._addSide(n,s,r,h,o,f,e,!0,t)})}return i.indices=h,i.positions=n,i.normals=s,i.uvs=r,i}_addSide(e,t,i,s,n,r,o,h,l){let c=e.length/3,u=0;for(let f=0;fl?Rl?Eno(a,{shape:e,holes:i,updatable:s,sideOrientation:n},t,r);F.ExtrudePolygon=(a,e,t,i,s,n,r,o=earcut)=>ro(a,{shape:e,holes:s,depth:t,updatable:n,sideOrientation:r},i,o);function Zu(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||F.NO_CAP,h=e.updatable,l=F._GetDefaultSideOrientation(e.sideOrientation),c=e.instance||null,u=e.invertUV||!1,f=e.closeShape||!1,d=e.closePath||!1;return Ju(a,s,i,n,r,null,null,d,f,o,!1,t,!!h,l,c,u,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function Qu(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,h=e.closeShape||e.ribbonClosePath||!1,l=e.cap===0?0:e.cap||F.NO_CAP,c=e.updatable,u=e.firstNormal||null,f=e.adjustFrame||!1,d=F._GetDefaultSideOrientation(e.sideOrientation),_=e.instance,p=e.invertUV||!1;return Ju(a,s,i,null,null,n,r,o,h,l,!0,t,!!c,d,_||null,p,e.frontUVs||null,e.backUVs||null,u,f)}function Ju(a,e,t,i,s,n,r,o,h,l,c,u,f,d,_,p,g,m,b,I){const T=(C,S,w,P,G,L,W,K,ce,$,z)=>{const k=w.getTangents(),M=w.getNormals(),V=w.getBinormals(),q=w.getDistances();if(z){for(let Q=0;Q0){let be=k[Q-1];v.Dot(be,k[Q])<0&&k[Q].scaleInPlace(-1),be=M[Q-1],v.Dot(be,M[Q])<0&&M[Q].scaleInPlace(-1),be=V[Q-1],v.Dot(be,V[Q])<0&&V[Q].scaleInPlace(-1)}}let he=0;const pe=()=>G!==null?G:1,ue=$&&K?K:()=>L!==null?L:0,me=$&&W?W:pe;let ne=ce===F.NO_CAP||ce===F.CAP_END?0:2;const Ie=N.Matrix[0];for(let Q=0;Q{const be=Array(),Be=v.Zero();let ze;for(ze=0;ze3?0:l,y=T(e,t,x,R,i,s,n,r,l,c,I);const E=zs(a,{pathArray:y,closeArray:o,closePath:h,updatable:f,sideOrientation:d,invertUV:p,frontUVs:g||void 0,backUVs:m||void 0},u);return E._creationDataStorage.pathArray=y,E._creationDataStorage.path3D=x,E._creationDataStorage.cap=l,E}F.ExtrudeShape=(a,e,t,i,s,n,r=null,o,h,l)=>{const c={shape:e,path:t,scale:i,rotation:s,cap:n===0?0:n||F.NO_CAP,sideOrientation:h,instance:l,updatable:o};return Zu(a,c,r)};F.ExtrudeShapeCustom=(a,e,t,i,s,n,r,o,h,l,c,u)=>{const f={shape:e,path:t,scaleFunction:i,rotationFunction:s,ribbonCloseArray:n,ribbonClosePath:r,cap:o===0?0:o||F.NO_CAP,sideOrientation:c,instance:u,updatable:l};return Qu(a,f,h)};function ef(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,h=e.clip||0,l=e.updatable,c=F._GetDefaultSideOrientation(e.sideOrientation),u=e.cap||F.NO_CAP,f=Math.PI*2,d=[],_=e.invertUV||!1;let p=0,g=0;const m=f/o*i;let b,I;for(p=0;p<=o-h;p++){for(I=[],(u==F.CAP_START||u==F.CAP_ALL)&&(I.push(new v(0,n[0].y,0)),I.push(new v(Math.cos(p*m)*n[0].x*r,n[0].y,Math.sin(p*m)*n[0].x*r))),g=0;gef(a,{shape:e,radius:t,tessellation:i,sideOrientation:r,updatable:n},s);function tf(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,h=n/2,l=r/2;t.push(-h,-l,0),i.push(0,0,-1),s.push(0,0),t.push(h,-l,0),i.push(0,0,-1),s.push(1,0),t.push(h,l,0),i.push(0,0,-1),s.push(1,1),t.push(-h,l,0),i.push(0,0,-1),s.push(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 sf(a,e={},t=null){const i=new F(a,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,tf(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=tf;F.CreatePlane=(a,e,t,i,s)=>sf(a,{size:e,width:e,height:e,sideOrientation:s,updatable:i},t);function nf(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 h=e.cap||F.NO_CAP;const l=e.invertUV||!1,c=e.updatable,u=F._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const f=(m,b,I,T,x,y,R,E)=>{const C=b.getTangents(),S=b.getNormals(),w=b.getDistances(),G=Math.PI*2/x*E,W=y||(()=>T);let K,ce,$,z;const k=N.Matrix[0];let M=R===F.NO_CAP||R===F.CAP_END?0:2;for(let q=0;q{const pe=Array();for(let se=0;se3?0:h,_=f(i,d,p,n,r,o,h,e.arc);const g=zs(a,{pathArray:_,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:l,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return g._creationDataStorage.pathArray=_,g._creationDataStorage.path3D=d,g._creationDataStorage.tessellation=r,g._creationDataStorage.cap=h,g._creationDataStorage.arc=e.arc,g._creationDataStorage.radius=n,g}F.CreateTube=(a,e,t,i,s,n,r,o,h,l)=>nf(a,{path:e,radius:t,tessellation:i,radiusFunction:s,arc:1,cap:n,updatable:o,sideOrientation:h,instance:l},r);function rf(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],h=o.face.length,l=a.faceUV||new Array(h),c=a.faceColors,u=a.flat===void 0?!0:a.flat,f=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,d=[],_=[],p=[],g=[],m=[];let b=0,I=0;const T=[];let x=0,y=0,R,E,C,S,w,P;if(u)for(y=0;yao(a,e,t);function af(a){const e=a.sideOrientation||j.DEFAULTSIDE,t=a.radius||1,i=a.flat===void 0?!0:a.flat,s=(a.subdivisions||4)|0,n=a.radiusX||t,r=a.radiusY||t,o=a.radiusZ||t,h=(1+Math.sqrt(5))/2,l=[-1,h,-0,1,h,0,-1,-h,0,1,-h,0,0,-1,-h,0,1,-h,0,-1,h,0,1,h,h,0,1,h,0,-1,-h,0,1,-h,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],f=[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],d=138/1024,_=239/1024,p=60/1024,g=26/1024,m=-40/1024,b=20/1024,I=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],T=[],x=[],y=[],R=[];let E=0;const C=new Array(3),S=new Array(3);let w;for(w=0;w<3;w++)C[w]=v.Zero(),S[w]=oe.Zero();for(let G=0;G<20;G++){for(w=0;w<3;w++){const W=c[3*G+w];C[w].copyFromFloats(l[3*u[W]],l[3*u[W]+1],l[3*u[W]+2]),C[w].normalize(),S[w].copyFromFloats(f[2*W]*d+p+I[G]*m,f[2*W+1]*_+g+I[G]*b)}const L=(W,K,ce,$)=>{const z=v.Lerp(C[0],C[2],K/s),k=v.Lerp(C[1],C[2],K/s),M=s===K?C[2]:v.Lerp(z,k,W/(s-K));M.normalize();let V;if(i){const se=v.Lerp(C[0],C[2],$/s),ue=v.Lerp(C[1],C[2],$/s);V=v.Lerp(se,ue,ce/(s-$))}else V=new v(M.x,M.y,M.z);V.x/=n,V.y/=r,V.z/=o,V.normalize();const q=oe.Lerp(S[0],S[2],K/s),he=oe.Lerp(S[1],S[2],K/s),pe=s===K?S[2]:oe.Lerp(q,he,W/(s-K));x.push(M.x*n,M.y*r,M.z*o),y.push(V.x,V.y,V.z),R.push(pe.x,pe.y),T.push(E),E++};for(let W=0;Wof(a,e,t);const Dv=new v(1,0,0),Fv=new v(-1,0,0),Ov=new v(0,1,0),Bv=new v(0,-1,0),Lv=new v(0,0,1),Nv=new v(0,0,-1);class Nr{constructor(e=v.Zero(),t=v.Up(),i=oe.Zero(),s=0,n=0,r=null,o=null,h=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=n,this.localPositionOverride=r,this.localNormalOverride=o,this.matrixIndicesOverride=h,this.matrixWeightsOverride=l}clone(){var e,t,i,s;return new Nr(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)==null?void 0:e.slice(),(t=this.localNormalOverride)==null?void 0:t.slice(),(i=this.matrixIndicesOverride)==null?void 0:i.slice(),(s=this.matrixWeightsOverride)==null?void 0:s.slice())}}function hf(a,e,t){var K,ce,$,z;const i=!!e.skeleton,s=t.localMode||i,n=e.getIndices(),r=i?e.getPositionData(!0,!0):e.getVerticesData(A.PositionKind),o=i?e.getNormalsData(!0,!0):e.getVerticesData(A.NormalKind),h=s?i?e.getVerticesData(A.PositionKind):r:null,l=s?i?e.getVerticesData(A.NormalKind):o:null,c=e.getVerticesData(A.UVKind),u=i?e.getVerticesData(A.MatricesIndicesKind):null,f=i?e.getVerticesData(A.MatricesWeightsKind):null,d=i?e.getVerticesData(A.MatricesIndicesExtraKind):null,_=i?e.getVerticesData(A.MatricesWeightsExtraKind):null,p=t.position||v.Zero();let g=t.normal||v.Up();const m=t.size||v.One(),b=t.angle||0;if(!g){const k=new v(0,0,1),M=e.getScene().activeCamera,V=v.TransformCoordinates(k,M.getWorldMatrix());g=M.globalPosition.subtract(V)}const I=-Math.atan2(g.z,g.x)-Math.PI/2,T=Math.sqrt(g.x*g.x+g.z*g.z),x=Math.atan2(g.y,T),y=new j;y.indices=[],y.positions=[],y.normals=[],y.uvs=[],y.matricesIndices=i?[]:null,y.matricesWeights=i?[]:null,y.matricesIndicesExtra=d?[]:null,y.matricesWeightsExtra=_?[]:null;let R=0;const E=(k,M)=>{const V=new Nr;if(!n||!r||!o)return V;const q=n[k];if(V.vertexIdx=q*3,V.vertexIdxForBones=q*4,V.position=new v(r[q*3],r[q*3+1],r[q*3+2]),v.TransformCoordinatesToRef(V.position,M,V.position),V.normal=new v(o[q*3],o[q*3+1],o[q*3+2]),v.TransformNormalToRef(V.normal,M,V.normal),t.captureUVS&&c){const he=c[q*2+1];V.uv=new oe(c[q*2],he)}return V},C=[0,0,0,0],S=(k,M)=>{if(k.length===0)return k;const V=.5*Math.abs(v.Dot(m,M)),q=(se,ue,me,ne)=>{for(let Ie=0;Ie{var Vt,Yt,$i,tr,ho,lo,co,uo,fo,_o,po,go,mo,vo,bo,xo;const me=v.GetClipFactor(se.position,ue.position,M,V);let ne=C,Ie=C;if(u&&f){const mn=se.matrixIndicesOverride?0:se.vertexIdxForBones,ua=(Vt=se.matrixIndicesOverride)!=null?Vt:u,yo=(Yt=se.matrixWeightsOverride)!=null?Yt:f,fa=ue.matrixIndicesOverride?0:ue.vertexIdxForBones,To=($i=ue.matrixIndicesOverride)!=null?$i:u,Ao=(tr=ue.matrixWeightsOverride)!=null?tr:f;ne=[0,0,0,0],Ie=[0,0,0,0];let Es=0;for(let Ai=0;Ai<4;++Ai)if(yo[mn+Ai]>0){const vn=q(To,ua[mn+Ai],fa,4);ne[Es]=ua[mn+Ai],Ie[Es]=Rr(yo[mn+Ai],vn>=0?Ao[vn]:0,me),Es++}for(let Ai=0;Ai<4&&Es<4;++Ai){const vn=To[fa+Ai];q(ua,vn,mn,4)===-1&&(ne[Es]=vn,Ie[Es]=Rr(0,Ao[fa+Ai],me),Es++)}const ir=Ie[0]+Ie[1]+Ie[2]+Ie[3];Ie[0]/=ir,Ie[1]/=ir,Ie[2]/=ir,Ie[3]/=ir}const Se=se.localPositionOverride?se.localPositionOverride[0]:(ho=h==null?void 0:h[se.vertexIdx])!=null?ho:0,Q=se.localPositionOverride?se.localPositionOverride[1]:(lo=h==null?void 0:h[se.vertexIdx+1])!=null?lo:0,be=se.localPositionOverride?se.localPositionOverride[2]:(co=h==null?void 0:h[se.vertexIdx+2])!=null?co:0,Be=ue.localPositionOverride?ue.localPositionOverride[0]:(uo=h==null?void 0:h[ue.vertexIdx])!=null?uo:0,ze=ue.localPositionOverride?ue.localPositionOverride[1]:(fo=h==null?void 0:h[ue.vertexIdx+1])!=null?fo:0,Ke=ue.localPositionOverride?ue.localPositionOverride[2]:(_o=h==null?void 0:h[ue.vertexIdx+2])!=null?_o:0,Rt=se.localNormalOverride?se.localNormalOverride[0]:(po=l==null?void 0:l[se.vertexIdx])!=null?po:0,Ct=se.localNormalOverride?se.localNormalOverride[1]:(go=l==null?void 0:l[se.vertexIdx+1])!=null?go:0,Ge=se.localNormalOverride?se.localNormalOverride[2]:(mo=l==null?void 0:l[se.vertexIdx+2])!=null?mo:0,Jt=ue.localNormalOverride?ue.localNormalOverride[0]:(vo=l==null?void 0:l[ue.vertexIdx])!=null?vo:0,Wt=ue.localNormalOverride?ue.localNormalOverride[1]:(bo=l==null?void 0:l[ue.vertexIdx+1])!=null?bo:0,ji=ue.localNormalOverride?ue.localNormalOverride[2]:(xo=l==null?void 0:l[ue.vertexIdx+2])!=null?xo:0,Is=Rt+(Jt-Rt)*me,Ti=Ct+(Wt-Ct)*me,Ht=Ge+(ji-Ge)*me,oi=Math.sqrt(Is*Is+Ti*Ti+Ht*Ht);return new Nr(v.Lerp(se.position,ue.position,me),v.Lerp(se.normal,ue.normal,me).normalize(),oe.Lerp(se.uv,ue.uv,me),-1,-1,h?[Se+(Be-Se)*me,Q+(ze-Q)*me,be+(Ke-be)*me]:null,l?[Is/oi,Ti/oi,Ht/oi]:null,ne,Ie)};let pe=null;k.length>3&&(pe=[]);for(let se=0;se0,Ke=be>0,Rt=Be>0;switch(ue=(ze?1:0)+(Ke?1:0)+(Rt?1:0),ue){case 0:k.length>3?(pe.push(k[se]),pe.push(k[se+1]),pe.push(k[se+2])):pe=k;break;case 1:if(pe=pe!=null?pe:new Array,ze&&(me=k[se+1],ne=k[se+2],Ie=he(k[se],me),Se=he(k[se],ne)),Ke){me=k[se],ne=k[se+2],Ie=he(k[se+1],me),Se=he(k[se+1],ne),pe.push(Ie),pe.push(ne.clone()),pe.push(me.clone()),pe.push(ne.clone()),pe.push(Ie.clone()),pe.push(Se);break}Rt&&(me=k[se],ne=k[se+1],Ie=he(k[se+2],me),Se=he(k[se+2],ne)),me&&ne&&Ie&&Se&&(pe.push(me.clone()),pe.push(ne.clone()),pe.push(Ie),pe.push(Se),pe.push(Ie.clone()),pe.push(ne.clone()));break;case 2:pe=pe!=null?pe:new Array,ze||(me=k[se].clone(),ne=he(me,k[se+1]),Ie=he(me,k[se+2]),pe.push(me),pe.push(ne),pe.push(Ie)),Ke||(me=k[se+1].clone(),ne=he(me,k[se+2]),Ie=he(me,k[se]),pe.push(me),pe.push(ne),pe.push(Ie)),Rt||(me=k[se+2].clone(),ne=he(me,k[se]),Ie=he(me,k[se+1]),pe.push(me),pe.push(ne),pe.push(Ie));break}}return pe},w=e instanceof F?e:null,P=w==null?void 0:w._thinInstanceDataStorage.matrixData,G=(w==null?void 0:w.thinInstanceCount)||1,L=N.Matrix[0];L.copyFrom(O.IdentityReadOnly);for(let k=0;khf(a,e,{position:t,normal:i,size:s,angle:n});function lf(a={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(a.subdivisions?a.subdivisions:2,1)|0,t=Math.max(a.tessellation?a.tessellation:16,3)|0,i=Math.max(a.height?a.height:1,0),s=Math.max(a.radius?a.radius:.25,0),n=Math.max(a.capSubdivisions?a.capSubdivisions:6,1)|0,r=t,o=e,h=Math.max(a.radiusTop?a.radiusTop:s,0),l=Math.max(a.radiusBottom?a.radiusBottom:s,0),c=i-(h+l),u=0,f=2*Math.PI,d=Math.max(a.topCapSubdivisions?a.topCapSubdivisions:n,1),_=Math.max(a.bottomCapSubdivisions?a.bottomCapSubdivisions:n,1),p=Math.acos((l-h)/i);let g=[];const m=[],b=[],I=[];let T=0;const x=[],y=c*.5,R=Math.PI*.5;let E,C;const S=v.Zero(),w=v.Zero(),P=Math.cos(p),G=Math.sin(p),L=new oe(h*G,y+h*P).subtract(new oe(l*G,-y+l*P)).length(),W=h*p+L+l*(R-p);let K=0;for(C=0;C<=d;C++){const k=[],M=R-p*(C/d);K+=h*p/d;const V=Math.cos(M),q=Math.sin(M),he=V*h;for(E=0;E<=r;E++){const pe=E/r,se=pe*f+u,ue=Math.sin(se),me=Math.cos(se);w.x=he*ue,w.y=y+q*h,w.z=he*me,m.push(w.x,w.y,w.z),S.set(V*ue,q,V*me),b.push(S.x,S.y,S.z),I.push(pe,1-K/W),k.push(T),T++}x.push(k)}const ce=i-h-l+P*h-P*l,$=G*(l-h)/ce;for(C=1;C<=o;C++){const k=[];K+=L/o;const M=G*(C*(l-h)/o+h);for(E=0;E<=r;E++){const V=E/r,q=V*f+u,he=Math.sin(q),pe=Math.cos(q);w.x=M*he,w.y=y+P*h-C*ce/o,w.z=M*pe,m.push(w.x,w.y,w.z),S.set(he,$,pe).normalize(),b.push(S.x,S.y,S.z),I.push(V,1-K/W),k.push(T),T++}x.push(k)}for(C=1;C<=_;C++){const k=[],M=R-p-(Math.PI-p)*(C/_);K+=l*p/_;const V=Math.cos(M),q=Math.sin(M),he=V*l;for(E=0;E<=r;E++){const pe=E/r,se=pe*f+u,ue=Math.sin(se),me=Math.cos(se);w.x=he*ue,w.y=-y+q*l,w.z=he*me,m.push(w.x,w.y,w.z),S.set(V*ue,q,V*me),b.push(S.x,S.y,S.z),I.push(pe,1-K/W),k.push(T),T++}x.push(k)}for(E=0;Ecf(a,e,t);j.CreateCapsule=lf;class at{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(e=Math.floor(e),U.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(t=Math.floor(t),U.Warn("y is not an integer, floor(y) used"))}clone(){return new at(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)&&(e=Math.floor(e),U.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),U.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)&&(e=Math.floor(e),U.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),U.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 at(0,0)}}class uf{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,yt,-1],[-yt,1,0],[-1,0,-yt],[1,0,-yt],[yt,1,0],[0,yt,1],[-1,0,yt],[-yt,-1,0],[0,-yt,-1],[yt,-1,0],[1,0,yt],[0,-yt,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=Ba(i,s)),r=i/n,o=s/n;let h,l,c,u,f;const d=at.Zero(),_=new at(i,s),p=new at(-s,i+s),g=at.Zero(),m=at.Zero(),b=at.Zero();let I=[],T,x,y,R;const E=[],C=this.vertByDist,S=(w,P,G,L)=>{T=w+"|"+G,x=P+"|"+L,T in t||x in t?T in t&&!(x in t)?t[x]=t[T]:x in t&&!(T in t)&&(t[T]=t[x]):(t[T]=e,t[x]=e,e++),C[G][0]>2?E[t[T]]=[-C[G][0],C[G][1],t[T]]:E[t[T]]=[I[C[G][0]],C[G][1],t[T]]};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(I=this.IDATA.face[w],c=I[2],u=I[1],f=I[0],y=d.x+"|"+d.y,T=w+"|"+y,T in t||(t[T]=c,E[c]=[I[C[y][0]],C[y][1]]),y=_.x+"|"+_.y,T=w+"|"+y,T in t||(t[T]=u,E[u]=[I[C[y][0]],C[y][1]]),y=p.x+"|"+p.y,T=w+"|"+y,T in t||(t[T]=f,E[f]=[I[C[y][0]],C[y][1]]),h=this.IDATA.edgematch[w][0],l=this.IDATA.edgematch[w][1],l==="B")for(let P=1;P2?E[t[T]]=[-C[y][0],C[y][1],t[T]]:E[t[T]]=[I[C[y][0]],C[y][1],t[T]])}this.closestTo=E,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 x=Ba(e,t),y=e/x,R=t/x;for(let C=1;Cx.x-y.x),i.sort((x,y)=>x.y-y.y);const o=new Array(e+t+1),h=new Array(e+t+1);for(let x=0;x{const R=x.clone();return y==="A"&&R.rotateNeg120(e,t),y==="B"&&R.rotate120(e,t),R.x<0?R.y:R.x+R.y},d=[],_=[],p=[],g=[],m={},b=[];let I=-1,T=-1;for(let x=0;xx[2]-y[2]),b.sort((x,y)=>x[3]-y[3]),b.sort((x,y)=>x[1]-y[1]),b.sort((x,y)=>x[0]-y[0]);for(let x=0;xt.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,h)=>o[1]-h[1]);for(let o=0;or[3]-o[3]);for(let r=0;r0;)n=t[h],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(h,1),h=0):h++;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 l=0;l{s=0,n=0,r=0,o=this.face[c];for(let u=0;u<3;u++)h=this.vertex[o[u]],s+=h[0],n+=h[1],r+=h[2];e.vertex[c]=[s/3,n/3,r/3]});return e}static BuildGeodesicData(e){const t=new ha("Geodesic-m-n","Geodesic",[[0,yt,-1],[-yt,1,0],[-1,0,-yt],[1,0,-yt],[yt,1,0],[0,yt,1],[-1,0,yt],[-yt,-1,0],[0,-yt,-1],[yt,-1,0],[1,0,yt],[0,-yt,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let s=0;si){const l=s;s=i,i=l,U.Warn("n > m therefore m and n swapped")}const n=new uf;n.build(i,s);const o={custom:ha.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 ao(a,o,t)}F._GoldbergMeshParser=(a,e)=>la.Parse(a,e);class la extends F{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&&(U.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(U.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(U.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i1&&(u=1),l.push(u,f);for(let d=0;d<6;d++)u=r.x+o*Math.cos(h+d*Math.PI/3),f=r.y+o*Math.sin(h+d*Math.PI/3),u<0&&(u=0),u>1&&(u=1),c.push(u,f);for(let d=s;dH.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 la(e.name,t);return s.goldbergData=i,s}}function kv(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=[],h=[],l=[],c=[];let u=1/0,f=-1/0,d=1/0,_=-1/0;for(let m=0;mo){const _=h;h=o,o=_,U.Warn("n > m therefore m and n swapped")}const l=new uf;l.build(o,h);const c=ha.BuildGeodesicData(l),u=c.toGoldbergPolyhedronData(),f=new la(a,t);e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),f._originalBuilderSideOrientation=e.sideOrientation,kv(e,u).applyToMesh(f,e.updatable),f.goldbergData.nbSharedFaces=c.sharedNodes,f.goldbergData.nbUnsharedFaces=c.poleNodes,f.goldbergData.adjacentFaces=c.adjacentFaces,f.goldbergData.nbFaces=f.goldbergData.nbSharedFaces+f.goldbergData.nbUnsharedFaces,f.goldbergData.nbFacesAtPole=(f.goldbergData.nbUnsharedFaces-12)/12;for(let _=0;_0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function zv(a,e,t,i,s,n){const r=n.glyphs[a]||n.glyphs["?"];if(!r)return null;const o=new Gv(s);if(r.o){const h=r.o.split(" ");for(let l=0,c=h.length;l=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};F.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(F.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(a){var i,s;const e=(s=this._thinInstanceDataStorage.matrixData)!=null?s:(i=this.source)==null?void 0:i._thinInstanceDataStorage.matrixData,t=e?e.length/16:0;a<=t&&(this._thinInstanceDataStorage.instancesCount=a)},enumerable:!0,configurable:!0});F.prototype._thinInstanceCreateMatrixBuffer=function(a,e,t=!0){const i=new ln(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};F.prototype.thinInstanceSetBuffer=function(a,e,t=0,i=!0){var s,n,r;t=t||16,a==="matrix"?((s=this._thinInstanceDataStorage.matrixBuffer)==null||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.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.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])))};F.prototype.thinInstanceBufferUpdated=function(a){var e,t,i;a==="matrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(a),(e=this._thinInstanceDataStorage.matrixBuffer)==null||e.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):a==="previousMatrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(a),(t=this._thinInstanceDataStorage.previousMatrixBuffer)==null||t.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(a===A.ColorKind&&(a=A.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[a]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[a].isUpdatable()&&this._thinInstanceRecreateBuffer(a),this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(this._userThinInstanceBuffersStorage.data[a],0)))};F.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.vertexBuffers[a]&&this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(e,t))};F.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const a=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let e=0;eimport("./kernelBlur.fragment-BJnJE4Wi.js"),__vite__mapDeps([52,53,3,4,5,6,7,8,9,10])),Oe(()=>import("./kernelBlur.vertex-SB8k7aXt.js"),__vite__mapDeps([54,53,3,4,5,6,7,8,9,10]))]))):t.push(Promise.all([Oe(()=>import("./kernelBlur.fragment-CAduVWsS.js"),__vite__mapDeps([55,56,3,4,5,6,7,8,9,10])),Oe(()=>import("./kernelBlur.vertex-Dciph_cp.js"),__vite__mapDeps([57,56,3,4,5,6,7,8,9,10]))]))}constructor(e,t=null,i,s,n){const r=!!(n!=null&&n.blockCompilation);super({...n,name:e,engine:t||le.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:si.FragmentUrl,uniforms:si.Uniforms,samplers:si.Samplers,vertexUrl:si.VertexUrl,blockCompilation:!0}),this._packedFloat=!1,this._staticDefines="",this.textureWidth=0,this.textureHeight=0,this.options.blockCompilation=r,i!==void 0&&(this.direction=i),s!==void 0&&(this.kernel=s)}set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.options.blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this.options.blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}bind(){super.bind(),this._drawWrapper.effect.setFloat2("delta",1/this.textureWidth*this.direction.x,1/this.textureHeight*this.direction.y)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let n=[],r=[],o=0;for(let g=0;g0)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+$/,"")}}si.VertexUrl="kernelBlur";si.FragmentUrl="kernelBlur";si.Uniforms=["delta","direction"];si.Samplers=["circleOfConfusionSampler"];class As extends mt{get direction(){return this._effectWrapper.direction}set direction(e){this._effectWrapper.direction=e}set kernel(e){this._effectWrapper.kernel=e}get kernel(){return this._effectWrapper.kernel}set packedFloat(e){this._effectWrapper.packedFloat=e}get packedFloat(){return this._effectWrapper.packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,n=null,r=ie.BILINEAR_SAMPLINGMODE,o,h,l=0,c="",u=!1,f=5){const d=typeof s=="number"?u:!!s.blockCompilation,_={uniforms:si.Uniforms,samplers:si.Samplers,size:typeof s=="number"?s:void 0,camera:n,samplingMode:r,engine:o,reusable:h,textureType:l,vertexUrl:si.VertexUrl,indexParameters:{varyingCount:0,depCount:0},textureFormat:f,defines:c,...s,blockCompilation:!0};super(e,si.FragmentUrl,{effectWrapper:typeof s=="number"||!s.effectWrapper?new si(e,o,void 0,void 0,_):void 0,..._}),this._effectWrapper.options.blockCompilation=d,this.direction=t,this.onApplyObservable.add(()=>{this._effectWrapper.textureWidth=this._outputTexture?this._outputTexture.width:this.width,this._effectWrapper.textureHeight=this._outputTexture?this._outputTexture.height:this.height}),this.kernel=i}updateEffect(e=null,t=null,i=null,s,n,r){this._effectWrapper._updateParameters(n,r)}static _Parse(e,t,i,s){return Ae.Parse(()=>new As(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,s)}}D([tc()],As.prototype,"direction",null);D([B()],As.prototype,"kernel",null);D([B()],As.prototype,"packedFloat",null);vt("BABYLON.BlurPostProcess",As);class xi{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||t===0)&&e.subMeshes)for(let s=0;s{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let 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 I;const s=this._scene.getEngine(),n=e.getMesh(),r=(I=n._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:I[s.currentRenderPassId];if(r)return r.isReadyForSubMesh(n,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const h=[],l=[A.PositionKind];let c=!1,u=!1;if(o){const T=o.needAlphaTesting(),x=o.getAlphaTestTexture(),y=x&&x.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);x&&(T||y)&&(h.push("#define DIFFUSE"),n.isVerticesDataPresent(A.UV2Kind)&&x.coordinatesIndex===1?(h.push("#define DIFFUSEUV2"),u=!0):n.isVerticesDataPresent(A.UVKind)&&(h.push("#define DIFFUSEUV1"),c=!0),T&&(h.push("#define ALPHATEST"),h.push("#define ALPHATESTVALUE 0.4")),x.gammaSpace||h.push("#define DIFFUSE_ISLINEAR"));const R=o.opacityTexture;R&&(h.push("#define OPACITY"),n.isVerticesDataPresent(A.UV2Kind)&&R.coordinatesIndex===1?(h.push("#define OPACITYUV2"),u=!0):n.isVerticesDataPresent(A.UVKind)&&(h.push("#define OPACITYUV1"),c=!0))}i&&(h.push("#define EMISSIVE"),n.isVerticesDataPresent(A.UV2Kind)&&i.coordinatesIndex===1?(h.push("#define EMISSIVEUV2"),u=!0):n.isVerticesDataPresent(A.UVKind)&&(h.push("#define EMISSIVEUV1"),c=!0),i.gammaSpace||h.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent(A.ColorKind)&&n.hasVertexAlpha&&o.transparencyMode!==X.MATERIAL_OPAQUE&&(l.push(A.ColorKind),h.push("#define VERTEXALPHA")),c&&(l.push(A.UVKind),h.push("#define UV1")),u&&(l.push(A.UV2Kind),h.push("#define UV2"));const f=new G0;if(n.useBones&&n.computeBonesUsingShaders){l.push(A.MatricesIndicesKind),l.push(A.MatricesWeightsKind),n.numBoneInfluencers>4&&(l.push(A.MatricesIndicesExtraKind),l.push(A.MatricesWeightsExtraKind)),h.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);const T=n.skeleton;T&&T.isUsingTextureForMatrices?h.push("#define BONETEXTURE"):h.push("#define BonesPerMesh "+(T?T.bones.length+1:0)),n.numBoneInfluencers>0&&f.addCPUSkinningFallback(0,n)}else h.push("#define NUM_BONE_INFLUENCERS 0");const d=n.morphTargetManager;let _=0;d&&(_=d.numMaxInfluencers||d.numInfluencers,_>0&&(h.push("#define MORPHTARGETS"),h.push("#define NUM_MORPH_INFLUENCERS "+_),d.isUsingTextureForTargets&&h.push("#define MORPHTARGETS_TEXTURE"),qp(l,n,_))),t&&(h.push("#define INSTANCES"),N0(l),e.getRenderingMesh().hasThinInstances&&h.push("#define THIN_INSTANCES")),Mc(o,this._scene,h),this._addCustomEffectDefines(h);const p=e._getDrawWrapper(void 0,!0),g=p.defines,m=h.join("\n");if(g!==m){const T=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];Xr(T),p.setEffect(this._engine.createEffect("glowMapGeneration",l,T,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,f,void 0,void 0,{maxSimultaneousMorphTargets:_},this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0}),m)}const b=p.effect.isReady();return this._arePostProcessAndMergeReady()&&b}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([Oe(()=>import("./glowMapGeneration.vertex-O7p-xSBA.js"),__vite__mapDeps([58,22,25,23,3,4,5,6,7,8,9,10])),Oe(()=>import("./glowMapGeneration.fragment-CfLBq-Y2.js"),__vite__mapDeps([59,29,3,4,5,6,7,8,9,10]))]):await Promise.all([Oe(()=>import("./glowMapGeneration.vertex-BcKlBU7O.js"),__vite__mapDeps([60,36,37,3,4,5,6,7,8,9,10])),Oe(()=>import("./glowMapGeneration.fragment-C2VnGqtj.js"),__vite__mapDeps([61,35,3,4,5,6,7,8,9,10]))])}_arePostProcessAndMergeReady(){let e=!0;for(let i=0;ib.setMatrix("world",T))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_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 J.Instantiate(e.customType).Parse(e,t,i)}}xi.ForceGLSL=!1;xi._SceneComponentInitialization=a=>{throw ye("EffectLayerSceneComponent")};D([B()],xi.prototype,"name",void 0);D([p0()],xi.prototype,"neutralColor",void 0);D([B()],xi.prototype,"isEnabled",void 0);D([e_()],xi.prototype,"camera",null);D([B()],xi.prototype,"renderingGroupId",null);D([B()],xi.prototype,"disableBoundingBoxesFromEffectLayer",void 0);it.prototype.getHighlightLayerByName=function(a){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===a&&this.effectLayers[t].getEffectName()===kt.EffectName)return this.effectLayers[t];return null};class ml extends mt{constructor(e,t,i,s,n,r=ie.BILINEAR_SAMPLINGMODE,o,h){super(e,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,s,n,r,o,h),this.direction=t,this.kernel=i,this.onApplyObservable.add(l=>{l.setFloat2("screenSize",this.width,this.height),l.setVector2("direction",this.direction),l.setFloat("blurWidth",this.kernel)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Oe(()=>import("./glowBlurPostProcess.fragment-D0h3Yhq8.js"),__vite__mapDeps([62,3,4,5,6,7,8,9,10])))):t.push(Oe(()=>import("./glowBlurPostProcess.fragment-BmYiq-YF.js"),__vite__mapDeps([63,3,4,5,6,7,8,9,10]))),super._gatherImports(e,t)}}class kt extends xi{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,i!==void 0?!!i.forceGLSL:!1),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new Z,this.onAfterBlurObservable=new Z,this._instanceGlowingMeshStencilReference=kt.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=kt.NeutralColor,this._engine.isStencilEnable||U.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,forceGLSL:!1,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([Oe(()=>import("./glowMapMerge.fragment-z1wsxOL6.js"),__vite__mapDeps([64,3,4,5,6,7,8,9,10])),Oe(()=>import("./glowMapMerge.vertex-BOpN3rPY.js"),__vite__mapDeps([65,3,4,5,6,7,8,9,10])),Oe(()=>import("./glowBlurPostProcess.fragment-D0h3Yhq8.js"),__vite__mapDeps([62,3,4,5,6,7,8,9,10]))]):await Promise.all([Oe(()=>import("./glowMapMerge.fragment-C9pBmOul.js"),__vite__mapDeps([66,3,4,5,6,7,8,9,10])),Oe(()=>import("./glowMapMerge.vertex-CYvG5BDv.js"),__vite__mapDeps([67,3,4,5,6,7,8,9,10])),Oe(()=>import("./glowBlurPostProcess.fragment-BmYiq-YF.js"),__vite__mapDeps([63,3,4,5,6,7,8,9,10]))]),await super._importShadersAsync()}getEffectName(){return kt.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[A.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0,void 0,void 0,void 0,void 0,this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0})}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?fi(e,this._maxSize):e,t=this._engine.needPOTTextures?fi(t,this._maxSize):t;let i=0;if(this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new us("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=ie.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=ie.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(ie.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2)this._downSamplePostprocess=new Yn("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,ie.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new ml("HighlightLayerHBP",new oe(1,0),this._options.blurHorizontalSize,1,null,ie.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new ml("HighlightLayerVBP",new oe(0,1),this._options.blurVerticalSize,1,null,ie.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess];else{this._horizontalBlurPostprocess=new As("HighlightLayerHBP",new oe(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,ie.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i);const s=this._horizontalBlurPostprocess;s.width=e,s.height=t,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add(n=>{n.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new As("HighlightLayerVBP",new oe(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,ie.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(X.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(X.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(kt.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=Ae.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=Ae.Parse(()=>new kt(e.name,t,e.options),e,t,i);let n;for(n=0;nnew zt(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return Ae.Parse(()=>new zt(e.name,t),e,t,i)}}D([ls()],zt.prototype,"mainColor",void 0);D([ls()],zt.prototype,"lineColor",void 0);D([B()],zt.prototype,"gridRatio",void 0);D([yi()],zt.prototype,"gridOffset",void 0);D([B()],zt.prototype,"majorUnitFrequency",void 0);D([B()],zt.prototype,"minorUnitVisibility",void 0);D([B()],zt.prototype,"opacity",void 0);D([B()],zt.prototype,"antialias",void 0);D([B()],zt.prototype,"preMultiplyAlpha",void 0);D([B()],zt.prototype,"useMaxLine",void 0);D([_i("opacityTexture")],zt.prototype,"_opacityTexture",void 0);D([je("_markAllSubMeshesAsTexturesDirty")],zt.prototype,"opacityTexture",void 0);vt("BABYLON.GridMaterial",zt);we.prototype.createDynamicTexture=function(a,e,t,i){const s=new ft(this,4);return s.baseWidth=a,s.baseHeight=e,t&&(a=this.needPOTTextures?fi(a,this._caps.maxTextureSize):a,e=this.needPOTTextures?fi(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};we.prototype.updateDynamicTexture=function(a,e,t,i=!1,s,n=!1,r=!1){if(!a)return;const o=this._gl,h=o.TEXTURE_2D,l=this._bindTextureDirectly(h,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),f=this._getRGBABufferInternalSizedFormat(a.type,u);o.texImage2D(h,0,f,u,c,e),a.generateMipMaps&&o.generateMipmap(h),l||this._bindTextureDirectly(h,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(a.format=s),a._dynamicTextureSource=e,a._premulAlpha=i,a.invertY=t||!1,a.isReady=!0};class Wn extends ie{constructor(e,t,i,s=!1,n=3,r=5,o){const h=!i||i._isScene,l=h?i:i==null?void 0:i.scene,c=h?!s:i;super(null,l,c,o,n,void 0,void 0,void 0,void 0,r),this.name=e,this.wrapU=ie.CLAMP_ADDRESSMODE,this.wrapV=ie.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const u=this._getEngine();if(!u)return;if(t.getContext)this._canvas=t,this._ownCanvas=!1,this._texture=u.createDynamicTexture(this._canvas.width,this._canvas.height,s,n);else{this._canvas=u.createCanvas(1,1),this._ownCanvas=!0;const d=t;d.width||d.width===0?this._texture=u.createDynamicTexture(d.width,d.height,s,n):this._texture=u.createDynamicTexture(t,t,s,n)}const f=this.getSize();this._canvas.width!==f.width&&(this._canvas.width=f.width),this._canvas.height!==f.height&&(this._canvas.height=f.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,e===void 0?!0:e,t,this._format||void 0,void 0,i)}drawText(e,t,i,s,n,r,o,h=!0){const l=this.getSize();if(r&&(this._context.fillStyle=r,this._context.fillRect(0,0,l.width,l.height)),this._context.font=s,t==null){const c=this._context.measureText(e);t=(l.width-c.width)/2}if(i==null){const c=parseInt(s.replace(/\D/g,""));i=l.height/2+c/3.65}this._context.fillStyle=n||"",this._context.fillText(e,t,i),h&&this.update(o)}dispose(){var e,t;super.dispose(),this._ownCanvas&&((t=(e=this._canvas)==null?void 0:e.remove)==null||t.call(e)),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Wn(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()&&U.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Wn._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()}}bt.AddNodeConstructor("Light_Type_3",(a,e)=>()=>new _n(a,v.Zero(),e));class _n extends Fe{constructor(e,t,i){super(e,i),this.groundColor=new de(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=O.Identity()),this._worldMatrix}getTypeID(){return Fe.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}D([ls()],_n.prototype,"groundColor",void 0);D([yi()],_n.prototype,"direction",void 0);vt("BABYLON.HemisphericLight",_n);function It(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */It=()=>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(S,w,P){return Object.defineProperty(S,w,{value:P,enumerable:!0,configurable:!0,writable:!0}),S[w]}try{o({},"")}catch{o=(w,P,G)=>w[P]=G}function h(S,w,P,G){var L=w&&w.prototype instanceof u?w:u,W=Object.create(L.prototype),K=new R(G||[]);return W._invoke=((ce,$,z)=>{var k="suspendedStart";return(M,V)=>{if(k==="executing")throw new Error("Generator is already running");if(k==="completed"){if(M==="throw")throw V;return C()}for(z.method=M,z.arg=V;;){var q=z.delegate;if(q){var he=T(q,z);if(he){if(he===c)continue;return he}}if(z.method==="next")z.sent=z._sent=z.arg;else if(z.method==="throw"){if(k==="suspendedStart")throw k="completed",z.arg;z.dispatchException(z.arg)}else z.method==="return"&&z.abrupt("return",z.arg);k="executing";var pe=l(ce,$,z);if(pe.type==="normal"){if(k=z.done?"completed":"suspendedYield",pe.arg===c)continue;return{value:pe.arg,done:z.done}}pe.type==="throw"&&(k="completed",z.method="throw",z.arg=pe.arg)}}})(S,P,K),W}function l(S,w,P){try{return{type:"normal",arg:S.call(w,P)}}catch(G){return{type:"throw",arg:G}}}a.wrap=h;var c={};function u(){}function f(){}function d(){}var _={};o(_,s,function(){return this});var p=Object.getPrototypeOf,g=p&&p(p(E([])));g&&g!==e&&t.call(g,s)&&(_=g);var m=d.prototype=u.prototype=Object.create(_);function b(S){["next","throw","return"].forEach(function(w){o(S,w,function(P){return this._invoke(w,P)})})}function I(S,w){function P(L,W,K,ce){var $=l(S[L],S,W);if($.type!=="throw"){var z=$.arg,k=z.value;return k&&typeof k=="object"&&t.call(k,"__await")?w.resolve(k.__await).then(M=>{P("next",M,K,ce)},M=>{P("throw",M,K,ce)}):w.resolve(k).then(M=>{z.value=M,K(z)},M=>P("throw",M,K,ce))}ce($.arg)}var G;this._invoke=(L,W)=>{function K(){return new w((ce,$)=>{P(L,W,ce,$)})}return G=G?G.then(K,K):K()}}function T(S,w){var P=S.iterator[w.method];if(P===void 0){if(w.delegate=null,w.method==="throw"){if(S.iterator.return&&(w.method="return",w.arg=void 0,T(S,w),w.method==="throw"))return c;w.method="throw",w.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var G=l(P,S.iterator,w.arg);if(G.type==="throw")return w.method="throw",w.arg=G.arg,w.delegate=null,c;var L=G.arg;return L?L.done?(w[S.resultName]=L.value,w.next=S.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 x(S){var w={tryLoc:S[0]};1 in S&&(w.catchLoc=S[1]),2 in S&&(w.finallyLoc=S[2],w.afterLoc=S[3]),this.tryEntries.push(w)}function y(S){var w=S.completion||{};w.type="normal",delete w.arg,S.completion=w}function R(S){this.tryEntries=[{tryLoc:"root"}],S.forEach(x,this),this.reset(!0)}function E(S){if(S){var w=S[s];if(w)return w.call(S);if(typeof S.next=="function")return S;if(!isNaN(S.length)){var P=-1,G=function L(){for(;++P{var w=typeof S=="function"&&S.constructor;return!!w&&(w===f||(w.displayName||w.name)==="GeneratorFunction")},a.mark=S=>(Object.setPrototypeOf?Object.setPrototypeOf(S,d):(S.__proto__=d,o(S,r,"GeneratorFunction")),S.prototype=Object.create(m),S),a.awrap=S=>({__await:S}),b(I.prototype),o(I.prototype,n,function(){return this}),a.AsyncIterator=I,a.async=(S,w,P,G,L)=>{L===void 0&&(L=Promise);var W=new I(h(S,w,P,G),L);return a.isGeneratorFunction(w)?W:W.next().then(K=>K.done?K.value:W.next())},b(m),o(m,r,"Generator"),o(m,s,function(){return this}),o(m,"toString",()=>"[object Generator]"),a.keys=S=>{var w=[];for(var P in S)w.push(P);return w.reverse(),function G(){for(;w.length;){var L=w.pop();if(L in S)return G.value=L,G.done=!1,G}return G.done=!0,G}},a.values=E,R.prototype={constructor:R,reset:function(S){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),!S)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 S=this.tryEntries[0].completion;if(S.type==="throw")throw S.arg;return this.rval},dispatchException:function(S){if(this.done)throw S;var w=this;function P($,z){return W.type="throw",W.arg=S,w.next=$,z&&(w.method="next",w.arg=void 0),!!z}for(var G=this.tryEntries.length-1;G>=0;--G){var L=this.tryEntries[G],W=L.completion;if(L.tryLoc==="root")return P("end");if(L.tryLoc<=this.prev){var K=t.call(L,"catchLoc"),ce=t.call(L,"finallyLoc");if(K&&ce){if(this.prev=0;--P){var G=this.tryEntries[P];if(G.tryLoc<=this.prev&&t.call(G,"finallyLoc")&&this.prev=0;--w){var P=this.tryEntries[w];if(P.finallyLoc===S)return this.complete(P.completion,P.afterLoc),y(P),c}},catch:function(S){for(var w=this.tryEntries.length-1;w>=0;--w){var P=this.tryEntries[w];if(P.tryLoc===S){var G=P.completion;if(G.type==="throw"){var L=G.arg;y(P)}return L}}throw new Error("illegal catch attempt")},delegateYield:function(S,w,P){return this.delegate={iterator:E(S),resultName:w,nextLoc:P},this.method==="next"&&(this.arg=void 0),c}},a}function e0(a){return e0=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?e=>typeof e:e=>e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e,e0(a)}function vl(a,e,t,i,s,n,r){try{var o=a[n](r),h=o.value}catch(l){return void t(l)}o.done?e(h):Promise.resolve(h).then(i,s)}function Gi(a){return function(){var e=this,t=arguments;return new Promise((i,s)=>{var n=a.apply(e,t);function r(h){vl(n,i,s,r,o,"next",h)}function o(h){vl(n,i,s,r,o,"throw",h)}r(void 0)})}}function Mt(a,e){if(!(a instanceof e))throw new TypeError("Cannot call a class as a function")}function bl(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=Ur(a);if(e){var s=Ur(this).constructor;t=Reflect.construct(i,arguments,s)}else t=i.apply(this,arguments);return Rb(this,t)}}function xl(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=[],h=!0,l=!1;try{for(s=s.call(t);!(h=(n=s.next()).done)&&(o.push(n.value),!i||o.length!==i);h=!0);}catch(c){l=!0,r=c}finally{try{h||s.return==null||s.return()}finally{if(l)throw r}}return o}}(a,e)||oo(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 yl(a){return function(e){if(Array.isArray(e))return i0(e)}(a)||function(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}(a)||oo(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 oo(a,e){if(a){if(typeof a=="string")return i0(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)?i0(a,e):void 0}}function i0(a,e){(e==null||e>a.length)&&(e=a.length);for(var t=0,i=new Array(e);tsetTimeout(a)).then(()=>Date.now())}var Ib=Math.PI/2,Eb=new v(2,2,2),Tl=function(){function a(){Mt(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 Pt(a,[{key:"length",value:function(){return v.Distance(this.start,this.end)}},{key:"renderLine",value:function(e){var t=[this.start,this.end],i=Zt.CreateLines("lines",t,e);i.enableEdgesRendering(),i.edgesWidth=10,i.edgesColor=new H(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(Eb),r=this.end.subtract(this.start),o=Math.sqrt(Math.pow(r.x,2)+Math.pow(r.y,2)+Math.pow(r.z,2)),h=Math.atan2(r.z,r.x),l=Math.acos(r.y/o);return i.matrix=O.Compose(new v(s,this.layerHeight,e),re.FromEulerVector(new v(0,-h,Ib-l)),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 H(1,1,1,1):new H(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,h=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 l=this.start.clone(),c=0;n.push(l.clone());var u=e/2*Math.cos(h),f=e/2*Math.sin(h),d=0;for(o!==0&&(d=(this.end.y-this.start.y)/o);ce)for(var _=l.x-i;_<=l.x+i;_+=e)for(var p=l.z-i;pt&&s){for(var g=[],m=0;m5e4||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==ts.Color&&!this.hasMixing}},{key:"forceDraw",value:function(){this.timeStamp=0}}]),a}(),Cb=function(a){Yi(t,ca);var e=qi(t);function t(i,s,n,r,o,h){var l;return Mt(this,t),(l=e.call(this,i,s,n,r,o)).meshIndex=h!=null?h:0,l.lostInSpace=O.Identity().setTranslation(new v(1e4,1e4,1e4)),l.additiveColor=new H(0,1,0,.8),l}return Pt(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=Zt.CreateBox("box",{width:1,height:1,depth:1,sideOrientation:F.FRONTSIDE},this.scene);return this.material=new ee("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),h=0;h.5&&_[L+3]<1){_[L+3]+=.02;var W=10*(_[L+3]-.9);_[L]=s.lerp(s.progressColor.r,n[P].color.r,W),_[L+1]=s.lerp(s.progressColor.g,n[P].color.g,W),_[L+2]=s.lerp(s.progressColor.b,n[P].color.b,W),S=!0}_[L+3]>=1&&!p[P]&&(n[P].color.toArray(_,L),_[L+3]=1,p[P]=!0,S=!0)}}else o[P]<=s.currentFilePosition?(n[P].color.toArray(_,L),n[P].matrix.copyToArray(d,16*P),_[L+3]=1,p[P]=!0):(s.getTransparentValue()===0?s.lostInSpace.copyToArray(d,16*P):n[P].matrix.copyToArray(d,16*P),_[L+3]=s.getTransparentValue(),p[P]=!1)}S&&b.thinInstanceBufferUpdated("color"),w&&(b.thinInstanceBufferUpdated("matrix"),b.thinInstanceRefreshBoundingInfo())};if(i.length!==0){var T=i[0].gcodeFilePosition,x=i.slice(-1)[0].gcodeFilePosition,y=0,R=!1,E=!1;this.timeStamp=Date.now();var C=function(){if(!(s.isLoading||Date.now()-s.timeStamp<200)){if(s.timeStamp=Date.now(),s.doScrub(y,T,x)||s.forceRedraw){R=!0,s.forceRedraw=!1,y=0;for(var S=0;S=T-3e4&&s.currentFilePosition<=x+3e4?(R=!1,E&&b.unfreezeWorldMatrix(),I()):E||(b.freezeWorldMatrix(),E=!0);y=s.currentFilePosition}};this.renderFuncs.push(C),this.scene.registerBeforeRender(C)}}}]),t}(),Sb=function(a){Yi(t,ca);var e=qi(t);function t(i,s,n,r,o,h){var l;return Mt(this,t),(l=e.call(this,i,s,n,r,o)).meshIndex=h!=null?h:0,l.lostInSpace=O.Identity().setTranslation(new v(1e4,1e4,1e4)),l.additiveColor=new H(0,1,0,.8),l}return Pt(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=Zt.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,ci.WORLD),i.bakeCurrentTransformIntoVertices(),this.material=new ee("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),h=0;h.5&&_[L+3]<1){_[L+3]+=.02;var W=10*(_[L+3]-.9);_[L]=s.lerp(s.progressColor.r,n[P].color.r,W),_[L+1]=s.lerp(s.progressColor.g,n[P].color.g,W),_[L+2]=s.lerp(s.progressColor.b,n[P].color.b,W)}_[L+3]>=1&&!p[P]&&(n[P].color.toArray(_,L),_[L+3]=1,p[P]=!0,S=!0)}}else o[P]<=s.currentFilePosition?(n[P].color.toArray(_,L),n[P].matrix.copyToArray(d,G),_[L+3]=1,p[P]=!0):(s.getTransparentValue()===0?s.lostInSpace.copyToArray(d,G):n[P].matrix.copyToArray(d,G),_[L+3]=s.getTransparentValue(),p[P]=!1)}S&&b.thinInstanceBufferUpdated("color"),w&&(b.thinInstanceBufferUpdated("matrix"),b.thinInstanceRefreshBoundingInfo())};if(i.length!==0){var T=i[0].gcodeFilePosition,x=i.slice(-1)[0].gcodeFilePosition,y=0,R=!1,E=!1;this.timeStamp=Date.now();var C=function(){if(!(s.isLoading||Date.now()-s.timeStamp<200)){if(s.timeStamp=Date.now(),s.doScrub(y,T,x)||s.forceRedraw){R=!0,s.forceRedraw=!1,y=0;for(var S=0;S=T-3e4&&s.currentFilePosition<=x+3e4?(R=!1,E&&b.unfreezeWorldMatrix(),I()):E||(E=!0,b.freezeWorldMatrix());y=s.currentFilePosition}};this.renderFuncs.push(C),this.scene.registerBeforeRender(C)}}}]),t}(),Mb=Pt(function a(e,t){Mt(this,a),this.filePosition=e,this.add=t,this.complete=!1}),df=function(a){Yi(i,ca);var e,t=qi(i);function i(s,n,r,o,h,l,c){var u;return Mt(this,i),(u=t.call(this,s,n,r,o,h)).voxelWidth=parseFloat(l),u.voxelHeight=parseFloat(c),u.solidMat,u.transparentMat,u.hasSubtractive=!1,u.lostInSpace=O.Identity().setTranslation(new v(1e4,1e4,1e4)),u.clearColor=new H(1,0,0,0),u.additiveColor=new H(0,1,0,.8),u.subtractiveColor=new H(1,0,0,.8),u}return Pt(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=Zt.CreateBox("box",{width:this.voxelWidth,height:this.voxelHeight,depth:this.voxelWidth},this.scene);return s.hasVertexAlpha=!0,s.updateFacetData=!0,this.material=new ee("mat",this.scene),this.material.needDepthPrePass=!0,this.material.forceDepthWrite=!0,this.material.backFaceCulling=!1,s.material=this.material,s}},{key:"render",value:(e=Gi(It().mark(function s(n){var r,o,h,l,c,u,f,d,_,p,g,m,b,I,T,x,y,R,E,C,S,w=this;return It().wrap(function(P){for(;;)switch(P.prev=P.next){case 0:for(this.isLoading=!0,r=parseInt(300/this.voxelWidth)+1,o=r,h=parseInt(300/this.voxelHeight)+1,l=new Array(o),c=0;c<=h;c++)l[c]=new Object;u=0,f=new Date,d=0;case 10:if(!(d5e3)){P.next=57;break}return f=new Date,this.loadingProgressCallback(d/n.length,"Generating Voxel Map..."),P.next=57,kr();case 57:b++,P.next=22;break;case 60:d++,P.next=10;break;case 63:this.loadingProgressCallback(d/n.length,"Rendering Voxel..."),C=It().mark(function G(L){var W,K,ce,$,z,k,M,V,q,he,pe,se,ue,me,ne,Ie,Se,Q,be,Be,ze,Ke,Rt,Ct,Ge,Jt,Wt,ji,Is;return It().wrap(Ti=>{for(;;)switch(Ti.prev=Ti.next){case 0:if(W=[],l[L]!==void 0){Ti.next=3;break}return Ti.abrupt("return","continue");case 3:for(K=999999999999,ce=-999999999999,$=[],z=0,k=Object.entries(l[L]);zce&&(ce=ne.voxelEvents[0].filePosition),(se=$).push.apply(se,yl(ne.voxelEvents.map(Ht=>Ht.filePosition))),ne.color.a=1,(Ie={matrix:O.Identity(),color:ne.color.clone(),voxelEvents:ne.voxelEvents,lastDrawnCount:0}).matrix.setTranslation(new v(V*w.voxelWidth,L*w.voxelHeight,me*w.voxelWidth)),W.push(Ie);for(Se=0,$=$.sort((Ht,oi)=>Ht-oi),$=yl(new Set($)),W.length,l[L]=null,(Q=w.buildBox()).alphaIndex=L,Q.renderingGroupId=1,be=new Float32Array(16*W.length),Be=new Float32Array(4*W.length),ze=0;ze{for(var Ht=!1,oi=!1,Vt=0;Vttr.filePositionCt&&$i.filePosition<=w.currentFilePosition&&(Yt.lastDrawnCount=0,w.hasSubtractive&&Yt.matrix.copyToArray(be,16*Vt)),Jt&&(Yt.lastDrawnCount=i.drawDelay),Yt.lastDrawnCount=Ct&&$i.filePosition<=w.currentFilePosition&&(Yt.lastDrawnCount=0),Jt&&(Yt.lastDrawnCount=i.drawDelay),Yt.lastDrawnCount{if(!(w.isLoading||Date.now()-ji<200)){if(ji=Date.now(),w.doScrub(Ct,K,ce)||Ge||w.forceRedraw){Se=0,Jt=!0,w.forceRedraw=!1;for(var Ht=0;HtVt.complete=!1);Rt(),Ge=!1}else if(Se<$.length-1&&$[Se]w.currentFilePosition));oi++);}else Wt<10&&(Wt++,Rt());Ct=w.currentFilePosition}},w.loadingProgressCallback&&w.loadingProgressCallback(L/u,"Rendering Voxels..."),w.renderFuncs.push(Is),w.scene.registerBeforeRender(Is),!(new Date-f>1e3)){Ti.next=36;break}return f=new Date,Ti.next=36,kr();case 36:case"end":return Ti.stop()}},G,this)}),S=0;case 67:if(!(Sz===!1);W<=S;W++){var K=8*W;if(h[W]||s.travels&&s.persistTravels){if(l[W])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[W][0].r,C[K+1]=o[W][0].g,C[K+2]=o[W][0].b,C[K+3]=1,C[K+4]=o[W][1].r,C[K+5]=o[W][1].g,C[K+6]=o[W][1].b,C[K+7]=1,l[W]=!0)}else{if(l[W])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,l[W]=!0)}x=W}for(var ce=S;ce=m-3e4&&s.currentFilePosition<=b+3e4&&(T=!1,y());I=s.currentFilePosition}};this.renderFuncs.push(E),this.scene.registerBeforeRender(E)}}]),t}(),Xs=function(){function a(){Mt(this,a),ff(this,"unknownFeatureColor",new H(.5,.5,.5,1)),this.feature=null,this.perimeter=!0,this.support=!1,this.missingFeatures=[]}return Pt(a,[{key:"isTypeComment",value:function(e){return!1}},{key:"getFeatureColor",value:function(e){return new H(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}(),Pb=function(a){Yi(t,Xs);var e=qi(t);function t(){var i;return Mt(this,t),(i=e.call(this)).featureList={Perimeter:{color:new H(1,.9,.3,1),perimeter:!1,support:!1},"External perimeter":{color:new H(1,.5,.2,1),perimeter:!0,support:!1},"Internal infill":{color:new H(.59,.19,.16,1),perimeter:!1,support:!1},"Solid infill":{color:new H(.59,.19,.8,1),perimeter:!1,support:!1},"Top solid infill":{color:new H(.95,.25,.25,1),perimeter:!0,support:!1},"Bridge infill":{color:new H(.3,.5,.73,1),perimeter:!1,support:!1},"Gap fill":{color:new H(1,1,1,1),perimeter:!1,support:!1},Skirt:{color:new H(0,.53,.43,1),perimeter:!1,support:!1},"Skirt/Brim":{color:new H(0,.53,.43,1),perimeter:!1,support:!1},"Supported material":{color:new H(0,1,0,1),perimeter:!1,support:!0},"Supported material interface":{color:new H(0,.5,0,1),perimeter:!1,support:!0},Custom:{color:new H(.5,.5,.5,1),perimeter:!1,support:!1},Unknown:{color:new H(.5,.5,.5,1),perimeter:!1,support:!1},"Support material":{color:new H(.5,.5,.5,1),perimeter:!1,support:!0},"Support material interface":{color:new H(.5,.5,.5,1),perimeter:!1,support:!0},"Overhang perimeter":{color:new H(.5,.5,.5,1),perimeter:!0,support:!1},"Wipe tower":{color:new H(.5,.5,.5,1),perimeter:!0,support:!1}},i}return Pt(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.unknownFeatureColor}},{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 Pt(a,[{key:"doUpdate",value:function(){this.lastUpdate=Date.now()}},{key:"setProgressColor",value:function(r){var o=this;this.progressColor=H.FromHexString(r.padEnd(9,"F")),this.renderInstances.forEach(h=>h.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=Ss.Voxel,this.meshBreakPoint=Rl,void(this.lines=new Array(Rl));this.lines=new Array(1.5*this.meshBreakPoint),o===void 0&&(o=1);var h=0,l=this.forceWireMode?2:1,c=2;switch(this.refreshTime=5e3,this.everyNthRow=1,this.renderTravels=!0,o){case 1:l=2,this.refreshTime=3e4,h=25e3,c=50,this.renderTravels=!1;break;case 2:l=2,this.refreshTime=3e4,h=5e5,c=10,this.renderTravels=!1;break;case 3:h=1e6,c=3;break;case 4:h=15e6,c=2;break;case 5:h=25e6;break;default:return this.renderVersion=Ss.Block,void(this.everyNthRow=1)}for(var u=l;u<4;u++){var f=void 0;switch(u){case 1:f=24;break;case 2:f=2;break;case 3:f=1}for(var d=this.everyNthRow;d<=c;d++)if(this.debug&&console.log("Mode: "+u+" NRow: "+d+" vertexcount: "+r*f/d),r*f/d0&&(_.extruding=!0,this.maxHeight=this.currentPosition.y);break;case"F":if(this.currentFeedRate=Number(m.substring(1)),_.feedRate=this.currentFeedRate,this.currentFeedRate>this.maxFeedRate&&(this.maxFeedRate=this.currentFeedRate),this.currentFeedRate=1?this.maxFeedColor:b<=0?this.minFeedColor:H.Lerp(this.minFeedColor,this.maxFeedColor,b)}}}if(this.zBelt&&(this.beltLength=this.currentPosition.z1&&_.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 I=this.hasSpindle&&c[0]==="G1",T=this.g1AsExtrusion||_.length()>=this.lineLengthTolerance;l&&(this.renderedLines.push(_),_.extruding&&this.lastZExtrusionthis.currentLayerHeight&&!this.isSupport&&p&&(this.previousLayerHeight=this.currentLayerHeight,this.currentLayerHeight=this.currentPosition.y)):this.renderTravels&&!_.extruding&&(_.color=new H(1,0,0,1),this.travels.push(_)),this.zBelt?_.layerHeight=Math.abs(this.currentLayerHeight-this.previousLayerHeight):this.g1AsExtrusion?_.layerHeight=1:_.layerHeight=this.currentLayerHeight-this.previousLayerHeight)}}},{key:"g2g3",value:function(r,o,h,l){var c=this,u=r.split(/(?=[GXYZIJKFREUVAB])/),f=r.indexOf("E")>0||this.g1AsExtrusion,d=u.filter(g=>g==="G2"||g==="G02"),_={position:this.currentPosition.clone(),points:[]};try{_=function(g,m,b,I,T,x,y){for(var R=new v(m.x,m.z,m.y),E=R.clone(),C=0,S=0,w=0,P=g.some(ji=>ji.includes("G2")),G=0;G=0)q=Math.sqrt(V/M);else if(V<-.02*Math.pow(w,2)){if(!T)return console.error("G2/G3: Radius too small"),{position:{x:E.x,y:E.z,z:E.y},points:[]};var he=Math.sqrt(Math.pow(z/2,2)+Math.pow(k/2,2));V=Math.pow(he,2)-M/4,q=Math.sqrt(V/M)}(P&&w<0||!P&&w>0)&&(q=-q),C=z/2+k*q,S=k/2-z*q}else if(C===0&&S===0)return{position:R.clone(),points:[]};var pe,se=R[W]===E[W]&&R[K]===E[K],ue=R[W]+C,me=R[K]+S,ne=Math.sqrt(C*C+S*S),Ie=Math.atan2(-S,-C),Se=Math.atan2(E[K]-me,E[W]-ue);se?pe=2*Math.PI:(pe=P?Ie-Se:Se-Ie)<0&&(pe+=2*Math.PI);var Q=ne*pe/I;Q<1&&(Q=1);var be=pe/Q;be*=P?-1:1;for(var Be=new Array,ze=(E[ce]-R[ce])/Q,Ke=R[W],Rt=R[K],Ct=R[ce],Ge=Ie,Jt=0;Jt{var b=new Tl;b.tool=c.currentTool,b.gcodeLineNumber=o,b.gcodeFilePosition=h,b.feedRate=c.currentFeedRate,b.isPerimeter=c.slicer.isPerimeter(),c.g1AsExtrusion?b.layerHeight=1:b.layerHeight=c.currentLayerHeight-c.previousLayerHeight,b.start=p.clone(),b.end=new v(g.x,g.y,g.z),b.extruding=f,b.color=f?c.currentColor.clone():new H(1,0,0,1),c.debug&&(b.color=d?new H(0,1,1,1):new H(1,1,0,1),m===0&&(b.color=new H(0,1,0,1))),p=b.end.clone(),c.debug&&console.log(b),l&&(c.renderedLines.push(b),b.extruding?c.lines[c.linesIndex++]=b:c.travels.push(b))}),this.currentPosition=new v(p.x,p.y,p.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])/),h=[1,1,1];if(this.colorMode!==ts.Feed){for(var l=1;l0&&(this.firstGCodeByte=f),this.lastGCodeByte=f,this.processLine(_,d,f,p)),!(Date.now()-this.timeStamp>10)){g.next=33;break}return this.loadingProgressCallback&&this.loadingProgressCallback(f/o.length,"Loading File..."),g.next=32,kr();case 32:this.timeStamp=g.sent;case 33:this.doUpdate(),g.next=19;break;case 36:if(this.layerDictionary.push(o.length),!this.renderTravels){g.next=40;break}return g.next=40,this.createTravelLines(this.scene);case 40:this.loadingProgressCallback&&this.loadingProgressCallback(1),o={};case 42:case"end":return g.stop()}},r,this)})),function(r,o,h){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=Gi(It().mark(function r(o,h,l){var c,u,f,d,_,p,g,m,b,I,T,x,y,R=arguments;return It().wrap(function(E){for(;;)switch(E.prev=E.next){case 0:if(c=!(R.length>3&&R[3]!==void 0)||R[3],(u=o.indexOf(";"))>-1&&(o=o.substring(0,u-1).trim()),o=o.toUpperCase(),(d=o.match(/[GM]+[0-9.]+/g))===null&&o.match(/[XYZ]+[+-]?[0-9.]+/g)!==null&&(d=this.lastCommand),_=o.trim().split(/[GM]+[0-9.]+/g),!d){E.next=62;break}p=0;case 9:if(!(pC.trim()==="X")&&(this.currentPosition.x=this.workplaceOffsets[this.currentWorkplace].x),f.some(C=>C.trim()==="Y")&&(this.currentPosition.z=this.workplaceOffsets[this.currentWorkplace].y),f.some(C=>C.trim()==="Z")&&(this.currentPosition.y=this.workplaceOffsets[this.currentWorkplace].z)),E.abrupt("break",56);case 32:return E.abrupt("break",56);case 33:return this.currentWorkplace=54-Number(d[p].substring(1)),this.currentPosition=this.workplaceOffsets[this.currentWorkplace].clone(),E.abrupt("break",56);case 36:return this.currentWorkplace=10*(58.6-Number(d[p].substring(1))),this.currentPosition=this.workplaceOffsets[this.currentWorkplace].clone(),E.abrupt("break",56);case 39:return this.absolute=!0,E.abrupt("break",56);case 41:return this.absolute=!1,E.abrupt("break",56);case 43:return E.abrupt("break",56);case 44:return this.hasSpindle=!0,E.abrupt("break",56);case 46:return g=o.split(/(?=[SM])/),(m=(m=g.filter(C=>C.startsWith("S")))[0]?Number(m[0].substring(1)):0)>0&&(this.hasSpindle=!0),E.abrupt("break",56);case 51:return this.hasMixing=!0,this.m567(o),E.abrupt("break",56);case 54:try{this.currentTool++,this.currentTool>=this.tools.length&&(this.currentTool=0),this.colorMode!==ts.Feed&&(this.currentColor=this.tools[this.currentTool].color.clone())}catch(C){console.log(C)}return E.abrupt("break",56);case 56:this.lastCommand=d;case 57:p++,E.next=9;break;case 60:E.next=64;break;case 62:o.startsWith("T")&&(b=Number.parseInt(o.substring(1),10),isNaN(b)||(this.currentPosition.z+=10,this.currentTool=b,this.currentTool>=this.tools.length?this.currentTool=this.currentTool%this.tools.length:b<0&&(this.currentTool=0),this.colorMode!==ts.Feed&&((y=Number(o.substring(1))%this.extruderCount)<0&&(y=0),this.currentColor=(I=(T=this.tools[y])===null||T===void 0||(x=T.color)===null||x===void 0?void 0:x.clone())!==null&&I!==void 0?I:new de(1,0,0)))),this.debug;case 64:if(!(this.linesIndex>=this.meshBreakPoint)){E.next=71;break}return E.next=67,this.createMesh(this.scene);case 67:return E.next=69,kr();case 69:this.doUpdate(),this.meshIndex++;case 71:case"end":return E.stop()}},r,this)})),function(r,o,h){return s.apply(this,arguments)})},{key:"createMesh",value:(i=Gi(It().mark(function r(o){var h,l,c;return It().wrap(function(u){for(;;)switch(u.prev=u.next){case 0:if(this.zBelt&&(h=this.lines[this.linesIndex-1].layerHeight,this.lines.forEach(f=>{f.layerHeight=h})),this.renderVersion===Ss.Line||this.renderVersion===Ss.Point?l=new Al(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.meshIndex):this.renderVersion===Ss.Block?l=this.highQualityExtrusion?new Sb(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.meshIndex):new Cb(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.meshIndex):this.renderVersion===Ss.Voxel&&(l=new df(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.voxelWidth,this.voxelHeight)),l.progressColor=this.progressColor,l.vertexAlpha=this.vertexAlpha,l.g1AsExtrusion=this.g1AsExtrusion,l.progressMode=this.progressMode,l.transparentValue=this.transparentValue,l.hasMixing=this.hasMixing,l.colorMode=this.colorMode,l.renderAnimation=this.renderAnimation,l.persistTravels=this.persistTravels,this.renderInstances.push(l),!((c=this.lines.slice(0,this.linesIndex-1))!=null&&c.length>0)){u.next=16;break}return u.next=16,l.render(c);case 16:this.linesIndex=0;case 17:case"end":return u.stop()}},r,this)})),function(r){return i.apply(this,arguments)})},{key:"chunk",value:function(r,o){for(var h=[],l=0,c=r.length;lh.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(h=>h.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]:s0.Extruder,l=new fr;l.color=H.FromHexString(r.padEnd(9,"F")),l.updateDarkerValue(),l.diameter=o,l.toolType=h,this.tools.push(l)}},{key:"updateTool",value:function(r,o,h){h{if(h.material!==null&&Object.prototype.hasOwnProperty.call(h.material,"specularColor"))try{h.material.specularColor=o}catch(l){console.error(l)}}),this.scene&&this.scene.render(!0,!0)}},{key:"g1AsExtrusion",value:function(r){this.g1AsExtrusion=r}},{key:"cancel",value:(e=Gi(It().mark(function r(){return It().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(h=>h.renderAnimation=o.renderAnimation)}},{key:"setTravelPersistence",value:function(r){var o=this;this.persistTravels=r,this.renderInstances.forEach(h=>{h.persistTravels=o.persistTravels})}}]),a}(),Il=0,Ub=1,kb=function(){function a(e){Mt(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 ee("bedBoxMaterial",this.scene),this.boxMaterial.alpha=0,this.debug=!1}return Pt(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 Ub: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=Zt.CreateDisc("BuildPlate",{radius:i},this.scene),this.bedMesh.rotationQuaternion=re.RotationAxis(new v(1,0,0),Math.PI/2),this.bedMesh.material=this.planeMaterial}else{var s=t.x,n=t.y;this.bedMesh=Zt.CreatePlane("BuildPlate",{width:s,height:n},this.scene),this.bedMesh.material=this.planeMaterial,this.bedMesh.rotationQuaternion=re.RotationAxis(new v(1,0,0),Math.PI/2),this.bedMesh.translate(new v(e.x,0,e.y),1,ci.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=Zt.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 H(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 kt("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=Zt.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 H(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 zt("bedMaterial",this.scene);return e.mainColor=new H(0,0,0,0),e.lineColor=de.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 H.FromHexString(this.getBedColor().padEnd(9,"F"))}},{key:"dispose",value:function(){this.bedMesh&&!this.bedMesh.isDisposed&&this.bedMesh.dispose(!1,!0)}}]),a}(),Vb=function(){function a(e){Mt(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 Pt(a,[{key:"setBuildMaterial",value:function(e,t,i){i||(i=this.alphaLevel);var s=new ee(e,this.scene);return s.diffuseColor=t,s.specularColor=new de(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 H(.1,.5,.1),.25),this.highlightMaterial=this.setBuildMaterial("BuildObjectHighlightMateria",new de(.8,.8,.8)),this.cancelledMaterial=this.setBuildMaterial("BuildObjectHighlightMateria",new de(1,0,0),.4),this.cancelledHighlightMaterial=this.setBuildMaterial("BuildObjectHighlightMateria",new de(1,1,0),.6);var e=ie.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"}),h=window.URL.createObjectURL(o);this.labelSVGS.push(h);var l=Zt.CreatePlane("TextPlane",{width:i,height:8},this.scene);return l.material=new ee("TextPlaneMaterial",this.scene),l.material.backFaceCulling=!1,l.material.specularColor=new de(0,0,0),l.material.diffuseTexture=new ie(h,this.scene),l.material.diffuseTexture.hasAlpha=!0,l.billboardMode=7,this.registerClipIgnore(l),l}},{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 Ce.POINTERDOWN:i=!0,s=Date.now();break;case Ce.POINTERUP:if(i=!1,Date.now()-s>200)return;e.handleClick(r);break;case Ce.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 H(1,0,0,1)):(e.material=this.baseMaterial,e.enableEdgesRendering(),e.edgesWidth=15,e.edgesColor=new H(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}(),Gb=function(){function a(e){Mt(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 Pt(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 Wn("DynamicTexture",50,this.scene,!0);s.hasAlpha=!0,s.drawText(e,5,40,"bold 36px Arial",t,"transparent",!0);var n=F.CreatePlane("TextPlane",i,this.scene,!0);return n.material=new ee("TextPlaneMaterial",this.scene),n.material.backFaceCulling=!1,n.material.specularColor=new de(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 F("axis",this.scene),this.registerClipIgnore(this.axesMesh);var i=F.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 de(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=F.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 de(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=F.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 de(0,0,1),o.parent=this.axesMesh;var h=this.makeTextPlane("Z","blue",this.size/10);h.billboardMode=7,h.position=new v(0,.9*this.size,-.05*this.size),h.parent=this.axesMesh,this.axesMesh.setEnabled(this.visible),this.axesMesh.getChildren().forEach(l=>t.registerClipIgnore(l)),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 Zs(a,e,t){var i=function(s,n,r,o,h,l){var c=arguments.length>6&&arguments[6]!==void 0?arguments[6]:75,u=uu("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 f=u.attr("title","test2").attr("version",1.1).attr("xmlns","http://www.w3.org/2000/svg").node(),d='',_=new XMLSerializer().serializeToString(f),p=new Blob([d+_],{type:"image/svg+xml"}),g=window.URL.createObjectURL(p),m=Zt.CreatePlane("TextPlane",{width:h,height:l},s);return m.material=new ee("TextPlaneMaterial",s),m.material.backFaceCulling=!1,m.material.specularColor=new de(0,0,0),m.material.diffuseTexture=new ie(g,s),m.material.diffuseTexture.hasAlpha=!1,m}(a,e,"white","white",6,6,90);i.name=e,i.lookAt(t),i.position=t.scale(-3),e==="Top"&&i.rotate(Gt.Z,Math.PI/2,ci.LOCAL),e==="Bottom"&&i.rotate(Gt.Z,-Math.PI/2,ci.LOCAL),i.metadata={x:Math.sign(t.x),y:Math.sign(t.y),z:Math.sign(t.z)},i.isPickable=!0}function gs(a,e,t){var i=Zt.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 n0,Ma=null;function pi(a,e,t){Ma||((Ma=new ee("edgematerial",a)).diffuseColor=new de(.5,.5,.5));var i=Zt.CreateBox(e,{width:.35,height:5.8,depth:.35},a),s=v.Zero();t.y!==0&&(i.rotate(Gt.Z,Math.PI/2,ci.WORLD),t.x!==0&&i.rotate(Gt.Y,Math.PI/2,ci.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=Ma}function zb(a,e,t){(Ze=new it(a)).autoClear=!1;var i=new tt("camera1",5*Math.PI/8,5*Math.PI/8,13,new v(0,0,0),Ze);i.viewport=new on(.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 _n("light1",new v(0,1,0),Ze).intensity=.8,new _n("light2",new v(-1,-.5,0),Ze).intensity=.8;var s=3.9;pi(Ze,"FrontLeft",new v(-3.9,0,-3.9)),pi(Ze,"BackLeft",new v(-3.9,0,s)),pi(Ze,"BackRight",new v(s,0,s)),pi(Ze,"FrontRight",new v(s,0,-3.9)),pi(Ze,"TopFront",new v(0,s,-3.9)),pi(Ze,"TopBack",new v(0,s,s)),pi(Ze,"TopLeft",new v(-3.9,s,0)),pi(Ze,"TopRight",new v(s,s,0)),pi(Ze,"BottomFront",new v(0,-3.9,-3.9)),pi(Ze,"BottomBack",new v(0,-3.9,s)),pi(Ze,"BottomLeft",new v(-3.9,-3.9,0)),pi(Ze,"BottomRight",new v(s,-3.9,0)),gs(Ze,"FrontTopLeft",new v(-3,3,-3)),gs(Ze,"FrontTopRight",new v(3,3,-3)),gs(Ze,"BackTopLeft",new v(-3,3,3)),gs(Ze,"BackTopRight",new v(3,3,3)),gs(Ze,"FrontBottomLeft",new v(-3,-3,-3)),gs(Ze,"FrontBottomRight",new v(3,-3,-3)),gs(Ze,"BackBottomLeft",new v(-3,-3,3)),gs(Ze,"BackBottomRight",new v(3,-3,3)),Zs(Ze,"Front",new v(0,0,1)),Zs(Ze,"Right",new v(-1,0,0)),Zs(Ze,"Back",new v(0,0,-1)),Zs(Ze,"Left",new v(1,0,0)),Zs(Ze,"Top",new v(0,-1,0)),Zs(Ze,"Bottom",new v(0,1,0)),Ze.onPointerDown=(n,r)=>{r.distance>0&&n0&&(n0(r.pickedMesh.metadata),Ze.render(!0))}}var Wb=function(){function a(e){Mt(this,a),this.visible=!0,this.scene=e,this.workplacePoints=[],this.workplaceMeshes=[],this.registerClipIgnore=()=>{}}return Pt(a,[{key:"setOffsets",value:function(e){this.workplacePoints=e,this.render()}},{key:"makeTextPlane",value:function(e,t,i){var s=new Wn("DynamicTexture",50,this.scene,!0);s.hasAlpha=!0,s.drawText(e,5,40,"bold 36px Arial",t,"transparent",!0);var n=F.CreatePlane("TextPlane",i,this.scene,!0);return n.material=new ee("TextPlaneMaterial",this.scene),n.material.backFaceCulling=!1,n.material.specularColor=new de(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 Pt(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 Xt(0,1,0,this.zTopClipValue),this.scene.clipPlane2=new Xt(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=Gi(It().mark(function n(r){var o,h,l=this;return It().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.16"," ")),c.next=4,Ye.IsSupportedAsync;case 4:if(!c.sent||!r){c.next=13;break}return console.log("WebGPU Supported"),this.engine=new Ye(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 le(this.canvas,!0,{doNotHandleContextLost:!0});case 15:this.engine.enableOfflineSupport=!1,this.engine.setHardwareScalingLevel(1/window.devicePixelRatio),this.scene=new it(this.engine),this.scene.performancePriority=Ha.BackwardCompatible,this.debug,this.scene.clearColor=de.FromHexString(this.getBackgroundColor()),this.bed=new kb(this.scene),this.bed.registerClipIgnore=u=>{l.registerClipIgnore(u)},o=this.bed.getCenter(),this.orbitCamera=new tt("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(),(h=new jr("light2",new v(0,1,-1),this.scene)).diffuse=new de(1,1,1),h.specular=new de(1,1,1),this.engine.runRenderLoop(()=>{if(!document.hidden){if(l.simulation){if(l.pause)return}else if(l.pause||Date.now()-l.gcodeProcessor.lastUpdate>l.renderTimeout&&l.isArcRotateCameraStopped(l.orbitCamera))return;if(l.simulation)try{l.runSimulation(),l.gcodeProcessor.doUpdate()}catch{l.simulation=!1,l.simulationStopped()}l.scene.render(!0),h.position=l.scene.cameras[0].position}}),this.buildObjects=new Vb(this.scene),this.buildObjects.getMaxHeight=()=>l.gcodeProcessor.getMaxHeight(),this.buildObjects.registerClipIgnore=u=>{l.registerClipIgnore(u)},this.bed.buildBed(),this.axes=new Gb(this.scene),this.axes.registerClipIgnore=u=>{l.registerClipIgnore(u)},this.axes.render(),this.workplace=new Wb(this.scene),this.workplace.registerClipIgnore=u=>{l.registerClipIgnore(u)},this.workplace.setOffsets(this.gcodeProcessor.workplaceOffsets),this.workplace.render(),this.resetCamera(),zb(this.engine,this.scene,this.orbitCamera),n0=u=>{console.log("viewbox callback",u),l.setViewboxCameraPosition(u)},setTimeout(()=>{l.forceRender()},1e3);case 50:case"end":return c.stop()}},n,this)})),function(n){return s.apply(this,arguments)})},{key:"setViewboxCameraPosition",value:function(n){var r=this.bed.getCenter(),o=this.bed.getSize();this.scene.activeCamera.radius=1.5*o.x,this.scene.activeCamera.target=new v(r.x,r.z,r.y);var h=v.Zero(),l=(n.x===0?1:0)+(n.y===0?1:0)+(n.z===0?1:0)==2?1.75:1.35;switch(n.x){case 1:h.x=r.x-o.x*l;break;case 0:h.x=r.x;break;case-1:h.x=r.x+o.x*l}switch(n.y){case 1:h.y=r.z-o.z*l;break;case 0:h.y=r.z;break;case-1:h.y=r.z+o.z*l}switch(n.z){case 1:h.z=r.y-o.y*l;break;case 0:h.z=r.y;break;case-1:h.z=r.y+o.y*l}n.x===0&&n.z===0?(this.scene.activeCamera.target=new v(r.x,0,r.y),this.scene.activeCamera.position=h,this.scene.activeCamera.alpha=3*Math.PI/2):this.scene.activeCamera.position=h,this.scene.render(!0),this.scene.render(!0)}},{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=Gi(It().mark(function n(r){return It().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(l,c){var u=typeof Symbol<"u"&&l[Symbol.iterator]||l["@@iterator"];if(!u){if(Array.isArray(l)||(u=oo(l))||c){u&&(l=u);var f=0,d=()=>{};return{s:d,n:()=>f>=l.length?{done:!0}:{done:!1,value:l[f++]},e:m=>{throw m},f:d}}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 _,p=!0,g=!1;return{s:()=>{u=u.call(l)},n:()=>{var m=u.next();return p=m.done,m},e:m=>{g=!0,_=m},f:()=>{try{p||u.return==null||u.return()}finally{if(g)throw _}}}}(this.scene.meshes);try{for(o.s();!(r=o.n()).done;){var h=r.value;h.name==="travels"&&(h.isVisible=n)}}catch(l){o.e(l)}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=de.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 h=this.scene.materials.length-1;h>=0;h--){var l=this.scene.materials[h];l.name==="solidMaterial"&&(l&&this.debug&&console.log("Disposing ".concat(l.name)),this.scene.removeMaterial(l),l&&typeof l.dispose=="function"&&l.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=Gi(It().mark(function n(){return It().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,h=0;if(this.buildtoolCursor(),n instanceof v)r=n.x,o=n.z,h=n.y;else for(var l=0;l{r.scene.clipPlane=null,r.scene.clipPlane2=null}),n.onAfterRenderObservable.add(()=>{r.scene.clipPlane=new Xt(0,1,0,r.zTopClipValue),r.scene.clipPlane2=new Xt(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(Gt.X,Math.PI/2-r*Math.PI/180,ci.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,h=this.scene.getAnimationRatio();h>3&&(o+=~~h),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:"setCameraPosition",value:function(n,r,o){var h=Number(n),l=Number(r),c=Number(o);h!==NaN&&l!==NaN&&c!==NaN&&(this.scene.activeCamera.position=new v(Number(n),Number(o),Number(r)),this.forceRender())}},{key:"setCameraTarget",value:function(n,r,o){var h=Number(n),l=Number(r),c=Number(o);h!==NaN&&l!==NaN&&c!==NaN&&(this.scene.activeCamera.target=new v(Number(n),Number(o),Number(r)),this.forceRender())}},{key:"createScreenshot",value:(e=Gi(It().mark(function n(){var r,o,h,l,c=arguments;return It().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,h=this.scene.clearColor,this.scene.clearColor=new H(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,$g.CreateScreenshotAsync(this.engine,this.scene.activeCamera,{width:r,height:o});case 13:return l=u.sent,this.scene.clearColor=h,u.abrupt("return",l);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}(),Kb=Object.defineProperty,Xb=Object.getOwnPropertyDescriptor,Je=(a,e,t,i)=>{for(var s=i>1?void 0:i?Xb(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&&Kb(e,t,s),s};let Y=null,$e=class extends El(Cl){constructor(){super(...arguments),this.mdiReloadAlert=Mf,this.mdiCameraRetake=Pf,this.mdiToggleSwitch=wf,this.mdiToggleSwitchOffOutline=Df,this.mdiClose=Ff,this.mdiCog=Of,this.mdiVideo3d=Bf,this.mdiPlay=Lf,this.mdiPause=Nf,this.mdiFastForward=Uf,this.mdiBroom=kf,this.mdiSelectionRemove=Vf,this.formatFilesize=Gf,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:{}},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,Y=(s=(i=this.$store.state.gcodeviewer)==null?void 0:i.viewerBackup)!=null?s:null,await this.init(),this.loadedFile!==null&&(this.scrubFileSize=Y.fileSize),Y&&(this.fileData=Y.fileData)}beforeDestroy(){Y&&(Y.gcodeProcessor.loadingProgressCallback=null,this.$store.dispatch("gcodeviewer/setLoadedFileBackup",this.loadedFile),this.$store.dispatch("gcodeviewer/setViewerBackup",Y)),this.scrubPlaying=!1,this.scrubInterval&&(clearInterval(this.scrubInterval),this.scrubInterval=void 0)}handleResize(){this.$nextTick(()=>{Y==null||Y.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,i;return(i=(t=(e=this.$store.state.printer)==null?void 0:e.exclude_object)==null?void 0:t.objects)!=null?i:[]}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.viewerCanvasContainer.appendChild(e),await this.$store.dispatch("gcodeviewer/setCanvasBackup",e)):(this.viewerCanvasContainer.appendChild(e),Y!=null&&Y.gcodeProcessor&&Y.gcodeProcessor.updateFilePosition(Y==null?void 0:Y.fileSize)),Y===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){Y=new Hb(e),await Y.init(),Y.setBackgroundColor(this.backgroundColor),Y.bed.setBedColor(this.gridColor),Y.setCursorVisiblity(this.showCursor),Y.setZClipPlane(1e6,-1e6),Y.axes.show(this.showAxes),Y.bed.setDelta(this.kinematics.includes("delta")),this.bedMaxSize!==null&&(Y.bed.buildVolume.x.max=this.bedMaxSize[0],Y.bed.buildVolume.y.max=this.bedMaxSize[1],Y.bed.buildVolume.z.max=this.bedMaxSize[2]),this.bedMinSize!==null&&(Y.bed.buildVolume.x.min=this.bedMinSize[0],Y.bed.buildVolume.y.min=this.bedMinSize[1],Y.bed.buildVolume.z.min=this.bedMinSize[2]),Y.gcodeProcessor.useHighQualityExtrusion(this.hdRendering),Y.gcodeProcessor.updateForceWireMode(this.forceLineRendering||this.cncMode),Y.gcodeProcessor.setAlpha(this.transparency),Y.gcodeProcessor.setVoxelMode(this.voxelMode),Y.gcodeProcessor.voxelWidth=this.voxelWidth,Y.gcodeProcessor.voxelHeight=this.voxelHeight,Y.gcodeProcessor.useSpecularColor(this.specularLighting),Y.gcodeProcessor.setLiveTracking(!1),Y.gcodeProcessor.g1AsExtrusion=this.cncMode,Y.buildObjects.objectCallback=this.objectCallback,this.loadToolColors(this.extruderColors),Y.lastLoadFailed()&&(this.renderQuality=this.renderQualities[0],Y.updateRenderQuality(1),Y.clearLoadFlag())}registerProgressCallback(){Y!==null&&(Y.gcodeProcessor.loadingProgressCallback=e=>{this.loadingPercent=Math.ceil(e*100),this.loading=this.loadingPercent<=99})}async cancelRendering(){Y!==null&&(Y.gcodeProcessor.cancelLoad=!0,await this.sleep(1e3))}clearLoadedFile(){Y!==null&&(this.scrubPlaying=!1,this.scrubFileSize=0,Y.clearScene(!0),this.loadedFile=null,this.tracking=!1)}chooseFile(){this.isBusy||this.fileInput.click()}finishLoad(){this.loading=!1,Y.setCursorVisiblity(this.showCursor),this.refreshPrintingObjects(),this.scrubFileSize=Y.fileSize,Y.gcodeProcessor.updateFilePosition(Y.fileSize)}refreshPrintingObjects(){if(this.loadedFile!==this.sdCardFilePath||this.printing_objects.length===0)return;let e=[];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)]})}),Y==null||Y.buildObjects.loadObjectBoundaries(e),Y==null||Y.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 Y.processFile(r),this.fileData=Y.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.filename=e.startsWith("gcodes/")?e.slice(7):e;const t=Co.CancelToken;this.downloadSnackbar.cancelTokenSource=t.source();const i=await Co.get(this.apiUrl+"/server/files/"+zf(e),{cancelToken:this.downloadSnackbar.cancelTokenSource.token,responseType:"blob",onDownloadProgress:s=>{var n,r,o;this.downloadSnackbar.percent=((n=s.progress)!=null?n:0)*100,this.downloadSnackbar.speed=(r=s.rate)!=null?r:0,this.downloadSnackbar.total=(o=s.total)!=null?o:0}}).then(s=>s.data.text()).catch(s=>{window.console.error(s.message)});this.downloadSnackbar.status=!1,this.loadedFile=this.downloadSnackbar.filename,Y.updateRenderQuality(this.renderQuality.value),await Y.processFile(i),this.fileData=Y.fileData,this.loadingPercent=100,this.finishLoad(),this.scrubFileSize=Y.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&&(Y.gcodeProcessor.cancelLoad=!0,await this.sleep(1e3)),this.reloadRequired=!1,this.loading=!0,this.loadingPercent=0,await Y.reload(),this.fileData=Y.fileData,this.loadingPercent=100,this.finishLoad()}resetCamera(){Y.resetCamera()}setReloadRequiredFlag(){this.loadedFile&&this.loadedFile!=""&&(this.reloadRequired=!0)}async renderQualityChanged(e){Y&&Y.renderQuality!==e&&(Y.updateRenderQuality(e),await this.reloadViewer())}currentPositionChanged(e){if(!Y||!this.tracking||this.scrubPlaying)return;const t=[{axes:"X",position:e[0]},{axes:"Y",position:e[1]},{axes:"Z",position:e[2]}];Y.updateToolPosition(t)}filePositionChanged(e){if(!Y||!this.tracking||this.scrubPlaying)return;const t=350;if(e>0&&this.printerIsPrinting&&this.tracking&&e>t){Y.gcodeProcessor.updateFilePosition(e-t),this.scrubPosition=e-t;return}Y.gcodeProcessor.updateFilePosition(Y.fileSize)}async trackingChanged(e){if(Y!==null){if(e){this.scrubPlaying=!1,Y.gcodeProcessor.updateFilePosition(0),Y==null||Y.forceRender();return}Y.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){Y==null||Y.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&&Y&&(this.fileData=Y.fileData),this.handleResize()}showTravelMovesChanged(e){Y==null||Y.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){Y==null||Y.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){Y!==null&&(Y.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){Y!==null&&(Y.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){Y!==null&&(Y.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){Y!==null&&(Y.gcodeProcessor.setVoxelMode(e),Y.gcodeProcessor.voxelWidth=this.voxelWidth,Y.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){Y!==null&&Y.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}),Y.gcodeProcessor.g1AsExtrusion=e,Y.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){Y&&e.length&&(Y.gcodeProcessor.resetTools(),e.forEach(t=>{Y.gcodeProcessor.addTool(t,this.nozzle_diameter)}),this.setReloadRequiredFlag())}extruderColorsChanged(e){Y&&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}),Y&&Y.gcodeProcessor.colorMode!==e&&(Y.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){Y!==null&&Y.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){Y!==null&&Y.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){Y!==null&&Y.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){Y!==null&&Y.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){Y!==null&&Y.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){Y!==null&&(Y.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){Y!==null&&(Y.gcodeProcessor.updateMaxFeedColor(e),this.setReloadRequiredFlag())}get kinematics(){var e,t,i,s,n,r,o,h;return(h=(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?h:""}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){Y===null||!e||Y.bed.setDelta(e.includes("delta"))}bedMinSizeChanged(e){e===null||Y===null||Y.bed===null||(Y.bed.buildVolume.x.min=e[0],Y.bed.buildVolume.y.min=e[1],Y.bed.buildVolume.z.min=e[2])}bedMaxSizeChanged(e){e===null||Y===null||Y.bed===null||(Y.bed.buildVolume.x.max=e[0],Y.bed.buildVolume.y.max=e[1],Y.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){Y==null||Y.setProgressColor(e)}scrubPlayingChanged(e){if(!e){this.scrubInterval&&clearInterval(this.scrubInterval),this.scrubPlaying=!1,this.scrubInterval=void 0;return}this.scrubInterval&&(clearInterval(this.scrubInterval),this.scrubInterval=void 0),this.scrubPlaying=!0,this.scrubPosition>=this.scrubFileSize&&(this.scrubPosition=0),Y.gcodeProcessor.updateFilePosition(this.scrubPosition-3e4),this.scrubInterval=setInterval(()=>{this.scrubPosition+=100*this.scrubSpeed,Y.gcodeProcessor.updateFilePosition(this.scrubPosition),Y.simulateToolPosition(),(this.tracking||this.scrubPosition>=this.scrubFileSize)&&(this.scrubPlaying=!1)},200)}get showScrubber(){return!this.tracking&&this.scrubFileSize>0}updateScrubPosition(e){Y===null||this.tracking||(Y.gcodeProcessor.updateFilePosition(e),Y.simulateToolPosition())}fastForward(){this.scrubPosition=this.scrubFileSize,Y.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}};Je([Vr({type:String,default:"",required:!1})],$e.prototype,"filename",2);Je([Sl("fileInput")],$e.prototype,"fileInput",2);Je([Sl("viewerCanvasContainer")],$e.prototype,"viewerCanvasContainer",2);Je([Ml(200)],$e.prototype,"handleResize",1);Je([nt("printing_objects")],$e.prototype,"printing_objectsChanged",1);Je([nt("excluded_objects")],$e.prototype,"excluded_objectsChanged",1);Je([nt("renderQuality")],$e.prototype,"renderQualityChanged",1);Je([nt("currentPosition")],$e.prototype,"currentPositionChanged",1);Je([nt("filePosition")],$e.prototype,"filePositionChanged",1);Je([nt("tracking")],$e.prototype,"trackingChanged",1);Je([nt("printerIsPrinting")],$e.prototype,"printerIsPrintingChanged",1);Je([nt("showCursor")],$e.prototype,"showCursorChanged",1);Je([nt("showTravelMoves")],$e.prototype,"showTravelMovesChanged",1);Je([nt("showObjectSelection")],$e.prototype,"showObjectSelectionChanged",1);Je([nt("hdRendering")],$e.prototype,"hdRenderingChanged",1);Je([nt("forceLineRendering")],$e.prototype,"forceLineRenderingChanged",1);Je([nt("transparency")],$e.prototype,"transparencyChanged",1);Je([nt("voxelMode")],$e.prototype,"voxelModeChanged",1);Je([nt("specularLighting")],$e.prototype,"specularLightingChanged",1);Je([nt("extruderColors")],$e.prototype,"extruderColorsChanged",1);Je([nt("backgroundColor")],$e.prototype,"backgroundColorChanged",1);Je([nt("gridColor")],$e.prototype,"gridColorChanged",1);Je([nt("showAxes")],$e.prototype,"showAxesChanged",1);Je([nt("minFeed")],$e.prototype,"minFeedChanged",1);Je([nt("maxFeed")],$e.prototype,"maxFeedChanged",1);Je([nt("minFeedColor")],$e.prototype,"minFeedColorUpdated",1);Je([nt("maxFeedColor")],$e.prototype,"maxFeedColorUpdated",1);Je([nt("kinematics",{immediate:!0})],$e.prototype,"kinematicsChanged",1);Je([nt("bedMinSize",{deep:!0,immediate:!0})],$e.prototype,"bedMinSizeChanged",1);Je([nt("bedMaxSize",{deep:!0,immediate:!0})],$e.prototype,"bedMaxSizeChanged",1);Je([nt("progressColor")],$e.prototype,"progressColorChanged",1);Je([nt("scrubPlaying")],$e.prototype,"scrubPlayingChanged",1);Je([Ml(200),nt("scrubPosition")],$e.prototype,"updateScrubPosition",1);$e=Je([a0({components:{Panel:Pl,CodeStream:wl}})],$e);var Yb=function(){var e=this,t=e._self._c;return e._self._setupProxy,t("div",[t(Pl,{attrs:{title:e.panelTitle,icon:e.mdiVideo3d,"card-class":"gcode-viewer-panel","margin-bottom":!1},scopedSlots:e._u([{key:"buttons",fn:function(){return[t(Bt,{directives:[{name:"show",rawName:"v-show",value:e.reloadRequired,expression:"reloadRequired"}],staticClass:"ml-3",attrs:{icon:e.$vuetify.breakpoint.xs,text:e.$vuetify.breakpoint.smAndUp,tile:"",color:"info"},on:{click:e.reloadViewer}},[t("span",{staticClass:"d-none d-sm-block"},[e._v(e._s(e.$t("GCodeViewer.ReloadRequired")))]),t(Ri,{staticClass:"d-sm-none"},[e._v(e._s(e.mdiReloadAlert))])],1),t(Bt,{attrs:{icon:"",tile:""},on:{click:e.resetCamera}},[t(Ri,[e._v(e._s(e.mdiCameraRetake))])],1)]},proxy:!0}])},[t(Ro,[t(sr,{class:e.showScrubber?"withScrubber":""},[t(ds,{attrs:{cols:e.showGCode?8:12}},[t("div",{ref:"viewerCanvasContainer"})]),t(ds,{directives:[{name:"show",rawName:"v-show",value:e.showGCode,expression:"showGCode"}],attrs:{cols:"4"}},[t("div",{staticClass:"viewer"},[t(wl,{ref:"gcodestream",attrs:{shown:e.showGCode,currentline:e.scrubPosition,document:e.fileData,"is-simulating":!e.printerIsPrinting},on:{"update:currentline":function(i){e.scrubPosition=i}}})],1)])],1),t(sr,{directives:[{name:"show",rawName:"v-show",value:e.showScrubber,expression:"showScrubber"}],staticClass:"scrubber"},[t(ds,{staticClass:"pt-0"},[t(gf,{attrs:{hint:e.scrubPosition+"/"+e.scrubFileSize,max:e.scrubFileSize,dense:"",min:"0","persistent-hint":""},model:{value:e.scrubPosition,callback:function(i){e.scrubPosition=i},expression:"scrubPosition"}})],1),t(ds,{staticClass:"col-auto pt-0 text-center"},[t(Bt,{staticClass:"px-2 minwidth-0",attrs:{color:"primary"},on:{click:function(i){e.scrubPlaying=!e.scrubPlaying}}},[e.scrubPlaying?t(Ri,[e._v(e._s(e.mdiPause))]):t(Ri,[e._v(e._s(e.mdiPlay))])],1),t(Bt,{staticClass:"px-2 minwidth-0 mx-3",attrs:{color:"primary"},on:{click:e.fastForward}},[t(Ri,[e._v(e._s(e.mdiFastForward))])],1),t(mf,{staticClass:"mt-3 mt-sm-0",attrs:{dense:"",mandatory:"",rounded:""},model:{value:e.scrubSpeed,callback:function(i){e.scrubSpeed=i},expression:"scrubSpeed"}},[t(Bt,{attrs:{value:1}},[e._v("1x")]),t(Bt,{attrs:{value:2}},[e._v("2x")]),t(Bt,{attrs:{value:5}},[e._v("5x")]),t(Bt,{attrs:{value:10}},[e._v("10x")]),t(Bt,{attrs:{value:20}},[e._v("20x")])],1)],1)],1),t(sr,{staticClass:"mt-0 d-flex align-top"},[t(ds,[t(sr,[t(ds,{staticClass:"d-flex align-content-space-around justify-center flex-wrap flex-md-nowrap col-12 col-md-4",attrs:{"order-md":"2"}},[e.loadedFile===null?[e.sdCardFilePath!==""&&e.sdCardFilePath!==e.loadedFile?t(Bt,{staticClass:"mr-3",on:{click:e.loadCurrentFile}},[e._v(" "+e._s(e.$t("GCodeViewer.LoadCurrentFile"))+" ")]):e._e(),t(Bt,{on:{click:e.chooseFile}},[e._v(e._s(e.$t("GCodeViewer.LoadLocal")))])]:[e.showTrackingButton?t(Bt,{staticClass:"mr-3",on:{click:function(i){e.tracking=!e.tracking}}},[t(Ri,{staticClass:"mr-2",domProps:{innerHTML:e._s(e.tracking?e.mdiToggleSwitch:e.mdiToggleSwitchOffOutline)}}),e._v(" "+e._s(e.$t("GCodeViewer.Tracking"))+" ")],1):e._e(),t(Bt,{on:{click:e.clearLoadedFile}},[t(Ri,{attrs:{left:""}},[e._v(e._s(e.mdiBroom))]),e._v(" "+e._s(e.$t("GCodeViewer.ClearLoadedFile"))+" ")],1)]],2),t(ds,{staticClass:"col-12 col-sm-6 col-md-4"},[t(Io,{attrs:{items:e.colorModes,label:e.$t("GCodeViewer.ColorMode"),"item-text":"text",dense:"","hide-details":"",outlined:""},model:{value:e.colorMode,callback:function(i){e.colorMode=i},expression:"colorMode"}})],1),t(ds,{staticClass:"col-12 col-sm-6 col-md-4 d-flex",attrs:{"order-md":"3"}},[t(Io,{attrs:{items:e.renderQualities,label:e.$t("GCodeViewer.RenderQuality"),"item-text":"label",dense:"","hide-details":"",outlined:""},model:{value:e.renderQuality,callback:function(i){e.renderQuality=i},expression:"renderQuality"}}),t(vf,{attrs:{"offset-y":!0,"offset-x":!0,top:"","close-on-content-click":!1,title:e.$t("Files.SetupCurrentList")},scopedSlots:e._u([{key:"activator",fn:function({on:i,attrs:s}){return[t(Bt,e._g(e._b({staticClass:"minwidth-0 px-2 ml-3"},"v-btn",s,!1),i),[t(Ri,[e._v(e._s(e.mdiCog))])],1)]}}])},[t(bf,[t(Bi,{staticClass:"minHeight36"},[t(Li,{staticClass:"mt-0",attrs:{"hide-details":"",label:e.$t("GCodeViewer.ShowToolhead")},model:{value:e.showCursor,callback:function(i){e.showCursor=i},expression:"showCursor"}})],1),t(Bi,{staticClass:"minHeight36"},[t(Li,{staticClass:"mt-0",attrs:{"hide-details":"",label:e.$t("GCodeViewer.ShowTravelMoves")},model:{value:e.showTravelMoves,callback:function(i){e.showTravelMoves=i},expression:"showTravelMoves"}})],1),t(Bi,{staticClass:"minHeight36"},[t(Li,{staticClass:"mt-0",attrs:{"hide-details":"",label:e.$t("GCodeViewer.ShowGCode")},model:{value:e.showGCode,callback:function(i){e.showGCode=i},expression:"showGCode"}})],1),e.loadedFile===e.sdCardFilePath&&e.printing_objects.length?t(Bi,{staticClass:"minHeight36"},[t(Li,{staticClass:"mt-0",attrs:{"hide-details":"",label:e.$t("GCodeViewer.ShowObjectSelection")},model:{value:e.showObjectSelection,callback:function(i){e.showObjectSelection=i},expression:"showObjectSelection"}})],1):e._e(),t(xf),t(Bi,{staticClass:"minHeight36"},[t(Li,{staticClass:"mt-0",attrs:{"hide-details":"",label:e.$t("GCodeViewer.HDRendering")},model:{value:e.hdRendering,callback:function(i){e.hdRendering=i},expression:"hdRendering"}})],1),t(Bi,{staticClass:"minHeight36"},[t(Li,{staticClass:"mt-0",attrs:{"hide-details":"",label:e.$t("GCodeViewer.ForceLineRendering")},model:{value:e.forceLineRendering,callback:function(i){e.forceLineRendering=i},expression:"forceLineRendering"}})],1),t(Bi,{staticClass:"minHeight36"},[t(Li,{staticClass:"mt-0",attrs:{"hide-details":"",label:e.$t("GCodeViewer.Transparency")},model:{value:e.transparency,callback:function(i){e.transparency=i},expression:"transparency"}})],1),t(Bi,{staticClass:"minHeight36"},[t(Li,{staticClass:"mt-0",attrs:{"hide-details":"",label:e.$t("GCodeViewer.VoxelMode")},model:{value:e.voxelMode,callback:function(i){e.voxelMode=i},expression:"voxelMode"}})],1),t(Bi,{staticClass:"minHeight36"},[t(Li,{staticClass:"mt-0",attrs:{"hide-details":"",label:e.$t("GCodeViewer.SpecularLighting")},model:{value:e.specularLighting,callback:function(i){e.specularLighting=i},expression:"specularLighting"}})],1),t(Bi,{staticClass:"minHeight36"},[t(Li,{staticClass:"mt-0",attrs:{"hide-details":"",label:e.$t("GCodeViewer.CNCMode")},model:{value:e.cncMode,callback:function(i){e.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:e.fileSelected}})],1),t("resize-observer",{on:{notify:e.handleResize}})],1),t(Eo,{attrs:{timeout:-1,fixed:"",right:"",bottom:""},scopedSlots:e._u([{key:"action",fn:function({attrs:i}){return[t(Bt,e._b({staticStyle:{"min-width":"auto"},attrs:{color:"red",text:""},on:{click:function(s){return e.cancelRendering()}}},"v-btn",i,!1),[t(Ri,{staticClass:"0"},[e._v(e._s(e.mdiClose))])],1)]}}]),model:{value:e.loading,callback:function(i){e.loading=i},expression:"loading"}},[t("div",[e._v(" "+e._s(e.$t("GCodeViewer.Rendering"))+" - "+e._s(e.loadingPercent)+"% "),t("br"),t("strong",[e._v(e._s(e.loadedFile))])]),t(da,{staticClass:"mt-2",attrs:{value:e.loadingPercent}})],1),t(Eo,{attrs:{timeout:-1,fixed:"",right:"",bottom:""},scopedSlots:e._u([{key:"action",fn:function({attrs:i}){return[t(Bt,e._b({staticStyle:{"min-width":"auto"},attrs:{color:"red",text:""},on:{click:e.cancelDownload}},"v-btn",i,!1),[t(Ri,{staticClass:"0"},[e._v(e._s(e.mdiClose))])],1)]}}]),model:{value:e.downloadSnackbar.status,callback:function(i){e.$set(e.downloadSnackbar,"status",i)},expression:"downloadSnackbar.status"}},[e.downloadSnackbar.total>0?[t("div",[e._v(" "+e._s(e.$t("GCodeViewer.Downloading"))+" - "+e._s(Math.round(e.downloadSnackbar.percent))+" % @ "+e._s(e.formatFilesize(Math.round(e.downloadSnackbar.speed)))+"/s "),t("br"),t("strong",[e._v(e._s(e.downloadSnackbar.filename))])]),t(da,{staticClass:"mt-2",attrs:{value:e.downloadSnackbar.percent}})]:[t("div",[e._v(" "+e._s(e.$t("GCodeViewer.Downloading"))+" "),t("br"),t("strong",[e._v(e._s(e.downloadSnackbar.filename))])]),t(da,{staticClass:"mt-2",attrs:{indeterminate:""}})]],2),t(yf,{attrs:{"max-width":"400"},model:{value:e.excludeObject.bool,callback:function(i){e.$set(e.excludeObject,"bool",i)},expression:"excludeObject.bool"}},[t(Tf,[t(Af,{attrs:{flat:"",dense:""}},[t(Rf,[t("span",{staticClass:"subheading"},[t(Ri,{attrs:{left:""}},[e._v(e._s(e.mdiSelectionRemove))]),e._v(" "+e._s(e.$t("Panels.StatusPanel.ExcludeObject.ExcludeObjectHeadline"))+" ")],1)])],1),t(Ro,{staticClass:"mt-3"},[e._v(" "+e._s(e.$t("Panels.StatusPanel.ExcludeObject.ExcludeObjectText",{name:e.excludeObject.name}))+" ")]),t(If,[t(Ef),t(Bt,{attrs:{text:""},on:{click:function(i){e.excludeObject.bool=!1}}},[e._v(" "+e._s(e.$t("Panels.StatusPanel.ExcludeObject.Cancel"))+" ")]),t(Bt,{attrs:{color:"primary",text:""},on:{click:e.cancelObject}},[e._v(" "+e._s(e.$t("Panels.StatusPanel.ExcludeObject.ExcludeObject"))+" ")])],1)],1)],1)],1)},qb=[],jb=o0($e,Yb,qb,!1,null,"4c02d29b");const _f=jb.exports;var $b=Object.getOwnPropertyDescriptor,Zb=(a,e,t,i)=>{for(var s=i>1?void 0:i?$b(e,t):e,n=a.length-1,r;n>=0;n--)(r=a[n])&&(s=r(s)||s);return s};let r0=class extends El(Cl){};r0=Zb([a0({components:{Viewer:_f}})],r0);var Qb=function(){var e=this,t=e._self._c;return e._self._setupProxy,t(_f)},Jb=[],ex=o0(r0,Qb,Jb,!1,null,null);const tx=ex.exports,ox=Object.freeze(Object.defineProperty({__proto__:null,default:tx},Symbol.toStringTag,{value:"Module"}));export{ae as A,st as B,ht as C,sp as F,ft as I,b0 as L,mt as P,g0 as R,Me as S,rx as T,v as V,Nd as _,U as a,Ir as b,de as c,On as d,Wd as e,J as f,ie as g,ec as h,ox as i};